diff options
Diffstat (limited to 'modules')
521 files changed, 11725 insertions, 9372 deletions
diff --git a/modules/SCsub b/modules/SCsub index 64da3bd0be..5ff4623743 100644 --- a/modules/SCsub +++ b/modules/SCsub @@ -10,6 +10,7 @@ env_modules = env.Clone() Export("env_modules") # Header with MODULE_*_ENABLED defines. +env.Depends("modules_enabled.gen.h", Value(env.module_list)) env.CommandNoCache( "modules_enabled.gen.h", Value(env.module_list), @@ -23,6 +24,7 @@ env.CommandNoCache( # Header to be included in `tests/test_main.cpp` to run module-specific tests. if env["tests"]: + env.Depends("modules_tests.gen.h", Value(env.module_list)) env.CommandNoCache( "modules_tests.gen.h", Value(env.module_list), diff --git a/modules/basis_universal/SCsub b/modules/basis_universal/SCsub index 351628a0e3..1f9fde966d 100644 --- a/modules/basis_universal/SCsub +++ b/modules/basis_universal/SCsub @@ -11,40 +11,45 @@ thirdparty_obj = [] # Not unbundled so far since not widespread as shared library thirdparty_dir = "#thirdparty/basis_universal/" -tool_sources = [ +# Sync list with upstream CMakeLists.txt +encoder_sources = [ + "apg_bmp.c", "basisu_astc_decomp.cpp", "basisu_backend.cpp", "basisu_basis_file.cpp", + "basisu_bc7enc.cpp", "basisu_comp.cpp", "basisu_enc.cpp", "basisu_etc.cpp", "basisu_frontend.cpp", "basisu_global_selector_palette_helpers.cpp", "basisu_gpu_texture.cpp", + "basisu_kernels_sse.cpp", "basisu_pvrtc1_4.cpp", - "basisu_resample_filters.cpp", "basisu_resampler.cpp", + "basisu_resample_filters.cpp", "basisu_ssim.cpp", + "basisu_uastc_enc.cpp", + "jpgd.cpp", "lodepng.cpp", ] -tool_sources = [thirdparty_dir + file for file in tool_sources] +encoder_sources = [thirdparty_dir + "encoder/" + file for file in encoder_sources] transcoder_sources = [thirdparty_dir + "transcoder/basisu_transcoder.cpp"] # Treat Basis headers as system headers to avoid raising warnings. Not supported on MSVC. if not env.msvc: - env_basisu.Append( - CPPFLAGS=["-isystem", Dir(thirdparty_dir).path, "-isystem", Dir(thirdparty_dir + "transcoder").path] - ) + env_basisu.Append(CPPFLAGS=["-isystem", Dir(thirdparty_dir).path]) else: - env_basisu.Prepend(CPPPATH=[thirdparty_dir, thirdparty_dir + "transcoder"]) + env_basisu.Prepend(CPPPATH=[thirdparty_dir]) if env["target"] == "debug": - env_basisu.Append(CPPFLAGS=["-DBASISU_DEVEL_MESSAGES=1", "-DBASISD_ENABLE_DEBUG_FLAGS=1"]) + 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"]: - env_thirdparty.add_source_files(thirdparty_obj, tool_sources) + 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) env.modules_sources += thirdparty_obj diff --git a/modules/basis_universal/register_types.cpp b/modules/basis_universal/register_types.cpp index cf5581265b..9a13406900 100644 --- a/modules/basis_universal/register_types.cpp +++ b/modules/basis_universal/register_types.cpp @@ -35,7 +35,7 @@ #include "texture_basisu.h" #ifdef TOOLS_ENABLED -#include <basisu_comp.h> +#include <encoder/basisu_comp.h> #endif #include <transcoder/basisu_transcoder.h> @@ -233,7 +233,7 @@ static Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) { basist::basisu_image_info info; tr.get_image_info(ptr, size, info, 0); - int block_size = basist::basis_get_bytes_per_block(format); + int block_size = basist::basis_get_bytes_per_block_or_pixel(format); Vector<uint8_t> gpudata; gpudata.resize(info.m_total_blocks * block_size); @@ -260,7 +260,7 @@ static Ref<Image> basis_universal_unpacker(const Vector<uint8_t> &p_buffer) { }; }; - image.instance(); + image.instantiate(); image->create(info.m_width, info.m_height, info.m_total_levels > 1, imgfmt, gpudata); return image; @@ -272,7 +272,7 @@ void register_basis_universal_types() { Image::basis_universal_packer = basis_universal_packer; #endif Image::basis_universal_unpacker = basis_universal_unpacker; - //ClassDB::register_class<TextureBasisU>(); + //GDREGISTER_CLASS(TextureBasisU); } void unregister_basis_universal_types() { diff --git a/modules/basis_universal/texture_basisu.cpp b/modules/basis_universal/texture_basisu.cpp index 92882a1cc8..9e917420ce 100644 --- a/modules/basis_universal/texture_basisu.cpp +++ b/modules/basis_universal/texture_basisu.cpp @@ -33,7 +33,7 @@ #include "core/os/os.h" #ifdef TOOLS_ENABLED -#include <basisu_comp.h> +#include <encoder/basisu_comp.h> #endif #include <transcoder/basisu_transcoder.h> @@ -130,7 +130,7 @@ void TextureBasisU::set_basisu_data(const Vector<uint8_t>& p_data) { }; Ref<Image> img; - img.instance(); + img.instantiate(); img->create(info.m_width, info.m_height, info.m_total_levels > 1, imgfmt, gpudata); RenderingServer::get_singleton()->texture_allocate(texture, tex_size.x, tex_size.y, 0, img->get_format(), RS::TEXTURE_TYPE_2D, flags); diff --git a/modules/basis_universal/texture_basisu.h b/modules/basis_universal/texture_basisu.h index 282a0dfc8a..3316035404 100644 --- a/modules/basis_universal/texture_basisu.h +++ b/modules/basis_universal/texture_basisu.h @@ -34,7 +34,7 @@ #include "scene/resources/texture.h" #ifdef TOOLS_ENABLED -#include <basisu_comp.h> +#include <encoder/basisu_comp.h> #endif #include <transcoder/basisu_transcoder.h> diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp index c7fdf56af4..171895ed24 100644 --- a/modules/bmp/image_loader_bmp.cpp +++ b/modules/bmp/image_loader_bmp.cpp @@ -130,23 +130,19 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, line_ptr += 1; } break; case 24: { - uint32_t color = *((uint32_t *)line_ptr); - - write_buffer[index + 2] = color & 0xff; - write_buffer[index + 1] = (color >> 8) & 0xff; - write_buffer[index + 0] = (color >> 16) & 0xff; + write_buffer[index + 2] = line_ptr[0]; + write_buffer[index + 1] = line_ptr[1]; + write_buffer[index + 0] = line_ptr[2]; write_buffer[index + 3] = 0xff; index += 4; line_ptr += 3; } break; case 32: { - uint32_t color = *((uint32_t *)line_ptr); - - write_buffer[index + 2] = color & 0xff; - write_buffer[index + 1] = (color >> 8) & 0xff; - write_buffer[index + 0] = (color >> 16) & 0xff; - write_buffer[index + 3] = color >> 24; + write_buffer[index + 2] = line_ptr[0]; + write_buffer[index + 1] = line_ptr[1]; + write_buffer[index + 0] = line_ptr[2]; + write_buffer[index + 3] = line_ptr[3]; index += 4; line_ptr += 4; @@ -172,11 +168,9 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, const uint8_t *cb = p_color_buffer; for (unsigned int i = 0; i < color_table_size; ++i) { - uint32_t color = *((uint32_t *)cb); - - pal[i * 4 + 0] = (color >> 16) & 0xff; - pal[i * 4 + 1] = (color >> 8) & 0xff; - pal[i * 4 + 2] = (color)&0xff; + pal[i * 4 + 0] = cb[2]; + pal[i * 4 + 1] = cb[1]; + pal[i * 4 + 2] = cb[0]; pal[i * 4 + 3] = 0xff; cb += 4; @@ -211,7 +205,7 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, // A valid bmp file should always at least have a // file header and a minimal info header - if (f->get_len() > BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_MIN_SIZE) { + if (f->get_length() > BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_MIN_SIZE) { // File Header bmp_header.bmp_file_header.bmp_signature = f->get_16(); if (bmp_header.bmp_file_header.bmp_signature == BITMAP_SIGNATURE) { @@ -304,7 +298,7 @@ static Ref<Image> _bmp_mem_loader_func(const uint8_t *p_bmp, int p_size) { Error open_memfile_error = memfile.open_custom(p_bmp, p_size); ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for BMP image buffer."); Ref<Image> img; - img.instance(); + img.instantiate(); Error load_error = ImageLoaderBMP().load_image(img, &memfile, false, 1.0f); ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load BMP image."); return img; diff --git a/modules/bullet/SCsub b/modules/bullet/SCsub index bfac0df5b0..ba57de303e 100644 --- a/modules/bullet/SCsub +++ b/modules/bullet/SCsub @@ -12,6 +12,8 @@ thirdparty_obj = [] if env["builtin_bullet"]: # Build only version 2 for now (as of 2.89) # Sync file list with relevant upstream CMakeLists.txt for each folder. + if env["float"] == "64": + env.Append(CPPDEFINES=["BT_USE_DOUBLE_PRECISION=1"]) thirdparty_dir = "#thirdparty/bullet/" bullet2_src = [ diff --git a/modules/bullet/bullet_physics_server.cpp b/modules/bullet/bullet_physics_server.cpp index e601884486..fc876a81cf 100644 --- a/modules/bullet/bullet_physics_server.cpp +++ b/modules/bullet/bullet_physics_server.cpp @@ -268,7 +268,7 @@ PhysicsServer3D::AreaSpaceOverrideMode BulletPhysicsServer3D::area_get_space_ove return area->get_spOv_mode(); } -void BulletPhysicsServer3D::area_add_shape(RID p_area, RID p_shape, const Transform &p_transform, bool p_disabled) { +void BulletPhysicsServer3D::area_add_shape(RID p_area, RID p_shape, const Transform3D &p_transform, bool p_disabled) { AreaBullet *area = area_owner.getornull(p_area); ERR_FAIL_COND(!area); @@ -288,7 +288,7 @@ void BulletPhysicsServer3D::area_set_shape(RID p_area, int p_shape_idx, RID p_sh area->set_shape(p_shape_idx, shape); } -void BulletPhysicsServer3D::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform) { +void BulletPhysicsServer3D::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform3D &p_transform) { AreaBullet *area = area_owner.getornull(p_area); ERR_FAIL_COND(!area); @@ -309,9 +309,9 @@ RID BulletPhysicsServer3D::area_get_shape(RID p_area, int p_shape_idx) const { return area->get_shape(p_shape_idx)->get_self(); } -Transform BulletPhysicsServer3D::area_get_shape_transform(RID p_area, int p_shape_idx) const { +Transform3D BulletPhysicsServer3D::area_get_shape_transform(RID p_area, int p_shape_idx) const { AreaBullet *area = area_owner.getornull(p_area); - ERR_FAIL_COND_V(!area, Transform()); + ERR_FAIL_COND_V(!area, Transform3D()); return area->get_shape_transform(p_shape_idx); } @@ -382,15 +382,15 @@ Variant BulletPhysicsServer3D::area_get_param(RID p_area, AreaParameter p_param) } } -void BulletPhysicsServer3D::area_set_transform(RID p_area, const Transform &p_transform) { +void BulletPhysicsServer3D::area_set_transform(RID p_area, const Transform3D &p_transform) { AreaBullet *area = area_owner.getornull(p_area); ERR_FAIL_COND(!area); area->set_transform(p_transform); } -Transform BulletPhysicsServer3D::area_get_transform(RID p_area) const { +Transform3D BulletPhysicsServer3D::area_get_transform(RID p_area) const { AreaBullet *area = area_owner.getornull(p_area); - ERR_FAIL_COND_V(!area, Transform()); + ERR_FAIL_COND_V(!area, Transform3D()); return area->get_transform(); } @@ -484,7 +484,7 @@ PhysicsServer3D::BodyMode BulletPhysicsServer3D::body_get_mode(RID p_body) const return body->get_mode(); } -void BulletPhysicsServer3D::body_add_shape(RID p_body, RID p_shape, const Transform &p_transform, bool p_disabled) { +void BulletPhysicsServer3D::body_add_shape(RID p_body, RID p_shape, const Transform3D &p_transform, bool p_disabled) { RigidBodyBullet *body = rigid_body_owner.getornull(p_body); ERR_FAIL_COND(!body); @@ -504,7 +504,7 @@ void BulletPhysicsServer3D::body_set_shape(RID p_body, int p_shape_idx, RID p_sh body->set_shape(p_shape_idx, shape); } -void BulletPhysicsServer3D::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform) { +void BulletPhysicsServer3D::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform3D &p_transform) { RigidBodyBullet *body = rigid_body_owner.getornull(p_body); ERR_FAIL_COND(!body); @@ -527,9 +527,9 @@ RID BulletPhysicsServer3D::body_get_shape(RID p_body, int p_shape_idx) const { return shape->get_self(); } -Transform BulletPhysicsServer3D::body_get_shape_transform(RID p_body, int p_shape_idx) const { +Transform3D BulletPhysicsServer3D::body_get_shape_transform(RID p_body, int p_shape_idx) const { RigidBodyBullet *body = rigid_body_owner.getornull(p_body); - ERR_FAIL_COND_V(!body, Transform()); + ERR_FAIL_COND_V(!body, Transform3D()); return body->get_shape_transform(p_shape_idx); } @@ -842,15 +842,15 @@ PhysicsDirectBodyState3D *BulletPhysicsServer3D::body_get_direct_state(RID p_bod return BulletPhysicsDirectBodyState3D::get_singleton(body); } -bool BulletPhysicsServer3D::body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result, bool p_exclude_raycast_shapes) { +bool BulletPhysicsServer3D::body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result, bool p_exclude_raycast_shapes, const Set<RID> &p_exclude) { RigidBodyBullet *body = rigid_body_owner.getornull(p_body); ERR_FAIL_COND_V(!body, false); ERR_FAIL_COND_V(!body->get_space(), false); - return body->get_space()->test_body_motion(body, p_from, p_motion, p_infinite_inertia, r_result, p_exclude_raycast_shapes); + return body->get_space()->test_body_motion(body, p_from, p_motion, p_infinite_inertia, r_result, p_exclude_raycast_shapes, p_exclude); } -int BulletPhysicsServer3D::body_test_ray_separation(RID p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, real_t p_margin) { +int BulletPhysicsServer3D::body_test_ray_separation(RID p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, real_t p_margin) { RigidBodyBullet *body = rigid_body_owner.getornull(p_body); ERR_FAIL_COND_V(!body, 0); ERR_FAIL_COND_V(!body->get_space(), 0); @@ -990,7 +990,7 @@ Variant BulletPhysicsServer3D::soft_body_get_state(RID p_body, BodyState p_state return Variant(); } -void BulletPhysicsServer3D::soft_body_set_transform(RID p_body, const Transform &p_transform) { +void BulletPhysicsServer3D::soft_body_set_transform(RID p_body, const Transform3D &p_transform) { SoftBodyBullet *body = soft_body_owner.getornull(p_body); ERR_FAIL_COND(!body); @@ -1205,7 +1205,7 @@ Vector3 BulletPhysicsServer3D::pin_joint_get_local_b(RID p_joint) const { return pin_joint->getPivotInB(); } -RID BulletPhysicsServer3D::joint_create_hinge(RID p_body_A, const Transform &p_hinge_A, RID p_body_B, const Transform &p_hinge_B) { +RID BulletPhysicsServer3D::joint_create_hinge(RID p_body_A, const Transform3D &p_hinge_A, RID p_body_B, const Transform3D &p_hinge_B) { RigidBodyBullet *body_A = rigid_body_owner.getornull(p_body_A); ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); @@ -1277,7 +1277,7 @@ bool BulletPhysicsServer3D::hinge_joint_get_flag(RID p_joint, HingeJointFlag p_f return hinge_joint->get_flag(p_flag); } -RID BulletPhysicsServer3D::joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) { +RID BulletPhysicsServer3D::joint_create_slider(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) { RigidBodyBullet *body_A = rigid_body_owner.getornull(p_body_A); ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); @@ -1313,7 +1313,7 @@ real_t BulletPhysicsServer3D::slider_joint_get_param(RID p_joint, SliderJointPar return slider_joint->get_param(p_param); } -RID BulletPhysicsServer3D::joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) { +RID BulletPhysicsServer3D::joint_create_cone_twist(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) { RigidBodyBullet *body_A = rigid_body_owner.getornull(p_body_A); ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); @@ -1347,7 +1347,7 @@ real_t BulletPhysicsServer3D::cone_twist_joint_get_param(RID p_joint, ConeTwistJ return coneTwist_joint->get_param(p_param); } -RID BulletPhysicsServer3D::joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) { +RID BulletPhysicsServer3D::joint_create_generic_6dof(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) { RigidBodyBullet *body_A = rigid_body_owner.getornull(p_body_A); ERR_FAIL_COND_V(!body_A, RID()); JointAssertSpace(body_A, "A", RID()); diff --git a/modules/bullet/bullet_physics_server.h b/modules/bullet/bullet_physics_server.h index de0379c873..7f0934e679 100644 --- a/modules/bullet/bullet_physics_server.h +++ b/modules/bullet/bullet_physics_server.h @@ -134,12 +134,12 @@ public: virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) override; virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const override; - virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false) override; + virtual void area_add_shape(RID p_area, RID p_shape, const Transform3D &p_transform = Transform3D(), bool p_disabled = false) override; virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape) override; - virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform) override; + virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform3D &p_transform) override; virtual int area_get_shape_count(RID p_area) const override; virtual RID area_get_shape(RID p_area, int p_shape_idx) const override; - virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const override; + virtual Transform3D area_get_shape_transform(RID p_area, int p_shape_idx) const override; virtual void area_remove_shape(RID p_area, int p_shape_idx) override; virtual void area_clear_shapes(RID p_area) override; virtual void area_set_shape_disabled(RID p_area, int p_shape_idx, bool p_disabled) override; @@ -153,8 +153,8 @@ public: virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) override; virtual Variant area_get_param(RID p_area, AreaParameter p_param) const override; - virtual void area_set_transform(RID p_area, const Transform &p_transform) override; - virtual Transform area_get_transform(RID p_area) const override; + virtual void area_set_transform(RID p_area, const Transform3D &p_transform) override; + virtual Transform3D area_get_transform(RID p_area) const override; virtual void area_set_collision_mask(RID p_area, uint32_t p_mask) override; virtual void area_set_collision_layer(RID p_area, uint32_t p_layer) override; @@ -166,7 +166,7 @@ public: /* RIGID BODY API */ - virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false) override; + virtual RID body_create(BodyMode p_mode = BODY_MODE_DYNAMIC, bool p_init_sleeping = false) override; virtual void body_set_space(RID p_body, RID p_space) override; virtual RID body_get_space(RID p_body) const override; @@ -174,14 +174,14 @@ public: virtual void body_set_mode(RID p_body, BodyMode p_mode) override; virtual BodyMode body_get_mode(RID p_body) const override; - virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform(), bool p_disabled = false) override; + virtual void body_add_shape(RID p_body, RID p_shape, const Transform3D &p_transform = Transform3D(), bool p_disabled = false) override; // Not supported, Please remove and add new shape virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape) override; - virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform) override; + virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform3D &p_transform) override; virtual int body_get_shape_count(RID p_body) const override; virtual RID body_get_shape(RID p_body, int p_shape_idx) const override; - virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const override; + virtual Transform3D body_get_shape_transform(RID p_body, int p_shape_idx) const override; virtual void body_set_shape_disabled(RID p_body, int p_shape_idx, bool p_disabled) override; @@ -253,8 +253,8 @@ public: // this function only works on physics process, errors and returns null otherwise virtual PhysicsDirectBodyState3D *body_get_direct_state(RID p_body) override; - virtual bool body_test_motion(RID p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = nullptr, bool p_exclude_raycast_shapes = true) override; - virtual int body_test_ray_separation(RID p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, real_t p_margin = 0.001) override; + virtual bool body_test_motion(RID p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, MotionResult *r_result = nullptr, bool p_exclude_raycast_shapes = true, const Set<RID> &p_exclude = Set<RID>()) override; + virtual int body_test_ray_separation(RID p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, SeparationResult *r_results, int p_result_max, real_t p_margin = 0.001) override; /* SOFT BODY API */ @@ -283,7 +283,7 @@ public: virtual Variant soft_body_get_state(RID p_body, BodyState p_state) const override; /// Special function. This function has bad performance - virtual void soft_body_set_transform(RID p_body, const Transform &p_transform) override; + virtual void soft_body_set_transform(RID p_body, const Transform3D &p_transform) override; virtual void soft_body_set_ray_pickable(RID p_body, bool p_enable) override; @@ -333,7 +333,7 @@ public: virtual void pin_joint_set_local_b(RID p_joint, const Vector3 &p_B) override; virtual Vector3 pin_joint_get_local_b(RID p_joint) const override; - virtual RID joint_create_hinge(RID p_body_A, const Transform &p_hinge_A, RID p_body_B, const Transform &p_hinge_B) override; + virtual RID joint_create_hinge(RID p_body_A, const Transform3D &p_hinge_A, RID p_body_B, const Transform3D &p_hinge_B) override; virtual RID joint_create_hinge_simple(RID p_body_A, const Vector3 &p_pivot_A, const Vector3 &p_axis_A, RID p_body_B, const Vector3 &p_pivot_B, const Vector3 &p_axis_B) override; virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, real_t p_value) override; @@ -343,19 +343,19 @@ public: virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const override; /// Reference frame is A - virtual RID joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) override; + virtual RID joint_create_slider(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) override; virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value) override; virtual real_t slider_joint_get_param(RID p_joint, SliderJointParam p_param) const override; /// Reference frame is A - virtual RID joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) override; + virtual RID joint_create_cone_twist(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) override; virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, real_t p_value) override; virtual real_t cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const override; /// Reference frame is A - virtual RID joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) override; + virtual RID joint_create_generic_6dof(RID p_body_A, const Transform3D &p_local_frame_A, RID p_body_B, const Transform3D &p_local_frame_B) override; virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param, real_t p_value) override; virtual real_t generic_6dof_joint_get_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param) override; diff --git a/modules/bullet/bullet_types_converter.cpp b/modules/bullet/bullet_types_converter.cpp index 19d4816372..01461767bd 100644 --- a/modules/bullet/bullet_types_converter.cpp +++ b/modules/bullet/bullet_types_converter.cpp @@ -59,7 +59,7 @@ void INVERT_B_TO_G(btMatrix3x3 const &inVal, Basis &outVal) { INVERT_B_TO_G(inVal[2], outVal[2]); } -void B_TO_G(btTransform const &inVal, Transform &outVal) { +void B_TO_G(btTransform const &inVal, Transform3D &outVal) { B_TO_G(inVal.getBasis(), outVal.basis); B_TO_G(inVal.getOrigin(), outVal.origin); } @@ -89,7 +89,7 @@ void INVERT_G_TO_B(Basis const &inVal, btMatrix3x3 &outVal) { INVERT_G_TO_B(inVal[2], outVal[2]); } -void G_TO_B(Transform const &inVal, btTransform &outVal) { +void G_TO_B(Transform3D const &inVal, btTransform &outVal) { G_TO_B(inVal.basis, outVal.getBasis()); G_TO_B(inVal.origin, outVal.getOrigin()); } diff --git a/modules/bullet/bullet_types_converter.h b/modules/bullet/bullet_types_converter.h index ca9b7175dd..e184fe1769 100644 --- a/modules/bullet/bullet_types_converter.h +++ b/modules/bullet/bullet_types_converter.h @@ -32,7 +32,7 @@ #define BULLET_TYPES_CONVERTER_H #include "core/math/basis.h" -#include "core/math/transform.h" +#include "core/math/transform_3d.h" #include "core/math/vector3.h" #include "core/typedefs.h" @@ -49,14 +49,14 @@ extern void B_TO_G(btVector3 const &inVal, Vector3 &outVal); extern void INVERT_B_TO_G(btVector3 const &inVal, Vector3 &outVal); extern void B_TO_G(btMatrix3x3 const &inVal, Basis &outVal); extern void INVERT_B_TO_G(btMatrix3x3 const &inVal, Basis &outVal); -extern void B_TO_G(btTransform const &inVal, Transform &outVal); +extern void B_TO_G(btTransform const &inVal, Transform3D &outVal); // Godot TO Bullet extern void G_TO_B(Vector3 const &inVal, btVector3 &outVal); extern void INVERT_G_TO_B(Vector3 const &inVal, btVector3 &outVal); extern void G_TO_B(Basis const &inVal, btMatrix3x3 &outVal); extern void INVERT_G_TO_B(Basis const &inVal, btMatrix3x3 &outVal); -extern void G_TO_B(Transform const &inVal, btTransform &outVal); +extern void G_TO_B(Transform3D const &inVal, btTransform &outVal); extern void UNSCALE_BT_BASIS(btTransform &scaledBasis); #endif diff --git a/modules/bullet/collision_object_bullet.cpp b/modules/bullet/collision_object_bullet.cpp index d9f5beb5a1..c45bd5bbc0 100644 --- a/modules/bullet/collision_object_bullet.cpp +++ b/modules/bullet/collision_object_bullet.cpp @@ -49,7 +49,7 @@ CollisionObjectBullet::ShapeWrapper::~ShapeWrapper() {} -void CollisionObjectBullet::ShapeWrapper::set_transform(const Transform &p_transform) { +void CollisionObjectBullet::ShapeWrapper::set_transform(const Transform3D &p_transform) { G_TO_B(p_transform.get_basis().get_scale_abs(), scale); G_TO_B(p_transform, transform); UNSCALE_BT_BASIS(transform); @@ -193,7 +193,7 @@ int CollisionObjectBullet::get_godot_object_flags() const { return bt_collision_object->getUserIndex2(); } -void CollisionObjectBullet::set_transform(const Transform &p_global_transform) { +void CollisionObjectBullet::set_transform(const Transform3D &p_global_transform) { set_body_scale(p_global_transform.basis.get_scale_abs()); btTransform bt_transform; @@ -203,8 +203,8 @@ void CollisionObjectBullet::set_transform(const Transform &p_global_transform) { set_transform__bullet(bt_transform); } -Transform CollisionObjectBullet::get_transform() const { - Transform t; +Transform3D CollisionObjectBullet::get_transform() const { + Transform3D t; B_TO_G(get_transform__bullet(), t); t.basis.scale(body_scale); return t; @@ -230,7 +230,7 @@ RigidCollisionObjectBullet::~RigidCollisionObjectBullet() { } } -void RigidCollisionObjectBullet::add_shape(ShapeBullet *p_shape, const Transform &p_transform, bool p_disabled) { +void RigidCollisionObjectBullet::add_shape(ShapeBullet *p_shape, const Transform3D &p_transform, bool p_disabled) { shapes.push_back(ShapeWrapper(p_shape, p_transform, !p_disabled)); p_shape->add_owner(this); reload_shapes(); @@ -296,7 +296,7 @@ void RigidCollisionObjectBullet::remove_all_shapes(bool p_permanentlyFromThisBod } } -void RigidCollisionObjectBullet::set_shape_transform(int p_index, const Transform &p_transform) { +void RigidCollisionObjectBullet::set_shape_transform(int p_index, const Transform3D &p_transform) { ERR_FAIL_INDEX(p_index, get_shape_count()); shapes.write[p_index].set_transform(p_transform); @@ -307,8 +307,8 @@ const btTransform &RigidCollisionObjectBullet::get_bt_shape_transform(int p_inde return shapes[p_index].transform; } -Transform RigidCollisionObjectBullet::get_shape_transform(int p_index) const { - Transform trs; +Transform3D RigidCollisionObjectBullet::get_shape_transform(int p_index) const { + Transform3D trs; B_TO_G(shapes[p_index].transform, trs); return trs; } diff --git a/modules/bullet/collision_object_bullet.h b/modules/bullet/collision_object_bullet.h index c8081a53f1..944ab89b87 100644 --- a/modules/bullet/collision_object_bullet.h +++ b/modules/bullet/collision_object_bullet.h @@ -31,7 +31,7 @@ #ifndef COLLISION_OBJECT_BULLET_H #define COLLISION_OBJECT_BULLET_H -#include "core/math/transform.h" +#include "core/math/transform_3d.h" #include "core/math/vector3.h" #include "core/object/class_db.h" #include "core/templates/vset.h" @@ -83,7 +83,7 @@ public: set_transform(p_transform); } - ShapeWrapper(ShapeBullet *p_shape, const Transform &p_transform, bool p_active) : + ShapeWrapper(ShapeBullet *p_shape, const Transform3D &p_transform, bool p_active) : shape(p_shape), active(p_active) { set_transform(p_transform); @@ -102,7 +102,7 @@ public: active = otherShape.active; } - void set_transform(const Transform &p_transform); + void set_transform(const Transform3D &p_transform); void set_transform(const btTransform &p_transform); btTransform get_adjusted_transform() const; @@ -202,8 +202,8 @@ public: void set_godot_object_flags(int flags); int get_godot_object_flags() const; - void set_transform(const Transform &p_global_transform); - Transform get_transform() const; + void set_transform(const Transform3D &p_global_transform); + Transform3D get_transform() const; virtual void set_transform__bullet(const btTransform &p_global_transform); virtual const btTransform &get_transform__bullet() const; @@ -225,7 +225,7 @@ public: _FORCE_INLINE_ btCollisionShape *get_main_shape() const { return mainShape; } - void add_shape(ShapeBullet *p_shape, const Transform &p_transform = Transform(), bool p_disabled = false); + void add_shape(ShapeBullet *p_shape, const Transform3D &p_transform = Transform3D(), bool p_disabled = false); void set_shape(int p_index, ShapeBullet *p_shape); int get_shape_count() const; @@ -238,10 +238,10 @@ public: void remove_shape_full(int p_index); void remove_all_shapes(bool p_permanentlyFromThisBody = false, bool p_force_not_reload = false); - void set_shape_transform(int p_index, const Transform &p_transform); + void set_shape_transform(int p_index, const Transform3D &p_transform); const btTransform &get_bt_shape_transform(int p_index) const; - Transform get_shape_transform(int p_index) const; + Transform3D get_shape_transform(int p_index) const; void set_shape_disabled(int p_index, bool p_disabled); bool is_shape_disabled(int p_index); diff --git a/modules/bullet/cone_twist_joint_bullet.cpp b/modules/bullet/cone_twist_joint_bullet.cpp index e785780c5b..34516d8b3b 100644 --- a/modules/bullet/cone_twist_joint_bullet.cpp +++ b/modules/bullet/cone_twist_joint_bullet.cpp @@ -40,16 +40,16 @@ @author AndreaCatania */ -ConeTwistJointBullet::ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &rbAFrame, const Transform &rbBFrame) : +ConeTwistJointBullet::ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &rbAFrame, const Transform3D &rbBFrame) : JointBullet() { - Transform scaled_AFrame(rbAFrame.scaled(rbA->get_body_scale())); + Transform3D scaled_AFrame(rbAFrame.scaled(rbA->get_body_scale())); scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); btTransform btFrameA; G_TO_B(scaled_AFrame, btFrameA); if (rbB) { - Transform scaled_BFrame(rbBFrame.scaled(rbB->get_body_scale())); + Transform3D scaled_BFrame(rbBFrame.scaled(rbB->get_body_scale())); scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); btTransform btFrameB; diff --git a/modules/bullet/cone_twist_joint_bullet.h b/modules/bullet/cone_twist_joint_bullet.h index 7d6bafd292..7e51f7d644 100644 --- a/modules/bullet/cone_twist_joint_bullet.h +++ b/modules/bullet/cone_twist_joint_bullet.h @@ -43,7 +43,7 @@ class ConeTwistJointBullet : public JointBullet { class btConeTwistConstraint *coneConstraint; public: - ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &rbAFrame, const Transform &rbBFrame); + ConeTwistJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &rbAFrame, const Transform3D &rbBFrame); virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_CONE_TWIST; } diff --git a/modules/bullet/config.py b/modules/bullet/config.py index be7cf74f6f..83605f1f9b 100644 --- a/modules/bullet/config.py +++ b/modules/bullet/config.py @@ -1,6 +1,7 @@ def can_build(env, platform): # API Changed and bullet is disabled at the moment return False + # Later change to return not env["disable_3d"] def configure(env): diff --git a/modules/bullet/generic_6dof_joint_bullet.cpp b/modules/bullet/generic_6dof_joint_bullet.cpp index 43ad6c56d5..7e04d57b9d 100644 --- a/modules/bullet/generic_6dof_joint_bullet.cpp +++ b/modules/bullet/generic_6dof_joint_bullet.cpp @@ -40,7 +40,7 @@ @author AndreaCatania */ -Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB) : +Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB) : JointBullet() { for (int i = 0; i < 3; i++) { for (int j = 0; j < PhysicsServer3D::G6DOF_JOINT_FLAG_MAX; j++) { @@ -48,7 +48,7 @@ Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBu } } - Transform scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); + Transform3D scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); @@ -56,7 +56,7 @@ Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBu G_TO_B(scaled_AFrame, btFrameA); if (rbB) { - Transform scaled_BFrame(frameInB.scaled(rbB->get_body_scale())); + Transform3D scaled_BFrame(frameInB.scaled(rbB->get_body_scale())); scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); @@ -71,30 +71,30 @@ Generic6DOFJointBullet::Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBu setup(sixDOFConstraint); } -Transform Generic6DOFJointBullet::getFrameOffsetA() const { +Transform3D Generic6DOFJointBullet::getFrameOffsetA() const { btTransform btTrs = sixDOFConstraint->getFrameOffsetA(); - Transform gTrs; + Transform3D gTrs; B_TO_G(btTrs, gTrs); return gTrs; } -Transform Generic6DOFJointBullet::getFrameOffsetB() const { +Transform3D Generic6DOFJointBullet::getFrameOffsetB() const { btTransform btTrs = sixDOFConstraint->getFrameOffsetB(); - Transform gTrs; + Transform3D gTrs; B_TO_G(btTrs, gTrs); return gTrs; } -Transform Generic6DOFJointBullet::getFrameOffsetA() { +Transform3D Generic6DOFJointBullet::getFrameOffsetA() { btTransform btTrs = sixDOFConstraint->getFrameOffsetA(); - Transform gTrs; + Transform3D gTrs; B_TO_G(btTrs, gTrs); return gTrs; } -Transform Generic6DOFJointBullet::getFrameOffsetB() { +Transform3D Generic6DOFJointBullet::getFrameOffsetB() { btTransform btTrs = sixDOFConstraint->getFrameOffsetB(); - Transform gTrs; + Transform3D gTrs; B_TO_G(btTrs, gTrs); return gTrs; } diff --git a/modules/bullet/generic_6dof_joint_bullet.h b/modules/bullet/generic_6dof_joint_bullet.h index 62b8e85a81..00567e3085 100644 --- a/modules/bullet/generic_6dof_joint_bullet.h +++ b/modules/bullet/generic_6dof_joint_bullet.h @@ -48,14 +48,14 @@ class Generic6DOFJointBullet : public JointBullet { bool flags[3][PhysicsServer3D::G6DOF_JOINT_FLAG_MAX]; public: - Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB); + Generic6DOFJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB); virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_6DOF; } - Transform getFrameOffsetA() const; - Transform getFrameOffsetB() const; - Transform getFrameOffsetA(); - Transform getFrameOffsetB(); + Transform3D getFrameOffsetA() const; + Transform3D getFrameOffsetB() const; + Transform3D getFrameOffsetA(); + Transform3D getFrameOffsetB(); void set_linear_lower_limit(const Vector3 &linearLower); void set_linear_upper_limit(const Vector3 &linearUpper); diff --git a/modules/bullet/godot_result_callbacks.cpp b/modules/bullet/godot_result_callbacks.cpp index e92b6c189c..1f962772e7 100644 --- a/modules/bullet/godot_result_callbacks.cpp +++ b/modules/bullet/godot_result_callbacks.cpp @@ -47,17 +47,12 @@ bool godotContactAddedCallback(btManifoldPoint &cp, const btCollisionObjectWrapp return true; } -bool GodotFilterCallback::test_collision_filters(uint32_t body0_collision_layer, uint32_t body0_collision_mask, uint32_t body1_collision_layer, uint32_t body1_collision_mask) { - return body0_collision_layer & body1_collision_mask || body1_collision_layer & body0_collision_mask; -} - bool GodotFilterCallback::needBroadphaseCollision(btBroadphaseProxy *proxy0, btBroadphaseProxy *proxy1) const { - return GodotFilterCallback::test_collision_filters(proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask, proxy1->m_collisionFilterGroup, proxy1->m_collisionFilterMask); + return (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) || (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask); } bool GodotClosestRayResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); - if (needs) { + if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); @@ -90,8 +85,7 @@ bool GodotAllConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) con return false; } - const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); - if (needs) { + if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); if (m_exclude->has(gObj->get_self())) { @@ -123,8 +117,7 @@ btScalar GodotAllConvexResultCallback::addSingleResult(btCollisionWorld::LocalCo } bool GodotKinClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); - if (needs) { + if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); if (gObj == m_self_object) { @@ -142,6 +135,10 @@ bool GodotKinClosestConvexResultCallback::needsCollision(btBroadphaseProxy *prox if (m_self_object->has_collision_exception(gObj) || gObj->has_collision_exception(m_self_object)) { return false; } + + if (m_exclude->has(gObj->get_self())) { + return false; + } } return true; } else { @@ -150,8 +147,7 @@ bool GodotKinClosestConvexResultCallback::needsCollision(btBroadphaseProxy *prox } bool GodotClosestConvexResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); - if (needs) { + if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); @@ -188,8 +184,7 @@ bool GodotAllContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) co return false; } - const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); - if (needs) { + if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); @@ -244,8 +239,7 @@ bool GodotContactPairContactResultCallback::needsCollision(btBroadphaseProxy *pr return false; } - const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); - if (needs) { + if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); @@ -287,8 +281,7 @@ btScalar GodotContactPairContactResultCallback::addSingleResult(btManifoldPoint } bool GodotRestInfoContactResultCallback::needsCollision(btBroadphaseProxy *proxy0) const { - const bool needs = GodotFilterCallback::test_collision_filters(m_collisionFilterGroup, m_collisionFilterMask, proxy0->m_collisionFilterGroup, proxy0->m_collisionFilterMask); - if (needs) { + if (proxy0->m_collisionFilterGroup & m_collisionFilterMask) { btCollisionObject *btObj = static_cast<btCollisionObject *>(proxy0->m_clientObject); CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(btObj->getUserPointer()); diff --git a/modules/bullet/godot_result_callbacks.h b/modules/bullet/godot_result_callbacks.h index f92665f3e4..96a649d77a 100644 --- a/modules/bullet/godot_result_callbacks.h +++ b/modules/bullet/godot_result_callbacks.h @@ -47,8 +47,6 @@ bool godotContactAddedCallback(btManifoldPoint &cp, const btCollisionObjectWrapp /// This class is required to implement custom collision behaviour in the broadphase struct GodotFilterCallback : public btOverlapFilterCallback { - static bool test_collision_filters(uint32_t body0_collision_layer, uint32_t body0_collision_mask, uint32_t body1_collision_layer, uint32_t body1_collision_mask); - // return true when pairs need collision virtual bool needBroadphaseCollision(btBroadphaseProxy *proxy0, btBroadphaseProxy *proxy1) const; }; @@ -102,11 +100,13 @@ public: struct GodotKinClosestConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback { public: const RigidBodyBullet *m_self_object; + const Set<RID> *m_exclude; const bool m_infinite_inertia; - GodotKinClosestConvexResultCallback(const btVector3 &convexFromWorld, const btVector3 &convexToWorld, const RigidBodyBullet *p_self_object, bool p_infinite_inertia) : + GodotKinClosestConvexResultCallback(const btVector3 &convexFromWorld, const btVector3 &convexToWorld, const RigidBodyBullet *p_self_object, bool p_infinite_inertia, const Set<RID> *p_exclude) : btCollisionWorld::ClosestConvexResultCallback(convexFromWorld, convexToWorld), m_self_object(p_self_object), + m_exclude(p_exclude), m_infinite_inertia(p_infinite_inertia) {} virtual bool needsCollision(btBroadphaseProxy *proxy0) const; diff --git a/modules/bullet/hinge_joint_bullet.cpp b/modules/bullet/hinge_joint_bullet.cpp index 4ceb98729f..b5fe50cf5f 100644 --- a/modules/bullet/hinge_joint_bullet.cpp +++ b/modules/bullet/hinge_joint_bullet.cpp @@ -40,16 +40,16 @@ @author AndreaCatania */ -HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameA, const Transform &frameB) : +HingeJointBullet::HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameA, const Transform3D &frameB) : JointBullet() { - Transform scaled_AFrame(frameA.scaled(rbA->get_body_scale())); + Transform3D scaled_AFrame(frameA.scaled(rbA->get_body_scale())); scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); btTransform btFrameA; G_TO_B(scaled_AFrame, btFrameA); if (rbB) { - Transform scaled_BFrame(frameB.scaled(rbB->get_body_scale())); + Transform3D scaled_BFrame(frameB.scaled(rbB->get_body_scale())); scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); btTransform btFrameB; diff --git a/modules/bullet/hinge_joint_bullet.h b/modules/bullet/hinge_joint_bullet.h index 06a95be374..dd0f69ba68 100644 --- a/modules/bullet/hinge_joint_bullet.h +++ b/modules/bullet/hinge_joint_bullet.h @@ -41,7 +41,7 @@ class HingeJointBullet : public JointBullet { class btHingeConstraint *hingeConstraint; public: - HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameA, const Transform &frameB); + HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameA, const Transform3D &frameB); HingeJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, const Vector3 &axisInA, const Vector3 &axisInB); virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_HINGE; } diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp index 675da1a597..0d2cd1f5a0 100644 --- a/modules/bullet/rigid_body_bullet.cpp +++ b/modules/bullet/rigid_body_bullet.cpp @@ -106,14 +106,24 @@ Vector3 BulletPhysicsDirectBodyState3D::get_angular_velocity() const { return body->get_angular_velocity(); } -void BulletPhysicsDirectBodyState3D::set_transform(const Transform &p_transform) { +void BulletPhysicsDirectBodyState3D::set_transform(const Transform3D &p_transform) { body->set_transform(p_transform); } -Transform BulletPhysicsDirectBodyState3D::get_transform() const { +Transform3D BulletPhysicsDirectBodyState3D::get_transform() const { return body->get_transform(); } +Vector3 BulletPhysicsDirectBodyState3D::get_velocity_at_local_position(const Vector3 &p_position) const { + btVector3 local_position; + G_TO_B(p_position, local_position); + + Vector3 velocity; + B_TO_G(body->btBody->getVelocityInLocalPoint(local_position), velocity); + + return velocity; +} + void BulletPhysicsDirectBodyState3D::add_central_force(const Vector3 &p_force) { body->apply_central_force(p_force); } @@ -268,7 +278,7 @@ RigidBodyBullet::RigidBodyBullet() : reload_shapes(); setupBulletCollisionObject(btBody); - set_mode(PhysicsServer3D::BODY_MODE_RIGID); + set_mode(PhysicsServer3D::BODY_MODE_DYNAMIC); reload_axis_lock(); areasWhereIam.resize(maxAreasWhereIam); @@ -531,14 +541,14 @@ void RigidBodyBullet::set_mode(PhysicsServer3D::BodyMode p_mode) { reload_axis_lock(); _internal_set_mass(0); break; - case PhysicsServer3D::BODY_MODE_RIGID: - mode = PhysicsServer3D::BODY_MODE_RIGID; + case PhysicsServer3D::BODY_MODE_DYNAMIC: + mode = PhysicsServer3D::BODY_MODE_DYNAMIC; reload_axis_lock(); _internal_set_mass(0 == mass ? 1 : mass); scratch_space_override_modificator(); break; - case PhysicsServer3D::BODY_MODE_CHARACTER: - mode = PhysicsServer3D::BODY_MODE_CHARACTER; + case PhysicsServer3D::MODE_DYNAMIC_LOCKED: + mode = PhysicsServer3D::MODE_DYNAMIC_LOCKED; reload_axis_lock(); _internal_set_mass(0 == mass ? 1 : mass); scratch_space_override_modificator(); @@ -711,7 +721,7 @@ bool RigidBodyBullet::is_axis_locked(PhysicsServer3D::BodyAxis p_axis) const { void RigidBodyBullet::reload_axis_lock() { btBody->setLinearFactor(btVector3(btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_X)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Y)), btScalar(!is_axis_locked(PhysicsServer3D::BODY_AXIS_LINEAR_Z)))); - if (PhysicsServer3D::BODY_MODE_CHARACTER == mode) { + if (PhysicsServer3D::MODE_DYNAMIC_LOCKED == mode) { /// When character angular is always locked btBody->setAngularFactor(btVector3(0., 0., 0.)); } else { @@ -1006,7 +1016,7 @@ void RigidBodyBullet::_internal_set_mass(real_t p_mass) { // Rigidbody is dynamic if and only if mass is non Zero, otherwise static const bool isDynamic = p_mass != 0.f; if (isDynamic) { - if (PhysicsServer3D::BODY_MODE_RIGID != mode && PhysicsServer3D::BODY_MODE_CHARACTER != mode) { + if (PhysicsServer3D::BODY_MODE_DYNAMIC != mode && PhysicsServer3D::MODE_DYNAMIC_LOCKED != mode) { return; } @@ -1015,7 +1025,7 @@ void RigidBodyBullet::_internal_set_mass(real_t p_mass) { mainShape->calculateLocalInertia(p_mass, localInertia); } - if (PhysicsServer3D::BODY_MODE_RIGID == mode) { + if (PhysicsServer3D::BODY_MODE_DYNAMIC == mode) { btBody->setCollisionFlags(clearedCurrentFlags); // Just set the flags without Kin and Static } else { btBody->setCollisionFlags(clearedCurrentFlags | btCollisionObject::CF_CHARACTER_OBJECT); diff --git a/modules/bullet/rigid_body_bullet.h b/modules/bullet/rigid_body_bullet.h index 843ff4a7af..5e102d8b05 100644 --- a/modules/bullet/rigid_body_bullet.h +++ b/modules/bullet/rigid_body_bullet.h @@ -107,8 +107,10 @@ public: virtual void set_angular_velocity(const Vector3 &p_velocity) override; virtual Vector3 get_angular_velocity() const override; - virtual void set_transform(const Transform &p_transform) override; - virtual Transform get_transform() const override; + virtual void set_transform(const Transform3D &p_transform) override; + virtual Transform3D get_transform() const override; + + virtual Vector3 get_velocity_at_local_position(const Vector3 &p_position) const override; virtual void add_central_force(const Vector3 &p_force) override; virtual void add_force(const Vector3 &p_force, const Vector3 &p_position = Vector3()) override; diff --git a/modules/bullet/slider_joint_bullet.cpp b/modules/bullet/slider_joint_bullet.cpp index 45c892851b..1d83118468 100644 --- a/modules/bullet/slider_joint_bullet.cpp +++ b/modules/bullet/slider_joint_bullet.cpp @@ -40,16 +40,16 @@ @author AndreaCatania */ -SliderJointBullet::SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB) : +SliderJointBullet::SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB) : JointBullet() { - Transform scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); + Transform3D scaled_AFrame(frameInA.scaled(rbA->get_body_scale())); scaled_AFrame.basis.rotref_posscale_decomposition(scaled_AFrame.basis); btTransform btFrameA; G_TO_B(scaled_AFrame, btFrameA); if (rbB) { - Transform scaled_BFrame(frameInB.scaled(rbB->get_body_scale())); + Transform3D scaled_BFrame(frameInB.scaled(rbB->get_body_scale())); scaled_BFrame.basis.rotref_posscale_decomposition(scaled_BFrame.basis); btTransform btFrameB; @@ -70,44 +70,44 @@ const RigidBodyBullet *SliderJointBullet::getRigidBodyB() const { return static_cast<RigidBodyBullet *>(sliderConstraint->getRigidBodyB().getUserPointer()); } -const Transform SliderJointBullet::getCalculatedTransformA() const { +const Transform3D SliderJointBullet::getCalculatedTransformA() const { btTransform btTransform = sliderConstraint->getCalculatedTransformA(); - Transform gTrans; + Transform3D gTrans; B_TO_G(btTransform, gTrans); return gTrans; } -const Transform SliderJointBullet::getCalculatedTransformB() const { +const Transform3D SliderJointBullet::getCalculatedTransformB() const { btTransform btTransform = sliderConstraint->getCalculatedTransformB(); - Transform gTrans; + Transform3D gTrans; B_TO_G(btTransform, gTrans); return gTrans; } -const Transform SliderJointBullet::getFrameOffsetA() const { +const Transform3D SliderJointBullet::getFrameOffsetA() const { btTransform btTransform = sliderConstraint->getFrameOffsetA(); - Transform gTrans; + Transform3D gTrans; B_TO_G(btTransform, gTrans); return gTrans; } -const Transform SliderJointBullet::getFrameOffsetB() const { +const Transform3D SliderJointBullet::getFrameOffsetB() const { btTransform btTransform = sliderConstraint->getFrameOffsetB(); - Transform gTrans; + Transform3D gTrans; B_TO_G(btTransform, gTrans); return gTrans; } -Transform SliderJointBullet::getFrameOffsetA() { +Transform3D SliderJointBullet::getFrameOffsetA() { btTransform btTransform = sliderConstraint->getFrameOffsetA(); - Transform gTrans; + Transform3D gTrans; B_TO_G(btTransform, gTrans); return gTrans; } -Transform SliderJointBullet::getFrameOffsetB() { +Transform3D SliderJointBullet::getFrameOffsetB() { btTransform btTransform = sliderConstraint->getFrameOffsetB(); - Transform gTrans; + Transform3D gTrans; B_TO_G(btTransform, gTrans); return gTrans; } diff --git a/modules/bullet/slider_joint_bullet.h b/modules/bullet/slider_joint_bullet.h index 90964671c2..0c93558449 100644 --- a/modules/bullet/slider_joint_bullet.h +++ b/modules/bullet/slider_joint_bullet.h @@ -44,18 +44,18 @@ class SliderJointBullet : public JointBullet { public: /// Reference frame is A - SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform &frameInA, const Transform &frameInB); + SliderJointBullet(RigidBodyBullet *rbA, RigidBodyBullet *rbB, const Transform3D &frameInA, const Transform3D &frameInB); virtual PhysicsServer3D::JointType get_type() const { return PhysicsServer3D::JOINT_SLIDER; } const RigidBodyBullet *getRigidBodyA() const; const RigidBodyBullet *getRigidBodyB() const; - const Transform getCalculatedTransformA() const; - const Transform getCalculatedTransformB() const; - const Transform getFrameOffsetA() const; - const Transform getFrameOffsetB() const; - Transform getFrameOffsetA(); - Transform getFrameOffsetB(); + const Transform3D getCalculatedTransformA() const; + const Transform3D getCalculatedTransformB() const; + const Transform3D getFrameOffsetA() const; + const Transform3D getFrameOffsetB() const; + Transform3D getFrameOffsetA(); + Transform3D getFrameOffsetB(); real_t getLowerLinLimit() const; void setLowerLinLimit(real_t lowerLimit); real_t getUpperLinLimit() const; diff --git a/modules/bullet/soft_body_bullet.cpp b/modules/bullet/soft_body_bullet.cpp index 2c8727baf2..bbbb0e7851 100644 --- a/modules/bullet/soft_body_bullet.cpp +++ b/modules/bullet/soft_body_bullet.cpp @@ -136,7 +136,7 @@ void SoftBodyBullet::destroy_soft_body() { bt_soft_body = nullptr; } -void SoftBodyBullet::set_soft_transform(const Transform &p_transform) { +void SoftBodyBullet::set_soft_transform(const Transform3D &p_transform) { reset_all_node_positions(); move_all_nodes(p_transform); } @@ -159,7 +159,7 @@ AABB SoftBodyBullet::get_bounds() const { return aabb; } -void SoftBodyBullet::move_all_nodes(const Transform &p_transform) { +void SoftBodyBullet::move_all_nodes(const Transform3D &p_transform) { if (!bt_soft_body) { return; } diff --git a/modules/bullet/soft_body_bullet.h b/modules/bullet/soft_body_bullet.h index 87023b2517..63708b57a7 100644 --- a/modules/bullet/soft_body_bullet.h +++ b/modules/bullet/soft_body_bullet.h @@ -104,11 +104,11 @@ public: void destroy_soft_body(); // Special function. This function has bad performance - void set_soft_transform(const Transform &p_transform); + void set_soft_transform(const Transform3D &p_transform); AABB get_bounds() const; - void move_all_nodes(const Transform &p_transform); + void move_all_nodes(const Transform3D &p_transform); void set_node_position(int node_index, const Vector3 &p_global_position); void set_node_position(int node_index, const btVector3 &p_global_position); void get_node_position(int node_index, Vector3 &r_position) const; diff --git a/modules/bullet/space_bullet.cpp b/modules/bullet/space_bullet.cpp index bdaec4a09e..c6d835742d 100644 --- a/modules/bullet/space_bullet.cpp +++ b/modules/bullet/space_bullet.cpp @@ -117,7 +117,7 @@ bool BulletPhysicsDirectSpaceState::intersect_ray(const Vector3 &p_from, const V } } -int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { +int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Transform3D &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { if (p_result_max <= 0) { return 0; } @@ -152,7 +152,7 @@ int BulletPhysicsDirectSpaceState::intersect_shape(const RID &p_shape, const Tra return btQuery.m_count; } -bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &r_closest_safe, real_t &r_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, ShapeRestInfo *r_info) { +bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transform3D &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &r_closest_safe, real_t &r_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas, ShapeRestInfo *r_info) { r_closest_safe = 0.0f; r_closest_unsafe = 0.0f; btVector3 bt_motion; @@ -214,7 +214,7 @@ bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transf } /// Returns the list of contacts pairs in this order: Local contact, other body contact -bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { +bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { if (p_result_max <= 0) { return false; } @@ -250,7 +250,7 @@ bool BulletPhysicsDirectSpaceState::collide_shape(RID p_shape, const Transform & return btQuery.m_count; } -bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { +bool BulletPhysicsDirectSpaceState::rest_info(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_collision_mask, bool p_collide_with_bodies, bool p_collide_with_areas) { ShapeBullet *shape = space->get_physics_server()->get_shape_owner()->getornull(p_shape); ERR_FAIL_COND_V(!shape, false); @@ -445,7 +445,7 @@ real_t SpaceBullet::get_param(PhysicsServer3D::SpaceParameter p_param) { case PhysicsServer3D::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: case PhysicsServer3D::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: default: - WARN_PRINT("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned."); + WARN_PRINT("The SpaceBullet doesn't support this get parameter (" + itos(p_param) + "), 0 is returned."); return 0.f; } } @@ -908,7 +908,7 @@ static Ref<StandardMaterial3D> red_mat; static Ref<StandardMaterial3D> blue_mat; #endif -bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes) { +bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes, const Set<RID> &p_exclude) { #if debug_test_motion /// Yes I know this is not good, but I've used it as fast debugging hack. /// I'm leaving it here just for speedup the other eventual debugs @@ -948,7 +948,7 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f btVector3 initial_recover_motion(0, 0, 0); { /// Phase one - multi shapes depenetration using margin for (int t(RECOVERING_MOVEMENT_CYCLES); 0 < t; --t) { - if (!recover_from_penetration(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, initial_recover_motion)) { + if (!recover_from_penetration(p_body, body_transform, RECOVERING_MOVEMENT_SCALE, p_infinite_inertia, initial_recover_motion, nullptr, p_exclude)) { break; } } @@ -1000,7 +1000,7 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f break; } - GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia); + GodotKinClosestConvexResultCallback btResult(shape_world_from.getOrigin(), shape_world_to.getOrigin(), p_body, p_infinite_inertia, &p_exclude); btResult.m_collisionFilterGroup = p_body->get_collision_layer(); btResult.m_collisionFilterMask = p_body->get_collision_mask(); @@ -1023,7 +1023,7 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f btVector3 __rec(0, 0, 0); RecoverResult r_recover_result; - has_penetration = recover_from_penetration(p_body, body_transform, 1, p_infinite_inertia, __rec, &r_recover_result); + has_penetration = recover_from_penetration(p_body, body_transform, 1, p_infinite_inertia, __rec, &r_recover_result, p_exclude); // Parse results if (r_result) { @@ -1062,7 +1062,7 @@ bool SpaceBullet::test_body_motion(RigidBodyBullet *p_body, const Transform &p_f return has_penetration; } -int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, real_t p_margin) { +int SpaceBullet::test_ray_separation(RigidBodyBullet *p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, real_t p_margin) { btTransform body_transform; G_TO_B(p_transform, body_transform); UNSCALE_BT_BASIS(body_transform); @@ -1093,7 +1093,6 @@ private: const btCollisionObject *self_collision_object; uint32_t collision_layer = 0; - uint32_t collision_mask = 0; struct CompoundLeafCallback : btDbvt::ICollide { private: @@ -1123,10 +1122,9 @@ public: Vector<BroadphaseResult> results; public: - RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, uint32_t p_collision_mask, btVector3 p_aabb_min, btVector3 p_aabb_max) : + RecoverPenetrationBroadPhaseCallback(const btCollisionObject *p_self_collision_object, uint32_t p_collision_layer, btVector3 p_aabb_min, btVector3 p_aabb_max) : self_collision_object(p_self_collision_object), - collision_layer(p_collision_layer), - collision_mask(p_collision_mask) { + collision_layer(p_collision_layer) { bounds = btDbvtVolume::FromMM(p_aabb_min, p_aabb_max); } @@ -1135,7 +1133,7 @@ public: virtual bool process(const btBroadphaseProxy *proxy) { btCollisionObject *co = static_cast<btCollisionObject *>(proxy->m_clientObject); if (co->getInternalType() <= btCollisionObject::CO_RIGID_BODY) { - if (self_collision_object != proxy->m_clientObject && GodotFilterCallback::test_collision_filters(collision_layer, collision_mask, proxy->m_collisionFilterGroup, proxy->m_collisionFilterMask)) { + if (self_collision_object != proxy->m_clientObject && (proxy->collision_layer & m_collisionFilterMask)) { if (co->getCollisionShape()->isCompound()) { const btCompoundShape *cs = static_cast<btCompoundShape *>(co->getCollisionShape()); @@ -1175,7 +1173,7 @@ public: } }; -bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result) { +bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result, const Set<RID> &p_exclude) { // Calculate the cumulative AABB of all shapes of the kinematic body btVector3 aabb_min, aabb_max; bool shapes_found = false; @@ -1218,7 +1216,7 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran } // Perform broadphase test - RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max); + RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), aabb_min, aabb_max); dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result); bool penetration = false; @@ -1244,6 +1242,12 @@ bool SpaceBullet::recover_from_penetration(RigidBodyBullet *p_body, const btTran for (int i = recover_broad_result.results.size() - 1; 0 <= i; --i) { btCollisionObject *otherObject = recover_broad_result.results[i].collision_object; + + CollisionObjectBullet *gObj = static_cast<CollisionObjectBullet *>(otherObject->getUserPointer()); + if (p_exclude.has(gObj->get_self())) { + continue; + } + if (p_infinite_inertia && !otherObject->isStaticOrKinematicObject()) { otherObject->activate(); // Force activation of hitten rigid, soft body continue; @@ -1409,7 +1413,7 @@ int SpaceBullet::recover_from_penetration_ray(RigidBodyBullet *p_body, const btT } // Perform broadphase test - RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), p_body->get_collision_mask(), aabb_min, aabb_max); + RecoverPenetrationBroadPhaseCallback recover_broad_result(p_body->get_bt_collision_object(), p_body->get_collision_layer(), aabb_min, aabb_max); dynamicsWorld->getBroadphase()->aabbTest(aabb_min, aabb_max, recover_broad_result); int ray_count = 0; diff --git a/modules/bullet/space_bullet.h b/modules/bullet/space_bullet.h index 87aa2b9e93..2070e0e633 100644 --- a/modules/bullet/space_bullet.h +++ b/modules/bullet/space_bullet.h @@ -78,11 +78,11 @@ public: virtual int intersect_point(const Vector3 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; virtual bool intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, bool p_pick_ray = false) override; - virtual int intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; - virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &r_closest_safe, real_t &r_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, ShapeRestInfo *r_info = nullptr) override; + virtual int intersect_shape(const RID &p_shape, const Transform3D &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; + virtual bool cast_motion(const RID &p_shape, const Transform3D &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &r_closest_safe, real_t &r_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false, ShapeRestInfo *r_info = nullptr) override; /// Returns the list of contacts pairs in this order: Local contact, other body contact - virtual bool collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; - virtual bool rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; + virtual bool collide_shape(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; + virtual bool rest_info(RID p_shape, const Transform3D &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_collision_mask = 0xFFFFFFFF, bool p_collide_with_bodies = true, bool p_collide_with_areas = false) override; virtual Vector3 get_closest_point_to_object_volume(RID p_object, const Vector3 p_point) const override; }; @@ -188,8 +188,8 @@ public: real_t get_linear_damp() const { return linear_damp; } real_t get_angular_damp() const { return angular_damp; } - bool test_body_motion(RigidBodyBullet *p_body, const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes); - int test_ray_separation(RigidBodyBullet *p_body, const Transform &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, real_t p_margin); + bool test_body_motion(RigidBodyBullet *p_body, const Transform3D &p_from, const Vector3 &p_motion, bool p_infinite_inertia, PhysicsServer3D::MotionResult *r_result, bool p_exclude_raycast_shapes, const Set<RID> &p_exclude = Set<RID>()); + int test_ray_separation(RigidBodyBullet *p_body, const Transform3D &p_transform, bool p_infinite_inertia, Vector3 &r_recover_motion, PhysicsServer3D::SeparationResult *r_results, int p_result_max, real_t p_margin); private: void create_empty_world(bool p_create_soft_world); @@ -209,7 +209,7 @@ private: RecoverResult() {} }; - bool recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = nullptr); + bool recover_from_penetration(RigidBodyBullet *p_body, const btTransform &p_body_position, btScalar p_recover_movement_scale, bool p_infinite_inertia, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = nullptr, const Set<RID> &p_exclude = Set<RID>()); /// This is an API that recover a kinematic object from penetration /// This allow only Convex Convex test and it always use GJK algorithm, With this API we don't benefit of Bullet special accelerated functions bool RFP_convex_convex_test(const btConvexShape *p_shapeA, const btConvexShape *p_shapeB, btCollisionObject *p_objectB, int p_shapeId_A, int p_shapeId_B, const btTransform &p_transformA, const btTransform &p_transformB, btScalar p_recover_movement_scale, btVector3 &r_delta_recover_movement, RecoverResult *r_recover_result = nullptr); diff --git a/modules/camera/camera_osx.h b/modules/camera/camera_osx.h index 964b7c1edc..84274f0bf6 100644 --- a/modules/camera/camera_osx.h +++ b/modules/camera/camera_osx.h @@ -32,7 +32,7 @@ #define CAMERAOSX_H ///@TODO this is a near duplicate of CameraIOS, we should find a way to combine those to minimize code duplication!!!! -// If you fix something here, make sure you fix it there as wel! +// If you fix something here, make sure you fix it there as well! #include "servers/camera_server.h" diff --git a/modules/camera/camera_osx.mm b/modules/camera/camera_osx.mm index 3d2053ad23..4875eb578a 100644 --- a/modules/camera/camera_osx.mm +++ b/modules/camera/camera_osx.mm @@ -29,7 +29,7 @@ /*************************************************************************/ ///@TODO this is a near duplicate of CameraIOS, we should find a way to combine those to minimize code duplication!!!! -// If you fix something here, make sure you fix it there as wel! +// If you fix something here, make sure you fix it there as well! #include "camera_osx.h" #include "servers/camera/camera_feed.h" @@ -106,15 +106,15 @@ if (input) { [self removeInput:input]; // don't release this - input = NULL; + input = nullptr; } // free up our output if (output) { [self removeOutput:output]; - [output setSampleBufferDelegate:nil queue:NULL]; + [output setSampleBufferDelegate:nil queue:nullptr]; [output release]; - output = NULL; + output = nullptr; } [self commitConfiguration]; @@ -141,9 +141,9 @@ // get our buffers unsigned char *dataY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0); unsigned char *dataCbCr = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1); - if (dataY == NULL) { + if (dataY == nullptr) { print_line("Couldn't access Y pixel buffer data"); - } else if (dataCbCr == NULL) { + } else if (dataCbCr == nullptr) { print_line("Couldn't access CbCr pixel buffer data"); } else { Ref<Image> img[2]; @@ -162,7 +162,7 @@ uint8_t *w = img_data[0].ptrw(); memcpy(w, dataY, new_width * new_height); - img[0].instance(); + img[0].instantiate(); img[0]->create(new_width, new_height, 0, Image::FORMAT_R8, img_data[0]); } @@ -181,7 +181,7 @@ memcpy(w, dataCbCr, 2 * new_width * new_height); ///TODO GLES2 doesn't support FORMAT_RG8, need to do some form of conversion - img[1].instance(); + img[1].instantiate(); img[1]->create(new_width, new_height, 0, Image::FORMAT_RG8, img_data[1]); } @@ -220,8 +220,8 @@ AVCaptureDevice *CameraFeedOSX::get_device() const { }; CameraFeedOSX::CameraFeedOSX() { - device = NULL; - capture_session = NULL; + device = nullptr; + capture_session = nullptr; }; void CameraFeedOSX::set_device(AVCaptureDevice *p_device) { @@ -240,14 +240,14 @@ void CameraFeedOSX::set_device(AVCaptureDevice *p_device) { }; CameraFeedOSX::~CameraFeedOSX() { - if (capture_session != NULL) { + if (capture_session != nullptr) { [capture_session release]; - capture_session = NULL; + capture_session = nullptr; }; - if (device != NULL) { + if (device != nullptr) { [device release]; - device = NULL; + device = nullptr; }; }; @@ -267,7 +267,7 @@ void CameraFeedOSX::deactivate_feed() { if (capture_session) { [capture_session cleanup]; [capture_session release]; - capture_session = NULL; + capture_session = nullptr; }; }; @@ -341,7 +341,7 @@ void CameraOSX::update_feeds() { if (!found) { Ref<CameraFeedOSX> newfeed; - newfeed.instance(); + newfeed.instantiate(); newfeed->set_device(device); // assume display camera so inverse diff --git a/modules/csg/config.py b/modules/csg/config.py index 9106cbceca..3991b846f9 100644 --- a/modules/csg/config.py +++ b/modules/csg/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return True + return not env["disable_3d"] def configure(env): diff --git a/modules/csg/csg.cpp b/modules/csg/csg.cpp index 7387842259..cb82b65307 100644 --- a/modules/csg/csg.cpp +++ b/modules/csg/csg.cpp @@ -42,7 +42,7 @@ inline static bool is_snapable(const Vector3 &p_point1, const Vector3 &p_point2, inline static Vector2 interpolate_segment_uv(const Vector2 p_segement_points[2], const Vector2 p_uvs[2], const Vector2 &p_interpolation_point) { float segment_length = (p_segement_points[1] - p_segement_points[0]).length(); - if (segment_length < CMP_EPSILON) { + if (p_segement_points[0].is_equal_approx(p_segement_points[1])) { return p_uvs[0]; } @@ -53,13 +53,13 @@ inline static Vector2 interpolate_segment_uv(const Vector2 p_segement_points[2], } inline static Vector2 interpolate_triangle_uv(const Vector2 p_vertices[3], const Vector2 p_uvs[3], const Vector2 &p_interpolation_point) { - if (p_interpolation_point.distance_squared_to(p_vertices[0]) < CMP_EPSILON2) { + if (p_interpolation_point.is_equal_approx(p_vertices[0])) { return p_uvs[0]; } - if (p_interpolation_point.distance_squared_to(p_vertices[1]) < CMP_EPSILON2) { + if (p_interpolation_point.is_equal_approx(p_vertices[1])) { return p_uvs[1]; } - if (p_interpolation_point.distance_squared_to(p_vertices[2]) < CMP_EPSILON2) { + if (p_interpolation_point.is_equal_approx(p_vertices[2])) { return p_uvs[2]; } @@ -265,7 +265,7 @@ void CSGBrush::build_from_faces(const Vector<Vector3> &p_vertices, const Vector< _regen_face_aabbs(); } -void CSGBrush::copy_from(const CSGBrush &p_brush, const Transform &p_xform) { +void CSGBrush::copy_from(const CSGBrush &p_brush, const Transform3D &p_xform) { faces = p_brush.faces; materials = p_brush.materials; @@ -530,8 +530,8 @@ void CSGBrushOperation::MeshMerge::_add_distance(List<real_t> &r_intersectionsA, List<real_t> &intersections = p_from_B ? r_intersectionsB : r_intersectionsA; // Check if distance exists. - for (const List<real_t>::Element *E = intersections.front(); E; E = E->next()) { - if (Math::is_equal_approx(**E, p_distance)) { + for (const real_t E : intersections) { + if (Math::is_equal_approx(E, p_distance)) { return; } } @@ -589,7 +589,7 @@ bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_de Vector3 intersection_point; // Check if faces are co-planar. - if ((current_normal - face_normal).length_squared() < CMP_EPSILON2 && + if (current_normal.is_equal_approx(face_normal) && is_point_in_triangle(face_center, current_points)) { // Only add an intersection if not a B face. if (!face.from_b) { diff --git a/modules/csg/csg.h b/modules/csg/csg.h index 3fbed66e5c..c872860486 100644 --- a/modules/csg/csg.h +++ b/modules/csg/csg.h @@ -33,10 +33,10 @@ #include "core/math/aabb.h" #include "core/math/plane.h" -#include "core/math/transform.h" +#include "core/math/transform_3d.h" #include "core/math/vector2.h" #include "core/math/vector3.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/templates/list.h" #include "core/templates/map.h" #include "core/templates/oa_hash_map.h" @@ -60,7 +60,7 @@ struct CSGBrush { // Create a brush from faces. void build_from_faces(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uvs, const Vector<bool> &p_smooth, const Vector<Ref<Material>> &p_materials, const Vector<bool> &p_invert_faces); - void copy_from(const CSGBrush &p_brush, const Transform &p_xform); + void copy_from(const CSGBrush &p_brush, const Transform3D &p_xform); }; struct CSGBrushOperation { @@ -165,8 +165,8 @@ struct CSGBrushOperation { Vector<Vertex2D> vertices; Vector<Face2D> faces; Plane plane; - Transform to_2D; - Transform to_3D; + Transform3D to_2D; + Transform3D to_3D; float vertex_snap2 = 0.0; inline int _get_point_idx(const Vector2 &p_point); diff --git a/modules/csg/csg_gizmos.cpp b/modules/csg/csg_gizmos.cpp index 8a46dcca65..2f8b354bb7 100644 --- a/modules/csg/csg_gizmos.cpp +++ b/modules/csg/csg_gizmos.cpp @@ -29,6 +29,8 @@ /*************************************************************************/ #include "csg_gizmos.h" +#include "editor/plugins/node_3d_editor_plugin.h" +#include "scene/3d/camera_3d.h" /////////// @@ -48,7 +50,7 @@ CSGShape3DGizmoPlugin::CSGShape3DGizmoPlugin() { create_handle_material("handles"); } -String CSGShape3DGizmoPlugin::get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_idx) const { +String CSGShape3DGizmoPlugin::get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_id) const { CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); if (Object::cast_to<CSGSphere3D>(cs)) { @@ -60,17 +62,17 @@ String CSGShape3DGizmoPlugin::get_handle_name(const EditorNode3DGizmo *p_gizmo, } if (Object::cast_to<CSGCylinder3D>(cs)) { - return p_idx == 0 ? "Radius" : "Height"; + return p_id == 0 ? "Radius" : "Height"; } if (Object::cast_to<CSGTorus3D>(cs)) { - return p_idx == 0 ? "InnerRadius" : "OuterRadius"; + return p_id == 0 ? "InnerRadius" : "OuterRadius"; } return ""; } -Variant CSGShape3DGizmoPlugin::get_handle_value(EditorNode3DGizmo *p_gizmo, int p_idx) const { +Variant CSGShape3DGizmoPlugin::get_handle_value(const EditorNode3DGizmo *p_gizmo, int p_id) const { CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); if (Object::cast_to<CSGSphere3D>(cs)) { @@ -85,23 +87,23 @@ Variant CSGShape3DGizmoPlugin::get_handle_value(EditorNode3DGizmo *p_gizmo, int if (Object::cast_to<CSGCylinder3D>(cs)) { CSGCylinder3D *s = Object::cast_to<CSGCylinder3D>(cs); - return p_idx == 0 ? s->get_radius() : s->get_height(); + return p_id == 0 ? s->get_radius() : s->get_height(); } if (Object::cast_to<CSGTorus3D>(cs)) { CSGTorus3D *s = Object::cast_to<CSGTorus3D>(cs); - return p_idx == 0 ? s->get_inner_radius() : s->get_outer_radius(); + return p_id == 0 ? s->get_inner_radius() : s->get_outer_radius(); } return Variant(); } -void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Camera3D *p_camera, const Point2 &p_point) { +void CSGShape3DGizmoPlugin::set_handle(const EditorNode3DGizmo *p_gizmo, int p_id, Camera3D *p_camera, const Point2 &p_point) { CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); - Transform gt = cs->get_global_transform(); + Transform3D gt = cs->get_global_transform(); //gt.orthonormalize(); - Transform gi = gt.affine_inverse(); + Transform3D gi = gt.affine_inverse(); Vector3 ray_from = p_camera->project_ray_origin(p_point); Vector3 ray_dir = p_camera->project_ray_normal(p_point); @@ -129,10 +131,16 @@ void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Ca CSGBox3D *s = Object::cast_to<CSGBox3D>(cs); Vector3 axis; - axis[p_idx] = 1.0; + axis[p_id] = 1.0; Vector3 ra, rb; Geometry3D::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb); - float d = ra[p_idx]; + float d = ra[p_id]; + + if (Math::is_nan(d)) { + // The handle is perpendicular to the camera. + return; + } + if (Node3DEditor::get_singleton()->is_snap_enabled()) { d = Math::snapped(d, Node3DEditor::get_singleton()->get_translate_snap()); } @@ -142,7 +150,7 @@ void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Ca } Vector3 h = s->get_size(); - h[p_idx] = d * 2; + h[p_id] = d * 2; s->set_size(h); } @@ -150,7 +158,7 @@ void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Ca CSGCylinder3D *s = Object::cast_to<CSGCylinder3D>(cs); Vector3 axis; - axis[p_idx == 0 ? 0 : 1] = 1.0; + axis[p_id == 0 ? 0 : 1] = 1.0; Vector3 ra, rb; Geometry3D::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb); float d = axis.dot(ra); @@ -162,9 +170,9 @@ void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Ca d = 0.001; } - if (p_idx == 0) { + if (p_id == 0) { s->set_radius(d); - } else if (p_idx == 1) { + } else if (p_id == 1) { s->set_height(d * 2.0); } } @@ -185,15 +193,15 @@ void CSGShape3DGizmoPlugin::set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Ca d = 0.001; } - if (p_idx == 0) { + if (p_id == 0) { s->set_inner_radius(d); - } else if (p_idx == 1) { + } else if (p_id == 1) { s->set_outer_radius(d); } } } -void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) { +void CSGShape3DGizmoPlugin::commit_handle(const EditorNode3DGizmo *p_gizmo, int p_id, const Variant &p_restore, bool p_cancel) { CSGShape3D *cs = Object::cast_to<CSGShape3D>(p_gizmo->get_spatial_node()); if (Object::cast_to<CSGSphere3D>(cs)) { @@ -227,7 +235,7 @@ void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, if (Object::cast_to<CSGCylinder3D>(cs)) { CSGCylinder3D *s = Object::cast_to<CSGCylinder3D>(cs); if (p_cancel) { - if (p_idx == 0) { + if (p_id == 0) { s->set_radius(p_restore); } else { s->set_height(p_restore); @@ -236,7 +244,7 @@ void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, } UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo(); - if (p_idx == 0) { + if (p_id == 0) { ur->create_action(TTR("Change Cylinder Radius")); ur->add_do_method(s, "set_radius", s->get_radius()); ur->add_undo_method(s, "set_radius", p_restore); @@ -252,7 +260,7 @@ void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, if (Object::cast_to<CSGTorus3D>(cs)) { CSGTorus3D *s = Object::cast_to<CSGTorus3D>(cs); if (p_cancel) { - if (p_idx == 0) { + if (p_id == 0) { s->set_inner_radius(p_restore); } else { s->set_outer_radius(p_restore); @@ -261,7 +269,7 @@ void CSGShape3DGizmoPlugin::commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, } UndoRedo *ur = Node3DEditor::get_singleton()->get_undo_redo(); - if (p_idx == 0) { + if (p_id == 0) { ur->create_action(TTR("Change Torus Inner Radius")); ur->add_do_method(s, "set_inner_radius", s->get_inner_radius()); ur->add_undo_method(s, "set_inner_radius", p_restore); @@ -356,7 +364,7 @@ void CSGShape3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) { break; } - p_gizmo->add_mesh(mesh, false, Ref<SkinReference>(), solid_material); + p_gizmo->add_mesh(mesh, solid_material); } if (Object::cast_to<CSGSphere3D>(cs)) { diff --git a/modules/csg/csg_gizmos.h b/modules/csg/csg_gizmos.h index 8f7da35de3..2a6ab91102 100644 --- a/modules/csg/csg_gizmos.h +++ b/modules/csg/csg_gizmos.h @@ -33,22 +33,22 @@ #include "csg_shape.h" #include "editor/editor_plugin.h" -#include "editor/node_3d_editor_gizmos.h" +#include "editor/plugins/node_3d_editor_gizmos.h" class CSGShape3DGizmoPlugin : public EditorNode3DGizmoPlugin { GDCLASS(CSGShape3DGizmoPlugin, EditorNode3DGizmoPlugin); public: - bool has_gizmo(Node3D *p_spatial) override; - String get_gizmo_name() const override; - int get_priority() const override; - bool is_selectable_when_hidden() const override; - void redraw(EditorNode3DGizmo *p_gizmo) override; - - String get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_idx) const override; - Variant get_handle_value(EditorNode3DGizmo *p_gizmo, int p_idx) const override; - void set_handle(EditorNode3DGizmo *p_gizmo, int p_idx, Camera3D *p_camera, const Point2 &p_point) override; - void commit_handle(EditorNode3DGizmo *p_gizmo, int p_idx, const Variant &p_restore, bool p_cancel) override; + virtual bool has_gizmo(Node3D *p_spatial) override; + virtual String get_gizmo_name() const override; + virtual int get_priority() const override; + virtual bool is_selectable_when_hidden() const override; + virtual void redraw(EditorNode3DGizmo *p_gizmo) override; + + virtual String get_handle_name(const EditorNode3DGizmo *p_gizmo, int p_id) const override; + virtual Variant get_handle_value(const EditorNode3DGizmo *p_gizmo, int p_id) const override; + virtual void set_handle(const EditorNode3DGizmo *p_gizmo, int p_id, Camera3D *p_camera, const Point2 &p_point) override; + virtual void commit_handle(const EditorNode3DGizmo *p_gizmo, int p_id, const Variant &p_restore, bool p_cancel) override; CSGShape3DGizmoPlugin(); }; diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp index 05927dafc0..b47fa35f1a 100644 --- a/modules/csg/csg_shape.cpp +++ b/modules/csg/csg_shape.cpp @@ -44,7 +44,7 @@ void CSGShape3D::set_use_collision(bool p_enable) { } if (use_collision) { - root_collision_shape.instance(); + root_collision_shape.instantiate(); root_collision_instance = PhysicsServer3D::get_singleton()->body_create(); PhysicsServer3D::get_singleton()->body_set_mode(root_collision_instance, PhysicsServer3D::BODY_MODE_STATIC); PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform()); @@ -89,6 +89,7 @@ uint32_t CSGShape3D::get_collision_mask() const { } void CSGShape3D::set_collision_mask_bit(int p_bit, bool p_value) { + ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision mask bit must be between 0 and 31 inclusive."); uint32_t mask = get_collision_mask(); if (p_value) { mask |= 1 << p_bit; @@ -99,20 +100,23 @@ void CSGShape3D::set_collision_mask_bit(int p_bit, bool p_value) { } bool CSGShape3D::get_collision_mask_bit(int p_bit) const { + ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision mask bit must be between 0 and 31 inclusive."); return get_collision_mask() & (1 << p_bit); } void CSGShape3D::set_collision_layer_bit(int p_bit, bool p_value) { - uint32_t mask = get_collision_layer(); + ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision layer bit must be between 0 and 31 inclusive."); + uint32_t layer = get_collision_layer(); if (p_value) { - mask |= 1 << p_bit; + layer |= 1 << p_bit; } else { - mask &= ~(1 << p_bit); + layer &= ~(1 << p_bit); } - set_collision_layer(mask); + set_collision_layer(layer); } bool CSGShape3D::get_collision_layer_bit(int p_bit) const { + ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision layer bit must be between 0 and 31 inclusive."); return get_collision_layer() & (1 << p_bit); } @@ -136,7 +140,7 @@ void CSGShape3D::_make_dirty() { if (parent) { parent->_make_dirty(); } else if (!dirty) { - call_deferred("_update_shape"); + call_deferred(SNAME("_update_shape")); } dirty = true; @@ -407,7 +411,7 @@ void CSGShape3D::_update_shape() { } } - root_mesh.instance(); + root_mesh.instantiate(); //create surfaces for (int i = 0; i < surfaces.size(); i++) { @@ -494,7 +498,7 @@ void CSGShape3D::_notification(int p_what) { } if (use_collision && is_root_shape()) { - root_collision_shape.instance(); + root_collision_shape.instantiate(); root_collision_instance = PhysicsServer3D::get_singleton()->body_create(); PhysicsServer3D::get_singleton()->body_set_mode(root_collision_instance, PhysicsServer3D::BODY_MODE_STATIC); PhysicsServer3D::get_singleton()->body_set_state(root_collision_instance, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform()); @@ -544,7 +548,7 @@ void CSGShape3D::_notification(int p_what) { void CSGShape3D::set_operation(Operation p_operation) { operation = p_operation; _make_dirty(); - update_gizmo(); + update_gizmos(); } CSGShape3D::Operation CSGShape3D::get_operation() const { @@ -574,7 +578,7 @@ Array CSGShape3D::get_meshes() const { if (root_mesh.is_valid()) { Array arr; arr.resize(2); - arr[0] = Transform(); + arr[0] = Transform3D(); arr[1] = root_mesh; return arr; } @@ -774,7 +778,7 @@ CSGBrush *CSGMesh3D::_build_brush() { } } - bool flat = normal[0].distance_to(normal[1]) < CMP_EPSILON && normal[0].distance_to(normal[2]) < CMP_EPSILON; + bool flat = normal[0].is_equal_approx(normal[1]) && normal[0].is_equal_approx(normal[2]); vw[as + j + 0] = vertex[0]; vw[as + j + 1] = vertex[1]; @@ -816,7 +820,7 @@ CSGBrush *CSGMesh3D::_build_brush() { } } - bool flat = normal[0].distance_to(normal[1]) < CMP_EPSILON && normal[0].distance_to(normal[2]) < CMP_EPSILON; + bool flat = normal[0].is_equal_approx(normal[1]) && normal[0].is_equal_approx(normal[2]); vw[as + j + 0] = vertex[0]; vw[as + j + 1] = vertex[1]; @@ -841,7 +845,7 @@ CSGBrush *CSGMesh3D::_build_brush() { void CSGMesh3D::_mesh_changed() { _make_dirty(); - update_gizmo(); + update_gizmos(); } void CSGMesh3D::set_material(const Ref<Material> &p_material) { @@ -864,7 +868,7 @@ void CSGMesh3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_material"), &CSGMesh3D::get_material); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "StandardMaterial3D,ShaderMaterial"), "set_material", "get_material"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial"), "set_material", "get_material"); } void CSGMesh3D::set_mesh(const Ref<Mesh> &p_mesh) { @@ -919,49 +923,51 @@ CSGBrush *CSGSphere3D::_build_brush() { Ref<Material> *materialsw = materials.ptrw(); bool *invertw = invert.ptrw(); + // We want to follow an order that's convenient for UVs. + // For latitude step we start at the top and move down like in an image. + const double latitude_step = -Math_PI / rings; + const double longitude_step = Math_TAU / radial_segments; int face = 0; - const double lat_step = Math_TAU / rings; - const double lon_step = Math_TAU / radial_segments; - - for (int i = 1; i <= rings; i++) { - double lat0 = lat_step * (i - 1) - Math_TAU / 4; - double z0 = Math::sin(lat0); - double zr0 = Math::cos(lat0); - double u0 = double(i - 1) / rings; - - double lat1 = lat_step * i - Math_TAU / 4; - double z1 = Math::sin(lat1); - double zr1 = Math::cos(lat1); - double u1 = double(i) / rings; - - for (int j = radial_segments; j >= 1; j--) { - double lng0 = lon_step * (j - 1); - double x0 = Math::cos(lng0); - double y0 = Math::sin(lng0); - double v0 = double(i - 1) / radial_segments; - - double lng1 = lon_step * j; - double x1 = Math::cos(lng1); - double y1 = Math::sin(lng1); - double v1 = double(i) / radial_segments; + for (int i = 0; i < rings; i++) { + double latitude0 = latitude_step * i + Math_TAU / 4; + double cos0 = Math::cos(latitude0); + double sin0 = Math::sin(latitude0); + double v0 = double(i) / rings; + + double latitude1 = latitude_step * (i + 1) + Math_TAU / 4; + double cos1 = Math::cos(latitude1); + double sin1 = Math::sin(latitude1); + double v1 = double(i + 1) / rings; + + for (int j = 0; j < radial_segments; j++) { + double longitude0 = longitude_step * j; + // We give sin to X and cos to Z on purpose. + // This allows UVs to be CCW on +X so it maps to images well. + double x0 = Math::sin(longitude0); + double z0 = Math::cos(longitude0); + double u0 = double(j) / radial_segments; + + double longitude1 = longitude_step * (j + 1); + double x1 = Math::sin(longitude1); + double z1 = Math::cos(longitude1); + double u1 = double(j + 1) / radial_segments; Vector3 v[4] = { - Vector3(x1 * zr0, z0, y1 * zr0) * radius, - Vector3(x1 * zr1, z1, y1 * zr1) * radius, - Vector3(x0 * zr1, z1, y0 * zr1) * radius, - Vector3(x0 * zr0, z0, y0 * zr0) * radius + Vector3(x0 * cos0, sin0, z0 * cos0) * radius, + Vector3(x1 * cos0, sin0, z1 * cos0) * radius, + Vector3(x1 * cos1, sin1, z1 * cos1) * radius, + Vector3(x0 * cos1, sin1, z0 * cos1) * radius, }; Vector2 u[4] = { - Vector2(v1, u0), - Vector2(v1, u1), - Vector2(v0, u1), - Vector2(v0, u0), - + Vector2(u0, v0), + Vector2(u1, v0), + Vector2(u1, v1), + Vector2(u0, v1), }; - if (i < rings) { - //face 1 + // Draw the first face, but skip this at the north pole (i == 0). + if (i > 0) { facesw[face * 3 + 0] = v[0]; facesw[face * 3 + 1] = v[1]; facesw[face * 3 + 2] = v[2]; @@ -977,8 +983,8 @@ CSGBrush *CSGSphere3D::_build_brush() { face++; } - if (i > 1) { - //face 2 + // Draw the second face, but skip this at the south pole (i == rings - 1). + if (i < rings - 1) { facesw[face * 3 + 0] = v[2]; facesw[face * 3 + 1] = v[3]; facesw[face * 3 + 2] = v[0]; @@ -1025,14 +1031,14 @@ void CSGSphere3D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "radial_segments", PROPERTY_HINT_RANGE, "1,100,1"), "set_radial_segments", "get_radial_segments"); ADD_PROPERTY(PropertyInfo(Variant::INT, "rings", PROPERTY_HINT_RANGE, "1,100,1"), "set_rings", "get_rings"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smooth_faces"), "set_smooth_faces", "get_smooth_faces"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "StandardMaterial3D,ShaderMaterial"), "set_material", "get_material"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial"), "set_material", "get_material"); } void CSGSphere3D::set_radius(const float p_radius) { ERR_FAIL_COND(p_radius <= 0); radius = p_radius; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGSphere3D::get_radius() const { @@ -1042,7 +1048,7 @@ float CSGSphere3D::get_radius() const { void CSGSphere3D::set_radial_segments(const int p_radial_segments) { radial_segments = p_radial_segments > 4 ? p_radial_segments : 4; _make_dirty(); - update_gizmo(); + update_gizmos(); } int CSGSphere3D::get_radial_segments() const { @@ -1052,7 +1058,7 @@ int CSGSphere3D::get_radial_segments() const { void CSGSphere3D::set_rings(const int p_rings) { rings = p_rings > 1 ? p_rings : 1; _make_dirty(); - update_gizmo(); + update_gizmos(); } int CSGSphere3D::get_rings() const { @@ -1195,13 +1201,13 @@ void CSGBox3D::_bind_methods() { ClassDB::bind_method(D_METHOD("get_material"), &CSGBox3D::get_material); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size"), "set_size", "get_size"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "StandardMaterial3D,ShaderMaterial"), "set_material", "get_material"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial"), "set_material", "get_material"); } void CSGBox3D::set_size(const Vector3 &p_size) { size = p_size; _make_dirty(); - update_gizmo(); + update_gizmos(); } Vector3 CSGBox3D::get_size() const { @@ -1211,7 +1217,7 @@ Vector3 CSGBox3D::get_size() const { void CSGBox3D::set_material(const Ref<Material> &p_material) { material = p_material; _make_dirty(); - update_gizmo(); + update_gizmos(); } Ref<Material> CSGBox3D::get_material() const { @@ -1371,18 +1377,18 @@ void CSGCylinder3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_smooth_faces", "smooth_faces"), &CSGCylinder3D::set_smooth_faces); ClassDB::bind_method(D_METHOD("get_smooth_faces"), &CSGCylinder3D::get_smooth_faces); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_radius", "get_radius"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "height", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_height", "get_height"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.001,1000.0,0.001,or_greater,exp"), "set_radius", "get_radius"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "height", PROPERTY_HINT_RANGE, "0.001,1000.0,0.001,or_greater,exp"), "set_height", "get_height"); ADD_PROPERTY(PropertyInfo(Variant::INT, "sides", PROPERTY_HINT_RANGE, "3,64,1"), "set_sides", "get_sides"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cone"), "set_cone", "is_cone"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smooth_faces"), "set_smooth_faces", "get_smooth_faces"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "StandardMaterial3D,ShaderMaterial"), "set_material", "get_material"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial"), "set_material", "get_material"); } void CSGCylinder3D::set_radius(const float p_radius) { radius = p_radius; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGCylinder3D::get_radius() const { @@ -1392,7 +1398,7 @@ float CSGCylinder3D::get_radius() const { void CSGCylinder3D::set_height(const float p_height) { height = p_height; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGCylinder3D::get_height() const { @@ -1403,7 +1409,7 @@ void CSGCylinder3D::set_sides(const int p_sides) { ERR_FAIL_COND(p_sides < 3); sides = p_sides; _make_dirty(); - update_gizmo(); + update_gizmos(); } int CSGCylinder3D::get_sides() const { @@ -1413,7 +1419,7 @@ int CSGCylinder3D::get_sides() const { void CSGCylinder3D::set_cone(const bool p_cone) { cone = p_cone; _make_dirty(); - update_gizmo(); + update_gizmos(); } bool CSGCylinder3D::is_cone() const { @@ -1590,18 +1596,18 @@ void CSGTorus3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_smooth_faces", "smooth_faces"), &CSGTorus3D::set_smooth_faces); ClassDB::bind_method(D_METHOD("get_smooth_faces"), &CSGTorus3D::get_smooth_faces); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "inner_radius", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_inner_radius", "get_inner_radius"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "outer_radius", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_outer_radius", "get_outer_radius"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "inner_radius", PROPERTY_HINT_RANGE, "0.001,1000.0,0.001,or_greater,exp"), "set_inner_radius", "get_inner_radius"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "outer_radius", PROPERTY_HINT_RANGE, "0.001,1000.0,0.001,or_greater,exp"), "set_outer_radius", "get_outer_radius"); ADD_PROPERTY(PropertyInfo(Variant::INT, "sides", PROPERTY_HINT_RANGE, "3,64,1"), "set_sides", "get_sides"); ADD_PROPERTY(PropertyInfo(Variant::INT, "ring_sides", PROPERTY_HINT_RANGE, "3,64,1"), "set_ring_sides", "get_ring_sides"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smooth_faces"), "set_smooth_faces", "get_smooth_faces"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "StandardMaterial3D,ShaderMaterial"), "set_material", "get_material"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial"), "set_material", "get_material"); } void CSGTorus3D::set_inner_radius(const float p_inner_radius) { inner_radius = p_inner_radius; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGTorus3D::get_inner_radius() const { @@ -1611,7 +1617,7 @@ float CSGTorus3D::get_inner_radius() const { void CSGTorus3D::set_outer_radius(const float p_outer_radius) { outer_radius = p_outer_radius; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGTorus3D::get_outer_radius() const { @@ -1622,7 +1628,7 @@ void CSGTorus3D::set_sides(const int p_sides) { ERR_FAIL_COND(p_sides < 3); sides = p_sides; _make_dirty(); - update_gizmo(); + update_gizmos(); } int CSGTorus3D::get_sides() const { @@ -1633,7 +1639,7 @@ void CSGTorus3D::set_ring_sides(const int p_ring_sides) { ERR_FAIL_COND(p_ring_sides < 3); ring_sides = p_ring_sides; _make_dirty(); - update_gizmo(); + update_gizmos(); } int CSGTorus3D::get_ring_sides() const { @@ -1976,13 +1982,13 @@ CSGBrush *CSGPolygon3D::_build_brush() { float u1 = 0.0; float u2 = path_continuous_u ? 0.0 : 1.0; - Transform path_to_this; + Transform3D path_to_this; if (!path_local) { // center on paths origin path_to_this = get_global_transform().affine_inverse() * path->get_global_transform(); } - Transform prev_xf; + Transform3D prev_xf; Vector3 lookat_dir; @@ -2004,7 +2010,7 @@ CSGBrush *CSGPolygon3D::_build_brush() { ofs = 0.0; } - Transform xf; + Transform3D xf; xf.origin = curve->interpolate_baked(ofs); Vector3 local_dir; @@ -2156,13 +2162,13 @@ void CSGPolygon3D::_notification(int p_what) { void CSGPolygon3D::_validate_property(PropertyInfo &property) const { if (property.name.begins_with("spin") && mode != MODE_SPIN) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } if (property.name.begins_with("path") && mode != MODE_PATH) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } if (property.name == "depth" && mode != MODE_DEPTH) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } CSGShape3D::_validate_property(property); @@ -2170,7 +2176,7 @@ void CSGPolygon3D::_validate_property(PropertyInfo &property) const { void CSGPolygon3D::_path_changed() { _make_dirty(); - update_gizmo(); + update_gizmos(); } void CSGPolygon3D::_path_exited() { @@ -2222,17 +2228,17 @@ void CSGPolygon3D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon"); ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Depth,Spin,Path"), "set_mode", "get_mode"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_depth", "get_depth"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "depth", PROPERTY_HINT_RANGE, "0.001,1000.0,0.001,or_greater,exp"), "set_depth", "get_depth"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "spin_degrees", PROPERTY_HINT_RANGE, "1,360,0.1"), "set_spin_degrees", "get_spin_degrees"); ADD_PROPERTY(PropertyInfo(Variant::INT, "spin_sides", PROPERTY_HINT_RANGE, "3,64,1"), "set_spin_sides", "get_spin_sides"); - ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "path_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Path"), "set_path_node", "get_path_node"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_interval", PROPERTY_HINT_EXP_RANGE, "0.001,1000.0,0.001,or_greater"), "set_path_interval", "get_path_interval"); + ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "path_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Path3D"), "set_path_node", "get_path_node"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_interval", PROPERTY_HINT_RANGE, "0.001,1000.0,0.001,or_greater,exp"), "set_path_interval", "get_path_interval"); ADD_PROPERTY(PropertyInfo(Variant::INT, "path_rotation", PROPERTY_HINT_ENUM, "Polygon,Path,PathFollow"), "set_path_rotation", "get_path_rotation"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "path_local"), "set_path_local", "is_path_local"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "path_continuous_u"), "set_path_continuous_u", "is_path_continuous_u"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "path_joined"), "set_path_joined", "is_path_joined"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smooth_faces"), "set_smooth_faces", "get_smooth_faces"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "StandardMaterial3D,ShaderMaterial"), "set_material", "get_material"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial"), "set_material", "get_material"); BIND_ENUM_CONSTANT(MODE_DEPTH); BIND_ENUM_CONSTANT(MODE_SPIN); @@ -2246,7 +2252,7 @@ void CSGPolygon3D::_bind_methods() { void CSGPolygon3D::set_polygon(const Vector<Vector2> &p_polygon) { polygon = p_polygon; _make_dirty(); - update_gizmo(); + update_gizmos(); } Vector<Vector2> CSGPolygon3D::get_polygon() const { @@ -2256,7 +2262,7 @@ Vector<Vector2> CSGPolygon3D::get_polygon() const { void CSGPolygon3D::set_mode(Mode p_mode) { mode = p_mode; _make_dirty(); - update_gizmo(); + update_gizmos(); notify_property_list_changed(); } @@ -2268,7 +2274,7 @@ void CSGPolygon3D::set_depth(const float p_depth) { ERR_FAIL_COND(p_depth < 0.001); depth = p_depth; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGPolygon3D::get_depth() const { @@ -2288,7 +2294,7 @@ void CSGPolygon3D::set_spin_degrees(const float p_spin_degrees) { ERR_FAIL_COND(p_spin_degrees < 0.01 || p_spin_degrees > 360); spin_degrees = p_spin_degrees; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGPolygon3D::get_spin_degrees() const { @@ -2299,7 +2305,7 @@ void CSGPolygon3D::set_spin_sides(const int p_spin_sides) { ERR_FAIL_COND(p_spin_sides < 3); spin_sides = p_spin_sides; _make_dirty(); - update_gizmo(); + update_gizmos(); } int CSGPolygon3D::get_spin_sides() const { @@ -2309,7 +2315,7 @@ int CSGPolygon3D::get_spin_sides() const { void CSGPolygon3D::set_path_node(const NodePath &p_path) { path_node = p_path; _make_dirty(); - update_gizmo(); + update_gizmos(); } NodePath CSGPolygon3D::get_path_node() const { @@ -2320,7 +2326,7 @@ void CSGPolygon3D::set_path_interval(float p_interval) { ERR_FAIL_COND_MSG(p_interval < 0.001, "Path interval cannot be smaller than 0.001."); path_interval = p_interval; _make_dirty(); - update_gizmo(); + update_gizmos(); } float CSGPolygon3D::get_path_interval() const { @@ -2330,7 +2336,7 @@ float CSGPolygon3D::get_path_interval() const { void CSGPolygon3D::set_path_rotation(PathRotation p_rotation) { path_rotation = p_rotation; _make_dirty(); - update_gizmo(); + update_gizmos(); } CSGPolygon3D::PathRotation CSGPolygon3D::get_path_rotation() const { @@ -2340,7 +2346,7 @@ CSGPolygon3D::PathRotation CSGPolygon3D::get_path_rotation() const { void CSGPolygon3D::set_path_local(bool p_enable) { path_local = p_enable; _make_dirty(); - update_gizmo(); + update_gizmos(); } bool CSGPolygon3D::is_path_local() const { @@ -2350,7 +2356,7 @@ bool CSGPolygon3D::is_path_local() const { void CSGPolygon3D::set_path_joined(bool p_enable) { path_joined = p_enable; _make_dirty(); - update_gizmo(); + update_gizmos(); } bool CSGPolygon3D::is_path_joined() const { diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h index de7de09f00..0106f230eb 100644 --- a/modules/csg/csg_shape.h +++ b/modules/csg/csg_shape.h @@ -83,14 +83,14 @@ private: Vector<Vector3> vertices; Vector<Vector3> normals; Vector<Vector2> uvs; - Vector<float> tans; + Vector<real_t> tans; Ref<Material> material; int last_added = 0; Vector3 *verticesw = nullptr; Vector3 *normalsw = nullptr; Vector2 *uvsw = nullptr; - float *tansw = nullptr; + real_t *tansw = nullptr; }; //mikktspace callbacks diff --git a/modules/csg/doc_classes/CSGBox3D.xml b/modules/csg/doc_classes/CSGBox3D.xml index b1d0454b76..5bb1c4e75b 100644 --- a/modules/csg/doc_classes/CSGBox3D.xml +++ b/modules/csg/doc_classes/CSGBox3D.xml @@ -14,7 +14,7 @@ <member name="material" type="Material" setter="set_material" getter="get_material"> The material used to render the box. </member> - <member name="size" type="Vector3" setter="set_size" getter="get_size" default="Vector3( 2, 2, 2 )"> + <member name="size" type="Vector3" setter="set_size" getter="get_size" default="Vector3(2, 2, 2)"> The box's width, height and depth. </member> </members> diff --git a/modules/csg/doc_classes/CSGMesh3D.xml b/modules/csg/doc_classes/CSGMesh3D.xml index 1bab8f4ee9..5fa8427843 100644 --- a/modules/csg/doc_classes/CSGMesh3D.xml +++ b/modules/csg/doc_classes/CSGMesh3D.xml @@ -4,7 +4,7 @@ A CSG Mesh shape that uses a mesh resource. </brief_description> <description> - This CSG node allows you to use any mesh resource as a CSG shape, provided it is closed, does not self-intersect, does not contain internal faces and has no edges that connect to more then two faces. + This CSG node allows you to use any mesh resource as a CSG shape, provided it is closed, does not self-intersect, does not contain internal faces and has no edges that connect to more than two faces. </description> <tutorials> </tutorials> @@ -16,6 +16,7 @@ </member> <member name="mesh" type="Mesh" setter="set_mesh" getter="get_mesh"> The [Mesh] resource to use as a CSG shape. + [b]Note:[/b] When using an [ArrayMesh], avoid meshes with vertex normals unless a flat shader is required. By default, CSGMesh will ignore the mesh's vertex normals and use a smooth shader calculated using the faces' normals. If a flat shader is required, ensure that all faces' vertex normals are parallel. </member> </members> <constants> diff --git a/modules/csg/doc_classes/CSGPolygon3D.xml b/modules/csg/doc_classes/CSGPolygon3D.xml index c55fa0983e..4f29786779 100644 --- a/modules/csg/doc_classes/CSGPolygon3D.xml +++ b/modules/csg/doc_classes/CSGPolygon3D.xml @@ -38,7 +38,7 @@ <member name="path_rotation" type="int" setter="set_path_rotation" getter="get_path_rotation" enum="CSGPolygon3D.PathRotation"> The method by which each slice is rotated along the path when [member mode] is [constant MODE_PATH]. </member> - <member name="polygon" type="PackedVector2Array" setter="set_polygon" getter="get_polygon" default="PackedVector2Array( 0, 0, 0, 1, 1, 1, 1, 0 )"> + <member name="polygon" type="PackedVector2Array" setter="set_polygon" getter="get_polygon" default="PackedVector2Array(0, 0, 0, 1, 1, 1, 1, 0)"> Point array that defines the shape that we'll extrude. </member> <member name="smooth_faces" type="bool" setter="set_smooth_faces" getter="get_smooth_faces" default="false"> diff --git a/modules/csg/doc_classes/CSGShape3D.xml b/modules/csg/doc_classes/CSGShape3D.xml index dac556c7f1..f42ce8c379 100644 --- a/modules/csg/doc_classes/CSGShape3D.xml +++ b/modules/csg/doc_classes/CSGShape3D.xml @@ -10,55 +10,43 @@ </tutorials> <methods> <method name="get_collision_layer_bit" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="bit" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="bit" type="int" /> <description> Returns an individual bit on the collision mask. </description> </method> <method name="get_collision_mask_bit" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="bit" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="bit" type="int" /> <description> Returns an individual bit on the collision mask. </description> </method> <method name="get_meshes" qualifiers="const"> - <return type="Array"> - </return> + <return type="Array" /> <description> - Returns an [Array] with two elements, the first is the [Transform] of this node and the second is the root [Mesh] of this node. Only works when this node is the root shape. + Returns an [Array] with two elements, the first is the [Transform3D] of this node and the second is the root [Mesh] of this node. Only works when this node is the root shape. </description> </method> <method name="is_root_shape" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns [code]true[/code] if this is a root shape and is thus the object that is rendered. </description> </method> <method name="set_collision_layer_bit"> - <return type="void"> - </return> - <argument index="0" name="bit" type="int"> - </argument> - <argument index="1" name="value" type="bool"> - </argument> + <return type="void" /> + <argument index="0" name="bit" type="int" /> + <argument index="1" name="value" type="bool" /> <description> Sets individual bits on the layer mask. Use this if you only need to change one layer's value. </description> </method> <method name="set_collision_mask_bit"> - <return type="void"> - </return> - <argument index="0" name="bit" type="int"> - </argument> - <argument index="1" name="value" type="bool"> - </argument> + <return type="void" /> + <argument index="0" name="bit" type="int" /> + <argument index="1" name="value" type="bool" /> <description> Sets individual bits on the collision mask. Use this if you only need to change one layer's value. </description> diff --git a/modules/csg/icons/CSGBox3D.svg b/modules/csg/icons/CSGBox3D.svg index ceef9196a7..2740cc2f8c 100644 --- a/modules/csg/icons/CSGBox3D.svg +++ b/modules/csg/icons/CSGBox3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/><path d="m8 .94531-7 3.5v7.2227l7 3.5.29492-.14844c-.18282-.30101-.29492-.64737-.29492-1.0195v-2c0-.72651.40824-1.3664 1-1.7168v-1.6699l4-2v1.3867h1c.36419 0 .70336.10754 1 .2832v-3.8379zm0 2.1152 3.9395 1.9707-3.9395 1.9688-3.9395-1.9688zm-5 3.5527 4 2v3.9414l-4-2.002z" fill="#fc9c9c" stroke-width="1.0667"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#5fb2ff"/><path d="m8 .94531-7 3.5v7.2227l7 3.5.29492-.14844c-.18282-.30101-.29492-.64737-.29492-1.0195v-2c0-.72651.40824-1.3664 1-1.7168v-1.6699l4-2v1.3867h1c.36419 0 .70336.10754 1 .2832v-3.8379zm0 2.1152 3.9395 1.9707-3.9395 1.9688-3.9395-1.9688zm-5 3.5527 4 2v3.9414l-4-2.002z" fill="#fc7f7f" stroke-width="1.0667"/></svg> diff --git a/modules/csg/icons/CSGCapsule3D.svg b/modules/csg/icons/CSGCapsule3D.svg index 14e582ee84..db4f71864b 100644 --- a/modules/csg/icons/CSGCapsule3D.svg +++ b/modules/csg/icons/CSGCapsule3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-2.7527 0-5 2.2418-5 4.9902v4.0176c0 2.7484 2.2473 4.9922 5 4.9922.092943 0 .18367-.008623.27539-.013672-.17055-.29341-.27539-.62792-.27539-.98633v-2c0-.72887.41095-1.3691 1.0059-1.7188v-.28125c.34771-.034464.68259-.10691 1.0156-.19922.10394-.99856.95603-1.8008 1.9785-1.8008h1v-2.0098c0-2.7484-2.2473-4.9902-5-4.9902zm-1.0059 2.127v4.8574c-.66556-.1047-1.2974-.37231-1.9941-.66211v-1.3223c0-1.3474.79841-2.4642 1.9941-2.873zm2.0117 0c1.1957.4088 1.9941 1.5256 1.9941 2.873v1.3457c-.68406.3054-1.3142.57292-1.9941.66602v-4.8848zm-4.0059 6.334c.67836.2231 1.3126.44599 1.9941.52539v2.8848c-1.1957-.4092-1.9941-1.5237-1.9941-2.8711v-.53906z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-2.7527 0-5 2.2418-5 4.9902v4.0176c0 2.7484 2.2473 4.9922 5 4.9922.092943 0 .18367-.008623.27539-.013672-.17055-.29341-.27539-.62792-.27539-.98633v-2c0-.72887.41095-1.3691 1.0059-1.7188v-.28125c.34771-.034464.68259-.10691 1.0156-.19922.10394-.99856.95603-1.8008 1.9785-1.8008h1v-2.0098c0-2.7484-2.2473-4.9902-5-4.9902zm-1.0059 2.127v4.8574c-.66556-.1047-1.2974-.37231-1.9941-.66211v-1.3223c0-1.3474.79841-2.4642 1.9941-2.873zm2.0117 0c1.1957.4088 1.9941 1.5256 1.9941 2.873v1.3457c-.68406.3054-1.3142.57292-1.9941.66602v-4.8848zm-4.0059 6.334c.67836.2231 1.3126.44599 1.9941.52539v2.8848c-1.1957-.4092-1.9941-1.5237-1.9941-2.8711v-.53906z" fill="#fc7f7f"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#5fb2ff"/></svg> diff --git a/modules/csg/icons/CSGCombiner3D.svg b/modules/csg/icons/CSGCombiner3D.svg index 50ce4179d9..692ba54cb8 100644 --- a/modules/csg/icons/CSGCombiner3D.svg +++ b/modules/csg/icons/CSGCombiner3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/><path d="m3 1c-1.1046 0-2 .89543-2 2h2zm2 0v2h2v-2zm4 0v2h2v-2zm4 0v2h2c0-1.1046-.89543-2-2-2zm-12 4v2h2v-2zm12 0v2h2v-2zm-12 4v2h2v-2zm0 4c0 1.1046.89543 2 2 2v-2zm4 0v2h2v-2z" fill="#fc9c9c"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#5fb2ff"/><path d="m3 1c-1.1046 0-2 .89543-2 2h2zm2 0v2h2v-2zm4 0v2h2v-2zm4 0v2h2c0-1.1046-.89543-2-2-2zm-12 4v2h2v-2zm12 0v2h2v-2zm-12 4v2h2v-2zm0 4c0 1.1046.89543 2 2 2v-2zm4 0v2h2v-2z" fill="#fc7f7f"/></svg> diff --git a/modules/csg/icons/CSGCylinder3D.svg b/modules/csg/icons/CSGCylinder3D.svg index c84594928a..4bc2427887 100644 --- a/modules/csg/icons/CSGCylinder3D.svg +++ b/modules/csg/icons/CSGCylinder3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 14.999999 14.999999" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-1.7469 0-3.328.22648-4.5586.63672-.61528.20512-1.1471.45187-1.5898.80078-.44272.34891-.85156.88101-.85156 1.5625v8c0 .68149.40884 1.2155.85156 1.5645.44272.34891.97457.59577 1.5898.80078 1.2306.41024 2.8117.63477 4.5586.63477.095648 0 .18467-.008426.2793-.009766-.1722-.29446-.2793-.62995-.2793-.99023v-1c-1.5668 0-2.9867-.2195-3.9277-.5332-.46329-.15435-.90474-.33752-1.0723-.4668v-5.8125c.1468.058667.2835.12515.44141.17773 1.2306.41024 2.8117.63477 4.5586.63477s3.328-.22453 4.5586-.63477c.15791-.052267.29461-.11864.44141-.17773v1.8125h1c.36396 0 .70348.10774 1 .2832v-4.2832c0-.68149-.40884-1.2136-.85156-1.5625-.44272-.34891-.97457-.59566-1.5898-.80078-1.2306-.41024-2.8117-.63672-4.5586-.63672zm0 2c1.5668 0 2.9867.22145 3.9277.53516.46368.15456.80138.33741.96875.4668-.16752.12928-.50546.3105-.96875.46484-.94102.31371-2.361.5332-3.9277.5332s-2.9867-.2195-3.9277-.5332c-.46329-.15435-.80123-.33556-.96875-.46484.16737-.12939.50507-.31224.96875-.4668.94102-.31371 2.361-.53516 3.9277-.53516z" fill="#fc9c9c" stroke-width="1.0667" transform="scale(.9375)"/><path d="m11.25 8.4375c-.51938 0-.9375.41812-.9375.9375v.9375h1.875v1.875h.9375c.51938 0 .9375-.41812.9375-.9375v-1.875c0-.51938-.41812-.9375-.9375-.9375zm.9375 3.75h-1.875v-1.875h-.9375c-.51938 0-.9375.41812-.9375.9375v1.875c0 .51938.41812.9375.9375.9375h1.875c.51938 0 .9375-.41812.9375-.9375z" fill="#84c2ff"/></svg> +<svg height="16" viewBox="0 0 14.999999 14.999999" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-1.7469 0-3.328.22648-4.5586.63672-.61528.20512-1.1471.45187-1.5898.80078-.44272.34891-.85156.88101-.85156 1.5625v8c0 .68149.40884 1.2155.85156 1.5645.44272.34891.97457.59577 1.5898.80078 1.2306.41024 2.8117.63477 4.5586.63477.095648 0 .18467-.008426.2793-.009766-.1722-.29446-.2793-.62995-.2793-.99023v-1c-1.5668 0-2.9867-.2195-3.9277-.5332-.46329-.15435-.90474-.33752-1.0723-.4668v-5.8125c.1468.058667.2835.12515.44141.17773 1.2306.41024 2.8117.63477 4.5586.63477s3.328-.22453 4.5586-.63477c.15791-.052267.29461-.11864.44141-.17773v1.8125h1c.36396 0 .70348.10774 1 .2832v-4.2832c0-.68149-.40884-1.2136-.85156-1.5625-.44272-.34891-.97457-.59566-1.5898-.80078-1.2306-.41024-2.8117-.63672-4.5586-.63672zm0 2c1.5668 0 2.9867.22145 3.9277.53516.46368.15456.80138.33741.96875.4668-.16752.12928-.50546.3105-.96875.46484-.94102.31371-2.361.5332-3.9277.5332s-2.9867-.2195-3.9277-.5332c-.46329-.15435-.80123-.33556-.96875-.46484.16737-.12939.50507-.31224.96875-.4668.94102-.31371 2.361-.53516 3.9277-.53516z" fill="#fc7f7f" stroke-width="1.0667" transform="scale(.9375)"/><path d="m11.25 8.4375c-.51938 0-.9375.41812-.9375.9375v.9375h1.875v1.875h.9375c.51938 0 .9375-.41812.9375-.9375v-1.875c0-.51938-.41812-.9375-.9375-.9375zm.9375 3.75h-1.875v-1.875h-.9375c-.51938 0-.9375.41812-.9375.9375v1.875c0 .51938.41812.9375.9375.9375h1.875c.51938 0 .9375-.41812.9375-.9375z" fill="#5fb2ff"/></svg> diff --git a/modules/csg/icons/CSGMesh3D.svg b/modules/csg/icons/CSGMesh3D.svg index 962e71f6ae..8f4a1736fb 100644 --- a/modules/csg/icons/CSGMesh3D.svg +++ b/modules/csg/icons/CSGMesh3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m3 1c-1.1046 0-2 .89543-2 2 .0005649.71397.38169 1.3735 1 1.7305v6.541c-.61771.35663-.99874 1.0152-1 1.7285 0 1.1046.89543 2 2 2 .71397-.000565 1.3735-.38169 1.7305-1h3.2695v-2h-3.2715c-.17478-.30301-.42598-.55488-.72852-.73047v-5.8555l4.916 4.916c.31428-.20669.68609-.33008 1.084-.33008 0-.3979.12338-.76971.33008-1.084l-4.916-4.916h5.8574c.17478.30301.42598.55488.72852.73047v3.2695h2v-3.2715c.61771-.35663.99874-1.0152 1-1.7285 0-1.1046-.89543-2-2-2-.71397.0005648-1.3735.38169-1.7305 1h-6.541c-.35663-.61771-1.0152-.99874-1.7285-1z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m3 1c-1.1046 0-2 .89543-2 2 .0005649.71397.38169 1.3735 1 1.7305v6.541c-.61771.35663-.99874 1.0152-1 1.7285 0 1.1046.89543 2 2 2 .71397-.000565 1.3735-.38169 1.7305-1h3.2695v-2h-3.2715c-.17478-.30301-.42598-.55488-.72852-.73047v-5.8555l4.916 4.916c.31428-.20669.68609-.33008 1.084-.33008 0-.3979.12338-.76971.33008-1.084l-4.916-4.916h5.8574c.17478.30301.42598.55488.72852.73047v3.2695h2v-3.2715c.61771-.35663.99874-1.0152 1-1.7285 0-1.1046-.89543-2-2-2-.71397.0005648-1.3735.38169-1.7305 1h-6.541c-.35663-.61771-1.0152-.99874-1.7285-1z" fill="#fc7f7f"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#5fb2ff"/></svg> diff --git a/modules/csg/icons/CSGPolygon3D.svg b/modules/csg/icons/CSGPolygon3D.svg index 1d496e5fd9..971f3577bb 100644 --- a/modules/csg/icons/CSGPolygon3D.svg +++ b/modules/csg/icons/CSGPolygon3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7.9629 1.002c-.14254.00487-.28238.04016-.41016.10352l-6 3c-.33878.16944-.55276.51574-.55273.89453v5.832c-.105.61631.37487 1.1768 1 1.168h5v2c.0000216.67546.64487 1.1297 1.2617.95898-.16118-.28721-.26172-.61135-.26172-.95898v-2c0-.72673.40794-1.3664 1-1.7168v-1.666l4-2v1.3828h1c.36397 0 .70348.10774 1 .2832v-3.2773c.000006-.00195.000006-.0039094 0-.0058594.000026-.37879-.21395-.72509-.55273-.89453l-6-3c-.15022-.074574-.31679-.11017-.48438-.10352zm.037109 2.1172 3.7637 1.8809-2.7637 1.3809v-1.3809c-.0000552-.55226-.44774-.99994-1-1h-1.7617l1.7617-.88086zm-5 2.8809h4v4h-4z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7.9629 1.002c-.14254.00487-.28238.04016-.41016.10352l-6 3c-.33878.16944-.55276.51574-.55273.89453v5.832c-.105.61631.37487 1.1768 1 1.168h5v2c.0000216.67546.64487 1.1297 1.2617.95898-.16118-.28721-.26172-.61135-.26172-.95898v-2c0-.72673.40794-1.3664 1-1.7168v-1.666l4-2v1.3828h1c.36397 0 .70348.10774 1 .2832v-3.2773c.000006-.00195.000006-.0039094 0-.0058594.000026-.37879-.21395-.72509-.55273-.89453l-6-3c-.15022-.074574-.31679-.11017-.48438-.10352zm.037109 2.1172 3.7637 1.8809-2.7637 1.3809v-1.3809c-.0000552-.55226-.44774-.99994-1-1h-1.7617l1.7617-.88086zm-5 2.8809h4v4h-4z" fill="#fc7f7f"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#5fb2ff"/></svg> diff --git a/modules/csg/icons/CSGSphere3D.svg b/modules/csg/icons/CSGSphere3D.svg index 639e38f49f..770af80632 100644 --- a/modules/csg/icons/CSGSphere3D.svg +++ b/modules/csg/icons/CSGSphere3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-3.8541 0-7 3.1459-7 7 0 3.8542 3.1459 7 7 7 .093042 0 .18321-.01004.27539-.013672-.17055-.29341-.27539-.62792-.27539-.98633v-2c0-.72673.40794-1.3664 1-1.7168v-.33398c.34074-.019259.67728-.069097 1.0156-.10547.083091-1.0187.94713-1.8438 1.9844-1.8438h2c.35841 0 .69292.10484.98633.27539.003633-.092184.013672-.18235.013672-.27539 0-3.8541-3.1459-7-7-7zm-1 2.0977v4.8711c-1.2931-.071342-2.6061-.29819-3.9434-.69141.30081-2.0978 1.8852-3.7665 3.9434-4.1797zm2 0c2.0549.41253 3.637 2.0767 3.9414 4.1699-1.3046.36677-2.6158.60259-3.9414.6875zm-5.7793 6.2988c1.2733.31892 2.5337.50215 3.7793.5625v2.9414c-1.8291-.36719-3.266-1.7339-3.7793-3.5039z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1c-3.8541 0-7 3.1459-7 7 0 3.8542 3.1459 7 7 7 .093042 0 .18321-.01004.27539-.013672-.17055-.29341-.27539-.62792-.27539-.98633v-2c0-.72673.40794-1.3664 1-1.7168v-.33398c.34074-.019259.67728-.069097 1.0156-.10547.083091-1.0187.94713-1.8438 1.9844-1.8438h2c.35841 0 .69292.10484.98633.27539.003633-.092184.013672-.18235.013672-.27539 0-3.8541-3.1459-7-7-7zm-1 2.0977v4.8711c-1.2931-.071342-2.6061-.29819-3.9434-.69141.30081-2.0978 1.8852-3.7665 3.9434-4.1797zm2 0c2.0549.41253 3.637 2.0767 3.9414 4.1699-1.3046.36677-2.6158.60259-3.9414.6875zm-5.7793 6.2988c1.2733.31892 2.5337.50215 3.7793.5625v2.9414c-1.8291-.36719-3.266-1.7339-3.7793-3.5039z" fill="#fc7f7f"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#5fb2ff"/></svg> diff --git a/modules/csg/icons/CSGTorus3D.svg b/modules/csg/icons/CSGTorus3D.svg index eb8c0f37cb..ece9c68d28 100644 --- a/modules/csg/icons/CSGTorus3D.svg +++ b/modules/csg/icons/CSGTorus3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 3c-1.8145 0-3.4691.41721-4.7461 1.1621-1.277.745-2.2539 1.9082-2.2539 3.3379 0 1.4298.9769 2.5949 2.2539 3.3398s2.9316 1.1602 4.7461 1.1602c0-1.0907.90931-2 2-2 0-.080836.013744-.15778.023438-.23633-.61769.14673-1.3008.23633-2.0234.23633-1.4992 0-2.8437-.36687-3.7383-.88867-.89456-.5219-1.2617-1.108-1.2617-1.6113 0-.5032.36716-1.0876 1.2617-1.6094.89456-.5219 2.2391-.89062 3.7383-.89062s2.8437.36872 3.7383.89062c.89456.5218 1.2617 1.1062 1.2617 1.6094 0 .15978-.053679.32822-.13281.5h1.1328c.32481 0 .62893.088408.90234.23047.057552-.23582.097656-.47718.097656-.73047 0-1.4297-.9769-2.5929-2.2539-3.3379-1.277-.7449-2.9316-1.1621-4.7461-1.1621z" fill="#fc9c9c"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#84c2ff"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 3c-1.8145 0-3.4691.41721-4.7461 1.1621-1.277.745-2.2539 1.9082-2.2539 3.3379 0 1.4298.9769 2.5949 2.2539 3.3398s2.9316 1.1602 4.7461 1.1602c0-1.0907.90931-2 2-2 0-.080836.013744-.15778.023438-.23633-.61769.14673-1.3008.23633-2.0234.23633-1.4992 0-2.8437-.36687-3.7383-.88867-.89456-.5219-1.2617-1.108-1.2617-1.6113 0-.5032.36716-1.0876 1.2617-1.6094.89456-.5219 2.2391-.89062 3.7383-.89062s2.8437.36872 3.7383.89062c.89456.5218 1.2617 1.1062 1.2617 1.6094 0 .15978-.053679.32822-.13281.5h1.1328c.32481 0 .62893.088408.90234.23047.057552-.23582.097656-.47718.097656-.73047 0-1.4297-.9769-2.5929-2.2539-3.3379-1.277-.7449-2.9316-1.1621-4.7461-1.1621z" fill="#fc7f7f"/><path d="m12 9c-.55401 0-1 .44599-1 1v1h2v2h1c.55401 0 1-.44599 1-1v-2c0-.55401-.44599-1-1-1zm1 4h-2v-2h-1c-.55401 0-1 .44599-1 1v2c0 .55401.44599 1 1 1h2c.55401 0 1-.44599 1-1z" fill="#5fb2ff"/></svg> diff --git a/modules/csg/register_types.cpp b/modules/csg/register_types.cpp index e28f44d1eb..a47390c2b2 100644 --- a/modules/csg/register_types.cpp +++ b/modules/csg/register_types.cpp @@ -36,15 +36,15 @@ void register_csg_types() { #ifndef _3D_DISABLED - ClassDB::register_virtual_class<CSGShape3D>(); - ClassDB::register_virtual_class<CSGPrimitive3D>(); - ClassDB::register_class<CSGMesh3D>(); - ClassDB::register_class<CSGSphere3D>(); - ClassDB::register_class<CSGBox3D>(); - ClassDB::register_class<CSGCylinder3D>(); - ClassDB::register_class<CSGTorus3D>(); - ClassDB::register_class<CSGPolygon3D>(); - ClassDB::register_class<CSGCombiner3D>(); + GDREGISTER_VIRTUAL_CLASS(CSGShape3D); + GDREGISTER_VIRTUAL_CLASS(CSGPrimitive3D); + GDREGISTER_CLASS(CSGMesh3D); + GDREGISTER_CLASS(CSGSphere3D); + GDREGISTER_CLASS(CSGBox3D); + GDREGISTER_CLASS(CSGCylinder3D); + GDREGISTER_CLASS(CSGTorus3D); + GDREGISTER_CLASS(CSGPolygon3D); + GDREGISTER_CLASS(CSGCombiner3D); #ifdef TOOLS_ENABLED EditorPlugins::add_by_type<EditorPluginCSG>(); diff --git a/modules/dds/register_types.cpp b/modules/dds/register_types.cpp index 1444d33171..60282c3f36 100644 --- a/modules/dds/register_types.cpp +++ b/modules/dds/register_types.cpp @@ -35,7 +35,7 @@ static Ref<ResourceFormatDDS> resource_loader_dds; void register_dds_types() { - resource_loader_dds.instance(); + resource_loader_dds.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_dds); } diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp index 2fef576b77..fced61a600 100644 --- a/modules/dds/texture_loader_dds.cpp +++ b/modules/dds/texture_loader_dds.cpp @@ -30,7 +30,7 @@ #include "texture_loader_dds.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #define PF_FOURCC(s) ((uint32_t)(((s)[3] << 24U) | ((s)[2] << 16U) | ((s)[1] << 8U) | ((s)[0]))) diff --git a/modules/enet/config.py b/modules/enet/config.py index 5fd343c75d..9102c74579 100644 --- a/modules/enet/config.py +++ b/modules/enet/config.py @@ -8,7 +8,9 @@ def configure(env): def get_doc_classes(): return [ - "NetworkedMultiplayerENet", + "ENetMultiplayerPeer", + "ENetConnection", + "ENetPacketPeer", ] diff --git a/modules/enet/doc_classes/ENetConnection.xml b/modules/enet/doc_classes/ENetConnection.xml new file mode 100644 index 0000000000..c2a85ffdf8 --- /dev/null +++ b/modules/enet/doc_classes/ENetConnection.xml @@ -0,0 +1,194 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="ENetConnection" inherits="RefCounted" version="4.0"> + <brief_description> + A wrapper class for an [url=http://enet.bespin.org/group__host.html]ENetHost[/url]. + </brief_description> + <description> + ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol). + </description> + <tutorials> + <link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link> + </tutorials> + <methods> + <method name="bandwidth_limit"> + <return type="void" /> + <argument index="0" name="in_bandwidth" type="int" default="0" /> + <argument index="1" name="out_bandwidth" type="int" default="0" /> + <description> + Adjusts the bandwidth limits of a host. + </description> + </method> + <method name="broadcast"> + <return type="void" /> + <argument index="0" name="channel" type="int" /> + <argument index="1" name="packet" type="PackedByteArray" /> + <argument index="2" name="flags" type="int" /> + <description> + Queues a [code]packet[/code] to be sent to all peers associated with the host over the specified [code]channel[/code]. See [ENetPacketPeer] [code]FLAG_*[/code] constants for available packet flags. + </description> + </method> + <method name="channel_limit"> + <return type="void" /> + <argument index="0" name="limit" type="int" /> + <description> + Limits the maximum allowed channels of future incoming connections. + </description> + </method> + <method name="compress"> + <return type="void" /> + <argument index="0" name="mode" type="int" enum="ENetConnection.CompressionMode" /> + <description> + Sets the compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all. + [b]Note:[/b] Most games' network design involve sending many small packets frequently (smaller than 4 KB each). If in doubt, it is recommended to keep the default compression algorithm as it works best on these small packets. + </description> + </method> + <method name="connect_to_host"> + <return type="ENetPacketPeer" /> + <argument index="0" name="address" type="String" /> + <argument index="1" name="port" type="int" /> + <argument index="2" name="channels" type="int" default="0" /> + <argument index="3" name="data" type="int" default="0" /> + <description> + Initiates a connection to a foreign [code]address[/code] using the specified [code]port[/code] and allocting the requested [code]channels[/code]. Optional [code]data[/code] can be passed during connection in the form of a 32 bit integer. + Note: You must call either [method create_host] or [method create_host_bound] before calling this method. + </description> + </method> + <method name="create_host"> + <return type="int" enum="Error" /> + <argument index="0" name="max_peers" type="int" default="32" /> + <argument index="1" name="max_channels" type="int" default="0" /> + <argument index="2" name="in_bandwidth" type="int" default="0" /> + <argument index="3" name="out_bandwidth" type="int" default="0" /> + <description> + Create an ENetHost that will allow up to [code]max_peers[/code] connected peers, each allocating up to [code]max_channels[/code] channels, optionally limiting bandwith to [code]in_bandwidth[/code] and [code]out_bandwidth[/code]. + </description> + </method> + <method name="create_host_bound"> + <return type="int" enum="Error" /> + <argument index="0" name="bind_address" type="String" /> + <argument index="1" name="bind_port" type="int" /> + <argument index="2" name="max_peers" type="int" default="32" /> + <argument index="3" name="max_channels" type="int" default="0" /> + <argument index="4" name="in_bandwidth" type="int" default="0" /> + <argument index="5" name="out_bandwidth" type="int" default="0" /> + <description> + Create an ENetHost like [method create_host] which is also bound to the given [code]bind_address[/code] and [code]bind_port[/code]. + </description> + </method> + <method name="destroy"> + <return type="void" /> + <description> + Destroys the host and all resources associated with it. + </description> + </method> + <method name="dtls_client_setup"> + <return type="int" enum="Error" /> + <argument index="0" name="certificate" type="X509Certificate" /> + <argument index="1" name="hostname" type="String" /> + <argument index="2" name="verify" type="bool" default="true" /> + <description> + Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet clients. Call this before [method connect_to_host] to have ENet connect using DTLS with [code]certificate[/code] and [code]hostname[/code] verification. Verification can be optionally turned off via the [code]verify[/code] parameter. + </description> + </method> + <method name="dtls_server_setup"> + <return type="int" enum="Error" /> + <argument index="0" name="key" type="CryptoKey" /> + <argument index="1" name="certificate" type="X509Certificate" /> + <description> + Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet servers. Call this right after [method create_host_bound] to have ENet expect peers to connect using DTLS. + </description> + </method> + <method name="flush"> + <return type="void" /> + <description> + Sends any queued packets on the host specified to its designated peers. + </description> + </method> + <method name="get_local_port" qualifiers="const"> + <return type="int" /> + <description> + Returns the local port to which this peer is bound. + </description> + </method> + <method name="get_max_channels" qualifiers="const"> + <return type="int" /> + <description> + Returns the maximum number of channels allowed for connected peers. + </description> + </method> + <method name="get_peers"> + <return type="Array" /> + <description> + Returns the list of peers associated with this host. + Note: This list might include some peers that are not fully connected or are still being disconnected. + </description> + </method> + <method name="pop_statistic"> + <return type="float" /> + <argument index="0" name="statistic" type="int" enum="ENetConnection.HostStatistic" /> + <description> + Returns and resets host statistics. See [enum HostStatistic] for more info. + </description> + </method> + <method name="refuse_new_connections"> + <return type="void" /> + <argument index="0" name="refuse" type="bool" /> + <description> + Configures the DTLS server to automatically drop new connections. + Note: This method is only relevant after calling [method dtls_server_setup]. + </description> + </method> + <method name="service"> + <return type="Array" /> + <argument index="0" name="timeout" type="int" default="0" /> + <description> + Waits for events on the host specified and shuttles packets between the host and its peers. The returned [Array] will have 4 elements. An [enum EventType], the [ENetPacketPeer] which generated the event, the event associated data (if any), the event associated channel (if any). If the generated event is [constant EVENT_RECEIVE], the received packet will be queued to the associated [ENetPacketPeer]. + Call this function regularly to handle connections, disconnections, and to receive new packets. + </description> + </method> + </methods> + <constants> + <constant name="COMPRESS_NONE" value="0" enum="CompressionMode"> + No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. This option may also be used to make network debugging using tools like Wireshark easier. + </constant> + <constant name="COMPRESS_RANGE_CODER" value="1" enum="CompressionMode"> + ENet's built-in range encoding. Works well on small packets, but is not the most efficient algorithm on packets larger than 4 KB. + </constant> + <constant name="COMPRESS_FASTLZ" value="2" enum="CompressionMode"> + [url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth. + </constant> + <constant name="COMPRESS_ZLIB" value="3" enum="CompressionMode"> + [url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources. + </constant> + <constant name="COMPRESS_ZSTD" value="4" enum="CompressionMode"> + [url=https://facebook.github.io/zstd/]Zstandard[/url] compression. Note that this algorithm is not very efficient on packets smaller than 4 KB. Therefore, it's recommended to use other compression algorithms in most cases. + </constant> + <constant name="EVENT_ERROR" value="-1" enum="EventType"> + An error occurred during [method service]. You will likely need to [method destroy] the host and recreate it. + </constant> + <constant name="EVENT_NONE" value="0" enum="EventType"> + No event occurred within the specified time limit. + </constant> + <constant name="EVENT_CONNECT" value="1" enum="EventType"> + A connection request initiated by enet_host_connect has completed. The array will contain the peer which successfully connected. + </constant> + <constant name="EVENT_DISCONNECT" value="2" enum="EventType"> + A peer has disconnected. This event is generated on a successful completion of a disconnect initiated by [method ENetPacketPeer.peer_disconnect], if a peer has timed out, or if a connection request intialized by [method connect_to_host] has timed out. The array will contain the peer which disconnected. The data field contains user supplied data describing the disconnection, or 0, if none is available. + </constant> + <constant name="EVENT_RECEIVE" value="3" enum="EventType"> + A packet has been received from a peer. The array will contain the peer which sent the packet, the channel number upon which the packet was received, and the received packet. + </constant> + <constant name="HOST_TOTAL_SENT_DATA" value="0" enum="HostStatistic"> + Total data sent. + </constant> + <constant name="HOST_TOTAL_SENT_PACKETS" value="1" enum="HostStatistic"> + Total UDP packets sent. + </constant> + <constant name="HOST_TOTAL_RECEIVED_DATA" value="2" enum="HostStatistic"> + Total data received. + </constant> + <constant name="HOST_TOTAL_RECEIVED_PACKETS" value="3" enum="HostStatistic"> + Total UDP packets received. + </constant> + </constants> +</class> diff --git a/modules/enet/doc_classes/ENetMultiplayerPeer.xml b/modules/enet/doc_classes/ENetMultiplayerPeer.xml new file mode 100644 index 0000000000..3a37b396a4 --- /dev/null +++ b/modules/enet/doc_classes/ENetMultiplayerPeer.xml @@ -0,0 +1,88 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="ENetMultiplayerPeer" inherits="MultiplayerPeer" version="4.0"> + <brief_description> + A MultiplayerPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library. + </brief_description> + <description> + A MultiplayerPeer implementation that should be passed to [member MultiplayerAPI.network_peer] after being initialized as either a client, server, or mesh. Events can then be handled by connecting to [MultiplayerAPI] signals. See [ENetConnection] for more information on the ENet library wrapper. + [b]Note:[/b] ENet only uses UDP, not TCP. When forwarding the server port to make your server accessible on the public Internet, you only need to forward the server port in UDP. You can use the [UPNP] class to try to forward the server port automatically when starting the server. + </description> + <tutorials> + <link title="High-level multiplayer">https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html</link> + <link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link> + </tutorials> + <methods> + <method name="add_mesh_peer"> + <return type="int" enum="Error" /> + <argument index="0" name="peer_id" type="int" /> + <argument index="1" name="host" type="ENetConnection" /> + <description> + Add a new remote peer with the given [code]peer_id[/code] connected to the given [code]host[/code]. + Note: 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" /> + <argument 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" /> + <argument index="0" name="address" type="String" /> + <argument index="1" name="port" type="int" /> + <argument index="2" name="channel_count" type="int" default="0" /> + <argument index="3" name="in_bandwidth" type="int" default="0" /> + <argument index="4" name="out_bandwidth" type="int" default="0" /> + <argument 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. + </description> + </method> + <method name="create_mesh"> + <return type="int" enum="Error" /> + <argument index="0" name="unique_id" type="int" /> + <description> + Initialize this [MultiplayerPeer] in mesh mode. The provided [code]unique_id[/code] will be used as the local peer network unique ID once assigned as the [member MultiplayerAPI.network_peer]. In the mesh configuration you will need to set up each new peer manually using [ENetConnection] before calling [method add_mesh_peer]. While this technique is more advanced, it allows for better control over the connection process (e.g. when dealing with NAT punch-through) and for better distribution of the network load (which would otherwise be more taxing on the server). + </description> + </method> + <method name="create_server"> + <return type="int" enum="Error" /> + <argument index="0" name="port" type="int" /> + <argument index="1" name="max_clients" type="int" default="32" /> + <argument index="2" name="max_channels" type="int" default="0" /> + <argument index="3" name="in_bandwidth" type="int" default="0" /> + <argument 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. + </description> + </method> + <method name="get_peer" qualifiers="const"> + <return type="ENetPacketPeer" /> + <argument index="0" name="id" type="int" /> + <description> + Return the [ENetPacketPeer] associated to the given [code]id[/code]. + </description> + </method> + <method name="set_bind_ip"> + <return type="void" /> + <argument index="0" name="ip" type="String" /> + <description> + The IP used when creating a server. This is set to the wildcard [code]"*"[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]"192.168.1.1"[/code]. + </description> + </method> + </methods> + <members> + <member name="host" type="ENetConnection" setter="" getter="get_host"> + The underlying [ENetConnection] created after [method create_client] and [method create_server]. + </member> + <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" /> + <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> + <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="MultiplayerPeer.TransferMode" default="2" /> + </members> + <constants> + </constants> +</class> diff --git a/modules/enet/doc_classes/ENetPacketPeer.xml b/modules/enet/doc_classes/ENetPacketPeer.xml new file mode 100644 index 0000000000..8f0693fb01 --- /dev/null +++ b/modules/enet/doc_classes/ENetPacketPeer.xml @@ -0,0 +1,183 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="ENetPacketPeer" inherits="PacketPeer" version="4.0"> + <brief_description> + A wrapper class for an [url=http://enet.bespin.org/group__peer.html]ENetPeer[/url]. + </brief_description> + <description> + A PacketPeer implementation representing a peer of an [ENetConnection]. + This class cannot be instantiated directly but can be retrieved during [method ENetConnection.service] or via [method ENetConnection.get_peers]. + </description> + <tutorials> + <link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link> + </tutorials> + <methods> + <method name="get_channels" qualifiers="const"> + <return type="int" /> + <description> + Returns the number of channels allocated for communication with peer. + </description> + </method> + <method name="get_state" qualifiers="const"> + <return type="int" enum="ENetPacketPeer.PeerState" /> + <description> + Returns the current peer state. See [enum PeerState]. + </description> + </method> + <method name="get_statistic"> + <return type="float" /> + <argument index="0" name="statistic" type="int" enum="ENetPacketPeer.PeerStatistic" /> + <description> + Returns the requested [code]statistic[/code] for this peer. See [enum PeerStatistic]. + </description> + </method> + <method name="is_active" qualifiers="const"> + <return type="bool" /> + <description> + Returns [code]true[/code] if the peer is currently active (i.e. the associated [ENetConnection] is still valid). + </description> + </method> + <method name="peer_disconnect"> + <return type="void" /> + <argument index="0" name="data" type="int" default="0" /> + <description> + Request a disconnection from a peer. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete. + </description> + </method> + <method name="peer_disconnect_later"> + <return type="void" /> + <argument index="0" name="data" type="int" default="0" /> + <description> + Request a disconnection from a peer, but only after all queued outgoing packets are sent. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete. + </description> + </method> + <method name="peer_disconnect_now"> + <return type="void" /> + <argument index="0" name="data" type="int" default="0" /> + <description> + Force an immediate disconnection from a peer. No [constant ENetConnection.EVENT_DISCONNECT] will be generated. The foreign peer is not guaranteed to receive the disconnect notification, and is reset immediately upon return from this function. + </description> + </method> + <method name="ping"> + <return type="void" /> + <description> + Sends a ping request to a peer. ENet automatically pings all connected peers at regular intervals, however, this function may be called to ensure more frequent ping requests. + </description> + </method> + <method name="ping_interval"> + <return type="void" /> + <argument 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. + </description> + </method> + <method name="reset"> + <return type="void" /> + <description> + Forcefully disconnects a peer. The foreign host represented by the peer is not notified of the disconnection and will timeout on its connection to the local host. + </description> + </method> + <method name="send"> + <return type="int" enum="Error" /> + <argument index="0" name="channel" type="int" /> + <argument index="1" name="packet" type="PackedByteArray" /> + <argument index="2" name="flags" type="int" /> + <description> + Queues a [code]packet[/code] to be sent over the specified [code]channel[/code]. See [code]FLAG_*[/code] constants for available packet flags. + </description> + </method> + <method name="set_timeout"> + <return type="void" /> + <argument index="0" name="timeout" type="int" /> + <argument index="1" name="timeout_min" type="int" /> + <argument index="2" name="timeout_max" type="int" /> + <description> + Sets the timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values are expressed in milliseconds. + The [code]timeout_limit[/code] is a factor that, multiplied by a value based on the average round trip time, will determine the timeout limit for a reliable packet. When that limit is reached, the timeout will be doubled, and the peer will be disconnected if that limit has reached [code]timeout_min[/code]. The [code]timeout_max[/code] parameter, on the other hand, defines a fixed timeout for which any packet must be acknowledged or the peer will be dropped. + </description> + </method> + <method name="throttle_configure"> + <return type="void" /> + <argument index="0" name="interval" type="int" /> + <argument index="1" name="acceleration" type="int" /> + <argument 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]). + 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. + 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"> + </constant> + <constant name="STATE_CONNECTING" value="1" enum="PeerState"> + </constant> + <constant name="STATE_ACKNOWLEDGING_CONNECT" value="2" enum="PeerState"> + </constant> + <constant name="STATE_CONNECTION_PENDING" value="3" enum="PeerState"> + </constant> + <constant name="STATE_CONNECTION_SUCCEEDED" value="4" enum="PeerState"> + </constant> + <constant name="STATE_CONNECTED" value="5" enum="PeerState"> + </constant> + <constant name="STATE_DISCONNECT_LATER" value="6" enum="PeerState"> + </constant> + <constant name="STATE_DISCONNECTING" value="7" enum="PeerState"> + </constant> + <constant name="STATE_ACKNOWLEDGING_DISCONNECT" value="8" enum="PeerState"> + </constant> + <constant name="STATE_ZOMBIE" value="9" enum="PeerState"> + </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]. + </constant> + <constant name="PEER_PACKET_LOSS_VARIANCE" value="1" enum="PeerStatistic"> + Packet loss variance. + </constant> + <constant name="PEER_PACKET_LOSS_EPOCH" value="2" enum="PeerStatistic"> + </constant> + <constant name="PEER_ROUND_TRIP_TIME" value="3" enum="PeerStatistic"> + Mean packet round trip time for reliable packets. + </constant> + <constant name="PEER_ROUND_TRIP_TIME_VARIANCE" value="4" enum="PeerStatistic"> + Variance of the mean round trip time. + </constant> + <constant name="PEER_LAST_ROUND_TRIP_TIME" value="5" enum="PeerStatistic"> + Last recorded round trip time for a reliable packet. + </constant> + <constant name="PEER_LAST_ROUND_TRIP_TIME_VARIANCE" value="6" enum="PeerStatistic"> + Variance of the last trip time recorded. + </constant> + <constant name="PEER_PACKET_THROTTLE" value="7" enum="PeerStatistic"> + </constant> + <constant name="PEER_PACKET_THROTTLE_LIMIT" value="8" enum="PeerStatistic"> + </constant> + <constant name="PEER_PACKET_THROTTLE_COUNTER" value="9" enum="PeerStatistic"> + </constant> + <constant name="PEER_PACKET_THROTTLE_EPOCH" value="10" enum="PeerStatistic"> + </constant> + <constant name="PEER_PACKET_THROTTLE_ACCELERATION" value="11" enum="PeerStatistic"> + </constant> + <constant name="PEER_PACKET_THROTTLE_DECELERATION" value="12" enum="PeerStatistic"> + </constant> + <constant name="PEER_PACKET_THROTTLE_INTERVAL" value="13" enum="PeerStatistic"> + </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]. + </constant> + <constant name="FLAG_RELIABLE" value="1"> + Mark the packet to be sent as reliable. + </constant> + <constant name="FLAG_UNSEQUENCED" value="2"> + Mark the packet to be sent unsequenced (unreliable). + </constant> + <constant name="FLAG_UNRELIABLE_FRAGMENT" value="8"> + Mark the packet to be sent unreliable even if the packet is too big and needs fragmentation (increasing the chance of it being dropped). + </constant> + </constants> +</class> diff --git a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml deleted file mode 100644 index c8f32ffde6..0000000000 --- a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml +++ /dev/null @@ -1,187 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<class name="NetworkedMultiplayerENet" inherits="NetworkedMultiplayerPeer" version="4.0"> - <brief_description> - PacketPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library. - </brief_description> - <description> - A PacketPeer implementation that should be passed to [member SceneTree.network_peer] after being initialized as either a client or server. Events can then be handled by connecting to [SceneTree] signals. - ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol). - [b]Note:[/b] ENet only uses UDP, not TCP. When forwarding the server port to make your server accessible on the public Internet, you only need to forward the server port in UDP. You can use the [UPNP] class to try to forward the server port automatically when starting the server. - </description> - <tutorials> - <link title="High-level multiplayer">https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html</link> - <link title="API documentation on the ENet website">http://enet.bespin.org/usergroup0.html</link> - </tutorials> - <methods> - <method name="close_connection"> - <return type="void"> - </return> - <argument index="0" name="wait_usec" type="int" default="100"> - </argument> - <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"> - </return> - <argument index="0" name="address" type="String"> - </argument> - <argument index="1" name="port" type="int"> - </argument> - <argument index="2" name="in_bandwidth" type="int" default="0"> - </argument> - <argument index="3" name="out_bandwidth" type="int" default="0"> - </argument> - <argument index="4" name="client_port" type="int" default="0"> - </argument> - <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]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 NetworkedMultiplayerENet 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]client_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_server"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="port" type="int"> - </argument> - <argument index="1" name="max_clients" type="int" default="32"> - </argument> - <argument index="2" name="in_bandwidth" type="int" default="0"> - </argument> - <argument index="3" name="out_bandwidth" type="int" default="0"> - </argument> - <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 NetworkedMultiplayerENet 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. - </description> - </method> - <method name="disconnect_peer"> - <return type="void"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="now" type="bool" default="false"> - </argument> - <description> - Disconnect the given peer. If "now" is set to [code]true[/code], the connection will be closed immediately without flushing queued messages. - </description> - </method> - <method name="get_last_packet_channel" qualifiers="const"> - <return type="int"> - </return> - <description> - Returns the channel of the last packet fetched via [method PacketPeer.get_packet]. - </description> - </method> - <method name="get_packet_channel" qualifiers="const"> - <return type="int"> - </return> - <description> - Returns the channel of the next packet that will be retrieved via [method PacketPeer.get_packet]. - </description> - </method> - <method name="get_peer_address" qualifiers="const"> - <return type="String"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - Returns the IP address of the given peer. - </description> - </method> - <method name="get_peer_port" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <description> - Returns the remote port of the given peer. - </description> - </method> - <method name="set_bind_ip"> - <return type="void"> - </return> - <argument index="0" name="ip" type="String"> - </argument> - <description> - The IP used when creating a server. This is set to the wildcard [code]"*"[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]"192.168.1.1"[/code]. - </description> - </method> - <method name="set_dtls_certificate"> - <return type="void"> - </return> - <argument index="0" name="certificate" type="X509Certificate"> - </argument> - <description> - Configure the [X509Certificate] to use when [member use_dtls] is [code]true[/code]. For servers, you must also setup the [CryptoKey] via [method set_dtls_key]. - </description> - </method> - <method name="set_dtls_key"> - <return type="void"> - </return> - <argument index="0" name="key" type="CryptoKey"> - </argument> - <description> - Configure the [CryptoKey] to use when [member use_dtls] is [code]true[/code]. Remember to also call [method set_dtls_certificate] to setup your [X509Certificate]. - </description> - </method> - <method name="set_peer_timeout"> - <return type="void"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="timeout_limit" type="int"> - </argument> - <argument index="2" name="timeout_min" type="int"> - </argument> - <argument index="3" name="timeout_max" type="int"> - </argument> - <description> - Sets the timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values are expressed in milliseconds. - The [code]timeout_limit[/code] is a factor that, multiplied by a value based on the avarage round trip time, will determine the timeout limit for a reliable packet. When that limit is reached, the timeout will be doubled, and the peer will be disconnected if that limit has reached [code]timeout_min[/code]. The [code]timeout_max[/code] parameter, on the other hand, defines a fixed timeout for which any packet must be acknowledged or the peer will be dropped. - </description> - </method> - </methods> - <members> - <member name="always_ordered" type="bool" setter="set_always_ordered" getter="is_always_ordered" default="false"> - Enforce ordered packets when using [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE] (thus behaving similarly to [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED]). This is the only way to use ordering with the RPC system. - </member> - <member name="channel_count" type="int" setter="set_channel_count" getter="get_channel_count" default="3"> - The number of channels to be used by ENet. Channels are used to separate different kinds of data. In reliable or ordered mode, for example, the packet delivery order is ensured on a per-channel basis. This is done to combat latency and reduces ordering restrictions on packets. The delivery status of a packet in one channel won't stall the delivery of other packets in another channel. - </member> - <member name="compression_mode" type="int" setter="set_compression_mode" getter="get_compression_mode" enum="NetworkedMultiplayerENet.CompressionMode" default="0"> - The compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all. - </member> - <member name="dtls_verify" type="bool" setter="set_dtls_verify_enabled" getter="is_dtls_verify_enabled" default="true"> - Enable or disable certificate verification when [member use_dtls] [code]true[/code]. - </member> - <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" /> - <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> - <member name="transfer_channel" type="int" setter="set_transfer_channel" getter="get_transfer_channel" default="-1"> - Set the default channel to be used to transfer data. By default, this value is [code]-1[/code] which means that ENet will only use 2 channels: one for reliable packets, and one for unreliable packets. The channel [code]0[/code] is reserved and cannot be used. Setting this member to any value between [code]0[/code] and [member channel_count] (excluded) will force ENet to use that channel for sending data. See [member channel_count] for more information about ENet channels. - </member> - <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="NetworkedMultiplayerPeer.TransferMode" default="2" /> - <member name="use_dtls" type="bool" setter="set_dtls_enabled" getter="is_dtls_enabled" default="false"> - When enabled, the client or server created by this peer, will use [PacketPeerDTLS] instead of raw UDP sockets for communicating with the remote peer. This will make the communication encrypted with DTLS at the cost of higher resource usage and potentially larger packet size. - Note: When creating a DTLS server, make sure you setup the key/certificate pair via [method set_dtls_key] and [method set_dtls_certificate]. For DTLS clients, have a look at the [member dtls_verify] option, and configure the certificate accordingly via [method set_dtls_certificate]. - </member> - </members> - <constants> - <constant name="COMPRESS_NONE" value="0" enum="CompressionMode"> - No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. - </constant> - <constant name="COMPRESS_RANGE_CODER" value="1" enum="CompressionMode"> - ENet's built-in range encoding. - </constant> - <constant name="COMPRESS_FASTLZ" value="2" enum="CompressionMode"> - [url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth. - </constant> - <constant name="COMPRESS_ZLIB" value="3" enum="CompressionMode"> - [url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources. - </constant> - <constant name="COMPRESS_ZSTD" value="4" enum="CompressionMode"> - [url=https://facebook.github.io/zstd/]Zstandard[/url] compression. - </constant> - </constants> -</class> diff --git a/modules/enet/enet_connection.cpp b/modules/enet/enet_connection.cpp new file mode 100644 index 0000000000..e833264d6a --- /dev/null +++ b/modules/enet/enet_connection.cpp @@ -0,0 +1,470 @@ +/*************************************************************************/ +/* enet_connection.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "enet_connection.h" + +#include "enet_packet_peer.h" + +#include "core/io/compression.h" +#include "core/io/ip.h" + +void ENetConnection::broadcast(enet_uint8 p_channel, ENetPacket *p_packet) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_MSG(p_channel >= host->channelLimit, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)host->channelLimit)); + enet_host_broadcast(host, p_channel, p_packet); +} + +Error ENetConnection::create_host_bound(const IPAddress &p_bind_address, int p_port, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { + ERR_FAIL_COND_V_MSG(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER, "Invalid bind IP."); + ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The local port number must be between 0 and 65535 (inclusive)."); + + ENetAddress address; + memset(&address, 0, sizeof(address)); + address.port = p_port; +#ifdef GODOT_ENET + if (p_bind_address.is_wildcard()) { + address.wildcard = 1; + } else { + enet_address_set_ip(&address, p_bind_address.get_ipv6(), 16); + } +#else + if (p_bind_address.is_wildcard()) { + address.host = 0; + } else { + ERR_FAIL_COND_V(!p_bind_address.is_ipv4(), ERR_INVALID_PARAMETER); + address.host = *(uint32_t *)p_bind_address.get_ipv4(); + } +#endif + return _create(&address, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth); +} + +Error ENetConnection::create_host(int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { + return _create(nullptr, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth); +} + +void ENetConnection::destroy() { + ERR_FAIL_COND_MSG(!host, "Host already destroyed"); + for (List<Ref<ENetPacketPeer>>::Element *E = peers.front(); E; E = E->next()) { + E->get()->_on_disconnect(); + } + peers.clear(); + enet_host_destroy(host); + host = nullptr; +} + +Ref<ENetPacketPeer> ENetConnection::connect_to_host(const String &p_address, int p_port, int p_channels, int p_data) { + Ref<ENetPacketPeer> out; + ERR_FAIL_COND_V_MSG(!host, out, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_V_MSG(peers.size(), out, "The ENetConnection is already connected to a peer."); + ERR_FAIL_COND_V_MSG(p_port < 1 || p_port > 65535, out, "The remote port number must be between 1 and 65535 (inclusive)."); + + IPAddress ip; + if (p_address.is_valid_ip_address()) { + ip = p_address; + } else { +#ifdef GODOT_ENET + ip = IP::get_singleton()->resolve_hostname(p_address); +#else + ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4); +#endif + ERR_FAIL_COND_V_MSG(!ip.is_valid(), out, "Couldn't resolve the server IP address or domain name."); + } + + ENetAddress address; +#ifdef GODOT_ENET + enet_address_set_ip(&address, ip.get_ipv6(), 16); +#else + ERR_FAIL_COND_V_MSG(!ip.is_ipv4(), out, "Connecting to an IPv6 server isn't supported when using vanilla ENet. Recompile Godot with the bundled ENet library."); + address.host = *(uint32_t *)ip.get_ipv4(); +#endif + address.port = p_port; + + // Initiate connection, allocating enough channels + ENetPeer *peer = enet_host_connect(host, &address, p_channels > 0 ? p_channels : ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, p_data); + + if (peer == nullptr) { + return nullptr; + } + out = Ref<ENetPacketPeer>(memnew(ENetPacketPeer(peer))); + peers.push_back(out); + return out; +} + +ENetConnection::EventType ENetConnection::service(int p_timeout, Event &r_event) { + ERR_FAIL_COND_V_MSG(!host, EVENT_ERROR, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_V(r_event.peer.is_valid(), EVENT_ERROR); + + // Drop peers that have already been disconnected. + // NOTE: Forcibly disconnected peers (i.e. peers disconnected via + // enet_peer_disconnect*) do not trigger DISCONNECTED events. + List<Ref<ENetPacketPeer>>::Element *E = peers.front(); + while (E) { + if (!E->get()->is_active()) { + peers.erase(E->get()); + } + E = E->next(); + } + + ENetEvent event; + int ret = enet_host_service(host, &event, p_timeout); + + if (ret < 0) { + return EVENT_ERROR; + } else if (ret == 0) { + return EVENT_NONE; + } + switch (event.type) { + case ENET_EVENT_TYPE_CONNECT: { + if (event.peer->data == nullptr) { + Ref<ENetPacketPeer> pp = memnew(ENetPacketPeer(event.peer)); + peers.push_back(pp); + } + r_event.peer = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data); + r_event.data = event.data; + return EVENT_CONNECT; + } break; + case ENET_EVENT_TYPE_DISCONNECT: { + // A peer disconnected. + if (event.peer->data != nullptr) { + Ref<ENetPacketPeer> pp = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data); + pp->_on_disconnect(); + peers.erase(pp); + r_event.peer = pp; + r_event.data = event.data; + return EVENT_DISCONNECT; + } + return EVENT_ERROR; + } break; + case ENET_EVENT_TYPE_RECEIVE: { + // Packet reveived. + if (event.peer->data != nullptr) { + Ref<ENetPacketPeer> pp = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data); + r_event.peer = Ref<ENetPacketPeer>((ENetPacketPeer *)event.peer->data); + r_event.channel_id = event.channelID; + r_event.packet = event.packet; + return EVENT_RECEIVE; + } + return EVENT_ERROR; + } break; + case ENET_EVENT_TYPE_NONE: + return EVENT_NONE; + default: + return EVENT_NONE; + } +} + +void ENetConnection::flush() { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_flush(host); +} + +void ENetConnection::bandwidth_limit(int p_in_bandwidth, int p_out_bandwidth) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_bandwidth_limit(host, p_in_bandwidth, p_out_bandwidth); +} + +void ENetConnection::channel_limit(int p_max_channels) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_channel_limit(host, p_max_channels); +} + +void ENetConnection::bandwidth_throttle() { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_bandwidth_throttle(host); +} + +void ENetConnection::compress(CompressionMode p_mode) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + Compressor::setup(host, p_mode); +} + +double ENetConnection::pop_statistic(HostStatistic p_stat) { + ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active."); + uint32_t *ptr = nullptr; + switch (p_stat) { + case HOST_TOTAL_SENT_DATA: + ptr = &(host->totalSentData); + break; + case HOST_TOTAL_SENT_PACKETS: + ptr = &(host->totalSentPackets); + break; + case HOST_TOTAL_RECEIVED_DATA: + ptr = &(host->totalReceivedData); + break; + case HOST_TOTAL_RECEIVED_PACKETS: + ptr = &(host->totalReceivedPackets); + break; + } + ERR_FAIL_COND_V_MSG(ptr == nullptr, 0, "Invalid statistic: " + itos(p_stat)); + uint32_t ret = *ptr; + *ptr = 0; + return ret; +} + +int ENetConnection::get_max_channels() const { + ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active."); + return host->channelLimit; +} + +int ENetConnection::get_local_port() const { + ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_V_MSG(!(host->socket), 0, "The ENetConnection instance isn't currently bound"); + ENetAddress address; + ERR_FAIL_COND_V_MSG(enet_socket_get_address(host->socket, &address), 0, "Unable to get socket address"); + return address.port; +} + +void ENetConnection::get_peers(List<Ref<ENetPacketPeer>> &r_peers) { + for (const Ref<ENetPacketPeer> &I : peers) { + r_peers.push_back(I); + } +} + +Array ENetConnection::_get_peers() { + ERR_FAIL_COND_V_MSG(!host, Array(), "The ENetConnection instance isn't currently active."); + Array out; + for (const Ref<ENetPacketPeer> &I : peers) { + out.push_back(I); + } + return out; +} + +Error ENetConnection::dtls_server_setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert) { +#ifdef GODOT_ENET + ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active."); + return enet_host_dtls_server_setup(host, p_key.ptr(), p_cert.ptr()) ? FAILED : OK; +#else + ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build."); +#endif +} + +void ENetConnection::refuse_new_connections(bool p_refuse) { +#ifdef GODOT_ENET + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_refuse_new_connections(host, p_refuse); +#else + ERR_FAIL_MSG("ENet DTLS support not available in this build."); +#endif +} + +Error ENetConnection::dtls_client_setup(Ref<X509Certificate> p_cert, const String &p_hostname, bool p_verify) { +#ifdef GODOT_ENET + ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active."); + return enet_host_dtls_client_setup(host, p_cert.ptr(), p_verify, p_hostname.utf8().get_data()) ? FAILED : OK; +#else + ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build."); +#endif +} + +Error ENetConnection::_create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { + ERR_FAIL_COND_V_MSG(host != nullptr, ERR_ALREADY_IN_USE, "The ENetConnection instance is already active."); + ERR_FAIL_COND_V_MSG(p_max_peers < 1 || p_max_peers > 4095, ERR_INVALID_PARAMETER, "The number of clients must be set between 1 and 4095 (inclusive)."); + ERR_FAIL_COND_V_MSG(p_max_channels < 0 || p_max_channels > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, ERR_INVALID_PARAMETER, "Invalid channel count. Must be between 0 and 255 (0 means maximum, i.e. 255)"); + ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); + ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); + + host = enet_host_create(p_address /* the address to bind the server host to */, + p_max_peers /* allow up to p_max_peers connections */, + p_max_channels /* allow up to p_max_channel to be used */, + p_in_bandwidth /* limit incoming bandwidth if > 0 */, + p_out_bandwidth /* limit outgoing bandwidth if > 0 */); + + ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create an ENet host."); + return OK; +} + +Array ENetConnection::_service(int p_timeout) { + Array out; + Event event; + Ref<ENetPacketPeer> peer; + EventType ret = service(p_timeout, event); + out.push_back(ret); + out.push_back(event.peer); + out.push_back(event.data); + out.push_back(event.channel_id); + if (event.packet && event.peer.is_valid()) { + event.peer->_queue_packet(event.packet); + } + return out; +} + +void ENetConnection::_broadcast(int p_channel, PackedByteArray p_packet, int p_flags) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_MSG(p_channel < 0 || p_channel > (int)host->channelLimit, "Invalid channel"); + ERR_FAIL_COND_MSG(p_flags & ~ENetPacketPeer::FLAG_ALLOWED, "Invalid flags"); + ENetPacket *pkt = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags); + broadcast(p_channel, pkt); +} + +void ENetConnection::_bind_methods() { + ClassDB::bind_method(D_METHOD("create_host_bound", "bind_address", "bind_port", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host_bound, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("create_host", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("destroy"), &ENetConnection::destroy); + ClassDB::bind_method(D_METHOD("connect_to_host", "address", "port", "channels", "data"), &ENetConnection::connect_to_host, DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("service", "timeout"), &ENetConnection::_service, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("flush"), &ENetConnection::flush); + ClassDB::bind_method(D_METHOD("bandwidth_limit", "in_bandwidth", "out_bandwidth"), &ENetConnection::bandwidth_limit, DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("channel_limit", "limit"), &ENetConnection::channel_limit); + ClassDB::bind_method(D_METHOD("broadcast", "channel", "packet", "flags"), &ENetConnection::_broadcast); + ClassDB::bind_method(D_METHOD("compress", "mode"), &ENetConnection::compress); + ClassDB::bind_method(D_METHOD("dtls_server_setup", "key", "certificate"), &ENetConnection::dtls_server_setup); + ClassDB::bind_method(D_METHOD("dtls_client_setup", "certificate", "hostname", "verify"), &ENetConnection::dtls_client_setup, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("refuse_new_connections", "refuse"), &ENetConnection::refuse_new_connections); + ClassDB::bind_method(D_METHOD("pop_statistic", "statistic"), &ENetConnection::pop_statistic); + ClassDB::bind_method(D_METHOD("get_max_channels"), &ENetConnection::get_max_channels); + ClassDB::bind_method(D_METHOD("get_local_port"), &ENetConnection::get_local_port); + ClassDB::bind_method(D_METHOD("get_peers"), &ENetConnection::_get_peers); + + BIND_ENUM_CONSTANT(COMPRESS_NONE); + BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER); + BIND_ENUM_CONSTANT(COMPRESS_FASTLZ); + BIND_ENUM_CONSTANT(COMPRESS_ZLIB); + BIND_ENUM_CONSTANT(COMPRESS_ZSTD); + + BIND_ENUM_CONSTANT(EVENT_ERROR); + BIND_ENUM_CONSTANT(EVENT_NONE); + BIND_ENUM_CONSTANT(EVENT_CONNECT); + BIND_ENUM_CONSTANT(EVENT_DISCONNECT); + BIND_ENUM_CONSTANT(EVENT_RECEIVE); + + BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_DATA); + BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_PACKETS); + BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_DATA); + BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_PACKETS); +} + +ENetConnection::~ENetConnection() { + if (host) { + destroy(); + } +} + +size_t ENetConnection::Compressor::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) { + Compressor *compressor = (Compressor *)(context); + + if (size_t(compressor->src_mem.size()) < inLimit) { + compressor->src_mem.resize(inLimit); + } + + int total = inLimit; + int ofs = 0; + while (total) { + for (size_t i = 0; i < inBufferCount; i++) { + int to_copy = MIN(total, int(inBuffers[i].dataLength)); + memcpy(&compressor->src_mem.write[ofs], inBuffers[i].data, to_copy); + ofs += to_copy; + total -= to_copy; + } + } + + Compression::Mode mode; + + switch (compressor->mode) { + case COMPRESS_FASTLZ: { + mode = Compression::MODE_FASTLZ; + } break; + case COMPRESS_ZLIB: { + mode = Compression::MODE_DEFLATE; + } break; + case COMPRESS_ZSTD: { + mode = Compression::MODE_ZSTD; + } break; + default: { + ERR_FAIL_V_MSG(0, vformat("Invalid ENet compression mode: %d", compressor->mode)); + } + } + + int req_size = Compression::get_max_compressed_buffer_size(ofs, mode); + if (compressor->dst_mem.size() < req_size) { + compressor->dst_mem.resize(req_size); + } + int ret = Compression::compress(compressor->dst_mem.ptrw(), compressor->src_mem.ptr(), ofs, mode); + + if (ret < 0) { + return 0; + } + + if (ret > int(outLimit)) { + return 0; // Do not bother + } + + memcpy(outData, compressor->dst_mem.ptr(), ret); + + return ret; +} + +size_t ENetConnection::Compressor::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) { + Compressor *compressor = (Compressor *)(context); + int ret = -1; + switch (compressor->mode) { + case COMPRESS_FASTLZ: { + ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ); + } break; + case COMPRESS_ZLIB: { + ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE); + } break; + case COMPRESS_ZSTD: { + ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD); + } break; + default: { + } + } + if (ret < 0) { + return 0; + } else { + return ret; + } +} + +void ENetConnection::Compressor::setup(ENetHost *p_host, CompressionMode p_mode) { + ERR_FAIL_COND(!p_host); + switch (p_mode) { + case COMPRESS_NONE: { + enet_host_compress(p_host, nullptr); + } break; + case COMPRESS_RANGE_CODER: { + enet_host_compress_with_range_coder(p_host); + } break; + case COMPRESS_FASTLZ: + case COMPRESS_ZLIB: + case COMPRESS_ZSTD: { + Compressor *compressor = memnew(Compressor(p_mode)); + enet_host_compress(p_host, &(compressor->enet_compressor)); + } break; + } +} + +ENetConnection::Compressor::Compressor(CompressionMode p_mode) { + mode = p_mode; + enet_compressor.context = this; + enet_compressor.compress = enet_compress; + enet_compressor.decompress = enet_decompress; + enet_compressor.destroy = enet_compressor_destroy; +} diff --git a/modules/enet/enet_connection.h b/modules/enet/enet_connection.h new file mode 100644 index 0000000000..0f7744953e --- /dev/null +++ b/modules/enet/enet_connection.h @@ -0,0 +1,138 @@ +/*************************************************************************/ +/* enet_connection.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 ENET_CONNECTION_H +#define ENET_CONNECTION_H + +#include "core/object/ref_counted.h" + +#include "core/crypto/crypto.h" +#include "enet_packet_peer.h" + +#include <enet/enet.h> + +class ENetConnection : public RefCounted { + GDCLASS(ENetConnection, RefCounted); + +public: + enum CompressionMode { + COMPRESS_NONE = 0, + COMPRESS_RANGE_CODER, + COMPRESS_FASTLZ, + COMPRESS_ZLIB, + COMPRESS_ZSTD, + }; + + enum HostStatistic { + HOST_TOTAL_SENT_DATA, + HOST_TOTAL_SENT_PACKETS, + HOST_TOTAL_RECEIVED_DATA, + HOST_TOTAL_RECEIVED_PACKETS, + }; + + enum EventType { + EVENT_ERROR = -1, + EVENT_NONE = 0, + EVENT_CONNECT, + EVENT_DISCONNECT, + EVENT_RECEIVE, + }; + + struct Event { + Ref<ENetPacketPeer> peer; + enet_uint8 channel_id = 0; + enet_uint32 data = 0; + ENetPacket *packet = nullptr; + }; + +protected: + static void _bind_methods(); + +private: + ENetHost *host = nullptr; + List<Ref<ENetPacketPeer>> peers; + + Error _create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth); + Array _service(int p_timeout = 0); + void _broadcast(int p_channel, PackedByteArray p_packet, int p_flags); + Array _get_peers(); + + class Compressor { + private: + CompressionMode mode = COMPRESS_NONE; + Vector<uint8_t> src_mem; + Vector<uint8_t> dst_mem; + ENetCompressor enet_compressor; + + Compressor(CompressionMode mode); + + static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit); + static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit); + static void enet_compressor_destroy(void *context) { + memdelete((Compressor *)context); + } + + public: + static void setup(ENetHost *p_host, CompressionMode p_mode); + }; + +public: + void broadcast(enet_uint8 p_channel, ENetPacket *p_packet); + Error create_host_bound(const IPAddress &p_bind_address = IPAddress("*"), int p_port = 0, int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0); + Error create_host(int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0); + void destroy(); + Ref<ENetPacketPeer> connect_to_host(const String &p_address, int p_port, int p_channels, int p_data = 0); + EventType service(int p_timeout, Event &r_event); + void flush(); + void bandwidth_limit(int p_in_bandwidth = 0, int p_out_bandwidth = 0); + void channel_limit(int p_max_channels); + void bandwidth_throttle(); + void compress(CompressionMode p_mode); + double pop_statistic(HostStatistic p_stat); + int get_max_channels() const; + + // Extras + void get_peers(List<Ref<ENetPacketPeer>> &r_peers); + int get_local_port() const; + + // Godot additions + Error dtls_server_setup(Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert); + Error dtls_client_setup(Ref<X509Certificate> p_cert, const String &p_hostname, bool p_verify = true); + void refuse_new_connections(bool p_refuse); + + ENetConnection() {} + ~ENetConnection(); +}; + +VARIANT_ENUM_CAST(ENetConnection::CompressionMode); +VARIANT_ENUM_CAST(ENetConnection::EventType); +VARIANT_ENUM_CAST(ENetConnection::HostStatistic); + +#endif // ENET_CONNECTION_H diff --git a/modules/enet/enet_multiplayer_peer.cpp b/modules/enet/enet_multiplayer_peer.cpp new file mode 100644 index 0000000000..38ca38385c --- /dev/null +++ b/modules/enet/enet_multiplayer_peer.cpp @@ -0,0 +1,687 @@ +/*************************************************************************/ +/* enet_multiplayer_peer.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "enet_multiplayer_peer.h" +#include "core/io/ip.h" +#include "core/io/marshalls.h" +#include "core/os/os.h" + +void ENetMultiplayerPeer::set_transfer_channel(int p_channel) { + transfer_channel = p_channel; +} + +int ENetMultiplayerPeer::get_transfer_channel() const { + return transfer_channel; +} + +void ENetMultiplayerPeer::set_transfer_mode(TransferMode p_mode) { + transfer_mode = p_mode; +} + +MultiplayerPeer::TransferMode ENetMultiplayerPeer::get_transfer_mode() const { + return transfer_mode; +} + +void ENetMultiplayerPeer::set_target_peer(int p_peer) { + target_peer = p_peer; +} + +int ENetMultiplayerPeer::get_packet_peer() 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); + + return incoming_packets.front()->get().from; +} + +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."); + Ref<ENetConnection> host; + host.instantiate(); + Error err = host->create_host_bound(bind_ip, p_port, p_max_clients, 0, p_max_channels > 0 ? p_max_channels + SYSCH_MAX : 0, p_out_bandwidth); + if (err != OK) { + return err; + } + + active_mode = MODE_SERVER; + refuse_connections = false; + unique_id = 1; + connection_status = CONNECTION_CONNECTED; + hosts[0] = host; + return OK; +} + +Error ENetMultiplayerPeer::create_client(const String &p_address, int p_port, int p_channel_count, int p_in_bandwidth, int p_out_bandwidth, int p_local_port) { + ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); + Ref<ENetConnection> host; + host.instantiate(); + Error err; + if (p_local_port) { + err = host->create_host_bound(bind_ip, p_local_port, 1, 0, p_in_bandwidth, p_out_bandwidth); + } else { + err = host->create_host(1, 0, p_in_bandwidth, p_out_bandwidth); + } + if (err != OK) { + return err; + } + + unique_id = generate_unique_id(); + + Ref<ENetPacketPeer> peer = host->connect_to_host(p_address, p_port, p_channel_count > 0 ? p_channel_count + SYSCH_MAX : 0, unique_id); + if (peer.is_null()) { + host->destroy(); + ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server."); + } + + // Need to wait for CONNECT event. + connection_status = CONNECTION_CONNECTING; + active_mode = MODE_CLIENT; + refuse_connections = false; + peers[1] = peer; + hosts[0] = host; + + return OK; +} + +Error ENetMultiplayerPeer::create_mesh(int p_id) { + ERR_FAIL_COND_V_MSG(p_id <= 0, ERR_INVALID_PARAMETER, "The unique ID must be greater then 0"); + ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); + active_mode = MODE_MESH; + refuse_connections = false; + unique_id = p_id; + connection_status = CONNECTION_CONNECTED; + return OK; +} + +Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) { + ERR_FAIL_COND_V(p_host.is_null(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V_MSG(active_mode != MODE_MESH, ERR_UNCONFIGURED, "The multiplayer instance is not configured as a mesh. Call 'create_mesh' first."); + List<Ref<ENetPacketPeer>> host_peers; + p_host->get_peers(host_peers); + ERR_FAIL_COND_V_MSG(host_peers.size() != 1 || host_peers[0]->get_state() != ENetPacketPeer::STATE_CONNECTED, ERR_INVALID_PARAMETER, "The provided host must have excatly one peer in the connected state."); + hosts[p_id] = p_host; + peers[p_id] = host_peers[0]; + emit_signal(SNAME("peer_connected"), p_id); + return OK; +} + +bool ENetMultiplayerPeer::_poll_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 true; + } + switch (ret) { + case ENetConnection::EVENT_CONNECT: { + if (refuse_connections) { + event.peer->reset(); + return false; + } + // Client joined with invalid ID, probably trying to exploit us. + if (event.data < 2 || peers.has((int)event.data)) { + event.peer->reset(); + return false; + } + int id = event.data; + event.peer->set_meta(SNAME("_net_id"), id); + peers[id] = event.peer; + + emit_signal(SNAME("peer_connected"), id); + if (server_relay) { + _notify_peers(id, true); + } + return false; + } + case ENetConnection::EVENT_DISCONNECT: { + int id = 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 (event.channel_id == SYSCH_CONFIG) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Only server can send config messages"); + } else { + if (event.packet->dataLength < 8) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Invalid packet size"); + } + + uint32_t source = decode_uint32(&event.packet->data[0]); + int target = decode_uint32(&event.packet->data[4]); + + uint32_t id = event.peer->get_meta(SNAME("_net_id")); + // Someone is cheating and trying to fake the source! + if (source != id) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Someone is cheating and trying to fake the source!"); + } + + Packet packet; + packet.packet = event.packet; + packet.channel = 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, event.channel_id, event.packet); + packet.packet->referenceCount--; + _destroy_unused(event.packet); + } + // Destroy packet later + } + return false; + } + default: + return true; + } +} + +bool ENetMultiplayerPeer::_poll_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(); + return true; + } + ENetConnection::Event event; + ENetConnection::EventType ret = hosts[0]->service(0, event); + if (ret == ENetConnection::EVENT_ERROR) { + return true; + } + switch (ret) { + 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 (event.channel_id == SYSCH_CONFIG) { + // Config message + if (event.packet->dataLength != 8) { + _destroy_unused(event.packet); + ERR_FAIL_V(false); + } + + int msg = decode_uint32(&event.packet->data[0]); + int id = decode_uint32(&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(event.packet); + } else { + if (event.packet->dataLength < 8) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Invalid packet size"); + } + + uint32_t source = decode_uint32(&event.packet->data[0]); + Packet packet; + packet.packet = event.packet; + packet.from = source; + packet.channel = event.channel_id; + + packet.packet->referenceCount++; + incoming_packets.push_back(packet); + // Destroy packet later + } + return false; + } + default: + return true; + } +} + +bool ENetMultiplayerPeer::_poll_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); + } + } + } + bool should_stop = true; + 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; + } + switch (ret) { + case ENetConnection::EVENT_CONNECT: + should_stop = false; + event.peer->reset(); + break; + case ENetConnection::EVENT_DISCONNECT: + should_stop = false; + if (peers.has(E.key)) { + emit_signal(SNAME("peer_disconnected"), E.key); + peers.erase(E.key); + } + hosts.erase(E.key); + break; + case ENetConnection::EVENT_RECEIVE: { + should_stop = false; + if (event.packet->dataLength < 8) { + _destroy_unused(event.packet); + ERR_CONTINUE_MSG(true, "Invalid packet size"); + } + + Packet packet; + packet.packet = event.packet; + packet.from = E.key; + packet.channel = event.channel_id; + + packet.packet->referenceCount++; + incoming_packets.push_back(packet); + } break; + default: + break; // Nothing to do + } + } + return should_stop; +} + +void ENetMultiplayerPeer::poll() { + ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active."); + + _pop_current_packet(); + + while (true) { + switch (active_mode) { + case MODE_CLIENT: + if (_poll_client()) { + return; + } + break; + case MODE_SERVER: + if (_poll_server()) { + return; + } + break; + case MODE_MESH: + if (_poll_mesh()) { + return; + } + break; + default: + return; + } + } +} + +bool ENetMultiplayerPeer::is_server() const { + return active_mode == MODE_SERVER; +} + +void ENetMultiplayerPeer::close_connection(uint32_t wait_usec) { + ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active."); + + _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; + } + } + + 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 + } + } + + active_mode = MODE_NONE; + incoming_packets.clear(); + peers.clear(); + hosts.clear(); + unique_id = 0; + connection_status = CONNECTION_DISCONNECTED; +} + +int ENetMultiplayerPeer::get_available_packet_count() const { + return incoming_packets.size(); +} + +Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available."); + + _pop_current_packet(); + + 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; + + return OK; +} + +Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V_MSG(!_is_active(), ERR_UNCONFIGURED, "The multiplayer instance isn't currently active."); + ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client."); + ERR_FAIL_COND_V_MSG(target_peer != 0 && !peers.has(ABS(target_peer)), ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer)); + ERR_FAIL_COND_V(active_mode == MODE_CLIENT && !peers.has(1), ERR_BUG); + + int packet_flags = 0; + int channel = SYSCH_RELIABLE; + if (transfer_channel > 0) { + channel = SYSCH_MAX + transfer_channel - 1; + } else { + switch (transfer_mode) { + case TRANSFER_MODE_UNRELIABLE: { + packet_flags = ENET_PACKET_FLAG_UNSEQUENCED; + channel = SYSCH_UNRELIABLE; + } break; + case TRANSFER_MODE_UNRELIABLE_ORDERED: { + packet_flags = 0; + channel = SYSCH_UNRELIABLE; + } break; + case TRANSFER_MODE_RELIABLE: { + packet_flags = ENET_PACKET_FLAG_RELIABLE; + channel = SYSCH_RELIABLE; + } break; + } + } + + 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); + + if (is_server()) { + if (target_peer == 0) { + hosts[0]->broadcast(channel, packet); + + } else if (target_peer < 0) { + // Send to all but one and make copies for sending. + int exclude = -target_peer; + for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { + if (E.key == exclude) { + continue; + } + E.value->send(channel, packet); + } + _destroy_unused(packet); + } else { + peers[target_peer]->send(channel, packet); + } + ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG); + hosts[0]->flush(); + + } else if (active_mode == MODE_CLIENT) { + peers[1]->send(channel, packet); // Send to server for broadcast. + ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG); + hosts[0]->flush(); + + } else { + if (target_peer <= 0) { + int exclude = ABS(target_peer); + for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) { + if (E.key == exclude) { + continue; + } + E.value->send(channel, packet); + ERR_CONTINUE(!hosts.has(E.key)); + hosts[E.key]->flush(); + } + _destroy_unused(packet); + } else { + peers[target_peer]->send(channel, packet); + ERR_FAIL_COND_V(!hosts.has(target_peer), ERR_BUG); + hosts[target_peer]->flush(); + } + } + + return OK; +} + +int ENetMultiplayerPeer::get_max_packet_size() const { + return 1 << 24; // Anything is good +} + +void ENetMultiplayerPeer::_pop_current_packet() { + if (current_packet.packet) { + current_packet.packet->referenceCount--; + _destroy_unused(current_packet.packet); + current_packet.packet = nullptr; + current_packet.from = 0; + current_packet.channel = -1; + } +} + +MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() const { + return connection_status; +} + +int ENetMultiplayerPeer::get_unique_id() const { + ERR_FAIL_COND_V_MSG(!_is_active(), 0, "The multiplayer instance isn't currently active."); + return unique_id; +} + +void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enable) { + refuse_connections = p_enable; +#ifdef GODOT_ENET + if (_is_active()) { + for (KeyValue<int, Ref<ENetConnection>> &E : hosts) { + E.value->refuse_new_connections(p_enable); + } + } +#endif +} + +bool ENetMultiplayerPeer::is_refusing_new_connections() const { + return refuse_connections; +} + +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); + return hosts[0]; +} + +Ref<ENetPacketPeer> ENetMultiplayerPeer::get_peer(int p_id) const { + ERR_FAIL_COND_V(!_is_active(), nullptr); + ERR_FAIL_COND_V(!peers.has(p_id), nullptr); + ERR_FAIL_COND_V(active_mode == MODE_CLIENT && p_id != 1, nullptr); + return peers[p_id]; +} + +void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) { + if (p_packet->referenceCount == 0) { + enet_packet_destroy(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"); +} + +ENetMultiplayerPeer::ENetMultiplayerPeer() { + bind_ip = IPAddress("*"); +} + +ENetMultiplayerPeer::~ENetMultiplayerPeer() { + if (_is_active()) { + close_connection(); + } +} + +// Sets IP for ENet to bind when using create_server or create_client +// if no IP is set, then ENet bind to ENET_HOST_ANY +void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) { + ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip))); + + bind_ip = p_ip; +} diff --git a/modules/enet/networked_multiplayer_enet.h b/modules/enet/enet_multiplayer_peer.h index b99b14d218..78e280db7c 100644 --- a/modules/enet/networked_multiplayer_enet.h +++ b/modules/enet/enet_multiplayer_peer.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* networked_multiplayer_enet.h */ +/* enet_multiplayer_peer.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -32,22 +32,13 @@ #define NETWORKED_MULTIPLAYER_ENET_H #include "core/crypto/crypto.h" -#include "core/io/compression.h" -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" +#include "enet_connection.h" #include <enet/enet.h> -class NetworkedMultiplayerENet : public NetworkedMultiplayerPeer { - GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer); - -public: - enum CompressionMode { - COMPRESS_NONE, - COMPRESS_RANGE_CODER, - COMPRESS_FASTLZ, - COMPRESS_ZLIB, - COMPRESS_ZSTD - }; +class ENetMultiplayerPeer : public MultiplayerPeer { + GDCLASS(ENetMultiplayerPeer, MultiplayerPeer); private: enum { @@ -56,33 +47,34 @@ private: }; enum { - SYSCH_CONFIG, - SYSCH_RELIABLE, - SYSCH_UNRELIABLE, - SYSCH_MAX + SYSCH_CONFIG = 0, + SYSCH_RELIABLE = 1, + SYSCH_UNRELIABLE = 2, + SYSCH_MAX = 3 }; - bool active = false; - bool server = false; + enum Mode { + MODE_NONE, + MODE_SERVER, + MODE_CLIENT, + MODE_MESH, + }; + + Mode active_mode = MODE_NONE; uint32_t unique_id = 0; int target_peer = 0; + int transfer_channel = 0; TransferMode transfer_mode = TRANSFER_MODE_RELIABLE; - int transfer_channel = -1; - int channel_count = SYSCH_MAX; - bool always_ordered = false; - - ENetEvent event; - ENetPeer *peer = nullptr; - ENetHost *host = nullptr; bool refuse_connections = false; bool server_relay = true; ConnectionStatus connection_status = CONNECTION_DISCONNECTED; - Map<int, ENetPeer *> peer_map; + Map<int, Ref<ENetConnection>> hosts; + Map<int, Ref<ENetPacketPeer>> peers; struct Packet { ENetPacket *packet = nullptr; @@ -90,47 +82,38 @@ private: int channel = 0; }; - CompressionMode compression_mode = COMPRESS_NONE; - List<Packet> incoming_packets; Packet current_packet; - uint32_t _gen_unique_id() const; void _pop_current_packet(); + bool _poll_server(); + bool _poll_client(); + bool _poll_mesh(); + 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 _destroy_unused(ENetPacket *p_packet); + _FORCE_INLINE_ bool _is_active() const { return active_mode != MODE_NONE; } - Vector<uint8_t> src_compressor_mem; - Vector<uint8_t> dst_compressor_mem; - - ENetCompressor enet_compressor; - static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit); - static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit); - static void enet_compressor_destroy(void *context); - void _setup_compressor(); - - IP_Address bind_ip; - - bool dtls_enabled = false; - Ref<CryptoKey> dtls_key; - Ref<X509Certificate> dtls_cert; - bool dtls_verify = true; + IPAddress bind_ip; protected: static void _bind_methods(); public: + virtual void set_transfer_channel(int p_channel) override; + virtual int get_transfer_channel() const override; + virtual void set_transfer_mode(TransferMode p_mode) override; virtual TransferMode get_transfer_mode() const override; virtual void set_target_peer(int p_peer) override; virtual int get_packet_peer() const override; - virtual IP_Address get_peer_address(int p_peer_id) const; - virtual int get_peer_port(int p_peer_id) const; - void set_peer_timeout(int p_peer_id, int p_timeout_limit, int p_timeout_min, int p_timeout_max); - - Error create_server(int p_port, int p_max_clients = 32, int p_in_bandwidth = 0, int p_out_bandwidth = 0); - Error create_client(const String &p_address, int p_port, int p_in_bandwidth = 0, int p_out_bandwidth = 0, int p_client_port = 0); + Error create_server(int p_port, int p_max_clients = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0); + Error create_client(const String &p_address, int p_port, int p_channel_count = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0, int p_local_port = 0); + 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); @@ -153,32 +136,15 @@ public: virtual int get_unique_id() const override; - void set_compression_mode(CompressionMode p_mode); - CompressionMode get_compression_mode() const; - - int get_packet_channel() const; - int get_last_packet_channel() const; - void set_transfer_channel(int p_channel); - int get_transfer_channel() const; - void set_channel_count(int p_channel); - int get_channel_count() const; - void set_always_ordered(bool p_ordered); - bool is_always_ordered() const; + void set_bind_ip(const IPAddress &p_ip); void set_server_relay_enabled(bool p_enabled); bool is_server_relay_enabled() const; - NetworkedMultiplayerENet(); - ~NetworkedMultiplayerENet(); + Ref<ENetConnection> get_host() const; + Ref<ENetPacketPeer> get_peer(int p_id) const; - void set_bind_ip(const IP_Address &p_ip); - void set_dtls_enabled(bool p_enabled); - bool is_dtls_enabled() const; - void set_dtls_verify_enabled(bool p_enabled); - bool is_dtls_verify_enabled() const; - void set_dtls_key(Ref<CryptoKey> p_key); - void set_dtls_certificate(Ref<X509Certificate> p_cert); + ENetMultiplayerPeer(); + ~ENetMultiplayerPeer(); }; -VARIANT_ENUM_CAST(NetworkedMultiplayerENet::CompressionMode); - #endif // NETWORKED_MULTIPLAYER_ENET_H diff --git a/modules/enet/enet_packet_peer.cpp b/modules/enet/enet_packet_peer.cpp new file mode 100644 index 0000000000..d7d2ec9ebe --- /dev/null +++ b/modules/enet/enet_packet_peer.cpp @@ -0,0 +1,263 @@ +/*************************************************************************/ +/* enet_packet_peer.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "enet_packet_peer.h" + +void ENetPacketPeer::peer_disconnect(int p_data) { + ERR_FAIL_COND(!peer); + enet_peer_disconnect(peer, p_data); +} + +void ENetPacketPeer::peer_disconnect_later(int p_data) { + ERR_FAIL_COND(!peer); + enet_peer_disconnect_later(peer, p_data); +} + +void ENetPacketPeer::peer_disconnect_now(int p_data) { + ERR_FAIL_COND(!peer); + enet_peer_disconnect_now(peer, p_data); + _on_disconnect(); +} + +void ENetPacketPeer::ping() { + ERR_FAIL_COND(!peer); + enet_peer_ping(peer); +} + +void ENetPacketPeer::ping_interval(int p_interval) { + ERR_FAIL_COND(!peer); + enet_peer_ping_interval(peer, p_interval); +} + +int ENetPacketPeer::send(uint8_t p_channel, ENetPacket *p_packet) { + ERR_FAIL_COND_V(peer == nullptr, -1); + ERR_FAIL_COND_V(p_packet == nullptr, -1); + ERR_FAIL_COND_V_MSG(p_channel >= peer->channelCount, -1, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)peer->channelCount)); + return enet_peer_send(peer, p_channel, p_packet); +} + +void ENetPacketPeer::reset() { + ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected"); + enet_peer_reset(peer); + _on_disconnect(); +} + +void ENetPacketPeer::throttle_configure(int p_interval, int p_acceleration, int p_deceleration) { + ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected"); + enet_peer_throttle_configure(peer, p_interval, p_acceleration, p_deceleration); +} + +void ENetPacketPeer::set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max) { + ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected"); + ERR_FAIL_COND_MSG(p_timeout > p_timeout_min || p_timeout_min > p_timeout_max, "Timeout limit must be less than minimum timeout, which itself must be less then maximum timeout"); + enet_peer_timeout(peer, p_timeout, p_timeout_min, p_timeout_max); +} + +int ENetPacketPeer::get_max_packet_size() const { + return 1 << 24; +} + +int ENetPacketPeer::get_available_packet_count() const { + return packet_queue.size(); +} + +Error ENetPacketPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!packet_queue.size(), ERR_UNAVAILABLE); + if (last_packet) { + enet_packet_destroy(last_packet); + last_packet = nullptr; + } + last_packet = packet_queue.front()->get(); + packet_queue.pop_front(); + *r_buffer = (const uint8_t *)(last_packet->data); + r_buffer_size = last_packet->dataLength; + return OK; +} + +Error ENetPacketPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED); + ENetPacket *packet = enet_packet_create(p_buffer, p_buffer_size, ENET_PACKET_FLAG_RELIABLE); + return send(0, packet) < 0 ? FAILED : OK; +} + +IPAddress ENetPacketPeer::get_remote_address() const { + ERR_FAIL_COND_V(!peer, IPAddress()); + IPAddress out; +#ifdef GODOT_ENET + out.set_ipv6((uint8_t *)&(peer->address.host)); +#else + out.set_ipv4((uint8_t *)&(peer->address.host)); +#endif + return out; +} + +int ENetPacketPeer::get_remote_port() const { + ERR_FAIL_COND_V(!peer, 0); + return peer->address.port; +} + +bool ENetPacketPeer::is_active() const { + return peer != nullptr; +} + +double ENetPacketPeer::get_statistic(PeerStatistic p_stat) { + ERR_FAIL_COND_V(!peer, 0); + switch (p_stat) { + case PEER_PACKET_LOSS: + return peer->packetLoss; + case PEER_PACKET_LOSS_VARIANCE: + return peer->packetLossVariance; + case PEER_PACKET_LOSS_EPOCH: + return peer->packetLossEpoch; + case PEER_ROUND_TRIP_TIME: + return peer->roundTripTime; + case PEER_ROUND_TRIP_TIME_VARIANCE: + return peer->roundTripTimeVariance; + case PEER_LAST_ROUND_TRIP_TIME: + return peer->lastRoundTripTime; + case PEER_LAST_ROUND_TRIP_TIME_VARIANCE: + return peer->lastRoundTripTimeVariance; + case PEER_PACKET_THROTTLE: + return peer->packetThrottle; + case PEER_PACKET_THROTTLE_LIMIT: + return peer->packetThrottleLimit; + case PEER_PACKET_THROTTLE_COUNTER: + return peer->packetThrottleCounter; + case PEER_PACKET_THROTTLE_EPOCH: + return peer->packetThrottleEpoch; + case PEER_PACKET_THROTTLE_ACCELERATION: + return peer->packetThrottleAcceleration; + case PEER_PACKET_THROTTLE_DECELERATION: + return peer->packetThrottleDeceleration; + case PEER_PACKET_THROTTLE_INTERVAL: + return peer->packetThrottleInterval; + } + ERR_FAIL_V(0); +} + +ENetPacketPeer::PeerState ENetPacketPeer::get_state() const { + if (!is_active()) { + return STATE_DISCONNECTED; + } + return (PeerState)peer->state; +} + +int ENetPacketPeer::get_channels() const { + ERR_FAIL_COND_V_MSG(!peer, 0, "The ENetConnection instance isn't currently active."); + return peer->channelCount; +} + +void ENetPacketPeer::_on_disconnect() { + if (peer) { + peer->data = nullptr; + } + peer = nullptr; +} + +void ENetPacketPeer::_queue_packet(ENetPacket *p_packet) { + ERR_FAIL_COND(!peer); + packet_queue.push_back(p_packet); +} + +Error ENetPacketPeer::_send(int p_channel, PackedByteArray p_packet, int p_flags) { + ERR_FAIL_COND_V_MSG(peer == nullptr, ERR_UNCONFIGURED, "Peer not connected"); + ERR_FAIL_COND_V_MSG(p_channel < 0 || p_channel > (int)peer->channelCount, ERR_INVALID_PARAMETER, "Invalid channel"); + ERR_FAIL_COND_V_MSG(p_flags & ~FLAG_ALLOWED, ERR_INVALID_PARAMETER, "Invalid flags"); + ENetPacket *packet = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags); + return send(p_channel, packet) == 0 ? OK : FAILED; +} + +void ENetPacketPeer::_bind_methods() { + ClassDB::bind_method(D_METHOD("peer_disconnect", "data"), &ENetPacketPeer::peer_disconnect, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("peer_disconnect_later", "data"), &ENetPacketPeer::peer_disconnect_later, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("peer_disconnect_now", "data"), &ENetPacketPeer::peer_disconnect_now, DEFVAL(0)); + + ClassDB::bind_method(D_METHOD("ping"), &ENetPacketPeer::ping); + ClassDB::bind_method(D_METHOD("ping_interval", "ping_interval"), &ENetPacketPeer::ping_interval); + ClassDB::bind_method(D_METHOD("reset"), &ENetPacketPeer::reset); + ClassDB::bind_method(D_METHOD("send", "channel", "packet", "flags"), &ENetPacketPeer::_send); + ClassDB::bind_method(D_METHOD("throttle_configure", "interval", "acceleration", "deceleration"), &ENetPacketPeer::throttle_configure); + ClassDB::bind_method(D_METHOD("set_timeout", "timeout", "timeout_min", "timeout_max"), &ENetPacketPeer::set_timeout); + ClassDB::bind_method(D_METHOD("get_statistic", "statistic"), &ENetPacketPeer::get_statistic); + ClassDB::bind_method(D_METHOD("get_state"), &ENetPacketPeer::get_state); + ClassDB::bind_method(D_METHOD("get_channels"), &ENetPacketPeer::get_channels); + ClassDB::bind_method(D_METHOD("is_active"), &ENetPacketPeer::is_active); + + BIND_ENUM_CONSTANT(STATE_DISCONNECTED); + BIND_ENUM_CONSTANT(STATE_CONNECTING); + BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_CONNECT); + BIND_ENUM_CONSTANT(STATE_CONNECTION_PENDING); + BIND_ENUM_CONSTANT(STATE_CONNECTION_SUCCEEDED); + BIND_ENUM_CONSTANT(STATE_CONNECTED); + BIND_ENUM_CONSTANT(STATE_DISCONNECT_LATER); + BIND_ENUM_CONSTANT(STATE_DISCONNECTING); + BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_DISCONNECT); + BIND_ENUM_CONSTANT(STATE_ZOMBIE); + + BIND_ENUM_CONSTANT(PEER_PACKET_LOSS); + BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_VARIANCE); + BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_EPOCH); + BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME); + BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME_VARIANCE); + BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME); + BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME_VARIANCE); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_LIMIT); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_COUNTER); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_EPOCH); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_ACCELERATION); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_DECELERATION); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_INTERVAL); + + BIND_CONSTANT(PACKET_LOSS_SCALE); + BIND_CONSTANT(PACKET_THROTTLE_SCALE); + + BIND_CONSTANT(FLAG_RELIABLE); + BIND_CONSTANT(FLAG_UNSEQUENCED); + BIND_CONSTANT(FLAG_UNRELIABLE_FRAGMENT); +} + +ENetPacketPeer::ENetPacketPeer(ENetPeer *p_peer) { + peer = p_peer; + peer->data = this; +} + +ENetPacketPeer::~ENetPacketPeer() { + _on_disconnect(); + if (last_packet) { + enet_packet_destroy(last_packet); + last_packet = nullptr; + } + for (List<ENetPacket *>::Element *E = packet_queue.front(); E; E = E->next()) { + enet_packet_destroy(E->get()); + } + packet_queue.clear(); +} diff --git a/modules/enet/enet_packet_peer.h b/modules/enet/enet_packet_peer.h new file mode 100644 index 0000000000..9af004de2f --- /dev/null +++ b/modules/enet/enet_packet_peer.h @@ -0,0 +1,131 @@ +/*************************************************************************/ +/* enet_packet_peer.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 ENET_PACKET_PEER_H +#define ENET_PACKET_PEER_H + +#include "core/io/packet_peer.h" + +#include <enet/enet.h> + +class ENetPacketPeer : public PacketPeer { + GDCLASS(ENetPacketPeer, PacketPeer); + +private: + ENetPeer *peer = nullptr; + List<ENetPacket *> packet_queue; + ENetPacket *last_packet = nullptr; + + static void _bind_methods(); + Error _send(int p_channel, PackedByteArray p_packet, int p_flags); + +protected: + friend class ENetConnection; + // Internally used by ENetConnection during service, destroy, etc. + void _on_disconnect(); + void _queue_packet(ENetPacket *p_packet); + +public: + enum { + PACKET_THROTTLE_SCALE = ENET_PEER_PACKET_THROTTLE_SCALE, + PACKET_LOSS_SCALE = ENET_PEER_PACKET_LOSS_SCALE, + }; + + enum { + FLAG_RELIABLE = ENET_PACKET_FLAG_RELIABLE, + FLAG_UNSEQUENCED = ENET_PACKET_FLAG_UNSEQUENCED, + FLAG_UNRELIABLE_FRAGMENT = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, + FLAG_ALLOWED = ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, + }; + + enum PeerState { + STATE_DISCONNECTED = ENET_PEER_STATE_DISCONNECTED, + STATE_CONNECTING = ENET_PEER_STATE_CONNECTING, + STATE_ACKNOWLEDGING_CONNECT = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT, + STATE_CONNECTION_PENDING = ENET_PEER_STATE_CONNECTION_PENDING, + STATE_CONNECTION_SUCCEEDED = ENET_PEER_STATE_CONNECTION_SUCCEEDED, + STATE_CONNECTED = ENET_PEER_STATE_CONNECTED, + STATE_DISCONNECT_LATER = ENET_PEER_STATE_DISCONNECT_LATER, + STATE_DISCONNECTING = ENET_PEER_STATE_DISCONNECTING, + STATE_ACKNOWLEDGING_DISCONNECT = ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT, + STATE_ZOMBIE = ENET_PEER_STATE_ZOMBIE, + }; + + enum PeerStatistic { + PEER_PACKET_LOSS, + PEER_PACKET_LOSS_VARIANCE, + PEER_PACKET_LOSS_EPOCH, + PEER_ROUND_TRIP_TIME, + PEER_ROUND_TRIP_TIME_VARIANCE, + PEER_LAST_ROUND_TRIP_TIME, + PEER_LAST_ROUND_TRIP_TIME_VARIANCE, + PEER_PACKET_THROTTLE, + PEER_PACKET_THROTTLE_LIMIT, + PEER_PACKET_THROTTLE_COUNTER, + PEER_PACKET_THROTTLE_EPOCH, + PEER_PACKET_THROTTLE_ACCELERATION, + PEER_PACKET_THROTTLE_DECELERATION, + PEER_PACKET_THROTTLE_INTERVAL, + }; + + int get_max_packet_size() const override; + int get_available_packet_count() const override; + 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; + + void peer_disconnect(int p_data = 0); + void peer_disconnect_later(int p_data = 0); + void peer_disconnect_now(int p_data = 0); + + void ping(); + void ping_interval(int p_interval); + void reset(); + int send(uint8_t p_channel, ENetPacket *p_packet); + void throttle_configure(int interval, int acceleration, int deceleration); + void set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max); + double get_statistic(PeerStatistic p_stat); + PeerState get_state() const; + int get_channels() const; + + // Extras + IPAddress get_remote_address() const; + int get_remote_port() const; + + // Used by ENetMultiplayer (TODO use meta? If only they where StringNames) + bool is_active() const; + + ENetPacketPeer(ENetPeer *p_peer); + ~ENetPacketPeer(); +}; + +VARIANT_ENUM_CAST(ENetPacketPeer::PeerState); +VARIANT_ENUM_CAST(ENetPacketPeer::PeerStatistic); + +#endif // ENET_PACKET_PEER_H diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp deleted file mode 100644 index 25b87145b6..0000000000 --- a/modules/enet/networked_multiplayer_enet.cpp +++ /dev/null @@ -1,926 +0,0 @@ -/*************************************************************************/ -/* networked_multiplayer_enet.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2021 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 "networked_multiplayer_enet.h" -#include "core/io/ip.h" -#include "core/io/marshalls.h" -#include "core/os/os.h" - -void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) { - transfer_mode = p_mode; -} - -NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const { - return transfer_mode; -} - -void NetworkedMultiplayerENet::set_target_peer(int p_peer) { - target_peer = p_peer; -} - -int NetworkedMultiplayerENet::get_packet_peer() const { - ERR_FAIL_COND_V_MSG(!active, 1, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_V(incoming_packets.size() == 0, 1); - - return incoming_packets.front()->get().from; -} - -int NetworkedMultiplayerENet::get_packet_channel() const { - ERR_FAIL_COND_V_MSG(!active, -1, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_V(incoming_packets.size() == 0, -1); - - return incoming_packets.front()->get().channel; -} - -int NetworkedMultiplayerENet::get_last_packet_channel() const { - ERR_FAIL_COND_V_MSG(!active, -1, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_V(!current_packet.packet, -1); - - return current_packet.channel; -} - -Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) { - ERR_FAIL_COND_V_MSG(active, ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); - ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The port number must be set between 0 and 65535 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_max_clients < 1 || p_max_clients > 4095, ERR_INVALID_PARAMETER, "The number of clients must be set between 1 and 4095 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - ERR_FAIL_COND_V(dtls_enabled && (dtls_key.is_null() || dtls_cert.is_null()), ERR_INVALID_PARAMETER); - - ENetAddress address; - memset(&address, 0, sizeof(address)); - -#ifdef GODOT_ENET - if (bind_ip.is_wildcard()) { - address.wildcard = 1; - } else { - enet_address_set_ip(&address, bind_ip.get_ipv6(), 16); - } -#else - if (bind_ip.is_wildcard()) { - address.host = 0; - } else { - ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER); - address.host = *(uint32_t *)bind_ip.get_ipv4(); - } -#endif - address.port = p_port; - - host = enet_host_create(&address /* the address to bind the server host to */, - p_max_clients /* allow up to 32 clients and/or outgoing connections */, - channel_count /* allow up to channel_count to be used */, - p_in_bandwidth /* limit incoming bandwidth if > 0 */, - p_out_bandwidth /* limit outgoing bandwidth if > 0 */); - - ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create an ENet multiplayer server."); -#ifdef GODOT_ENET - if (dtls_enabled) { - enet_host_dtls_server_setup(host, dtls_key.ptr(), dtls_cert.ptr()); - } - enet_host_refuse_new_connections(host, refuse_connections); -#endif - - _setup_compressor(); - active = true; - server = true; - refuse_connections = false; - unique_id = 1; - connection_status = CONNECTION_CONNECTED; - return OK; -} - -Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth, int p_client_port) { - ERR_FAIL_COND_V_MSG(active, ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); - ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The server port number must be set between 0 and 65535 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_client_port < 0 || p_client_port > 65535, ERR_INVALID_PARAMETER, "The client port number must be set between 0 and 65535 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - - if (p_client_port != 0) { - ENetAddress c_client; - -#ifdef GODOT_ENET - if (bind_ip.is_wildcard()) { - c_client.wildcard = 1; - } else { - enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16); - } -#else - if (bind_ip.is_wildcard()) { - c_client.host = 0; - } else { - ERR_FAIL_COND_V_MSG(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER, "Wildcard IP addresses are only permitted in IPv4, not IPv6."); - c_client.host = *(uint32_t *)bind_ip.get_ipv4(); - } -#endif - - c_client.port = p_client_port; - - host = enet_host_create(&c_client /* create a client host */, - 1 /* only allow 1 outgoing connection */, - channel_count /* allow up to channel_count to be used */, - p_in_bandwidth /* limit incoming bandwidth if > 0 */, - p_out_bandwidth /* limit outgoing bandwidth if > 0 */); - } else { - host = enet_host_create(nullptr /* create a client host */, - 1 /* only allow 1 outgoing connection */, - channel_count /* allow up to channel_count to be used */, - p_in_bandwidth /* limit incoming bandwidth if > 0 */, - p_out_bandwidth /* limit outgoing bandwidth if > 0 */); - } - - ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create the ENet client host."); -#ifdef GODOT_ENET - if (dtls_enabled) { - enet_host_dtls_client_setup(host, dtls_cert.ptr(), dtls_verify, p_address.utf8().get_data()); - } - enet_host_refuse_new_connections(host, refuse_connections); -#endif - - _setup_compressor(); - - IP_Address ip; - if (p_address.is_valid_ip_address()) { - ip = p_address; - } else { -#ifdef GODOT_ENET - ip = IP::get_singleton()->resolve_hostname(p_address); -#else - ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4); -#endif - - ERR_FAIL_COND_V_MSG(!ip.is_valid(), ERR_CANT_RESOLVE, "Couldn't resolve the server IP address or domain name."); - } - - ENetAddress address; -#ifdef GODOT_ENET - enet_address_set_ip(&address, ip.get_ipv6(), 16); -#else - ERR_FAIL_COND_V_MSG(!ip.is_ipv4(), ERR_INVALID_PARAMETER, "Connecting to an IPv6 server isn't supported when using vanilla ENet. Recompile Godot with the bundled ENet library."); - address.host = *(uint32_t *)ip.get_ipv4(); -#endif - address.port = p_port; - - unique_id = _gen_unique_id(); - - // Initiate connection, allocating enough channels - ENetPeer *peer = enet_host_connect(host, &address, channel_count, unique_id); - - if (peer == nullptr) { - enet_host_destroy(host); - ERR_FAIL_COND_V_MSG(!peer, ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server."); - } - - // Technically safe to ignore the peer or anything else. - - connection_status = CONNECTION_CONNECTING; - active = true; - server = false; - refuse_connections = false; - - return OK; -} - -void NetworkedMultiplayerENet::poll() { - ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); - - _pop_current_packet(); - - ENetEvent event; - /* Keep servicing until there are no available events left in queue. */ - while (true) { - if (!host || !active) { // Might have been disconnected while emitting a notification - return; - } - - int ret = enet_host_service(host, &event, 0); - - if (ret < 0) { - // Error, do something? - break; - } else if (ret == 0) { - break; - } - - switch (event.type) { - case ENET_EVENT_TYPE_CONNECT: { - // Store any relevant client information here. - - if (server && refuse_connections) { - enet_peer_reset(event.peer); - break; - } - - // A client joined with an invalid ID (negative values, 0, and 1 are reserved). - // Probably trying to exploit us. - if (server && ((int)event.data < 2 || peer_map.has((int)event.data))) { - enet_peer_reset(event.peer); - ERR_CONTINUE(true); - } - - int *new_id = memnew(int); - *new_id = event.data; - - if (*new_id == 0) { // Data zero is sent by server (ENet won't let you configure this). Server is always 1. - *new_id = 1; - } - - event.peer->data = new_id; - - peer_map[*new_id] = event.peer; - - connection_status = CONNECTION_CONNECTED; // If connecting, this means it connected to something! - - emit_signal("peer_connected", *new_id); - - if (server) { - // Do not notify other peers when server_relay is disabled. - if (!server_relay) { - break; - } - - // Someone connected, notify all the peers available - for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - if (E->key() == *new_id) { - continue; - } - // Send existing peers to new peer - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]); - encode_uint32(E->key(), &packet->data[4]); - enet_peer_send(event.peer, SYSCH_CONFIG, packet); - // Send the new peer to existing peers - packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]); - encode_uint32(*new_id, &packet->data[4]); - enet_peer_send(E->get(), SYSCH_CONFIG, packet); - } - } else { - emit_signal("connection_succeeded"); - } - - } break; - case ENET_EVENT_TYPE_DISCONNECT: { - // Reset the peer's client information. - - int *id = (int *)event.peer->data; - - if (!id) { - if (!server) { - emit_signal("connection_failed"); - } - // Never fully connected. - break; - } - - if (!server) { - // Client just disconnected from server. - emit_signal("server_disconnected"); - close_connection(); - return; - } else if (server_relay) { - // Server just received a client disconnect and is in relay mode, notify everyone else. - for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - if (E->key() == *id) { - continue; - } - - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); - encode_uint32(*id, &packet->data[4]); - enet_peer_send(E->get(), SYSCH_CONFIG, packet); - } - } - - emit_signal("peer_disconnected", *id); - peer_map.erase(*id); - memdelete(id); - } break; - case ENET_EVENT_TYPE_RECEIVE: { - if (event.channelID == SYSCH_CONFIG) { - // Some config message - ERR_CONTINUE(event.packet->dataLength < 8); - - // Only server can send config messages - ERR_CONTINUE(server); - - int msg = decode_uint32(&event.packet->data[0]); - int id = decode_uint32(&event.packet->data[4]); - - switch (msg) { - case SYSMSG_ADD_PEER: { - peer_map[id] = nullptr; - emit_signal("peer_connected", id); - - } break; - case SYSMSG_REMOVE_PEER: { - peer_map.erase(id); - emit_signal("peer_disconnected", id); - } break; - } - - enet_packet_destroy(event.packet); - } else if (event.channelID < channel_count) { - Packet packet; - packet.packet = event.packet; - - uint32_t *id = (uint32_t *)event.peer->data; - - ERR_CONTINUE(event.packet->dataLength < 8); - - uint32_t source = decode_uint32(&event.packet->data[0]); - int target = decode_uint32(&event.packet->data[4]); - - packet.from = source; - packet.channel = event.channelID; - - if (server) { - // Someone is cheating and trying to fake the source! - ERR_CONTINUE(source != *id); - - packet.from = *id; - - if (target == 1) { - // To myself and only myself - incoming_packets.push_back(packet); - } else if (!server_relay) { - // No other destination is allowed when server is not relaying - continue; - } else if (target == 0) { - // Re-send to everyone but sender :| - - incoming_packets.push_back(packet); - // And make copies for sending - for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - if (uint32_t(E->key()) == source) { // Do not resend to self - continue; - } - - ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags); - - enet_peer_send(E->get(), event.channelID, packet2); - } - - } else if (target < 0) { - // To all but one - - // And make copies for sending - for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - if (uint32_t(E->key()) == source || E->key() == -target) { // Do not resend to self, also do not send to excluded - continue; - } - - ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags); - - enet_peer_send(E->get(), event.channelID, packet2); - } - - if (-target != 1) { - // Server is not excluded - incoming_packets.push_back(packet); - } else { - // Server is excluded, erase packet - enet_packet_destroy(packet.packet); - } - - } else { - // To someone else, specifically - ERR_CONTINUE(!peer_map.has(target)); - enet_peer_send(peer_map[target], event.channelID, packet.packet); - } - } else { - incoming_packets.push_back(packet); - } - - // Destroy packet later - } else { - ERR_CONTINUE(true); - } - - } break; - case ENET_EVENT_TYPE_NONE: { - // Do nothing - } break; - } - } -} - -bool NetworkedMultiplayerENet::is_server() const { - ERR_FAIL_COND_V_MSG(!active, false, "The multiplayer instance isn't currently active."); - - return server; -} - -void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) { - ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); - - _pop_current_packet(); - - bool peers_disconnected = false; - for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - if (E->get()) { - enet_peer_disconnect_now(E->get(), unique_id); - int *id = (int *)(E->get()->data); - memdelete(id); - peers_disconnected = true; - } - } - - if (peers_disconnected) { - enet_host_flush(host); - - if (wait_usec > 0) { - OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send - } - } - - enet_host_destroy(host); - active = false; - incoming_packets.clear(); - peer_map.clear(); - unique_id = 1; // Server is 1 - connection_status = CONNECTION_DISCONNECTED; -} - -void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) { - ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_MSG(!is_server(), "Can't disconnect a peer when not acting as a server."); - ERR_FAIL_COND_MSG(!peer_map.has(p_peer), vformat("Peer ID %d not found in the list of peers.", p_peer)); - - if (now) { - int *id = (int *)peer_map[p_peer]->data; - enet_peer_disconnect_now(peer_map[p_peer], 0); - - // enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT, - // notify everyone else, send disconnect signal & remove from peer_map like in poll() - if (server_relay) { - for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) { - if (E->key() == p_peer) { - continue; - } - - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); - encode_uint32(p_peer, &packet->data[4]); - enet_peer_send(E->get(), SYSCH_CONFIG, packet); - } - } - - if (id) { - memdelete(id); - } - - emit_signal("peer_disconnected", p_peer); - peer_map.erase(p_peer); - } else { - enet_peer_disconnect_later(peer_map[p_peer], 0); - } -} - -int NetworkedMultiplayerENet::get_available_packet_count() const { - return incoming_packets.size(); -} - -Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available."); - - _pop_current_packet(); - - 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; - - return OK; -} - -Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V_MSG(!active, ERR_UNCONFIGURED, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client."); - - int packet_flags = 0; - int channel = SYSCH_RELIABLE; - - switch (transfer_mode) { - case TRANSFER_MODE_UNRELIABLE: { - if (always_ordered) { - packet_flags = 0; - } else { - packet_flags = ENET_PACKET_FLAG_UNSEQUENCED; - } - channel = SYSCH_UNRELIABLE; - } break; - case TRANSFER_MODE_UNRELIABLE_ORDERED: { - packet_flags = 0; - channel = SYSCH_UNRELIABLE; - } break; - case TRANSFER_MODE_RELIABLE: { - packet_flags = ENET_PACKET_FLAG_RELIABLE; - channel = SYSCH_RELIABLE; - } break; - } - - if (transfer_channel > SYSCH_CONFIG) { - channel = transfer_channel; - } - - Map<int, ENetPeer *>::Element *E = nullptr; - - if (target_peer != 0) { - E = peer_map.find(ABS(target_peer)); - ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer)); - } - - 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 - copymem(&packet->data[8], p_buffer, p_buffer_size); - - if (server) { - if (target_peer == 0) { - enet_host_broadcast(host, channel, packet); - } else if (target_peer < 0) { - // Send to all but one - // and make copies for sending - - int exclude = -target_peer; - - for (Map<int, ENetPeer *>::Element *F = peer_map.front(); F; F = F->next()) { - if (F->key() == exclude) { // Exclude packet - continue; - } - - ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags); - - enet_peer_send(F->get(), channel, packet2); - } - - enet_packet_destroy(packet); // Original packet no longer needed - } else { - enet_peer_send(E->get(), channel, packet); - } - } else { - ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG); - enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast - } - - enet_host_flush(host); - - return OK; -} - -int NetworkedMultiplayerENet::get_max_packet_size() const { - return 1 << 24; // Anything is good -} - -void NetworkedMultiplayerENet::_pop_current_packet() { - if (current_packet.packet) { - enet_packet_destroy(current_packet.packet); - current_packet.packet = nullptr; - current_packet.from = 0; - current_packet.channel = -1; - } -} - -NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const { - return connection_status; -} - -uint32_t NetworkedMultiplayerENet::_gen_unique_id() const { - uint32_t hash = 0; - - while (hash == 0 || hash == 1) { - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_ticks_usec()); - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_unix_time(), hash); - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash); - hash = hash_djb2_one_32( - (uint32_t)((uint64_t)this), hash); // Rely on ASLR heap - hash = hash_djb2_one_32( - (uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack - - hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion - } - - return hash; -} - -int NetworkedMultiplayerENet::get_unique_id() const { - ERR_FAIL_COND_V_MSG(!active, 0, "The multiplayer instance isn't currently active."); - return unique_id; -} - -void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) { - refuse_connections = p_enable; -#ifdef GODOT_ENET - if (active) { - enet_host_refuse_new_connections(host, p_enable); - } -#endif -} - -bool NetworkedMultiplayerENet::is_refusing_new_connections() const { - return refuse_connections; -} - -void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) { - compression_mode = p_mode; -} - -NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const { - return compression_mode; -} - -size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) { - NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context); - - if (size_t(enet->src_compressor_mem.size()) < inLimit) { - enet->src_compressor_mem.resize(inLimit); - } - - int total = inLimit; - int ofs = 0; - while (total) { - for (size_t i = 0; i < inBufferCount; i++) { - int to_copy = MIN(total, int(inBuffers[i].dataLength)); - copymem(&enet->src_compressor_mem.write[ofs], inBuffers[i].data, to_copy); - ofs += to_copy; - total -= to_copy; - } - } - - Compression::Mode mode; - - switch (enet->compression_mode) { - case COMPRESS_FASTLZ: { - mode = Compression::MODE_FASTLZ; - } break; - case COMPRESS_ZLIB: { - mode = Compression::MODE_DEFLATE; - } break; - case COMPRESS_ZSTD: { - mode = Compression::MODE_ZSTD; - } break; - default: { - ERR_FAIL_V_MSG(0, vformat("Invalid ENet compression mode: %d", enet->compression_mode)); - } - } - - int req_size = Compression::get_max_compressed_buffer_size(ofs, mode); - if (enet->dst_compressor_mem.size() < req_size) { - enet->dst_compressor_mem.resize(req_size); - } - int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode); - - if (ret < 0) { - return 0; - } - - if (ret > int(outLimit)) { - return 0; // Do not bother - } - - copymem(outData, enet->dst_compressor_mem.ptr(), ret); - - return ret; -} - -size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) { - NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context); - int ret = -1; - switch (enet->compression_mode) { - case COMPRESS_FASTLZ: { - ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ); - } break; - case COMPRESS_ZLIB: { - ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE); - } break; - case COMPRESS_ZSTD: { - ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD); - } break; - default: { - } - } - if (ret < 0) { - return 0; - } else { - return ret; - } -} - -void NetworkedMultiplayerENet::_setup_compressor() { - switch (compression_mode) { - case COMPRESS_NONE: { - enet_host_compress(host, nullptr); - } break; - case COMPRESS_RANGE_CODER: { - enet_host_compress_with_range_coder(host); - } break; - case COMPRESS_FASTLZ: - case COMPRESS_ZLIB: - case COMPRESS_ZSTD: { - enet_host_compress(host, &enet_compressor); - } break; - } -} - -void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) { - // Nothing to do -} - -IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const { - ERR_FAIL_COND_V_MSG(!peer_map.has(p_peer_id), IP_Address(), vformat("Peer ID %d not found in the list of peers.", p_peer_id)); - ERR_FAIL_COND_V_MSG(!is_server() && p_peer_id != 1, IP_Address(), "Can't get the address of peers other than the server (ID -1) when acting as a client."); - ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == nullptr, IP_Address(), vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id)); - - IP_Address out; -#ifdef GODOT_ENET - out.set_ipv6((uint8_t *)&(peer_map[p_peer_id]->address.host)); -#else - out.set_ipv4((uint8_t *)&(peer_map[p_peer_id]->address.host)); -#endif - - return out; -} - -int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const { - ERR_FAIL_COND_V_MSG(!peer_map.has(p_peer_id), 0, vformat("Peer ID %d not found in the list of peers.", p_peer_id)); - ERR_FAIL_COND_V_MSG(!is_server() && p_peer_id != 1, 0, "Can't get the address of peers other than the server (ID -1) when acting as a client."); - ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == nullptr, 0, vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id)); -#ifdef GODOT_ENET - return peer_map[p_peer_id]->address.port; -#else - return peer_map[p_peer_id]->address.port; -#endif -} - -void NetworkedMultiplayerENet::set_peer_timeout(int p_peer_id, int p_timeout_limit, int p_timeout_min, int p_timeout_max) { - ERR_FAIL_COND_MSG(!peer_map.has(p_peer_id), vformat("Peer ID %d not found in the list of peers.", p_peer_id)); - ERR_FAIL_COND_MSG(!is_server() && p_peer_id != 1, "Can't change the timeout of peers other then the server when acting as a client."); - ERR_FAIL_COND_MSG(peer_map[p_peer_id] == nullptr, vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id)); - ERR_FAIL_COND_MSG(p_timeout_limit > p_timeout_min || p_timeout_min > p_timeout_max, "Timeout limit must be less than minimum timeout, which itself must be less then maximum timeout"); - enet_peer_timeout(peer_map[p_peer_id], p_timeout_limit, p_timeout_min, p_timeout_max); -} - -void NetworkedMultiplayerENet::set_transfer_channel(int p_channel) { - ERR_FAIL_COND_MSG(p_channel < -1 || p_channel >= channel_count, vformat("The transfer channel must be set between 0 and %d, inclusive (got %d).", channel_count - 1, p_channel)); - ERR_FAIL_COND_MSG(p_channel == SYSCH_CONFIG, vformat("The channel %d is reserved.", SYSCH_CONFIG)); - transfer_channel = p_channel; -} - -int NetworkedMultiplayerENet::get_transfer_channel() const { - return transfer_channel; -} - -void NetworkedMultiplayerENet::set_channel_count(int p_channel) { - ERR_FAIL_COND_MSG(active, "The channel count can't be set while the multiplayer instance is active."); - ERR_FAIL_COND_MSG(p_channel < SYSCH_MAX, vformat("The channel count must be greater than or equal to %d to account for reserved channels (got %d).", SYSCH_MAX, p_channel)); - channel_count = p_channel; -} - -int NetworkedMultiplayerENet::get_channel_count() const { - return channel_count; -} - -void NetworkedMultiplayerENet::set_always_ordered(bool p_ordered) { - always_ordered = p_ordered; -} - -bool NetworkedMultiplayerENet::is_always_ordered() const { - return always_ordered; -} - -void NetworkedMultiplayerENet::set_server_relay_enabled(bool p_enabled) { - ERR_FAIL_COND_MSG(active, "Server relaying can't be toggled while the multiplayer instance is active."); - - server_relay = p_enabled; -} - -bool NetworkedMultiplayerENet::is_server_relay_enabled() const { - return server_relay; -} - -void NetworkedMultiplayerENet::_bind_methods() { - ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0)); - ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "client_port"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0)); - ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &NetworkedMultiplayerENet::close_connection, DEFVAL(100)); - ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &NetworkedMultiplayerENet::disconnect_peer, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode); - ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode); - ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip); - ClassDB::bind_method(D_METHOD("set_dtls_enabled", "enabled"), &NetworkedMultiplayerENet::set_dtls_enabled); - ClassDB::bind_method(D_METHOD("is_dtls_enabled"), &NetworkedMultiplayerENet::is_dtls_enabled); - ClassDB::bind_method(D_METHOD("set_dtls_key", "key"), &NetworkedMultiplayerENet::set_dtls_key); - ClassDB::bind_method(D_METHOD("set_dtls_certificate", "certificate"), &NetworkedMultiplayerENet::set_dtls_certificate); - ClassDB::bind_method(D_METHOD("set_dtls_verify_enabled", "enabled"), &NetworkedMultiplayerENet::set_dtls_verify_enabled); - ClassDB::bind_method(D_METHOD("is_dtls_verify_enabled"), &NetworkedMultiplayerENet::is_dtls_verify_enabled); - ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &NetworkedMultiplayerENet::get_peer_address); - ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &NetworkedMultiplayerENet::get_peer_port); - ClassDB::bind_method(D_METHOD("set_peer_timeout", "id", "timeout_limit", "timeout_min", "timeout_max"), &NetworkedMultiplayerENet::set_peer_timeout); - - ClassDB::bind_method(D_METHOD("get_packet_channel"), &NetworkedMultiplayerENet::get_packet_channel); - ClassDB::bind_method(D_METHOD("get_last_packet_channel"), &NetworkedMultiplayerENet::get_last_packet_channel); - ClassDB::bind_method(D_METHOD("set_transfer_channel", "channel"), &NetworkedMultiplayerENet::set_transfer_channel); - ClassDB::bind_method(D_METHOD("get_transfer_channel"), &NetworkedMultiplayerENet::get_transfer_channel); - ClassDB::bind_method(D_METHOD("set_channel_count", "channels"), &NetworkedMultiplayerENet::set_channel_count); - ClassDB::bind_method(D_METHOD("get_channel_count"), &NetworkedMultiplayerENet::get_channel_count); - ClassDB::bind_method(D_METHOD("set_always_ordered", "ordered"), &NetworkedMultiplayerENet::set_always_ordered); - ClassDB::bind_method(D_METHOD("is_always_ordered"), &NetworkedMultiplayerENet::is_always_ordered); - ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &NetworkedMultiplayerENet::set_server_relay_enabled); - ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &NetworkedMultiplayerENet::is_server_relay_enabled); - - ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_channel"), "set_transfer_channel", "get_transfer_channel"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "channel_count"), "set_channel_count", "get_channel_count"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "always_ordered"), "set_always_ordered", "is_always_ordered"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dtls_verify"), "set_dtls_verify_enabled", "is_dtls_verify_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_dtls"), "set_dtls_enabled", "is_dtls_enabled"); - - BIND_ENUM_CONSTANT(COMPRESS_NONE); - BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER); - BIND_ENUM_CONSTANT(COMPRESS_FASTLZ); - BIND_ENUM_CONSTANT(COMPRESS_ZLIB); - BIND_ENUM_CONSTANT(COMPRESS_ZSTD); -} - -NetworkedMultiplayerENet::NetworkedMultiplayerENet() { - enet_compressor.context = this; - enet_compressor.compress = enet_compress; - enet_compressor.decompress = enet_decompress; - enet_compressor.destroy = enet_compressor_destroy; - - bind_ip = IP_Address("*"); -} - -NetworkedMultiplayerENet::~NetworkedMultiplayerENet() { - if (active) { - close_connection(); - } -} - -// Sets IP for ENet to bind when using create_server or create_client -// if no IP is set, then ENet bind to ENET_HOST_ANY -void NetworkedMultiplayerENet::set_bind_ip(const IP_Address &p_ip) { - ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip))); - - bind_ip = p_ip; -} - -void NetworkedMultiplayerENet::set_dtls_enabled(bool p_enabled) { - ERR_FAIL_COND(active); - dtls_enabled = p_enabled; -} - -bool NetworkedMultiplayerENet::is_dtls_enabled() const { - return dtls_enabled; -} - -void NetworkedMultiplayerENet::set_dtls_verify_enabled(bool p_enabled) { - ERR_FAIL_COND(active); - dtls_verify = p_enabled; -} - -bool NetworkedMultiplayerENet::is_dtls_verify_enabled() const { - return dtls_verify; -} - -void NetworkedMultiplayerENet::set_dtls_key(Ref<CryptoKey> p_key) { - ERR_FAIL_COND(active); - dtls_key = p_key; -} - -void NetworkedMultiplayerENet::set_dtls_certificate(Ref<X509Certificate> p_cert) { - ERR_FAIL_COND(active); - dtls_cert = p_cert; -} diff --git a/modules/enet/register_types.cpp b/modules/enet/register_types.cpp index 8da2d17e13..7570f5b643 100644 --- a/modules/enet/register_types.cpp +++ b/modules/enet/register_types.cpp @@ -30,7 +30,9 @@ #include "register_types.h" #include "core/error/error_macros.h" -#include "networked_multiplayer_enet.h" +#include "enet_connection.h" +#include "enet_multiplayer_peer.h" +#include "enet_packet_peer.h" static bool enet_ok = false; @@ -41,7 +43,9 @@ void register_enet_types() { enet_ok = true; } - ClassDB::register_class<NetworkedMultiplayerENet>(); + GDREGISTER_CLASS(ENetMultiplayerPeer); + GDREGISTER_VIRTUAL_CLASS(ENetPacketPeer); + GDREGISTER_CLASS(ENetConnection); } void unregister_enet_types() { diff --git a/modules/fbx/README.md b/modules/fbx/README.md index 2a2f186463..8eca4bd3c9 100644 --- a/modules/fbx/README.md +++ b/modules/fbx/README.md @@ -15,7 +15,7 @@ functionality. If anything we should give this parser back to assimp at some poi # Updating assimp fbx parser -Don't. it's not possible the code is rewritten in many areas to remove thirdparty deps and various bugs are fixed. +Don't. It's not possible the code is rewritten in many areas to remove thirdparty deps and various bugs are fixed. Many days were put into rewriting the parser to use safe code and safe memory accessors. @@ -79,23 +79,23 @@ enum RotOrder { // references: ComputePivotTransform / run the calculation // This is the local pivot transform for the node, not the global transforms Transform ComputePivotTransform( - Transform chain[TransformationComp_MAXIMUM], - Transform &geometric_transform) { + Transform3D chain[TransformationComp_MAXIMUM], + Transform3D &geometric_transform) { // Maya pivots - Transform T = chain[TransformationComp_Translation]; - Transform Roff = chain[TransformationComp_RotationOffset]; - Transform Rp = chain[TransformationComp_RotationPivot]; - Transform Rpre = chain[TransformationComp_PreRotation]; - Transform R = chain[TransformationComp_Rotation]; - Transform Rpost = chain[TransformationComp_PostRotation]; - Transform Soff = chain[TransformationComp_ScalingOffset]; - Transform Sp = chain[TransformationComp_ScalingPivot]; - Transform S = chain[TransformationComp_Scaling]; + Transform3D T = chain[TransformationComp_Translation]; + Transform3D Roff = chain[TransformationComp_RotationOffset]; + Transform3D Rp = chain[TransformationComp_RotationPivot]; + Transform3D Rpre = chain[TransformationComp_PreRotation]; + Transform3D R = chain[TransformationComp_Rotation]; + Transform3D Rpost = chain[TransformationComp_PostRotation]; + Transform3D Soff = chain[TransformationComp_ScalingOffset]; + Transform3D Sp = chain[TransformationComp_ScalingPivot]; + Transform3D S = chain[TransformationComp_Scaling]; // 3DS Max Pivots - Transform OT = chain[TransformationComp_GeometricTranslation]; - Transform OR = chain[TransformationComp_GeometricRotation]; - Transform OS = chain[TransformationComp_GeometricScaling]; + Transform3D OT = chain[TransformationComp_GeometricTranslation]; + Transform3D OR = chain[TransformationComp_GeometricRotation]; + Transform3D OS = chain[TransformationComp_GeometricScaling]; // Calculate 3DS max pivot transform - use geometric space (e.g doesn't effect children nodes only the current node) geometric_transform = OT * OR * OS; diff --git a/modules/fbx/data/fbx_bone.h b/modules/fbx/data/fbx_bone.h index efba147b89..83918ad1e2 100644 --- a/modules/fbx/data/fbx_bone.h +++ b/modules/fbx/data/fbx_bone.h @@ -38,7 +38,7 @@ struct PivotTransform; -struct FBXBone : public Reference { +struct FBXBone : public RefCounted { uint64_t parent_bone_id = 0; uint64_t bone_id = 0; diff --git a/modules/fbx/data/fbx_material.cpp b/modules/fbx/data/fbx_material.cpp index d54ac86e9f..fb6c67f7b9 100644 --- a/modules/fbx/data/fbx_material.cpp +++ b/modules/fbx/data/fbx_material.cpp @@ -29,6 +29,10 @@ /*************************************************************************/ #include "fbx_material.h" + +// FIXME: Shouldn't depend on core_bind.h! Use DirAccessRef like the rest of +// the engine instead of _Directory. +#include "core/core_bind.h" #include "scene/resources/material.h" #include "scene/resources/texture.h" #include "tools/validation_tools.h" @@ -160,7 +164,7 @@ Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) { const String p_fbx_current_directory = state.path; Ref<StandardMaterial3D> spatial_material; - spatial_material.instance(); + spatial_material.instantiate(); // read the material file // is material two sided @@ -223,7 +227,7 @@ Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) { } else if (fbx_texture_data != nullptr && fbx_texture_data->Media() != nullptr && fbx_texture_data->Media()->IsEmbedded()) { // This is an embedded texture. Extract it. Ref<Image> image; - //image.instance(); // oooo double instance bug? why make Image::_png_blah call + //image.instantiate(); // oooo double instance bug? why make Image::_png_blah call const String extension = texture_name.get_extension().to_upper(); if (extension == "PNG") { @@ -256,7 +260,7 @@ Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) { } Ref<ImageTexture> image_texture; - image_texture.instance(); + image_texture.instantiate(); image_texture->create_from_image(image); texture = image_texture; @@ -324,7 +328,7 @@ Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) { if (spatial_material.is_null()) { // Done here so if no data no material is created. - spatial_material.instance(); + spatial_material.instantiate(); } const FBXDocParser::TypedProperty<real_t> *real_value = dynamic_cast<const FBXDocParser::TypedProperty<real_t> *>(prop); @@ -420,7 +424,7 @@ Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) { } break; case PROPERTY_DESC_COAT_ROUGHNESS: { // meaning is that approx equal to zero is disabled not actually zero. ;) - if (real_value && Math::is_equal_approx(real_value->Value(), 0.0f)) { + if (real_value && Math::is_zero_approx(real_value->Value())) { print_verbose("clearcoat real value: " + rtos(real_value->Value())); spatial_material->set_clearcoat_gloss(1.0 - real_value->Value()); } else { @@ -428,7 +432,7 @@ Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) { } } break; case PROPERTY_DESC_EMISSIVE: { - if (real_value && Math::is_equal_approx(real_value->Value(), 0.0f)) { + if (real_value && Math::is_zero_approx(real_value->Value())) { print_verbose("Emissive real value: " + rtos(real_value->Value())); spatial_material->set_emission_energy(real_value->Value()); } else if (vector_value && !vector_value->Value().is_equal_approx(Vector3(0, 0, 0))) { diff --git a/modules/fbx/data/fbx_material.h b/modules/fbx/data/fbx_material.h index 23310b8e1d..5fd4d9212b 100644 --- a/modules/fbx/data/fbx_material.h +++ b/modules/fbx/data/fbx_material.h @@ -33,10 +33,10 @@ #include "tools/import_utils.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/string/ustring.h" -struct FBXMaterial : public Reference { +struct FBXMaterial : public RefCounted { String material_name = String(); bool warning_non_pbr_material = false; FBXDocParser::Material *material = nullptr; @@ -266,7 +266,7 @@ struct FBXMaterial : public Reference { /* storing the texture properties like color */ template <class T> - struct TexturePropertyMapping : Reference { + struct TexturePropertyMapping : RefCounted { StandardMaterial3D::TextureParam map_mode = StandardMaterial3D::TextureParam::TEXTURE_ALBEDO; const T property = T(); }; diff --git a/modules/fbx/data/fbx_mesh_data.cpp b/modules/fbx/data/fbx_mesh_data.cpp index 304d1598f6..dcea476275 100644 --- a/modules/fbx/data/fbx_mesh_data.cpp +++ b/modules/fbx/data/fbx_mesh_data.cpp @@ -211,7 +211,7 @@ EditorSceneImporterMeshNode3D *FBXMeshData::create_fbx_mesh(const ImportState &s const int surface_id = polygon_surfaces[*polygon_id]; if (surfaces.has(surface_id) == false) { SurfaceData sd; - sd.surface_tool.instance(); + sd.surface_tool.instantiate(); sd.surface_tool->begin(Mesh::PRIMITIVE_TRIANGLES); if (surface_id < 0) { @@ -316,7 +316,7 @@ EditorSceneImporterMeshNode3D *FBXMeshData::create_fbx_mesh(const ImportState &s Vector3 *normals_ptr = morph_data->normals.ptrw(); Ref<SurfaceTool> morph_st; - morph_st.instance(); + morph_st.instantiate(); morph_st->begin(Mesh::PRIMITIVE_TRIANGLES); for (unsigned int vi = 0; vi < surface->vertices_map.size(); vi += 1) { @@ -345,7 +345,7 @@ EditorSceneImporterMeshNode3D *FBXMeshData::create_fbx_mesh(const ImportState &s // Phase 6. Compose the mesh and return it. Ref<EditorSceneImporterMesh> mesh; - mesh.instance(); + mesh.instantiate(); // Add blend shape info. for (const String *morph_name = morphs.next(nullptr); morph_name != nullptr; morph_name = morphs.next(morph_name)) { @@ -433,7 +433,7 @@ void FBXMeshData::sanitize_vertex_weights(const ImportState &state) { { // Sort - real_t *weights_ptr = vm->weights.ptrw(); + float *weights_ptr = vm->weights.ptrw(); int *bones_ptr = vm->bones.ptrw(); for (int i = 0; i < vm->weights.size(); i += 1) { for (int x = i + 1; x < vm->weights.size(); x += 1) { @@ -449,7 +449,7 @@ void FBXMeshData::sanitize_vertex_weights(const ImportState &state) { // Resize vm->weights.resize(max_vertex_influence_count); vm->bones.resize(max_vertex_influence_count); - real_t *weights_ptr = vm->weights.ptrw(); + float *weights_ptr = vm->weights.ptrw(); int *bones_ptr = vm->bones.ptrw(); for (int i = initial_size; i < max_vertex_influence_count; i += 1) { weights_ptr[i] = 0.0; @@ -525,7 +525,7 @@ void FBXMeshData::reorganize_vertices( } const Vector3 vert_poly_normal = *nrml_arr->getptr(*pid); - if ((this_vert_poly_normal - vert_poly_normal).length_squared() > CMP_EPSILON) { + if (!vert_poly_normal.is_equal_approx(this_vert_poly_normal)) { // Yes this polygon need duplication. need_duplication = true; break; @@ -586,7 +586,7 @@ void FBXMeshData::reorganize_vertices( continue; } const Vector2 vert_poly_uv = *uvs->getptr(*pid); - if (((*this_vert_poly_uv) - vert_poly_uv).length_squared() > CMP_EPSILON) { + if (!vert_poly_uv.is_equal_approx(*this_vert_poly_uv)) { // Yes this polygon need duplication. need_duplication = true; break; @@ -945,7 +945,7 @@ void FBXMeshData::triangulate_polygon(SurfaceData *surface, const Vector<int> &p for (List<TPPLPoly>::Element *I = out_poly.front(); I; I = I->next()) { TPPLPoly &tp = I->get(); - ERR_FAIL_COND_MSG(tp.GetNumPoints() != 3, "The triangulator retuned more points, how this is possible?"); + ERR_FAIL_COND_MSG(tp.GetNumPoints() != 3, "The triangulator returned more points, how this is possible?"); // Find Index for (int i = 2; i >= 0; i -= 1) { const Vector2 vertex = tp.GetPoint(i); @@ -1126,8 +1126,8 @@ HashMap<int, R> FBXMeshData::extract_per_vertex_data( } const int vertex_index = get_vertex_from_polygon_vertex(p_mesh_indices, polygon_vertex_index); ERR_FAIL_COND_V_MSG(vertex_index < 0, (HashMap<int, R>()), "FBX file corrupted: #ERR8"); - ERR_FAIL_COND_V_MSG(vertex_index >= p_vertex_count, (HashMap<int, R>()), "FBX file seems corrupted: #ERR9."); - ERR_FAIL_COND_V_MSG(p_mapping_data.index[polygon_vertex_index] < 0, (HashMap<int, R>()), "FBX file seems corrupted: #ERR10."); + ERR_FAIL_COND_V_MSG(vertex_index >= p_vertex_count, (HashMap<int, R>()), "FBX file seems corrupted: #ERR9."); + ERR_FAIL_COND_V_MSG(p_mapping_data.index[polygon_vertex_index] < 0, (HashMap<int, R>()), "FBX file seems corrupted: #ERR10."); ERR_FAIL_COND_V_MSG(p_mapping_data.index[polygon_vertex_index] >= (int)p_mapping_data.data.size(), (HashMap<int, R>()), "FBX file seems corrupted: #ERR11."); aggregate_vertex_data[vertex_index].push_back({ polygon_id, p_mapping_data.data[p_mapping_data.index[polygon_vertex_index]] }); } diff --git a/modules/fbx/data/fbx_mesh_data.h b/modules/fbx/data/fbx_mesh_data.h index 575f833584..24db4a5469 100644 --- a/modules/fbx/data/fbx_mesh_data.h +++ b/modules/fbx/data/fbx_mesh_data.h @@ -64,7 +64,7 @@ struct SurfaceData { }; struct VertexWeightMapping { - Vector<real_t> weights; + Vector<float> weights; Vector<int> bones; // This extra vector is used because the bone id is computed in a second step. // TODO Get rid of this extra step is a good idea. @@ -78,7 +78,7 @@ struct VertexData { }; // Caches mesh information and instantiates meshes for you using helper functions. -struct FBXMeshData : Reference { +struct FBXMeshData : RefCounted { struct MorphVertexData { // TODO we have only these?? /// Each element is a vertex. Not supposed to be void. @@ -156,7 +156,7 @@ private: /// [0, 2, 1, 3, 4] /// The negative values are computed using this formula: `(-value) - 1` /// - /// Returns the vertex index from the poligon vertex. + /// Returns the vertex index from the polygon vertex. /// Returns -1 if `p_index` is invalid. int get_vertex_from_polygon_vertex(const std::vector<int> &p_face_indices, int p_index) const; diff --git a/modules/fbx/data/fbx_node.h b/modules/fbx/data/fbx_node.h index a6f62f3388..75461e397d 100644 --- a/modules/fbx/data/fbx_node.h +++ b/modules/fbx/data/fbx_node.h @@ -40,7 +40,7 @@ class Node3D; struct PivotTransform; -struct FBXNode : Reference, ModelAbstraction { +struct FBXNode : RefCounted, ModelAbstraction { uint64_t current_node_id = 0; String node_name = String(); Node3D *godot_node = nullptr; diff --git a/modules/fbx/data/fbx_skeleton.h b/modules/fbx/data/fbx_skeleton.h index df937cde49..b6103df949 100644 --- a/modules/fbx/data/fbx_skeleton.h +++ b/modules/fbx/data/fbx_skeleton.h @@ -35,14 +35,14 @@ #include "fbx_node.h" #include "model_abstraction.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "scene/3d/skeleton_3d.h" struct FBXNode; struct ImportState; struct FBXBone; -struct FBXSkeleton : Reference { +struct FBXSkeleton : RefCounted { Ref<FBXNode> fbx_node = Ref<FBXNode>(); Vector<Ref<FBXBone>> skeleton_bones = Vector<Ref<FBXBone>>(); Skeleton3D *skeleton = nullptr; diff --git a/modules/fbx/data/import_state.h b/modules/fbx/data/import_state.h index 83bc43faff..9ba60eaacf 100644 --- a/modules/fbx/data/import_state.h +++ b/modules/fbx/data/import_state.h @@ -37,7 +37,6 @@ #include "pivot_transform.h" -#include "core/core_bind.h" #include "core/io/resource_importer.h" #include "core/templates/vector.h" #include "editor/import/resource_importer_scene.h" diff --git a/modules/fbx/data/pivot_transform.cpp b/modules/fbx/data/pivot_transform.cpp index f4055c830f..4cf42257a4 100644 --- a/modules/fbx/data/pivot_transform.cpp +++ b/modules/fbx/data/pivot_transform.cpp @@ -90,7 +90,7 @@ void PivotTransform::ReadTransformChain() { if (ok) { geometric_rotation = ImportUtils::EulerToQuaternion(rot, ImportUtils::deg2rad(GeometricRotation)); } else { - geometric_rotation = Quat(); + geometric_rotation = Quaternion(); } const Vector3 &GeometricTranslation = ImportUtils::safe_import_vector3(FBXDocParser::PropertyGet<Vector3>(props, "GeometricTranslation", ok)); @@ -100,7 +100,7 @@ void PivotTransform::ReadTransformChain() { geometric_translation = Vector3(0, 0, 0); } - if (geometric_rotation != Quat()) { + if (geometric_rotation != Quaternion()) { print_error("geometric rotation is unsupported!"); //CRASH_COND(true); } @@ -116,8 +116,8 @@ void PivotTransform::ReadTransformChain() { } } -Transform PivotTransform::ComputeLocalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const { - Transform T, Roff, Rp, Soff, Sp, S; +Transform3D PivotTransform::ComputeLocalTransform(Vector3 p_translation, Quaternion p_rotation, Vector3 p_scaling) const { + Transform3D T, Roff, Rp, Soff, Sp, S; // Here I assume this is the operation which needs done. // Its WorldTransform * V @@ -132,29 +132,29 @@ Transform PivotTransform::ComputeLocalTransform(Vector3 p_translation, Quat p_ro // Scaling node S.scale(p_scaling); // Rotation pivots - Transform Rpre = Transform(pre_rotation); - Transform R = Transform(p_rotation); - Transform Rpost = Transform(post_rotation); + Transform3D Rpre = Transform3D(pre_rotation); + Transform3D R = Transform3D(p_rotation); + Transform3D Rpost = Transform3D(post_rotation); return T * Roff * Rp * Rpre * R * Rpost.affine_inverse() * Rp.affine_inverse() * Soff * Sp * S * Sp.affine_inverse(); } -Transform PivotTransform::ComputeGlobalTransform(Transform t) const { +Transform3D PivotTransform::ComputeGlobalTransform(Transform3D t) const { Vector3 pos = t.origin; Vector3 scale = t.basis.get_scale(); - Quat rot = t.basis.get_rotation_quat(); + Quaternion rot = t.basis.get_rotation_quaternion(); return ComputeGlobalTransform(pos, rot, scale); } -Transform PivotTransform::ComputeLocalTransform(Transform t) const { +Transform3D PivotTransform::ComputeLocalTransform(Transform3D t) const { Vector3 pos = t.origin; Vector3 scale = t.basis.get_scale(); - Quat rot = t.basis.get_rotation_quat(); + Quaternion rot = t.basis.get_rotation_quaternion(); return ComputeLocalTransform(pos, rot, scale); } -Transform PivotTransform::ComputeGlobalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const { - Transform T, Roff, Rp, Soff, Sp, S; +Transform3D PivotTransform::ComputeGlobalTransform(Vector3 p_translation, Quaternion p_rotation, Vector3 p_scaling) const { + Transform3D T, Roff, Rp, Soff, Sp, S; // Here I assume this is the operation which needs done. // Its WorldTransform * V @@ -170,26 +170,26 @@ Transform PivotTransform::ComputeGlobalTransform(Vector3 p_translation, Quat p_r S.scale(p_scaling); // Rotation pivots - Transform Rpre = Transform(pre_rotation); - Transform R = Transform(p_rotation); - Transform Rpost = Transform(post_rotation); + Transform3D Rpre = Transform3D(pre_rotation); + Transform3D R = Transform3D(p_rotation); + Transform3D Rpost = Transform3D(post_rotation); - Transform parent_global_xform; - Transform parent_local_scaling_m; + Transform3D parent_global_xform; + Transform3D parent_local_scaling_m; if (parent_transform.is_valid()) { parent_global_xform = parent_transform->GlobalTransform; parent_local_scaling_m = parent_transform->Local_Scaling_Matrix; } - Transform local_rotation_m, parent_global_rotation_m; - Quat parent_global_rotation = parent_global_xform.basis.get_rotation_quat(); - parent_global_rotation_m.basis.set_quat(parent_global_rotation); + Transform3D local_rotation_m, parent_global_rotation_m; + Quaternion parent_global_rotation = parent_global_xform.basis.get_rotation_quaternion(); + parent_global_rotation_m.basis.set_quaternion(parent_global_rotation); local_rotation_m = Rpre * R * Rpost; - //Basis parent_global_rotation = Basis(parent_global_xform.get_basis().get_rotation_quat().normalized()); + //Basis parent_global_rotation = Basis(parent_global_xform.get_basis().get_rotation_quaternion().normalized()); - Transform local_shear_scaling, parent_shear_scaling, parent_shear_rotation, parent_shear_translation; + Transform3D local_shear_scaling, parent_shear_scaling, parent_shear_rotation, parent_shear_translation; Vector3 parent_translation = parent_global_xform.get_origin(); parent_shear_translation.origin = parent_translation; parent_shear_rotation = parent_shear_translation.affine_inverse() * parent_global_xform; @@ -197,26 +197,26 @@ Transform PivotTransform::ComputeGlobalTransform(Vector3 p_translation, Quat p_r local_shear_scaling = S; // Inherit type handler - we don't care about T here, just reordering RSrs etc. - Transform global_rotation_scale; + Transform3D global_rotation_scale; if (inherit_type == FBXDocParser::Transform_RrSs) { global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_shear_scaling * local_shear_scaling; } else if (inherit_type == FBXDocParser::Transform_RSrs) { global_rotation_scale = parent_global_rotation_m * parent_shear_scaling * local_rotation_m * local_shear_scaling; } else if (inherit_type == FBXDocParser::Transform_Rrs) { - Transform parent_global_shear_m_noLocal = parent_shear_scaling * parent_local_scaling_m.affine_inverse(); + Transform3D parent_global_shear_m_noLocal = parent_shear_scaling * parent_local_scaling_m.affine_inverse(); global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_global_shear_m_noLocal * local_shear_scaling; } - Transform local_transform = T * Roff * Rp * Rpre * R * Rpost.affine_inverse() * Rp.affine_inverse() * Soff * Sp * S * Sp.affine_inverse(); - //Transform local_translation_pivoted = Transform(Basis(), LocalTransform.origin); + Transform3D local_transform = T * Roff * Rp * Rpre * R * Rpost.affine_inverse() * Rp.affine_inverse() * Soff * Sp * S * Sp.affine_inverse(); + //Transform3D local_translation_pivoted = Transform3D(Basis(), LocalTransform.origin); - ERR_FAIL_COND_V_MSG(local_transform.basis.determinant() == 0, Transform(), "Det == 0 prevented in scene file"); + ERR_FAIL_COND_V_MSG(local_transform.basis.determinant() == 0, Transform3D(), "Det == 0 prevented in scene file"); // manual hack to force SSC not to be compensated for - until we can handle it properly with tests return parent_global_xform * local_transform; } void PivotTransform::ComputePivotTransform() { - Transform T, Roff, Rp, Soff, Sp, S; + Transform3D T, Roff, Rp, Soff, Sp, S; // Here I assume this is the operation which needs done. // Its WorldTransform * V @@ -237,26 +237,26 @@ void PivotTransform::ComputePivotTransform() { Local_Scaling_Matrix = S; // copy for when node / child is looking for the value of this. // Rotation pivots - Transform Rpre = Transform(pre_rotation); - Transform R = Transform(rotation); - Transform Rpost = Transform(post_rotation); + Transform3D Rpre = Transform3D(pre_rotation); + Transform3D R = Transform3D(rotation); + Transform3D Rpost = Transform3D(post_rotation); - Transform parent_global_xform; - Transform parent_local_scaling_m; + Transform3D parent_global_xform; + Transform3D parent_local_scaling_m; if (parent_transform.is_valid()) { parent_global_xform = parent_transform->GlobalTransform; parent_local_scaling_m = parent_transform->Local_Scaling_Matrix; } - Transform local_rotation_m, parent_global_rotation_m; - Quat parent_global_rotation = parent_global_xform.basis.get_rotation_quat(); - parent_global_rotation_m.basis.set_quat(parent_global_rotation); + Transform3D local_rotation_m, parent_global_rotation_m; + Quaternion parent_global_rotation = parent_global_xform.basis.get_rotation_quaternion(); + parent_global_rotation_m.basis.set_quaternion(parent_global_rotation); local_rotation_m = Rpre * R * Rpost; - //Basis parent_global_rotation = Basis(parent_global_xform.get_basis().get_rotation_quat().normalized()); + //Basis parent_global_rotation = Basis(parent_global_xform.get_basis().get_rotation_quaternion().normalized()); - Transform local_shear_scaling, parent_shear_scaling, parent_shear_rotation, parent_shear_translation; + Transform3D local_shear_scaling, parent_shear_scaling, parent_shear_rotation, parent_shear_translation; Vector3 parent_translation = parent_global_xform.get_origin(); parent_shear_translation.origin = parent_translation; parent_shear_rotation = parent_shear_translation.affine_inverse() * parent_global_xform; @@ -264,24 +264,24 @@ void PivotTransform::ComputePivotTransform() { local_shear_scaling = S; // Inherit type handler - we don't care about T here, just reordering RSrs etc. - Transform global_rotation_scale; + Transform3D global_rotation_scale; if (inherit_type == FBXDocParser::Transform_RrSs) { global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_shear_scaling * local_shear_scaling; } else if (inherit_type == FBXDocParser::Transform_RSrs) { global_rotation_scale = parent_global_rotation_m * parent_shear_scaling * local_rotation_m * local_shear_scaling; } else if (inherit_type == FBXDocParser::Transform_Rrs) { - Transform parent_global_shear_m_noLocal = parent_shear_scaling * parent_local_scaling_m.inverse(); + Transform3D parent_global_shear_m_noLocal = parent_shear_scaling * parent_local_scaling_m.inverse(); global_rotation_scale = parent_global_rotation_m * local_rotation_m * parent_global_shear_m_noLocal * local_shear_scaling; } - LocalTransform = Transform(); + LocalTransform = Transform3D(); LocalTransform = T * Roff * Rp * Rpre * R * Rpost.affine_inverse() * Rp.affine_inverse() * Soff * Sp * S * Sp.affine_inverse(); ERR_FAIL_COND_MSG(LocalTransform.basis.determinant() == 0, "invalid scale reset"); - Transform local_translation_pivoted = Transform(Basis(), LocalTransform.origin); - GlobalTransform = Transform(); + Transform3D local_translation_pivoted = Transform3D(Basis(), LocalTransform.origin); + GlobalTransform = Transform3D(); //GlobalTransform = parent_global_xform * LocalTransform; - Transform global_origin = Transform(Basis(), parent_translation); + Transform3D global_origin = Transform3D(Basis(), parent_translation); GlobalTransform = (global_origin * local_translation_pivoted) * global_rotation_scale; ImportUtils::debug_xform("local xform calculation", LocalTransform); diff --git a/modules/fbx/data/pivot_transform.h b/modules/fbx/data/pivot_transform.h index 9996027870..099b268075 100644 --- a/modules/fbx/data/pivot_transform.h +++ b/modules/fbx/data/pivot_transform.h @@ -31,8 +31,8 @@ #ifndef PIVOT_TRANSFORM_H #define PIVOT_TRANSFORM_H -#include "core/math/transform.h" -#include "core/object/reference.h" +#include "core/math/transform_3d.h" +#include "core/object/ref_counted.h" #include "model_abstraction.h" @@ -55,13 +55,13 @@ enum TransformationComp { TransformationComp_MAXIMUM }; // Abstract away pivot data so its simpler to handle -struct PivotTransform : Reference, ModelAbstraction { +struct PivotTransform : RefCounted, ModelAbstraction { // at the end we want to keep geometric_ everything, post and pre rotation // these are used during animation data processing / keyframe ingestion the rest can be simplified down / out. - Quat pre_rotation = Quat(); - Quat post_rotation = Quat(); - Quat rotation = Quat(); - Quat geometric_rotation = Quat(); + Quaternion pre_rotation = Quaternion(); + Quaternion post_rotation = Quaternion(); + Quaternion rotation = Quaternion(); + Quaternion geometric_rotation = Quaternion(); Vector3 rotation_pivot = Vector3(); Vector3 rotation_offset = Vector3(); Vector3 scaling_offset = Vector3(1.0, 1.0, 1.0); @@ -85,10 +85,10 @@ struct PivotTransform : Reference, ModelAbstraction { print_verbose("raw post_rotation " + raw_post_rotation * (180 / Math_PI)); } - Transform ComputeGlobalTransform(Transform t) const; - Transform ComputeLocalTransform(Transform t) const; - Transform ComputeGlobalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const; - Transform ComputeLocalTransform(Vector3 p_translation, Quat p_rotation, Vector3 p_scaling) const; + Transform3D ComputeGlobalTransform(Transform3D t) const; + Transform3D ComputeLocalTransform(Transform3D t) const; + Transform3D ComputeGlobalTransform(Vector3 p_translation, Quaternion p_rotation, Vector3 p_scaling) const; + Transform3D ComputeLocalTransform(Vector3 p_translation, Quaternion p_rotation, Vector3 p_scaling) const; /* Extract into xforms and calculate once */ void ComputePivotTransform(); @@ -105,10 +105,10 @@ struct PivotTransform : Reference, ModelAbstraction { //Transform chain[TransformationComp_MAXIMUM]; // cached for later use - Transform GlobalTransform = Transform(); - Transform LocalTransform = Transform(); - Transform Local_Scaling_Matrix = Transform(); // used for inherit type. - Transform GeometricTransform = Transform(); // 3DS max only + Transform3D GlobalTransform = Transform3D(); + Transform3D LocalTransform = Transform3D(); + Transform3D Local_Scaling_Matrix = Transform3D(); // used for inherit type. + Transform3D GeometricTransform = Transform3D(); // 3DS max only FBXDocParser::TransformInheritance inherit_type = FBXDocParser::TransformInheritance_MAX; // maya fbx requires this - sorry <3 }; diff --git a/modules/fbx/editor_scene_importer_fbx.cpp b/modules/fbx/editor_scene_importer_fbx.cpp index edea1963a7..e3f36ef3e3 100644 --- a/modules/fbx/editor_scene_importer_fbx.cpp +++ b/modules/fbx/editor_scene_importer_fbx.cpp @@ -102,9 +102,9 @@ Node3D *EditorSceneImporterFBX::import_scene(const String &p_path, uint32_t p_fl FBXDocParser::TokenList tokens; bool is_binary = false; - data.resize(f->get_len()); + data.resize(f->get_length()); - ERR_FAIL_COND_V(data.size() < 64, NULL); + ERR_FAIL_COND_V(data.size() < 64, nullptr); f->get_buffer(data.ptrw(), data.size()); PackedByteArray fbx_header; @@ -258,24 +258,24 @@ struct EditorSceneImporterAssetImportInterpolate { //thank you for existing, partial specialization template <> -struct EditorSceneImporterAssetImportInterpolate<Quat> { - Quat lerp(const Quat &a, const Quat &b, float c) const { - ERR_FAIL_COND_V(!a.is_normalized(), Quat()); - ERR_FAIL_COND_V(!b.is_normalized(), Quat()); +struct EditorSceneImporterAssetImportInterpolate<Quaternion> { + Quaternion lerp(const Quaternion &a, const Quaternion &b, float c) const { + ERR_FAIL_COND_V(!a.is_normalized(), Quaternion()); + ERR_FAIL_COND_V(!b.is_normalized(), Quaternion()); return a.slerp(b, c).normalized(); } - Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) { - ERR_FAIL_COND_V(!p1.is_normalized(), Quat()); - ERR_FAIL_COND_V(!p2.is_normalized(), Quat()); + Quaternion catmull_rom(const Quaternion &p0, const Quaternion &p1, const Quaternion &p2, const Quaternion &p3, float c) { + ERR_FAIL_COND_V(!p1.is_normalized(), Quaternion()); + ERR_FAIL_COND_V(!p2.is_normalized(), Quaternion()); return p1.slerp(p2, c).normalized(); } - Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) { - ERR_FAIL_COND_V(!start.is_normalized(), Quat()); - ERR_FAIL_COND_V(!end.is_normalized(), Quat()); + Quaternion bezier(Quaternion start, Quaternion control_1, Quaternion control_2, Quaternion end, float t) { + ERR_FAIL_COND_V(!start.is_normalized(), Quaternion()); + ERR_FAIL_COND_V(!end.is_normalized(), Quaternion()); return start.slerp(end, t).normalized(); } @@ -373,7 +373,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( scene_root->add_child(state.root); state.root->set_owner(scene_root); - state.fbx_root_node.instance(); + state.fbx_root_node.instantiate(); state.fbx_root_node->godot_node = state.root; // Size relative to cm. @@ -389,11 +389,11 @@ Node3D *EditorSceneImporterFBX::_generate_scene( // Enabled by default. state.enable_animation_import = true; Ref<FBXNode> root_node; - root_node.instance(); + root_node.instantiate(); // make sure fake noFBXDocParser::PropertyPtr ptrde always has a transform too ;) Ref<PivotTransform> pivot_transform; - pivot_transform.instance(); + pivot_transform.instantiate(); root_node->pivot_transform = pivot_transform; root_node->node_name = "root node"; root_node->current_node_id = 0; @@ -479,7 +479,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( if (state.renderer_mesh_data.has(mesh_id)) { mesh_vertex_data = state.renderer_mesh_data[mesh_id]; } else { - mesh_vertex_data.instance(); + mesh_vertex_data.instantiate(); state.renderer_mesh_data.insert(mesh_id, mesh_vertex_data); } @@ -535,7 +535,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( ERR_CONTINUE_MSG(!mat, "Could not convert fbx material by id: " + itos(material_id)); Ref<FBXMaterial> material; - material.instance(); + material.instantiate(); material->set_imported_material(mat); Ref<StandardMaterial3D> godot_material = material->import_material(state); @@ -575,7 +575,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( if (state.skeleton_map.has(armature_id)) { fbx_skeleton_inst = state.skeleton_map[armature_id]; } else { - fbx_skeleton_inst.instance(); + fbx_skeleton_inst.instantiate(); state.skeleton_map.insert(armature_id, fbx_skeleton_inst); } @@ -650,7 +650,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( if (state.renderer_mesh_data.has(mesh_id)) { mesh_data_precached = state.renderer_mesh_data[mesh_id]; } else { - mesh_data_precached.instance(); + mesh_data_precached.instantiate(); state.renderer_mesh_data.insert(mesh_id, mesh_data_precached); } @@ -735,7 +735,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( Ref<Skin> skin; if (!state.MeshSkins.has(mesh_id)) { print_verbose("Created new skin"); - skin.instance(); + skin.instantiate(); state.MeshSkins.insert(mesh_id, skin); } else { print_verbose("Grabbed skin"); @@ -848,7 +848,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( } Ref<Animation> animation; - animation.instance(); + animation.instantiate(); animation->set_name(animation_name); animation->set_length(duration); @@ -888,7 +888,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( // we need to know what object the curves are for. // we need the target ID and the target name for the track reduction. - FBXDocParser::Model::RotOrder quat_rotation_order = FBXDocParser::Model::RotOrder_EulerXYZ; + FBXDocParser::Model::RotOrder quaternion_rotation_order = FBXDocParser::Model::RotOrder_EulerXYZ; // T:: R:: S:: Visible:: Custom:: for (const FBXDocParser::AnimationCurveNode *curve_node : node_list) { @@ -910,7 +910,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( continue; } else { //print_verbose("[doc] applied rotation order: " + itos(target->RotationOrder())); - quat_rotation_order = target->RotationOrder(); + quaternion_rotation_order = target->RotationOrder(); } uint64_t target_id = target->ID(); @@ -1011,7 +1011,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( // track count is 5. // next track id is 5. const uint64_t target_id = track->key(); - int track_idx = animation->add_track(Animation::TYPE_TRANSFORM); + int track_idx = animation->add_track(Animation::TYPE_TRANSFORM3D); // animation->track_set_path(track_idx, node_path); Ref<FBXBone> bone; @@ -1023,7 +1023,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( bone = state.fbx_bone_map[target_id]; } - Transform target_transform; + Transform3D target_transform; if (state.fbx_target_map.has(target_id)) { Ref<FBXNode> node_ref = state.fbx_target_map[target_id]; @@ -1056,7 +1056,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( //print_verbose("[doc] node animation path: " + node_path); } } else { - // note: this could actually be unsafe this means we should be careful about continuing here, if we see bizzare effects later we should disable this. + // note: this could actually be unsafe this means we should be careful about continuing here, if we see bizarre effects later we should disable this. // I am not sure if this is unsafe or not, testing will tell us this. print_error("[doc] invalid fbx target detected for this track"); continue; @@ -1086,7 +1086,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( Vector<float> pos_times; Vector<Vector3> scale_values; Vector<float> scale_times; - Vector<Quat> rot_values; + Vector<Quaternion> rot_values; Vector<float> rot_times; double max_duration = 0; @@ -1122,8 +1122,8 @@ Node3D *EditorSceneImporterFBX::_generate_scene( bool got_pre = false; bool got_post = false; - Quat post_rotation; - Quat pre_rotation; + Quaternion post_rotation; + Quaternion pre_rotation; // Rotation matrix const Vector3 &PreRotation = FBXDocParser::PropertyGet<Vector3>(props, "PreRotation", got_pre); @@ -1137,24 +1137,24 @@ Node3D *EditorSceneImporterFBX::_generate_scene( post_rotation = ImportUtils::EulerToQuaternion(rot_order, ImportUtils::deg2rad(PostRotation)); } - Quat lastQuat = Quat(); + Quaternion lastQuaternion = Quaternion(); for (std::pair<int64_t, Vector3> rotation_key : rotation_keys.keyframes) { double animation_track_time = CONVERT_FBX_TIME(rotation_key.first); //print_verbose("euler rotation key: " + rotation_key.second); - Quat rot_key_value = ImportUtils::EulerToQuaternion(quat_rotation_order, ImportUtils::deg2rad(rotation_key.second)); + Quaternion rot_key_value = ImportUtils::EulerToQuaternion(quaternion_rotation_order, ImportUtils::deg2rad(rotation_key.second)); - if (lastQuat != Quat() && rot_key_value.dot(lastQuat) < 0) { + if (lastQuaternion != Quaternion() && rot_key_value.dot(lastQuaternion) < 0) { rot_key_value.x = -rot_key_value.x; rot_key_value.y = -rot_key_value.y; rot_key_value.z = -rot_key_value.z; rot_key_value.w = -rot_key_value.w; } // pre_post rotation possibly could fix orientation - Quat final_rotation = pre_rotation * rot_key_value * post_rotation; + Quaternion final_rotation = pre_rotation * rot_key_value * post_rotation; - lastQuat = final_rotation; + lastQuaternion = final_rotation; if (animation_track_time > max_duration) { max_duration = animation_track_time; @@ -1165,7 +1165,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( } bool valid_rest = false; - Transform bone_rest; + Transform3D bone_rest; int skeleton_bone = -1; if (state.fbx_bone_map.has(target_id)) { if (bone.is_valid() && bone->fbx_skeleton.is_valid()) { @@ -1182,13 +1182,13 @@ Node3D *EditorSceneImporterFBX::_generate_scene( } const Vector3 def_pos = translation_keys.has_default ? (translation_keys.default_value * state.scale) : bone_rest.origin; - const Quat def_rot = rotation_keys.has_default ? ImportUtils::EulerToQuaternion(quat_rotation_order, ImportUtils::deg2rad(rotation_keys.default_value)) : bone_rest.basis.get_rotation_quat(); + const Quaternion def_rot = rotation_keys.has_default ? ImportUtils::EulerToQuaternion(quaternion_rotation_order, ImportUtils::deg2rad(rotation_keys.default_value)) : bone_rest.basis.get_rotation_quaternion(); const Vector3 def_scale = scale_keys.has_default ? scale_keys.default_value : bone_rest.basis.get_scale(); print_verbose("track defaults: p(" + def_pos + ") s(" + def_scale + ") r(" + def_rot + ")"); while (true) { Vector3 pos = def_pos; - Quat rot = def_rot; + Quaternion rot = def_rot; Vector3 scale = def_scale; if (pos_values.size()) { @@ -1197,7 +1197,7 @@ Node3D *EditorSceneImporterFBX::_generate_scene( } if (rot_values.size()) { - rot = _interpolate_track<Quat>(rot_times, rot_values, time, + rot = _interpolate_track<Quaternion>(rot_times, rot_values, time, AssetImportAnimation::INTERP_LINEAR); } @@ -1208,13 +1208,13 @@ Node3D *EditorSceneImporterFBX::_generate_scene( // node animations must also include pivots if (skeleton_bone >= 0) { - Transform xform = Transform(); - xform.basis.set_quat_scale(rot, scale); + Transform3D xform = Transform3D(); + xform.basis.set_quaternion_scale(rot, scale); xform.origin = pos; - const Transform t = bone_rest.affine_inverse() * xform; + const Transform3D t = bone_rest.affine_inverse() * xform; // populate this again - rot = t.basis.get_rotation_quat(); + rot = t.basis.get_rotation_quaternion(); rot.normalize(); scale = t.basis.get_scale(); pos = t.origin; @@ -1312,7 +1312,7 @@ void EditorSceneImporterFBX::BuildDocumentBones(Ref<FBXBone> p_parent_bone, // declare our bone element reference (invalid, unless we create a bone in this step) // this lets us pass valid armature information into children objects and this is why we moved this up here - // previously this was created .instanced() on the same line. + // previously this was created .instantiated() on the same line. Ref<FBXBone> bone_element; if (model != nullptr) { @@ -1324,7 +1324,7 @@ void EditorSceneImporterFBX::BuildDocumentBones(Ref<FBXBone> p_parent_bone, ERR_FAIL_COND_MSG(state.fbx_bone_map.has(limb_node->ID()), "[serious] duplicate LimbNode detected"); bool parent_is_bone = state.fbx_bone_map.find(p_id); - bone_element.instance(); + bone_element.instantiate(); // used to build the bone hierarchy in the skeleton bone_element->parent_bone_id = parent_is_bone ? p_id : 0; @@ -1404,12 +1404,12 @@ void EditorSceneImporterFBX::BuildDocumentNodes( uint64_t current_node_id = model->ID(); Ref<FBXNode> new_node; - new_node.instance(); + new_node.instantiate(); new_node->current_node_id = current_node_id; new_node->node_name = ImportUtils::FBXNodeToName(model->Name()); Ref<PivotTransform> fbx_transform; - fbx_transform.instance(); + fbx_transform.instantiate(); fbx_transform->set_parent(parent_transform); fbx_transform->set_model(model); fbx_transform->debug_pivot_xform("name: " + new_node->node_name); diff --git a/modules/fbx/editor_scene_importer_fbx.h b/modules/fbx/editor_scene_importer_fbx.h index 4bb2c9d21b..4a3b78480b 100644 --- a/modules/fbx/editor_scene_importer_fbx.h +++ b/modules/fbx/editor_scene_importer_fbx.h @@ -36,7 +36,6 @@ #include "data/import_state.h" #include "tools/import_utils.h" -#include "core/core_bind.h" #include "core/io/resource_importer.h" #include "core/string/ustring.h" #include "core/templates/local_vector.h" diff --git a/modules/fbx/fbx_parser/ByteSwapper.h b/modules/fbx/fbx_parser/ByteSwapper.h index 5c16383974..08d38147d5 100644 --- a/modules/fbx/fbx_parser/ByteSwapper.h +++ b/modules/fbx/fbx_parser/ByteSwapper.h @@ -70,7 +70,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ -/** @file Helper class tp perform various byte oder swappings +/** @file Helper class tp perform various byte order swappings (e.g. little to big endian) */ #ifndef BYTE_SWAPPER_H #define BYTE_SWAPPER_H diff --git a/modules/fbx/fbx_parser/FBXAnimation.cpp b/modules/fbx/fbx_parser/FBXAnimation.cpp index 1690df6943..0fbff035fd 100644 --- a/modules/fbx/fbx_parser/FBXAnimation.cpp +++ b/modules/fbx/fbx_parser/FBXAnimation.cpp @@ -128,7 +128,7 @@ AnimationCurve::~AnimationCurve() { // ------------------------------------------------------------------------------------------------ AnimationCurveNode::AnimationCurveNode(uint64_t id, const ElementPtr element, const std::string &name, - const Document &doc, const char *const *target_prop_whitelist /*= NULL*/, + const Document &doc, const char *const *target_prop_whitelist /*= nullptr*/, size_t whitelist_size /*= 0*/) : Object(id, element, name), target(), doc(doc) { // find target node diff --git a/modules/fbx/fbx_parser/FBXDeformer.cpp b/modules/fbx/fbx_parser/FBXDeformer.cpp index 039718ae15..4220ba62a7 100644 --- a/modules/fbx/fbx_parser/FBXDeformer.cpp +++ b/modules/fbx/fbx_parser/FBXDeformer.cpp @@ -78,7 +78,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FBXMeshGeometry.h" #include "FBXParser.h" #include "core/math/math_funcs.h" -#include "core/math/transform.h" +#include "core/math/transform_3d.h" #include <iostream> diff --git a/modules/fbx/fbx_parser/FBXDocument.cpp b/modules/fbx/fbx_parser/FBXDocument.cpp index bb85d6ff7c..92c62e68b5 100644 --- a/modules/fbx/fbx_parser/FBXDocument.cpp +++ b/modules/fbx/fbx_parser/FBXDocument.cpp @@ -198,7 +198,7 @@ ObjectPtr LazyObject::LoadObject() { object.reset(new ModelLimbNode(id, element, doc, name)); } else if (strcmp(classtag.c_str(), "IKEffector") && strcmp(classtag.c_str(), "FKEffector")) { - // FK and IK effectors are not supporte + // FK and IK effectors are not supported. object.reset(new Model(id, element, doc, name)); } } else if (!strncmp(obtype, "Material", length)) { @@ -487,7 +487,7 @@ const std::vector<const AnimationStack *> &Document::AnimationStacks() const { const AnimationStack *stack = lazy->Get<AnimationStack>(); ERR_CONTINUE_MSG(!stack, "invalid ptr to AnimationStack - conversion failure"); - // We push back the weak reference :) to keep things simple, as ownership is on the parser side so it wont be cleaned up. + // We push back the weak reference :) to keep things simple, as ownership is on the parser side so it won't be cleaned up. animationStacksResolved.push_back(stack); } diff --git a/modules/fbx/fbx_parser/FBXDocument.h b/modules/fbx/fbx_parser/FBXDocument.h index 49b7c11c31..885ff8fca4 100644 --- a/modules/fbx/fbx_parser/FBXDocument.h +++ b/modules/fbx/fbx_parser/FBXDocument.h @@ -37,7 +37,7 @@ #include "FBXCommon.h" #include "FBXParser.h" #include "FBXProperties.h" -#include "core/math/transform.h" +#include "core/math/transform_3d.h" #include "core/math/vector2.h" #include "core/math/vector3.h" #include "core/string/print_string.h" @@ -242,13 +242,13 @@ public: return target_id; } - Transform GetBindPose() const { + Transform3D GetBindPose() const { return transform; } private: uint64_t target_id = 0; - Transform transform; + Transform3D transform; }; /** DOM base class for FBX cameras attached to a node */ @@ -699,7 +699,7 @@ private: typedef std::vector<int64_t> KeyTimeList; typedef std::vector<float> KeyValueList; -/** Represents a FBX animation curve (i.e. a 1-dimensional set of keyframes and values therefor) */ +/** Represents a FBX animation curve (i.e. a 1-dimensional set of keyframes and values therefore) */ class AnimationCurve : public Object { public: AnimationCurve(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc); @@ -759,7 +759,7 @@ public: const AnimationMap &Curves() const; - /** Object the curve is assigned to, this can be NULL if the + /** Object the curve is assigned to, this can be nullptr if the * target object has no DOM representation or could not * be read for other reasons.*/ Object *Target() const { @@ -905,11 +905,11 @@ public: } /** */ - const Transform &GetTransform() const { + const Transform3D &GetTransform() const { return transform; } - const Transform &TransformLink() const { + const Transform3D &TransformLink() const { return transformLink; } @@ -917,7 +917,7 @@ public: return node; } - const Transform &TransformAssociateModel() const { + const Transform3D &TransformAssociateModel() const { return transformAssociateModel; } @@ -941,9 +941,9 @@ private: std::vector<float> weights; std::vector<unsigned int> indices; - Transform transform; - Transform transformLink; - Transform transformAssociateModel; + Transform3D transform; + Transform3D transformLink; + Transform3D transformAssociateModel; SkinLinkMode link_mode; bool valid_transformAssociateModel = false; const Model *node = nullptr; @@ -989,7 +989,7 @@ public: // note: a connection ensures that the source and dest objects exist, but // not that they have DOM representations, so the return value of one of - // these functions can still be NULL. + // these functions can still be nullptr. Object *SourceObject() const; Object *DestinationObject() const; diff --git a/modules/fbx/fbx_parser/FBXDocumentUtil.cpp b/modules/fbx/fbx_parser/FBXDocumentUtil.cpp index 3930e005c3..4a33024969 100644 --- a/modules/fbx/fbx_parser/FBXDocumentUtil.cpp +++ b/modules/fbx/fbx_parser/FBXDocumentUtil.cpp @@ -95,14 +95,14 @@ void DOMError(const std::string &message, const std::shared_ptr<Token> token) { print_error("[FBX-DOM]" + String(message.c_str()) + ";" + String(token->StringContents().c_str())); } -void DOMError(const std::string &message, const Element *element /*= NULL*/) { +void DOMError(const std::string &message, const Element *element /*= nullptr*/) { if (element) { DOMError(message, element->KeyToken()); } print_error("[FBX-DOM] " + String(message.c_str())); } -void DOMError(const std::string &message, const std::shared_ptr<Element> element /*= NULL*/) { +void DOMError(const std::string &message, const std::shared_ptr<Element> element /*= nullptr*/) { if (element) { DOMError(message, element->KeyToken()); } @@ -117,7 +117,7 @@ void DOMWarning(const std::string &message, const Token *token) { print_verbose("[FBX-DOM] warning:" + String(message.c_str()) + ";" + String(token->StringContents().c_str())); } -void DOMWarning(const std::string &message, const Element *element /*= NULL*/) { +void DOMWarning(const std::string &message, const Element *element /*= nullptr*/) { if (element) { DOMWarning(message, element->KeyToken()); return; @@ -129,7 +129,7 @@ void DOMWarning(const std::string &message, const std::shared_ptr<Token> token) print_verbose("[FBX-DOM] warning:" + String(message.c_str()) + ";" + String(token->StringContents().c_str())); } -void DOMWarning(const std::string &message, const std::shared_ptr<Element> element /*= NULL*/) { +void DOMWarning(const std::string &message, const std::shared_ptr<Element> element /*= nullptr*/) { if (element) { DOMWarning(message, element->KeyToken()); return; diff --git a/modules/fbx/fbx_parser/FBXMeshGeometry.cpp b/modules/fbx/fbx_parser/FBXMeshGeometry.cpp index a28e7565c6..2cc25a0690 100644 --- a/modules/fbx/fbx_parser/FBXMeshGeometry.cpp +++ b/modules/fbx/fbx_parser/FBXMeshGeometry.cpp @@ -125,7 +125,7 @@ MeshGeometry::MeshGeometry(uint64_t id, const ElementPtr element, const std::str ScopePtr sc = element->Compound(); ERR_FAIL_COND_MSG(sc == nullptr, "failed to read geometry, prevented crash"); - ERR_FAIL_COND_MSG(!HasElement(sc, "Vertices"), "Detected mesh with no vertexes, didn't populate the mesh"); + ERR_FAIL_COND_MSG(!HasElement(sc, "Vertices"), "Detected mesh with no vertices, didn't populate the mesh"); // must have Mesh elements: const ElementPtr Vertices = GetRequiredElement(sc, "Vertices", element); @@ -140,7 +140,7 @@ MeshGeometry::MeshGeometry(uint64_t id, const ElementPtr element, const std::str ParseVectorDataArray(m_vertices, Vertices); ParseVectorDataArray(m_face_indices, PolygonVertexIndex); - ERR_FAIL_COND_MSG(m_vertices.empty(), "mesh with no vertexes in FBX file, did you mean to delete it?"); + ERR_FAIL_COND_MSG(m_vertices.empty(), "mesh with no vertices in FBX file, did you mean to delete it?"); ERR_FAIL_COND_MSG(m_face_indices.empty(), "mesh has no faces, was this intended?"); // Retrieve layer elements, for all of the mesh @@ -278,7 +278,7 @@ MeshGeometry::MeshGeometry(uint64_t id, const ElementPtr element, const std::str } } // As the algorithm above, this check is useless. Because the first - // ever vertex is always considered the begining of a polygon. + // ever vertex is always considered the beginning of a polygon. ERR_FAIL_COND_MSG(found_it == false, "Was not possible to find the first vertex of this polygon. FBX file is corrupted."); } else { @@ -418,7 +418,7 @@ MeshGeometry::MappingData<T> MeshGeometry::resolve_vertex_data_array( // parse data into array ParseVectorDataArray(tempData.data, GetRequiredElement(source, dataElementName)); - // index array wont always exist + // index array won't always exist const ElementPtr element = GetOptionalElement(source, indexDataElementName); if (element) { ParseVectorDataArray(tempData.index, element); diff --git a/modules/fbx/fbx_parser/FBXMeshGeometry.h b/modules/fbx/fbx_parser/FBXMeshGeometry.h index 710e644c68..c9b25f008d 100644 --- a/modules/fbx/fbx_parser/FBXMeshGeometry.h +++ b/modules/fbx/fbx_parser/FBXMeshGeometry.h @@ -96,7 +96,7 @@ public: Geometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc); virtual ~Geometry(); - /** Get the Skin attached to this geometry or NULL */ + /** Get the Skin attached to this geometry or nullptr */ const Skin *DeformerSkin() const; const std::vector<const BlendShape *> &get_blend_shapes() const; @@ -122,7 +122,7 @@ typedef std::vector<int> MatIndexArray; /// ## Map Type: /// * None The mapping is undetermined. /// * ByVertex There will be one mapping coordinate for each surface control point/vertex (ControlPoint is a vertex). -/// * If you have direct reference type verticies[x] +/// * If you have direct reference type vertices[x] /// * If you have IndexToDirect reference type the UV /// * ByPolygonVertex There will be one mapping coordinate for each vertex, for every polygon of which it is a part. This means that a vertex will have as many mapping coordinates as polygons of which it is a part. (Sorted by polygon, referencing vertex) /// * ByPolygon There can be only one mapping coordinate for the whole polygon. @@ -186,7 +186,7 @@ public: /// Returns -1 if the vertices doesn't form an edge. Vertex order, doesn't // matter. static int get_edge_id(const std::vector<Edge> &p_map, int p_vertex_a, int p_vertex_b); - // Retuns the edge point bu that ID, or the edge with -1 vertices if the + // Returns the edge point bu that ID, or the edge with -1 vertices if the // id is not valid. static Edge get_edge(const std::vector<Edge> &p_map, int p_id); diff --git a/modules/fbx/fbx_parser/FBXParser.cpp b/modules/fbx/fbx_parser/FBXParser.cpp index 2a76c3f67c..a92b23f4ee 100644 --- a/modules/fbx/fbx_parser/FBXParser.cpp +++ b/modules/fbx/fbx_parser/FBXParser.cpp @@ -82,7 +82,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "FBXParser.h" #include "FBXTokenizer.h" #include "core/math/math_defs.h" -#include "core/math/transform.h" +#include "core/math/transform_3d.h" #include "core/math/vector3.h" #include "core/string/print_string.h" @@ -1157,7 +1157,7 @@ void ParseVectorDataArray(std::vector<int64_t> &out, const ElementPtr el) { } // ------------------------------------------------------------------------------------------------ -Transform ReadMatrix(const ElementPtr element) { +Transform3D ReadMatrix(const ElementPtr element) { std::vector<float> values; ParseVectorDataArray(values, element); @@ -1167,12 +1167,12 @@ Transform ReadMatrix(const ElementPtr element) { // clean values to prevent any IBM damage on inverse() / affine_inverse() for (float &value : values) { - if (::Math::is_equal_approx(0, value)) { + if (::Math::is_zero_approx(value)) { value = 0; } } - Transform xform; + Transform3D xform; Basis basis; basis.set( @@ -1206,7 +1206,7 @@ std::string ParseTokenAsString(const TokenPtr t) { // ------------------------------------------------------------------------------------------------ // extract a required element from a scope, abort if the element cannot be found -ElementPtr GetRequiredElement(const ScopePtr sc, const std::string &index, const ElementPtr element /*= NULL*/) { +ElementPtr GetRequiredElement(const ScopePtr sc, const std::string &index, const ElementPtr element /*= nullptr*/) { const ElementPtr el = sc->GetElement(index); TokenPtr token = el->KeyToken(); ERR_FAIL_COND_V(!token, nullptr); @@ -1227,7 +1227,7 @@ bool HasElement(const ScopePtr sc, const std::string &index) { // ------------------------------------------------------------------------------------------------ // extract a required element from a scope, abort if the element cannot be found -ElementPtr GetOptionalElement(const ScopePtr sc, const std::string &index, const ElementPtr element /*= NULL*/) { +ElementPtr GetOptionalElement(const ScopePtr sc, const std::string &index, const ElementPtr element /*= nullptr*/) { const ElementPtr el = sc->GetElement(index); return el; } diff --git a/modules/fbx/fbx_parser/FBXParser.h b/modules/fbx/fbx_parser/FBXParser.h index 8b248e8791..93836c2205 100644 --- a/modules/fbx/fbx_parser/FBXParser.h +++ b/modules/fbx/fbx_parser/FBXParser.h @@ -81,7 +81,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <memory> #include "core/math/color.h" -#include "core/math/transform.h" +#include "core/math/transform_3d.h" #include "core/math/vector2.h" #include "core/math/vector3.h" @@ -264,7 +264,7 @@ TokenPtr GetRequiredToken(const ElementPtr el, unsigned int index); // ------------------------------------------------------------------------------------------------ // read a 4x4 matrix from an array of 16 floats -Transform ReadMatrix(const ElementPtr element); +Transform3D ReadMatrix(const ElementPtr element); } // namespace FBXDocParser #endif // FBX_PARSER_H diff --git a/modules/fbx/fbx_parser/FBXProperties.cpp b/modules/fbx/fbx_parser/FBXProperties.cpp index 1b3f29ec04..37717e9109 100644 --- a/modules/fbx/fbx_parser/FBXProperties.cpp +++ b/modules/fbx/fbx_parser/FBXProperties.cpp @@ -94,7 +94,7 @@ Property::~Property() { namespace { // ------------------------------------------------------------------------------------------------ -// read a typed property out of a FBX element. The return value is NULL if the property cannot be read. +// read a typed property out of a FBX element. The return value is nullptr if the property cannot be read. PropertyPtr ReadTypedProperty(const ElementPtr element) { //ai_assert(element.KeyToken().StringContents() == "P"); diff --git a/modules/fbx/register_types.cpp b/modules/fbx/register_types.cpp index c0591dbc77..a75da8f3a9 100644 --- a/modules/fbx/register_types.cpp +++ b/modules/fbx/register_types.cpp @@ -36,7 +36,7 @@ #ifdef TOOLS_ENABLED static void _editor_init() { Ref<EditorSceneImporterFBX> import_fbx; - import_fbx.instance(); + import_fbx.instantiate(); ResourceImporterScene::get_singleton()->add_importer(import_fbx); } #endif @@ -46,7 +46,7 @@ void register_fbx_types() { ClassDB::APIType prev_api = ClassDB::get_current_api(); ClassDB::set_current_api(ClassDB::API_EDITOR); - ClassDB::register_class<EditorSceneImporterFBX>(); + GDREGISTER_CLASS(EditorSceneImporterFBX); ClassDB::set_current_api(prev_api); diff --git a/modules/fbx/tools/import_utils.cpp b/modules/fbx/tools/import_utils.cpp index c87dd1fd3a..66b0153308 100644 --- a/modules/fbx/tools/import_utils.cpp +++ b/modules/fbx/tools/import_utils.cpp @@ -80,7 +80,7 @@ Basis ImportUtils::EulerToBasis(FBXDocParser::Model::RotOrder mode, const Vector return ret; } -Quat ImportUtils::EulerToQuaternion(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation) { +Quaternion ImportUtils::EulerToQuaternion(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation) { return ImportUtils::EulerToBasis(mode, p_rotation); } @@ -117,18 +117,18 @@ Vector3 ImportUtils::BasisToEuler(FBXDocParser::Model::RotOrder mode, const Basi } } -Vector3 ImportUtils::QuaternionToEuler(FBXDocParser::Model::RotOrder mode, const Quat &p_rotation) { +Vector3 ImportUtils::QuaternionToEuler(FBXDocParser::Model::RotOrder mode, const Quaternion &p_rotation) { return BasisToEuler(mode, p_rotation); } -Transform get_unscaled_transform(const Transform &p_initial, real_t p_scale) { - Transform unscaled = Transform(p_initial.basis, p_initial.origin * p_scale); - ERR_FAIL_COND_V_MSG(unscaled.basis.determinant() == 0, Transform(), "det is zero unscaled?"); +Transform3D get_unscaled_transform(const Transform3D &p_initial, real_t p_scale) { + Transform3D unscaled = Transform3D(p_initial.basis, p_initial.origin * p_scale); + ERR_FAIL_COND_V_MSG(unscaled.basis.determinant() == 0, Transform3D(), "det is zero unscaled?"); return unscaled; } Vector3 get_poly_normal(const std::vector<Vector3> &p_vertices) { - ERR_FAIL_COND_V_MSG(p_vertices.size() < 3, Vector3(0, 0, 0), "At least 3 vertices are necesary"); + ERR_FAIL_COND_V_MSG(p_vertices.size() < 3, Vector3(0, 0, 0), "At least 3 vertices are necessary"); // Using long double to make sure that normal is computed for even really tiny objects. typedef long double ldouble; ldouble x = 0.0; diff --git a/modules/fbx/tools/import_utils.h b/modules/fbx/tools/import_utils.h index bea28ffeda..fbe7dbd82f 100644 --- a/modules/fbx/tools/import_utils.h +++ b/modules/fbx/tools/import_utils.h @@ -56,15 +56,15 @@ public: static Basis EulerToBasis(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation); /// Converts rotation order vector (in rad) to quaternion. - static Quat EulerToQuaternion(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation); + static Quaternion EulerToQuaternion(FBXDocParser::Model::RotOrder mode, const Vector3 &p_rotation); /// Converts basis into rotation order vector (in rad). static Vector3 BasisToEuler(FBXDocParser::Model::RotOrder mode, const Basis &p_rotation); /// Converts quaternion into rotation order vector (in rad). - static Vector3 QuaternionToEuler(FBXDocParser::Model::RotOrder mode, const Quat &p_rotation); + static Vector3 QuaternionToEuler(FBXDocParser::Model::RotOrder mode, const Quaternion &p_rotation); - static void debug_xform(String name, const Transform &t) { + static void debug_xform(String name, const Transform3D &t) { print_verbose(name + " " + t.origin + " rotation: " + (t.basis.get_euler() * (180 / Math_PI))); } @@ -137,15 +137,15 @@ public: static Vector3 safe_import_vector3(const Vector3 &p_vec) { Vector3 vector = p_vec; - if (Math::is_equal_approx(0, vector.x)) { + if (Math::is_zero_approx(vector.x)) { vector.x = 0; } - if (Math::is_equal_approx(0, vector.y)) { + if (Math::is_zero_approx(vector.y)) { vector.y = 0; } - if (Math::is_equal_approx(0, vector.z)) { + if (Math::is_zero_approx(vector.z)) { vector.z = 0; } return vector; @@ -267,7 +267,7 @@ public: */ // static void set_texture_mapping_mode(aiTextureMapMode *map_mode, Ref<ImageTexture> texture) { // ERR_FAIL_COND(texture.is_null()); - // ERR_FAIL_COND(map_mode == NULL); + // ERR_FAIL_COND(map_mode == nullptr); // aiTextureMapMode tex_mode = map_mode[0]; // int32_t flags = Texture::FLAGS_DEFAULT; @@ -317,7 +317,7 @@ public: // } // } else { // Ref<Image> img; - // img.instance(); + // img.instantiate(); // PoolByteArray arr; // uint32_t size = tex->mWidth * tex->mHeight; // arr.resize(size); @@ -362,7 +362,7 @@ public: // if (found) { // image_state.raw_image = AssimpUtils::load_image(state, state.assimp_scene, path); // if (image_state.raw_image.is_valid()) { - // image_state.texture.instance(); + // image_state.texture.instantiate(); // image_state.texture->create_from_image(image_state.raw_image); // image_state.texture->set_storage(ImageTexture::STORAGE_COMPRESS_LOSSY); // return true; @@ -382,7 +382,7 @@ public: // String &path, // AssimpImageData &image_state) { // aiString ai_filename = aiString(); - // if (AI_SUCCESS == ai_material->GetTexture(texture_type, 0, &ai_filename, NULL, NULL, NULL, NULL, image_state.map_mode)) { + // if (AI_SUCCESS == ai_material->GetTexture(texture_type, 0, &ai_filename, nullptr, nullptr, nullptr, nullptr, image_state.map_mode)) { // return CreateAssimpTexture(state, ai_filename, filename, path, image_state); // } @@ -391,7 +391,7 @@ public: }; // Apply the transforms so the basis will have scale 1. -Transform get_unscaled_transform(const Transform &p_initial, real_t p_scale); +Transform3D get_unscaled_transform(const Transform3D &p_initial, real_t p_scale); /// Uses the Newell's method to compute any polygon normal. /// The polygon must be at least size of 3 or bigger. diff --git a/modules/fbx/tools/validation_tools.h b/modules/fbx/tools/validation_tools.h index fe0c92b22f..906a721045 100644 --- a/modules/fbx/tools/validation_tools.h +++ b/modules/fbx/tools/validation_tools.h @@ -33,9 +33,8 @@ #ifdef TOOLS_ENABLED -#include "core/io/json.h" -#include "core/os/file_access.h" -#include "core/string/ustring.h" +#include "core/io/file_access.h" +#include "core/string/print_string.h" #include "core/templates/local_vector.h" #include "core/templates/map.h" diff --git a/modules/freetype/SCsub b/modules/freetype/SCsub index fc2535a6ca..476cb9cf2a 100644 --- a/modules/freetype/SCsub +++ b/modules/freetype/SCsub @@ -80,6 +80,7 @@ if env["builtin_freetype"]: # Forcibly undefine this macro so SIMD is not used in this file, # since currently unsupported in WASM tmp_env = env_freetype.Clone() + tmp_env.disable_warnings() tmp_env.Append(CPPFLAGS=["-U__OPTIMIZE__"]) sfnt = tmp_env.Object(sfnt) thirdparty_sources += [sfnt] diff --git a/modules/gdnative/doc_classes/GDNative.xml b/modules/gdnative/doc_classes/GDNative.xml index 44d9e32ed8..e4c5d34a2c 100644 --- a/modules/gdnative/doc_classes/GDNative.xml +++ b/modules/gdnative/doc_classes/GDNative.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="GDNative" inherits="Reference" version="4.0"> +<class name="GDNative" inherits="RefCounted" version="4.0"> <brief_description> </brief_description> <description> @@ -8,26 +8,20 @@ </tutorials> <methods> <method name="call_native"> - <return type="Variant"> - </return> - <argument index="0" name="calling_type" type="StringName"> - </argument> - <argument index="1" name="procedure_name" type="StringName"> - </argument> - <argument index="2" name="arguments" type="Array"> - </argument> + <return type="Variant" /> + <argument index="0" name="calling_type" type="StringName" /> + <argument index="1" name="procedure_name" type="StringName" /> + <argument index="2" name="arguments" type="Array" /> <description> </description> </method> <method name="initialize"> - <return type="bool"> - </return> + <return type="bool" /> <description> </description> </method> <method name="terminate"> - <return type="bool"> - </return> + <return type="bool" /> <description> </description> </method> diff --git a/modules/gdnative/doc_classes/GDNativeLibrary.xml b/modules/gdnative/doc_classes/GDNativeLibrary.xml index 05cda05f9f..f84d4e60f3 100644 --- a/modules/gdnative/doc_classes/GDNativeLibrary.xml +++ b/modules/gdnative/doc_classes/GDNativeLibrary.xml @@ -12,15 +12,13 @@ </tutorials> <methods> <method name="get_current_dependencies" qualifiers="const"> - <return type="PackedStringArray"> - </return> + <return type="PackedStringArray" /> <description> Returns paths to all dependency libraries for the current platform and architecture. </description> </method> <method name="get_current_library_path" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the path to the dynamic library file for the current platform and architecture. </description> diff --git a/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml b/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml index 9f33d32e81..b88f5e7e1e 100644 --- a/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml +++ b/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="MultiplayerPeerGDNative" inherits="NetworkedMultiplayerPeer" version="4.0"> +<class name="MultiplayerPeerGDNative" inherits="MultiplayerPeer" version="4.0"> <brief_description> </brief_description> <description> diff --git a/modules/gdnative/doc_classes/NativeScript.xml b/modules/gdnative/doc_classes/NativeScript.xml index f2e9cac6dc..397d12a3a9 100644 --- a/modules/gdnative/doc_classes/NativeScript.xml +++ b/modules/gdnative/doc_classes/NativeScript.xml @@ -8,42 +8,34 @@ </tutorials> <methods> <method name="get_class_documentation" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the documentation string that was previously set with [code]godot_nativescript_set_class_documentation[/code]. </description> </method> <method name="get_method_documentation" qualifiers="const"> - <return type="String"> - </return> - <argument index="0" name="method" type="StringName"> - </argument> + <return type="String" /> + <argument index="0" name="method" type="StringName" /> <description> Returns the documentation string that was previously set with [code]godot_nativescript_set_method_documentation[/code]. </description> </method> <method name="get_property_documentation" qualifiers="const"> - <return type="String"> - </return> - <argument index="0" name="path" type="StringName"> - </argument> + <return type="String" /> + <argument index="0" name="path" type="StringName" /> <description> Returns the documentation string that was previously set with [code]godot_nativescript_set_property_documentation[/code]. </description> </method> <method name="get_signal_documentation" qualifiers="const"> - <return type="String"> - </return> - <argument index="0" name="signal_name" type="StringName"> - </argument> + <return type="String" /> + <argument index="0" name="signal_name" type="StringName" /> <description> Returns the documentation string that was previously set with [code]godot_nativescript_set_signal_documentation[/code]. </description> </method> <method name="new" qualifiers="vararg"> - <return type="Variant"> - </return> + <return type="Variant" /> <description> Constructs a new object of the base type with a script of this type already attached. [i]Note[/i]: Any arguments passed to this function will be ignored and not passed to the native constructor function. This will change with in a future API extension. diff --git a/modules/gdnative/doc_classes/PluginScript.xml b/modules/gdnative/doc_classes/PluginScript.xml index 9616101090..8e28187482 100644 --- a/modules/gdnative/doc_classes/PluginScript.xml +++ b/modules/gdnative/doc_classes/PluginScript.xml @@ -8,8 +8,7 @@ </tutorials> <methods> <method name="new" qualifiers="vararg"> - <return type="Variant"> - </return> + <return type="Variant" /> <description> Returns a new instance of the script. </description> diff --git a/modules/gdnative/doc_classes/VideoStreamGDNative.xml b/modules/gdnative/doc_classes/VideoStreamGDNative.xml index 153988bad8..8b1a3210df 100644 --- a/modules/gdnative/doc_classes/VideoStreamGDNative.xml +++ b/modules/gdnative/doc_classes/VideoStreamGDNative.xml @@ -11,17 +11,14 @@ </tutorials> <methods> <method name="get_file"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the video file handled by this [VideoStreamGDNative]. </description> </method> <method name="set_file"> - <return type="void"> - </return> - <argument index="0" name="file" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="file" type="String" /> <description> Sets the video file that this [VideoStreamGDNative] resource handles. The supported extensions depend on the GDNative plugins used to expose video formats. </description> diff --git a/modules/gdnative/gdnative.cpp b/modules/gdnative/gdnative.cpp index 0de6b27d27..9445fac1c6 100644 --- a/modules/gdnative/gdnative.cpp +++ b/modules/gdnative/gdnative.cpp @@ -32,8 +32,9 @@ #include "core/config/project_settings.h" #include "core/core_constants.h" +#include "core/io/dir_access.h" +#include "core/io/file_access.h" #include "core/io/file_access_encrypted.h" -#include "core/os/file_access.h" #include "core/os/os.h" #include "scene/main/scene_tree.h" @@ -51,7 +52,7 @@ extern const godot_gdnative_core_api_struct api_struct; Map<String, Vector<Ref<GDNative>>> GDNativeLibrary::loaded_libraries; GDNativeLibrary::GDNativeLibrary() { - config_file.instance(); + config_file.instantiate(); symbol_prefix = default_symbol_prefix; load_once = default_load_once; @@ -111,7 +112,7 @@ bool GDNativeLibrary::_get(const StringName &p_name, Variant &r_property) const } void GDNativeLibrary::reset_state() { - config_file.instance(); + config_file.instantiate(); current_library_path = ""; current_dependencies.clear(); symbol_prefix = default_symbol_prefix; @@ -128,9 +129,7 @@ void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const { config_file->get_section_keys("entry", &entry_key_list); } - for (List<String>::Element *E = entry_key_list.front(); E; E = E->next()) { - String key = E->get(); - + for (const String &key : entry_key_list) { PropertyInfo prop; prop.type = Variant::STRING; @@ -146,9 +145,7 @@ void GDNativeLibrary::_get_property_list(List<PropertyInfo> *p_list) const { config_file->get_section_keys("dependencies", &dependency_key_list); } - for (List<String>::Element *E = dependency_key_list.front(); E; E = E->next()) { - String key = E->get(); - + for (const String &key : dependency_key_list) { PropertyInfo prop; prop.type = Variant::STRING; @@ -174,9 +171,7 @@ void GDNativeLibrary::set_config_file(Ref<ConfigFile> p_config_file) { p_config_file->get_section_keys("entry", &entry_keys); } - for (List<String>::Element *E = entry_keys.front(); E; E = E->next()) { - String key = E->get(); - + for (const String &key : entry_keys) { Vector<String> tags = key.split("."); bool skip = false; @@ -206,9 +201,7 @@ void GDNativeLibrary::set_config_file(Ref<ConfigFile> p_config_file) { p_config_file->get_section_keys("dependencies", &dependency_keys); } - for (List<String>::Element *E = dependency_keys.front(); E; E = E->next()) { - String key = E->get(); - + for (const String &key : dependency_keys) { Vector<String> tags = key.split("."); bool skip = false; @@ -251,7 +244,7 @@ void GDNativeLibrary::_bind_methods() { ClassDB::bind_method(D_METHOD("set_symbol_prefix", "symbol_prefix"), &GDNativeLibrary::set_symbol_prefix); ClassDB::bind_method(D_METHOD("set_reloadable", "reloadable"), &GDNativeLibrary::set_reloadable); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "config_file", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile", 0), "set_config_file", "get_config_file"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "config_file", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile", PROPERTY_USAGE_NONE), "set_config_file", "get_config_file"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "load_once"), "set_load_once", "should_load_once"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "singleton"), "set_singleton", "is_singleton"); @@ -335,9 +328,18 @@ bool GDNative::initialize() { // On OSX the exported libraries are located under the Frameworks directory. // So we need to replace the library path. String path = ProjectSettings::get_singleton()->globalize_path(lib_path); - if (!FileAccess::exists(path)) { + DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + + if (!da->file_exists(path) && !da->dir_exists(path)) { path = OS::get_singleton()->get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(lib_path.get_file()); } + + if (da->dir_exists(path)) { // Target library is a ".framework", add library base name to the path. + path = path.plus_file(path.get_file().get_basename()); + } + + memdelete(da); + #else String path = ProjectSettings::get_singleton()->globalize_path(lib_path); #endif @@ -522,7 +524,7 @@ Error GDNative::get_symbol(StringName p_procedure_name, void *&r_handle, bool p_ RES GDNativeLibraryResourceLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) { Ref<GDNativeLibrary> lib; - lib.instance(); + lib.instantiate(); Ref<ConfigFile> config = lib->get_config_file(); diff --git a/modules/gdnative/gdnative.h b/modules/gdnative/gdnative.h index a28c58ec0d..0cc6487ea4 100644 --- a/modules/gdnative/gdnative.h +++ b/modules/gdnative/gdnative.h @@ -138,8 +138,8 @@ struct GDNativeCallRegistry { Vector<StringName> get_native_call_types(); }; -class GDNative : public Reference { - GDCLASS(GDNative, Reference); +class GDNative : public RefCounted { + GDCLASS(GDNative, RefCounted); Ref<GDNativeLibrary> library; diff --git a/modules/gdnative/gdnative/quat.cpp b/modules/gdnative/gdnative/quaternion.cpp index 8ebcf7c91f..62bcbbd382 100644 --- a/modules/gdnative/gdnative/quat.cpp +++ b/modules/gdnative/gdnative/quaternion.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* quat.cpp */ +/* quaternion.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,31 +28,31 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "gdnative/quat.h" +#include "gdnative/quaternion.h" -#include "core/math/quat.h" +#include "core/math/quaternion.h" -static_assert(sizeof(godot_quat) == sizeof(Quat), "Quat size mismatch"); +static_assert(sizeof(godot_quaternion) == sizeof(Quaternion), "Quaternion size mismatch"); #ifdef __cplusplus extern "C" { #endif -void GDAPI godot_quat_new(godot_quat *p_self) { - memnew_placement(p_self, Quat); +void GDAPI godot_quaternion_new(godot_quaternion *p_self) { + memnew_placement(p_self, Quaternion); } -void GDAPI godot_quat_new_copy(godot_quat *r_dest, const godot_quat *p_src) { - memnew_placement(r_dest, Quat(*(Quat *)p_src)); +void GDAPI godot_quaternion_new_copy(godot_quaternion *r_dest, const godot_quaternion *p_src) { + memnew_placement(r_dest, Quaternion(*(Quaternion *)p_src)); } -godot_real_t GDAPI *godot_quat_operator_index(godot_quat *p_self, godot_int p_index) { - Quat *self = (Quat *)p_self; +godot_real_t GDAPI *godot_quaternion_operator_index(godot_quaternion *p_self, godot_int p_index) { + Quaternion *self = (Quaternion *)p_self; return (godot_real_t *)&self->operator[](p_index); } -const godot_real_t GDAPI *godot_quat_operator_index_const(const godot_quat *p_self, godot_int p_index) { - const Quat *self = (const Quat *)p_self; +const godot_real_t GDAPI *godot_quaternion_operator_index_const(const godot_quaternion *p_self, godot_int p_index) { + const Quaternion *self = (const Quaternion *)p_self; return (const godot_real_t *)&self->operator[](p_index); } diff --git a/modules/gdnative/gdnative/transform.cpp b/modules/gdnative/gdnative/transform_3d.cpp index bfaaa13db2..8bd2a68d63 100644 --- a/modules/gdnative/gdnative/transform.cpp +++ b/modules/gdnative/gdnative/transform_3d.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* transform.cpp */ +/* transform_3d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,22 +28,22 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "gdnative/transform.h" +#include "gdnative/transform_3d.h" -#include "core/math/transform.h" +#include "core/math/transform_3d.h" -static_assert(sizeof(godot_transform) == sizeof(Transform), "Transform size mismatch"); +static_assert(sizeof(godot_transform3d) == sizeof(Transform3D), "Transform3D size mismatch"); #ifdef __cplusplus extern "C" { #endif -void GDAPI godot_transform_new(godot_transform *p_self) { - memnew_placement(p_self, Transform); +void GDAPI godot_transform3d_new(godot_transform3d *p_self) { + memnew_placement(p_self, Transform3D); } -void GDAPI godot_transform_new_copy(godot_transform *r_dest, const godot_transform *p_src) { - memnew_placement(r_dest, Transform(*(Transform *)p_src)); +void GDAPI godot_transform3d_new_copy(godot_transform3d *r_dest, const godot_transform3d *p_src) { + memnew_placement(r_dest, Transform3D(*(Transform3D *)p_src)); } #ifdef __cplusplus diff --git a/modules/gdnative/gdnative/variant.cpp b/modules/gdnative/gdnative/variant.cpp index 7801e21ab2..1d75ea206c 100644 --- a/modules/gdnative/gdnative/variant.cpp +++ b/modules/gdnative/gdnative/variant.cpp @@ -30,7 +30,7 @@ #include "gdnative/variant.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/variant/variant.h" #ifdef __cplusplus @@ -143,10 +143,10 @@ void GDAPI godot_variant_new_plane(godot_variant *r_dest, const godot_plane *p_p memnew_placement_custom(dest, Variant, Variant(*plane)); } -void GDAPI godot_variant_new_quat(godot_variant *r_dest, const godot_quat *p_quat) { +void GDAPI godot_variant_new_quaternion(godot_variant *r_dest, const godot_quaternion *p_quaternion) { Variant *dest = (Variant *)r_dest; - const Quat *quat = (const Quat *)p_quat; - memnew_placement_custom(dest, Variant, Variant(*quat)); + const Quaternion *quaternion = (const Quaternion *)p_quaternion; + memnew_placement_custom(dest, Variant, Variant(*quaternion)); } void GDAPI godot_variant_new_aabb(godot_variant *r_dest, const godot_aabb *p_aabb) { @@ -161,9 +161,9 @@ void GDAPI godot_variant_new_basis(godot_variant *r_dest, const godot_basis *p_b memnew_placement_custom(dest, Variant, Variant(*basis)); } -void GDAPI godot_variant_new_transform(godot_variant *r_dest, const godot_transform *p_trans) { +void GDAPI godot_variant_new_transform3d(godot_variant *r_dest, const godot_transform3d *p_trans) { Variant *dest = (Variant *)r_dest; - const Transform *trans = (const Transform *)p_trans; + const Transform3D *trans = (const Transform3D *)p_trans; memnew_placement_custom(dest, Variant, Variant(*trans)); } @@ -200,17 +200,17 @@ void GDAPI godot_variant_new_signal(godot_variant *r_dest, const godot_signal *p void GDAPI godot_variant_new_object(godot_variant *r_dest, const godot_object *p_obj) { Variant *dest = (Variant *)r_dest; const Object *obj = (const Object *)p_obj; - const Reference *reference = Object::cast_to<Reference>(obj); + const RefCounted *ref_counted = Object::cast_to<RefCounted>(obj); REF ref; - if (reference) { - ref = REF(reference); + if (ref_counted) { + ref = REF(ref_counted); } if (!ref.is_null()) { memnew_placement_custom(dest, Variant, Variant(ref)); } else { #if defined(DEBUG_METHODS_ENABLED) - if (reference) { - ERR_PRINT("Reference object has 0 refcount in godot_variant_new_object - you lost it somewhere."); + if (ref_counted) { + ERR_PRINT("RefCounted object has 0 refcount in godot_variant_new_object - you lost it somewhere."); } #endif memnew_placement_custom(dest, Variant, Variant(obj)); @@ -378,10 +378,10 @@ godot_plane GDAPI godot_variant_as_plane(const godot_variant *p_self) { return raw_dest; } -godot_quat GDAPI godot_variant_as_quat(const godot_variant *p_self) { - godot_quat raw_dest; +godot_quaternion GDAPI godot_variant_as_quaternion(const godot_variant *p_self) { + godot_quaternion raw_dest; const Variant *self = (const Variant *)p_self; - Quat *dest = (Quat *)&raw_dest; + Quaternion *dest = (Quaternion *)&raw_dest; *dest = *self; return raw_dest; } @@ -402,10 +402,10 @@ godot_basis GDAPI godot_variant_as_basis(const godot_variant *p_self) { return raw_dest; } -godot_transform GDAPI godot_variant_as_transform(const godot_variant *p_self) { - godot_transform raw_dest; +godot_transform3d GDAPI godot_variant_as_transform3d(const godot_variant *p_self) { + godot_transform3d raw_dest; const Variant *self = (const Variant *)p_self; - Transform *dest = (Transform *)&raw_dest; + Transform3D *dest = (Transform3D *)&raw_dest; *dest = *self; return raw_dest; } @@ -915,8 +915,8 @@ void GDAPI godot_variant_get_builtin_method_list(godot_variant_type p_type, godo List<StringName> list; Variant::get_builtin_method_list((Variant::Type)p_type, &list); int i = 0; - for (const List<StringName>::Element *E = list.front(); E; E = E->next()) { - memnew_placement_custom(&r_list[i], StringName, StringName(E->get())); + for (const StringName &E : list) { + memnew_placement_custom(&r_list[i], StringName, StringName(E)); } } @@ -970,8 +970,8 @@ void GDAPI godot_variant_get_member_list(godot_variant_type p_type, godot_string List<StringName> members; Variant::get_member_list((Variant::Type)p_type, &members); int i = 0; - for (const List<StringName>::Element *E = members.front(); E; E = E->next()) { - memnew_placement_custom(&r_list[i++], StringName, StringName(E->get())); + for (const StringName &E : members) { + memnew_placement_custom(&r_list[i++], StringName, StringName(E)); } } @@ -1075,8 +1075,8 @@ void GDAPI godot_variant_get_constants_list(godot_variant_type p_type, godot_str List<StringName> constants; int i = 0; Variant::get_constants_for_type((Variant::Type)p_type, &constants); - for (const List<StringName>::Element *E = constants.front(); E; E = E->next()) { - memnew_placement_custom(&r_list[i++], StringName, StringName(E->get())); + for (const StringName &E : constants) { + memnew_placement_custom(&r_list[i++], StringName, StringName(E)); } } @@ -1227,8 +1227,8 @@ void GDAPI godot_variant_get_utility_function_list(godot_string_name *r_function godot_string_name *func = r_functions; Variant::get_utility_function_list(&functions); - for (const List<StringName>::Element *E = functions.front(); E; E = E->next()) { - memnew_placement_custom(func++, StringName, StringName(E->get())); + for (const StringName &E : functions) { + memnew_placement_custom(func++, StringName, StringName(E)); } } diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json index 489083e795..8c65447e5d 100644 --- a/modules/gdnative/gdnative_api.json +++ b/modules/gdnative/gdnative_api.json @@ -469,7 +469,7 @@ ] }, { - "name": "godot_variant_new_quat", + "name": "godot_variant_new_quaternion", "return_type": "void", "arguments": [ [ @@ -477,8 +477,8 @@ "r_dest" ], [ - "const godot_quat *", - "p_quat" + "const godot_quaternion *", + "p_quaternion" ] ] }, @@ -511,7 +511,7 @@ ] }, { - "name": "godot_variant_new_transform", + "name": "godot_variant_new_transform3d", "return_type": "void", "arguments": [ [ @@ -519,7 +519,7 @@ "r_dest" ], [ - "const godot_transform *", + "const godot_transform3d *", "p_trans" ] ] @@ -893,8 +893,8 @@ ] }, { - "name": "godot_variant_as_quat", - "return_type": "godot_quat", + "name": "godot_variant_as_quaternion", + "return_type": "godot_quaternion", "arguments": [ [ "const godot_variant *", @@ -923,8 +923,8 @@ ] }, { - "name": "godot_variant_as_transform", - "return_type": "godot_transform", + "name": "godot_variant_as_transform3d", + "return_type": "godot_transform3d", "arguments": [ [ "const godot_variant *", @@ -3866,35 +3866,35 @@ ] }, { - "name": "godot_quat_new", + "name": "godot_quaternion_new", "return_type": "void", "arguments": [ [ - "godot_quat *", + "godot_quaternion *", "p_self" ] ] }, { - "name": "godot_quat_new_copy", + "name": "godot_quaternion_new_copy", "return_type": "void", "arguments": [ [ - "godot_quat *", + "godot_quaternion *", "r_dest" ], [ - "const godot_quat *", + "const godot_quaternion *", "p_src" ] ] }, { - "name": "godot_quat_operator_index", + "name": "godot_quaternion_operator_index", "return_type": "godot_real_t *", "arguments": [ [ - "godot_quat *", + "godot_quaternion *", "p_self" ], [ @@ -3904,11 +3904,11 @@ ] }, { - "name": "godot_quat_operator_index_const", + "name": "godot_quaternion_operator_index_const", "return_type": "const godot_real_t *", "arguments": [ [ - "const godot_quat *", + "const godot_quaternion *", "p_self" ], [ @@ -4344,25 +4344,25 @@ ] }, { - "name": "godot_transform_new", + "name": "godot_transform3d_new", "return_type": "void", "arguments": [ [ - "godot_transform *", + "godot_transform3d *", "r_dest" ] ] }, { - "name": "godot_transform_new_copy", + "name": "godot_transform3d_new_copy", "return_type": "void", "arguments": [ [ - "godot_transform *", + "godot_transform3d *", "r_dest" ], [ - "const godot_transform *", + "const godot_transform3d *", "p_src" ] ] @@ -5068,12 +5068,12 @@ }, { "name": "godot_xr_get_worldscale", - "return_type": "godot_float", + "return_type": "godot_real_t", "arguments": [] }, { "name": "godot_xr_get_reference_frame", - "return_type": "godot_transform", + "return_type": "godot_transform3d", "arguments": [] }, { @@ -5145,7 +5145,7 @@ "p_controller_id" ], [ - "godot_transform *", + "godot_transform3d *", "p_transform" ], [ @@ -5189,7 +5189,7 @@ "p_exis" ], [ - "godot_float", + "godot_real_t", "p_value" ], [ @@ -5200,7 +5200,7 @@ }, { "name": "godot_xr_get_controller_rumble", - "return_type": "godot_float", + "return_type": "godot_real_t", "arguments": [ [ "godot_int", diff --git a/modules/gdnative/gdnative_library_editor_plugin.cpp b/modules/gdnative/gdnative_library_editor_plugin.cpp index dfb26c13e3..f965bcd014 100644 --- a/modules/gdnative/gdnative_library_editor_plugin.cpp +++ b/modules/gdnative/gdnative_library_editor_plugin.cpp @@ -74,9 +74,9 @@ void GDNativeLibraryEditor::_update_tree() { platform->set_text(0, E->get().name); platform->set_metadata(0, E->get().library_extension); - platform->set_custom_bg_color(0, get_theme_color("prop_category", "Editor")); - platform->set_custom_bg_color(1, get_theme_color("prop_category", "Editor")); - platform->set_custom_bg_color(2, get_theme_color("prop_category", "Editor")); + platform->set_custom_bg_color(0, get_theme_color(SNAME("prop_category"), SNAME("Editor"))); + platform->set_custom_bg_color(1, get_theme_color(SNAME("prop_category"), SNAME("Editor"))); + platform->set_custom_bg_color(2, get_theme_color(SNAME("prop_category"), SNAME("Editor"))); platform->set_selectable(0, false); platform->set_expand_right(0, true); @@ -87,31 +87,31 @@ void GDNativeLibraryEditor::_update_tree() { bit->set_text(0, it->get()); bit->set_metadata(0, target); bit->set_selectable(0, false); - bit->set_custom_bg_color(0, get_theme_color("prop_subsection", "Editor")); + bit->set_custom_bg_color(0, get_theme_color(SNAME("prop_subsection"), SNAME("Editor"))); - bit->add_button(1, get_theme_icon("Folder", "EditorIcons"), BUTTON_SELECT_LIBRARY, false, TTR("Select the dynamic library for this entry")); + bit->add_button(1, get_theme_icon(SNAME("Folder"), SNAME("EditorIcons")), BUTTON_SELECT_LIBRARY, false, TTR("Select the dynamic library for this entry")); String file = entry_configs[target].library; if (!file.is_empty()) { - bit->add_button(1, get_theme_icon("Clear", "EditorIcons"), BUTTON_CLEAR_LIBRARY, false, TTR("Clear")); + bit->add_button(1, get_theme_icon(SNAME("Clear"), SNAME("EditorIcons")), BUTTON_CLEAR_LIBRARY, false, TTR("Clear")); } bit->set_text(1, file); - bit->add_button(2, get_theme_icon("Folder", "EditorIcons"), BUTTON_SELECT_DEPENDENCES, false, TTR("Select dependencies of the library for this entry")); + bit->add_button(2, get_theme_icon(SNAME("Folder"), SNAME("EditorIcons")), BUTTON_SELECT_DEPENDENCES, false, TTR("Select dependencies of the library for this entry")); Array files = entry_configs[target].dependencies; if (files.size()) { - bit->add_button(2, get_theme_icon("Clear", "EditorIcons"), BUTTON_CLEAR_DEPENDENCES, false, TTR("Clear")); + bit->add_button(2, get_theme_icon(SNAME("Clear"), SNAME("EditorIcons")), BUTTON_CLEAR_DEPENDENCES, false, TTR("Clear")); } bit->set_text(2, Variant(files)); - bit->add_button(3, get_theme_icon("MoveUp", "EditorIcons"), BUTTON_MOVE_UP, false, TTR("Move Up")); - bit->add_button(3, get_theme_icon("MoveDown", "EditorIcons"), BUTTON_MOVE_DOWN, false, TTR("Move Down")); - bit->add_button(3, get_theme_icon("Remove", "EditorIcons"), BUTTON_ERASE_ENTRY, false, TTR("Remove current entry")); + bit->add_button(3, get_theme_icon(SNAME("MoveUp"), SNAME("EditorIcons")), BUTTON_MOVE_UP, false, TTR("Move Up")); + bit->add_button(3, get_theme_icon(SNAME("MoveDown"), SNAME("EditorIcons")), BUTTON_MOVE_DOWN, false, TTR("Move Down")); + bit->add_button(3, get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_ERASE_ENTRY, false, TTR("Remove current entry")); } TreeItem *new_arch = tree->create_item(platform); new_arch->set_text(0, TTR("Double click to create a new entry")); new_arch->set_text_align(0, TreeItem::ALIGN_CENTER); - new_arch->set_custom_color(0, get_theme_color("accent_color", "Editor")); + new_arch->set_custom_color(0, get_theme_color(SNAME("accent_color"), SNAME("Editor"))); new_arch->set_expand_right(0, true); new_arch->set_metadata(1, E->key()); @@ -131,7 +131,7 @@ void GDNativeLibraryEditor::_on_item_button(Object *item, int column, int id) { EditorFileDialog::FileMode mode = EditorFileDialog::FILE_MODE_OPEN_FILE; if (id == BUTTON_SELECT_DEPENDENCES) { mode = EditorFileDialog::FILE_MODE_OPEN_FILES; - } else if (treeItem->get_text(0) == "iOS") { + } else if (treeItem->get_text(0) == "iOS" || treeItem->get_text(0) == "macOS") { mode = EditorFileDialog::FILE_MODE_OPEN_ANY; } @@ -278,11 +278,10 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() { platforms["X11"] = platform_linux; NativePlatformConfig platform_osx; - platform_osx.name = "Mac OSX"; + platform_osx.name = "macOS"; platform_osx.entries.push_back("64"); - platform_osx.entries.push_back("32"); - platform_osx.library_extension = "*.dylib"; - platforms["OSX"] = platform_osx; + platform_osx.library_extension = "*.framework; Framework, *.dylib; Dynamic Library"; + platforms["macOS"] = platform_osx; NativePlatformConfig platform_haiku; platform_haiku.name = "Haiku"; @@ -357,12 +356,12 @@ GDNativeLibraryEditor::GDNativeLibraryEditor() { tree->set_column_titles_visible(true); tree->set_columns(4); tree->set_column_expand(0, false); - tree->set_column_min_width(0, int(200 * EDSCALE)); + tree->set_column_custom_minimum_width(0, int(200 * EDSCALE)); tree->set_column_title(0, TTR("Platform")); tree->set_column_title(1, TTR("Dynamic Library")); tree->set_column_title(2, TTR("Dependencies")); tree->set_column_expand(3, false); - tree->set_column_min_width(3, int(110 * EDSCALE)); + tree->set_column_custom_minimum_width(3, int(110 * EDSCALE)); tree->connect("button_pressed", callable_mp(this, &GDNativeLibraryEditor::_on_item_button)); tree->connect("item_collapsed", callable_mp(this, &GDNativeLibraryEditor::_on_item_collapsed)); tree->connect("item_activated", callable_mp(this, &GDNativeLibraryEditor::_on_item_activated)); diff --git a/modules/gdnative/include/gdnative/callable.h b/modules/gdnative/include/gdnative/callable.h index b84b0c1f1f..1d52ca7a68 100644 --- a/modules/gdnative/include/gdnative/callable.h +++ b/modules/gdnative/include/gdnative/callable.h @@ -37,6 +37,7 @@ extern "C" { #include <stdint.h> +// Alignment hardcoded in `core/variant/callable.h`. #define GODOT_CALLABLE_SIZE (16) #ifndef GODOT_CORE_API_GODOT_CALLABLE_TYPE_DEFINED diff --git a/modules/gdnative/include/gdnative/gdnative.h b/modules/gdnative/include/gdnative/gdnative.h index 9af9226a79..d8c290f6bd 100644 --- a/modules/gdnative/include/gdnative/gdnative.h +++ b/modules/gdnative/include/gdnative/gdnative.h @@ -149,9 +149,9 @@ typedef void godot_object; #include <gdnative/plane.h> -/////// Quat +/////// Quaternion -#include <gdnative/quat.h> +#include <gdnative/quaternion.h> /////// AABB @@ -161,9 +161,9 @@ typedef void godot_object; #include <gdnative/basis.h> -/////// Transform +/////// Transform3D -#include <gdnative/transform.h> +#include <gdnative/transform_3d.h> /////// Color diff --git a/modules/gdnative/include/gdnative/quat.h b/modules/gdnative/include/gdnative/quaternion.h index 00abdb4404..75754e6ab5 100644 --- a/modules/gdnative/include/gdnative/quat.h +++ b/modules/gdnative/include/gdnative/quaternion.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* quat.h */ +/* quaternion.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GODOT_QUAT_H -#define GODOT_QUAT_H +#ifndef GODOT_QUATERNION_H +#define GODOT_QUATERNION_H #ifdef __cplusplus extern "C" { @@ -37,24 +37,24 @@ extern "C" { #include <gdnative/math_defs.h> -#define GODOT_QUAT_SIZE (sizeof(godot_real_t) * 4) +#define GODOT_QUATERNION_SIZE (sizeof(godot_real_t) * 4) -#ifndef GODOT_CORE_API_GODOT_QUAT_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_QUAT_TYPE_DEFINED +#ifndef GODOT_CORE_API_GODOT_QUATERNION_TYPE_DEFINED +#define GODOT_CORE_API_GODOT_QUATERNION_TYPE_DEFINED typedef struct { - uint8_t _dont_touch_that[GODOT_QUAT_SIZE]; -} godot_quat; + uint8_t _dont_touch_that[GODOT_QUATERNION_SIZE]; +} godot_quaternion; #endif #include <gdnative/gdnative.h> -void GDAPI godot_quat_new(godot_quat *p_self); -void GDAPI godot_quat_new_copy(godot_quat *r_dest, const godot_quat *p_src); -godot_real_t GDAPI *godot_quat_operator_index(godot_quat *p_self, godot_int p_index); -const godot_real_t GDAPI *godot_quat_operator_index_const(const godot_quat *p_self, godot_int p_index); +void GDAPI godot_quaternion_new(godot_quaternion *p_self); +void GDAPI godot_quaternion_new_copy(godot_quaternion *r_dest, const godot_quaternion *p_src); +godot_real_t GDAPI *godot_quaternion_operator_index(godot_quaternion *p_self, godot_int p_index); +const godot_real_t GDAPI *godot_quaternion_operator_index_const(const godot_quaternion *p_self, godot_int p_index); #ifdef __cplusplus } #endif -#endif // GODOT_QUAT_H +#endif // GODOT_QUATERNION_H diff --git a/modules/gdnative/include/gdnative/signal.h b/modules/gdnative/include/gdnative/signal.h index f4dc17e089..41a76d0510 100644 --- a/modules/gdnative/include/gdnative/signal.h +++ b/modules/gdnative/include/gdnative/signal.h @@ -37,6 +37,7 @@ extern "C" { #include <stdint.h> +// Alignment hardcoded in `core/variant/callable.h`. #define GODOT_SIGNAL_SIZE (16) #ifndef GODOT_CORE_API_GODOT_SIGNAL_TYPE_DEFINED diff --git a/modules/gdnative/include/gdnative/transform.h b/modules/gdnative/include/gdnative/transform_3d.h index 3861b5683a..97ad451e9b 100644 --- a/modules/gdnative/include/gdnative/transform.h +++ b/modules/gdnative/include/gdnative/transform_3d.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* transform.h */ +/* transform_3d.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GODOT_TRANSFORM_H -#define GODOT_TRANSFORM_H +#ifndef GODOT_TRANSFORM3D_H +#define GODOT_TRANSFORM3D_H #ifdef __cplusplus extern "C" { @@ -37,22 +37,24 @@ extern "C" { #include <gdnative/math_defs.h> -#define GODOT_TRANSFORM_SIZE (sizeof(godot_real_t) * 12) +#define GODOT_TRANSFORM3D_SIZE (sizeof(godot_real_t) * 12) -#ifndef GODOT_CORE_API_GODOT_TRANSFORM_TYPE_DEFINED -#define GODOT_CORE_API_GODOT_TRANSFORM_TYPE_DEFINED +#ifndef GODOT_CORE_API_GODOT_TRANSFORM3D_TYPE_DEFINED +#define GODOT_CORE_API_GODOT_TRANSFORM3D_TYPE_DEFINED typedef struct { - uint8_t _dont_touch_that[GODOT_TRANSFORM_SIZE]; -} godot_transform; + uint8_t _dont_touch_that[GODOT_TRANSFORM3D_SIZE]; +} godot_transform3d; #endif #include <gdnative/gdnative.h> -void GDAPI godot_transform_new(godot_transform *p_self); -void GDAPI godot_transform_new_copy(godot_transform *r_dest, const godot_transform *p_src); +void GDAPI godot_transform3d_new(godot_transform3d *p_self); +void GDAPI godot_transform3d_new_copy(godot_transform3d *r_dest, const godot_transform3d *p_src); +godot_vector3 GDAPI *godot_transform3d_operator_index(godot_transform3d *p_self, godot_int p_index); +const godot_vector3 GDAPI *godot_transform3d_operator_index_const(const godot_transform3d *p_self, godot_int p_index); #ifdef __cplusplus } #endif -#endif // GODOT_TRANSFORM_H +#endif // GODOT_TRANSFORM3D_H diff --git a/modules/gdnative/include/gdnative/variant.h b/modules/gdnative/include/gdnative/variant.h index 3e06ed9aa4..a88bd2878a 100644 --- a/modules/gdnative/include/gdnative/variant.h +++ b/modules/gdnative/include/gdnative/variant.h @@ -56,10 +56,10 @@ typedef enum godot_variant_type { GODOT_VARIANT_TYPE_VECTOR3I, GODOT_VARIANT_TYPE_TRANSFORM2D, GODOT_VARIANT_TYPE_PLANE, - GODOT_VARIANT_TYPE_QUAT, + GODOT_VARIANT_TYPE_QUATERNION, GODOT_VARIANT_TYPE_AABB, GODOT_VARIANT_TYPE_BASIS, - GODOT_VARIANT_TYPE_TRANSFORM, + GODOT_VARIANT_TYPE_TRANSFORM3D, // misc types GODOT_VARIANT_TYPE_COLOR, @@ -164,7 +164,7 @@ typedef void (*godot_validated_keyed_getter)(const godot_variant *p_base, const typedef bool (*godot_validated_keyed_checker)(const godot_variant *p_base, const godot_variant *p_key, bool *r_valid); typedef void (*godot_ptr_keyed_setter)(void *p_base, const void *p_key, const void *p_value); typedef void (*godot_ptr_keyed_getter)(const void *p_base, const void *p_key, void *r_value); -typedef bool (*godot_ptr_keyed_checker)(const godot_variant *p_base, const godot_variant *p_key); +typedef uint32_t (*godot_ptr_keyed_checker)(const godot_variant *p_base, const godot_variant *p_key); typedef void (*godot_validated_utility_function)(godot_variant *r_return, const godot_variant **p_arguments, int p_argument_count); typedef void (*godot_ptr_utility_function)(void *r_return, const void **p_arguments, int p_argument_count); @@ -177,14 +177,14 @@ typedef void (*godot_ptr_utility_function)(void *r_return, const void **p_argume #include <gdnative/node_path.h> #include <gdnative/packed_arrays.h> #include <gdnative/plane.h> -#include <gdnative/quat.h> +#include <gdnative/quaternion.h> #include <gdnative/rect2.h> #include <gdnative/rid.h> #include <gdnative/signal.h> #include <gdnative/string.h> #include <gdnative/string_name.h> -#include <gdnative/transform.h> #include <gdnative/transform2d.h> +#include <gdnative/transform_3d.h> #include <gdnative/variant.h> #include <gdnative/vector2.h> #include <gdnative/vector3.h> @@ -208,10 +208,10 @@ void GDAPI godot_variant_new_vector3(godot_variant *r_dest, const godot_vector3 void GDAPI godot_variant_new_vector3i(godot_variant *r_dest, const godot_vector3i *p_v3); void GDAPI godot_variant_new_transform2d(godot_variant *r_dest, const godot_transform2d *p_t2d); void GDAPI godot_variant_new_plane(godot_variant *r_dest, const godot_plane *p_plane); -void GDAPI godot_variant_new_quat(godot_variant *r_dest, const godot_quat *p_quat); +void GDAPI godot_variant_new_quaternion(godot_variant *r_dest, const godot_quaternion *p_quaternion); void GDAPI godot_variant_new_aabb(godot_variant *r_dest, const godot_aabb *p_aabb); void GDAPI godot_variant_new_basis(godot_variant *r_dest, const godot_basis *p_basis); -void GDAPI godot_variant_new_transform(godot_variant *r_dest, const godot_transform *p_trans); +void GDAPI godot_variant_new_transform3d(godot_variant *r_dest, const godot_transform3d *p_trans); void GDAPI godot_variant_new_color(godot_variant *r_dest, const godot_color *p_color); void GDAPI godot_variant_new_string_name(godot_variant *r_dest, const godot_string_name *p_s); void GDAPI godot_variant_new_node_path(godot_variant *r_dest, const godot_node_path *p_np); @@ -243,10 +243,10 @@ godot_vector3 GDAPI godot_variant_as_vector3(const godot_variant *p_self); godot_vector3i GDAPI godot_variant_as_vector3i(const godot_variant *p_self); godot_transform2d GDAPI godot_variant_as_transform2d(const godot_variant *p_self); godot_plane GDAPI godot_variant_as_plane(const godot_variant *p_self); -godot_quat GDAPI godot_variant_as_quat(const godot_variant *p_self); +godot_quaternion GDAPI godot_variant_as_quaternion(const godot_variant *p_self); godot_aabb GDAPI godot_variant_as_aabb(const godot_variant *p_self); godot_basis GDAPI godot_variant_as_basis(const godot_variant *p_self); -godot_transform GDAPI godot_variant_as_transform(const godot_variant *p_self); +godot_transform3d GDAPI godot_variant_as_transform3d(const godot_variant *p_self); godot_color GDAPI godot_variant_as_color(const godot_variant *p_self); godot_string_name GDAPI godot_variant_as_string_name(const godot_variant *p_self); godot_node_path GDAPI godot_variant_as_node_path(const godot_variant *p_self); diff --git a/modules/gdnative/include/net/godot_net.h b/modules/gdnative/include/net/godot_net.h index 2fa576a5bf..3fb7b9e1cc 100644 --- a/modules/gdnative/include/net/godot_net.h +++ b/modules/gdnative/include/net/godot_net.h @@ -90,7 +90,9 @@ typedef struct { godot_int (*get_available_packet_count)(const void *); godot_int (*get_max_packet_size)(const void *); - /* This is NetworkedMultiplayerPeer */ + /* This is MultiplayerPeer */ + void (*set_transfer_channel)(void *, godot_int); + godot_int (*get_transfer_channel)(void *); void (*set_transfer_mode)(void *, godot_int); godot_int (*get_transfer_mode)(const void *); // 0 = broadcast, 1 = server, <0 = all but abs(value) diff --git a/modules/gdnative/include/net/godot_webrtc.h b/modules/gdnative/include/net/godot_webrtc.h index 25aa72dae1..52006e56ec 100644 --- a/modules/gdnative/include/net/godot_webrtc.h +++ b/modules/gdnative/include/net/godot_webrtc.h @@ -37,8 +37,8 @@ extern "C" { #endif -#define GODOT_NET_WEBRTC_API_MAJOR 3 -#define GODOT_NET_WEBRTC_API_MINOR 2 +#define GODOT_NET_WEBRTC_API_MAJOR 4 +#define GODOT_NET_WEBRTC_API_MINOR 0 /* Library Interface (used to set default GDNative WebRTC implementation */ typedef struct { @@ -101,6 +101,7 @@ typedef struct { int (*get_max_retransmits)(const void *); const char *(*get_protocol)(const void *); bool (*is_negotiated)(const void *); + int (*get_buffered_amount)(const void *); godot_error (*poll)(void *); void (*close)(void *); diff --git a/modules/gdnative/include/pluginscript/godot_pluginscript.h b/modules/gdnative/include/pluginscript/godot_pluginscript.h index b76f89cc99..02ee4066d0 100644 --- a/modules/gdnative/include/pluginscript/godot_pluginscript.h +++ b/modules/gdnative/include/pluginscript/godot_pluginscript.h @@ -61,7 +61,7 @@ typedef struct { //this is used by script languages that keep a reference counter of their own //you can make make Ref<> not die when it reaches zero, so deleting the reference //depends entirely from the script. - // Note: You can set those function pointer to nullptr if not needed. + // Note: You can set those function pointer to nullptr if not needed. void (*refcount_incremented)(godot_pluginscript_instance_data *p_data); bool (*refcount_decremented)(godot_pluginscript_instance_data *p_data); // return true if it can die } godot_pluginscript_instance_desc; @@ -121,18 +121,18 @@ typedef struct { const char *name; const char *type; const char *extension; - const char **recognized_extensions; // nullptr terminated array + const char **recognized_extensions; // nullptr terminated array godot_pluginscript_language_data *(*init)(); void (*finish)(godot_pluginscript_language_data *p_data); - const char **reserved_words; // nullptr terminated array - const char **comment_delimiters; // nullptr terminated array - const char **string_delimiters; // nullptr terminated array + const char **reserved_words; // nullptr terminated array + const char **comment_delimiters; // nullptr terminated array + const char **string_delimiters; // nullptr terminated array godot_bool has_named_classes; godot_bool supports_builtin_mode; godot_bool can_inherit_from_file; godot_string (*get_template_source_code)(godot_pluginscript_language_data *p_data, const godot_string *p_class_name, const godot_string *p_base_class_name); - godot_bool (*validate)(godot_pluginscript_language_data *p_data, const godot_string *p_script, int *r_line_error, int *r_col_error, godot_string *r_test_error, const godot_string *p_path, godot_packed_string_array *r_functions); + godot_bool (*validate)(godot_pluginscript_language_data *p_data, const godot_string *p_script, const godot_string *p_path, godot_packed_string_array *r_functions, godot_array *r_errors); // errors = Array of Dictionary with "line", "column", "message" keys int (*find_function)(godot_pluginscript_language_data *p_data, const godot_string *p_function, const godot_string *p_code); // Can be nullptr godot_string (*make_function)(godot_pluginscript_language_data *p_data, const godot_string *p_class, const godot_string *p_name, const godot_packed_string_array *p_args); godot_error (*complete_code)(godot_pluginscript_language_data *p_data, const godot_string *p_code, const godot_string *p_path, godot_object *p_owner, godot_array *r_options, godot_bool *r_force, godot_string *r_call_hint); diff --git a/modules/gdnative/include/text/godot_text.h b/modules/gdnative/include/text/godot_text.h index f3c50e6f87..6428f2f149 100644 --- a/modules/gdnative/include/text/godot_text.h +++ b/modules/gdnative/include/text/godot_text.h @@ -143,13 +143,14 @@ typedef struct { bool (*shaped_text_shape)(void *, godot_rid *); bool (*shaped_text_update_breaks)(void *, godot_rid *); bool (*shaped_text_update_justification_ops)(void *, godot_rid *); + void (*shaped_text_overrun_trim_to_width)(void *, godot_rid *, float, uint8_t); bool (*shaped_text_is_ready)(void *, godot_rid *); godot_packed_glyph_array (*shaped_text_get_glyphs)(void *, godot_rid *); godot_vector2i (*shaped_text_get_range)(void *, godot_rid *); godot_packed_glyph_array (*shaped_text_sort_logical)(void *, godot_rid *); godot_packed_vector2i_array (*shaped_text_get_line_breaks_adv)(void *, godot_rid *, godot_packed_float32_array *, int, bool, uint8_t); godot_packed_vector2i_array (*shaped_text_get_line_breaks)(void *, godot_rid *, float, int, uint8_t); - godot_packed_vector2i_array (*shaped_text_get_word_breaks)(void *, godot_rid *); + godot_packed_vector2i_array (*shaped_text_get_word_breaks)(void *, godot_rid *, int); godot_array (*shaped_text_get_objects)(void *, godot_rid *); godot_rect2 (*shaped_text_get_object_rect)(void *, godot_rid *, const godot_variant *); godot_vector2 (*shaped_text_get_size)(void *, godot_rid *); diff --git a/modules/gdnative/include/xr/godot_xr.h b/modules/gdnative/include/xr/godot_xr.h index 7eaf1c7ec3..53cb830cbb 100644 --- a/modules/gdnative/include/xr/godot_xr.h +++ b/modules/gdnative/include/xr/godot_xr.h @@ -41,8 +41,8 @@ extern "C" { // version info to detect whether a call is available // Use these to populate version in your plugin -#define GODOTVR_API_MAJOR 1 -#define GODOTVR_API_MINOR 1 +#define GODOTVR_API_MAJOR 4 +#define GODOTVR_API_MINOR 0 typedef struct { godot_gdnative_api_version version; /* version of our API */ @@ -52,25 +52,32 @@ typedef struct { godot_int (*get_capabilities)(const void *); godot_bool (*get_anchor_detection_is_enabled)(const void *); void (*set_anchor_detection_is_enabled)(void *, godot_bool); - godot_bool (*is_stereo)(const void *); + godot_int (*get_view_count)(const void *); godot_bool (*is_initialized)(const void *); godot_bool (*initialize)(void *); void (*uninitialize)(void *); godot_vector2 (*get_render_targetsize)(const void *); - godot_transform (*get_transform_for_eye)(void *, godot_int, godot_transform *); - void (*fill_projection_for_eye)(void *, godot_float *, godot_int, godot_float, godot_float, godot_float); - void (*commit_for_eye)(void *, godot_int, godot_rid *, godot_rect2 *); + + godot_transform3d (*get_camera_transform)(void *); + godot_transform3d (*get_transform_for_view)(void *, godot_int, godot_transform3d *); + void (*fill_projection_for_view)(void *, godot_real_t *, godot_int, godot_real_t, godot_real_t, godot_real_t); + void (*commit_views)(void *, godot_rid *, godot_rect2 *); + void (*process)(void *); - godot_int (*get_external_texture_for_eye)(void *, godot_int); void (*notification)(void *, godot_int); godot_int (*get_camera_feed_id)(void *); + + // possibly deprecate but adding/keeping as a reminder these are in Godot 3 + void (*commit_for_eye)(void *, godot_int, godot_rid *, godot_rect2 *); + godot_int (*get_external_texture_for_eye)(void *, godot_int); + godot_int (*get_external_depth_for_eye)(void *, godot_int); } godot_xr_interface_gdnative; void GDAPI godot_xr_register_interface(const godot_xr_interface_gdnative *p_interface); // helper functions to access XRServer data -godot_float GDAPI godot_xr_get_worldscale(); -godot_transform GDAPI godot_xr_get_reference_frame(); +godot_real_t GDAPI godot_xr_get_worldscale(); +godot_transform3d GDAPI godot_xr_get_reference_frame(); // helper functions for rendering void GDAPI godot_xr_blit(godot_int p_eye, godot_rid *p_render_target, godot_rect2 *p_rect); @@ -79,10 +86,10 @@ godot_int GDAPI godot_xr_get_texid(godot_rid *p_render_target); // helper functions for updating XR controllers godot_int GDAPI godot_xr_add_controller(char *p_device_name, godot_int p_hand, godot_bool p_tracks_orientation, godot_bool p_tracks_position); void GDAPI godot_xr_remove_controller(godot_int p_controller_id); -void GDAPI godot_xr_set_controller_transform(godot_int p_controller_id, godot_transform *p_transform, godot_bool p_tracks_orientation, godot_bool p_tracks_position); +void GDAPI godot_xr_set_controller_transform(godot_int p_controller_id, godot_transform3d *p_transform, godot_bool p_tracks_orientation, godot_bool p_tracks_position); void GDAPI godot_xr_set_controller_button(godot_int p_controller_id, godot_int p_button, godot_bool p_is_pressed); -void GDAPI godot_xr_set_controller_axis(godot_int p_controller_id, godot_int p_axis, godot_float p_value, godot_bool p_can_be_negative); -godot_float GDAPI godot_xr_get_controller_rumble(godot_int p_controller_id); +void GDAPI godot_xr_set_controller_axis(godot_int p_controller_id, godot_int p_axis, godot_real_t p_value, godot_bool p_can_be_negative); +godot_real_t GDAPI godot_xr_get_controller_rumble(godot_int p_controller_id); #ifdef __cplusplus } diff --git a/modules/gdnative/nativescript/api_generator.cpp b/modules/gdnative/nativescript/api_generator.cpp index f184c84615..df0f29277e 100644 --- a/modules/gdnative/nativescript/api_generator.cpp +++ b/modules/gdnative/nativescript/api_generator.cpp @@ -34,10 +34,11 @@ #include "core/config/engine.h" #include "core/core_constants.h" +#include "core/io/file_access.h" #include "core/object/class_db.h" -#include "core/os/file_access.h" #include "core/string/string_builder.h" #include "core/templates/pair.h" +#include "core/variant/variant_parser.h" // helper stuff @@ -121,7 +122,7 @@ struct ClassAPI { String singleton_name; bool is_instantiable = false; // @Unclear - bool is_reference = false; + bool is_ref_counted = false; bool has_indexing = false; // For builtin types. String indexed_type; // For builtin types. bool is_keyed = false; // For builtin types. @@ -250,14 +251,14 @@ List<ClassAPI> generate_c_api_classes() { class_api.singleton_name = name; } } - class_api.is_instantiable = !class_api.is_singleton && ClassDB::can_instance(class_name); + class_api.is_instantiable = !class_api.is_singleton && ClassDB::can_instantiate(class_name); { List<StringName> inheriters; - ClassDB::get_inheriters_from_class("Reference", &inheriters); - bool is_reference = !!inheriters.find(class_name) || class_name == "Reference"; + ClassDB::get_inheriters_from_class("RefCounted", &inheriters); + bool is_ref_counted = !!inheriters.find(class_name) || class_name == "RefCounted"; // @Unclear - class_api.is_reference = !class_api.is_singleton && is_reference; + class_api.is_ref_counted = !class_api.is_singleton && is_ref_counted; } // constants @@ -404,7 +405,7 @@ List<ClassAPI> generate_c_api_classes() { arg_type = Variant::get_type_name(arg_info.type); } } else { - arg_type = Variant::get_type_name(arg_info.type); + arg_type = get_type_name(arg_info); } method_api.argument_names.push_back(arg_name); @@ -424,11 +425,11 @@ List<ClassAPI> generate_c_api_classes() { List<EnumAPI> enums; List<StringName> enum_names; ClassDB::get_enum_list(class_name, &enum_names, true); - for (List<StringName>::Element *E = enum_names.front(); E; E = E->next()) { + for (const StringName &E : enum_names) { List<StringName> value_names; EnumAPI enum_api; - enum_api.name = E->get(); - ClassDB::get_enum_constants(class_name, E->get(), &value_names, true); + enum_api.name = E; + ClassDB::get_enum_constants(class_name, E, &value_names, true); for (List<StringName>::Element *val_e = value_names.front(); val_e; val_e = val_e->next()) { int int_val = ClassDB::get_integer_constant(class_name, val_e->get(), nullptr); enum_api.values.push_back(Pair<int, String>(int_val, val_e->get())); @@ -458,8 +459,8 @@ List<ClassAPI> generate_c_builtin_api_types() { List<StringName> utility_functions; Variant::get_utility_function_list(&utility_functions); - for (const List<StringName>::Element *E = utility_functions.front(); E; E = E->next()) { - const StringName &function_name = E->get(); + for (const StringName &E : utility_functions) { + const StringName &function_name = E; MethodAPI function_api; function_api.method_name = function_name; @@ -509,10 +510,10 @@ List<ClassAPI> generate_c_builtin_api_types() { case Variant::PACKED_VECTOR2_ARRAY: case Variant::PACKED_VECTOR3_ARRAY: case Variant::PACKED_COLOR_ARRAY: - class_api.is_reference = true; + class_api.is_ref_counted = true; break; default: - class_api.is_reference = false; + class_api.is_ref_counted = false; break; } @@ -520,8 +521,8 @@ List<ClassAPI> generate_c_builtin_api_types() { List<StringName> methods; Variant::get_builtin_method_list(type, &methods); - for (const List<StringName>::Element *E = methods.front(); E; E = E->next()) { - const StringName &method_name = E->get(); + for (const StringName &E : methods) { + const StringName &method_name = E; MethodAPI method_api; @@ -577,8 +578,8 @@ List<ClassAPI> generate_c_builtin_api_types() { List<StringName> constants; Variant::get_constants_for_type(type, &constants); - for (const List<StringName>::Element *E = constants.front(); E; E = E->next()) { - const StringName &constant_name = E->get(); + for (const StringName &E : constants) { + const StringName &constant_name = E; ConstantAPI constant_api; constant_api.constant_name = constant_name; @@ -592,8 +593,8 @@ List<ClassAPI> generate_c_builtin_api_types() { List<StringName> members; Variant::get_member_list(type, &members); - for (const List<StringName>::Element *E = members.front(); E; E = E->next()) { - const StringName &member_name = E->get(); + for (const StringName &E : members) { + const StringName &member_name = E; PropertyAPI member_api; member_api.name = member_name; @@ -638,6 +639,7 @@ static List<String> generate_c_api_json(const List<ClassAPI> &p_api) { // I'm sorry for the \t mess List<String> source; + VariantWriter writer; source.push_back("[\n"); @@ -652,7 +654,7 @@ static List<String> generate_c_api_json(const List<ClassAPI> &p_api) { source.push_back(String("\t\t\"singleton\": ") + (api.is_singleton ? "true" : "false") + ",\n"); source.push_back("\t\t\"singleton_name\": \"" + api.singleton_name + "\",\n"); source.push_back(String("\t\t\"instantiable\": ") + (api.is_instantiable ? "true" : "false") + ",\n"); - source.push_back(String("\t\t\"is_reference\": ") + (api.is_reference ? "true" : "false") + ",\n"); + source.push_back(String("\t\t\"is_ref_counted\": ") + (api.is_ref_counted ? "true" : "false") + ",\n"); source.push_back("\t\t\"constants\": {\n"); for (List<ConstantAPI>::Element *e = api.constants.front(); e; e = e->next()) { @@ -682,7 +684,12 @@ static List<String> generate_c_api_json(const List<ClassAPI> &p_api) { source.push_back("\t\t\t\t\t\t\"name\": \"" + e->get().argument_names[i] + "\",\n"); source.push_back("\t\t\t\t\t\t\"type\": \"" + e->get().argument_types[i] + "\",\n"); source.push_back(String("\t\t\t\t\t\t\"has_default_value\": ") + (e->get().default_arguments.has(i) ? "true" : "false") + ",\n"); - source.push_back("\t\t\t\t\t\t\"default_value\": \"" + (e->get().default_arguments.has(i) ? (String)e->get().default_arguments[i] : "") + "\"\n"); + String default_value; + if (e->get().default_arguments.has(i)) { + writer.write_to_string(e->get().default_arguments[i], default_value); + default_value = default_value.replace("\n", "").json_escape(); + } + source.push_back("\t\t\t\t\t\t\"default_value\": \"" + default_value + "\"\n"); source.push_back(String("\t\t\t\t\t}") + ((i < e->get().argument_names.size() - 1) ? "," : "") + "\n"); } source.push_back("\t\t\t\t]\n"); @@ -708,7 +715,12 @@ static List<String> generate_c_api_json(const List<ClassAPI> &p_api) { source.push_back("\t\t\t\t\t\t\"name\": \"" + e->get().argument_names[i] + "\",\n"); source.push_back("\t\t\t\t\t\t\"type\": \"" + e->get().argument_types[i] + "\",\n"); source.push_back(String("\t\t\t\t\t\t\"has_default_value\": ") + (e->get().default_arguments.has(i) ? "true" : "false") + ",\n"); - source.push_back("\t\t\t\t\t\t\"default_value\": \"" + (e->get().default_arguments.has(i) ? (String)e->get().default_arguments[i] : "") + "\"\n"); + String default_value; + if (e->get().default_arguments.has(i)) { + writer.write_to_string(e->get().default_arguments[i], default_value); + default_value = default_value.replace("\n", "").json_escape(); + } + source.push_back("\t\t\t\t\t\t\"default_value\": \"" + default_value + "\"\n"); source.push_back(String("\t\t\t\t\t}") + ((i < e->get().argument_names.size() - 1) ? "," : "") + "\n"); } source.push_back("\t\t\t\t]\n"); @@ -756,6 +768,8 @@ static void append_indented(StringBuilder &p_source, const char *p_text) { } static void write_builtin_method(StringBuilder &p_source, const MethodAPI &p_method) { + VariantWriter writer; + append_indented(p_source, vformat(R"("name": "%s",)", p_method.method_name)); append_indented(p_source, vformat(R"("return_type": "%s",)", p_method.return_type)); append_indented(p_source, vformat(R"("is_const": %s,)", p_method.is_const ? "true" : "false")); @@ -771,7 +785,12 @@ static void write_builtin_method(StringBuilder &p_source, const MethodAPI &p_met append_indented(p_source, vformat(R"("name": "%s",)", p_method.argument_names[i])); append_indented(p_source, vformat(R"("type": "%s",)", p_method.argument_types[i])); append_indented(p_source, vformat(R"("has_default_value": %s,)", p_method.default_arguments.has(i) ? "true" : "false")); - append_indented(p_source, vformat(R"("default_value": "%s")", p_method.default_arguments.has(i) ? p_method.default_arguments[i].operator String() : "")); + String default_value; + if (p_method.default_arguments.has(i)) { + writer.write_to_string(p_method.default_arguments[i], default_value); + default_value = default_value.replace("\n", "").json_escape(); + } + append_indented(p_source, vformat(R"("default_value": "%s")", default_value)); indent_level--; append_indented(p_source, i < p_method.argument_count - 1 ? "}," : "}"); @@ -794,7 +813,7 @@ static List<String> generate_c_builtin_api_json(const List<ClassAPI> &p_api) { append_indented(source, vformat(R"("name": "%s",)", class_api.class_name)); append_indented(source, vformat(R"("is_instantiable": %s,)", class_api.is_instantiable ? "true" : "false")); - append_indented(source, vformat(R"("is_reference": %s,)", class_api.is_reference ? "true" : "false")); + append_indented(source, vformat(R"("is_ref_counted": %s,)", class_api.is_ref_counted ? "true" : "false")); append_indented(source, vformat(R"("has_indexing": %s,)", class_api.has_indexing ? "true" : "false")); append_indented(source, vformat(R"("indexed_type": "%s",)", class_api.has_indexing && class_api.indexed_type == "Nil" ? "Variant" : class_api.indexed_type)); append_indented(source, vformat(R"("is_keyed": %s,)", class_api.is_keyed ? "true" : "false")); diff --git a/modules/gdnative/nativescript/godot_nativescript.cpp b/modules/gdnative/nativescript/godot_nativescript.cpp index b2abf8b8ae..70b14836bf 100644 --- a/modules/gdnative/nativescript/godot_nativescript.cpp +++ b/modules/gdnative/nativescript/godot_nativescript.cpp @@ -70,8 +70,7 @@ void GDAPI godot_nativescript_register_class(void *p_gdnative_handle, const char const NativeScriptDesc *b = desc.base_data; while (b) { - desc.rpc_count += b->rpc_count; - desc.rset_count += b->rset_count; + desc.rpc_methods.append_array(b->rpc_methods); b = b->base_data; } @@ -94,8 +93,6 @@ void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const desc.destroy_func = p_destroy_func; desc.is_tool = true; desc.base = p_base; - desc.rpc_count = 0; - desc.rset_count = 0; if (classes->has(p_base)) { desc.base_data = &(*classes)[p_base]; @@ -103,8 +100,7 @@ void GDAPI godot_nativescript_register_tool_class(void *p_gdnative_handle, const const NativeScriptDesc *b = desc.base_data; while (b) { - desc.rpc_count += b->rpc_count; - desc.rset_count += b->rset_count; + desc.rpc_methods.append_array(b->rpc_methods); b = b->base_data; } @@ -126,13 +122,16 @@ void GDAPI godot_nativescript_register_method(void *p_gdnative_handle, const cha method.method = p_method; method.rpc_mode = p_attr.rpc_type; method.rpc_method_id = UINT16_MAX; - if (p_attr.rpc_type != GODOT_METHOD_RPC_MODE_DISABLED) { - method.rpc_method_id = E->get().rpc_count; - E->get().rpc_count += 1; - } method.info = MethodInfo(p_function_name); E->get().methods.insert(p_function_name, method); + + if (p_attr.rpc_type != GODOT_METHOD_RPC_MODE_DISABLED) { + MultiplayerAPI::RPCConfig nd; + nd.name = String(p_name); + nd.rpc_mode = MultiplayerAPI::RPCMode(p_attr.rpc_type); + E->get().rpc_methods.push_back(nd); + } } void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const char *p_name, const char *p_path, godot_nativescript_property_attributes *p_attr, godot_nativescript_property_set_func p_set_func, godot_nativescript_property_get_func p_get_func) { @@ -144,11 +143,6 @@ void GDAPI godot_nativescript_register_property(void *p_gdnative_handle, const c NativeScriptDesc::Property property; property.default_value = *(Variant *)&p_attr->default_value; property.getter = p_get_func; - property.rset_mode = p_attr->rset_type; - if (p_attr->rset_type != GODOT_METHOD_RPC_MODE_DISABLED) { - property.rset_property_id = E->get().rset_count; - E->get().rset_count += 1; - } property.setter = p_set_func; property.info = PropertyInfo((Variant::Type)p_attr->type, p_path, @@ -338,7 +332,7 @@ void GDAPI godot_nativescript_unregister_instance_binding_data_functions(int p_i } void GDAPI *godot_nativescript_get_instance_binding_data(int p_idx, godot_object *p_object) { - return NativeScriptLanguage::get_singleton()->get_instance_binding_data(p_idx, (Object *)p_object); + return nullptr; } void GDAPI godot_nativescript_profiling_add_data(const char *p_signature, uint64_t p_time) { diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp index 3283f28de5..26d3aed702 100644 --- a/modules/gdnative/nativescript/nativescript.cpp +++ b/modules/gdnative/nativescript/nativescript.cpp @@ -37,8 +37,8 @@ #include "core/config/project_settings.h" #include "core/core_constants.h" #include "core/core_string_names.h" +#include "core/io/file_access.h" #include "core/io/file_access_encrypted.h" -#include "core/os/file_access.h" #include "core/os/os.h" #include "main/main.h" @@ -98,10 +98,10 @@ void NativeScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) List<PropertyInfo> info; get_script_property_list(&info); Map<StringName, Variant> values; - for (List<PropertyInfo>::Element *E = info.front(); E; E = E->next()) { + for (const PropertyInfo &E : info) { Variant value; - get_property_default_value(E->get().name, value); - values[E->get().name] = value; + get_property_default_value(E.name, value); + values[E.name] = value; } p_placeholder->update(info, values); @@ -114,9 +114,25 @@ void NativeScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) #endif bool NativeScript::inherits_script(const Ref<Script> &p_script) const { -#ifndef _MSC_VER -#warning inheritance needs to be implemented in NativeScript -#endif + Ref<NativeScript> ns = p_script; + if (ns.is_null()) { + return false; + } + + const NativeScriptDesc *other_s = ns->get_script_desc(); + if (!other_s) { + return false; + } + + const NativeScriptDesc *s = get_script_desc(); + + while (s) { + if (s == other_s) { + return true; + } + s = s->base_data; + } + return false; } @@ -170,7 +186,7 @@ String NativeScript::get_script_class_icon_path() const { return script_class_icon_path; } -bool NativeScript::can_instance() const { +bool NativeScript::can_instantiate() const { NativeScriptDesc *script_data = get_script_desc(); #ifdef TOOLS_ENABLED @@ -415,245 +431,11 @@ void NativeScript::get_script_property_list(List<PropertyInfo> *p_list) const { } } -Vector<ScriptNetData> NativeScript::get_rpc_methods() const { - Vector<ScriptNetData> v; - - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - for (Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.front(); E; E = E->next()) { - if (E->get().rpc_mode != GODOT_METHOD_RPC_MODE_DISABLED) { - ScriptNetData nd; - nd.name = E->key(); - nd.mode = MultiplayerAPI::RPCMode(E->get().rpc_mode); - v.push_back(nd); - } - } - - script_data = script_data->base_data; - } - - return v; -} - -uint16_t NativeScript::get_rpc_method_id(const StringName &p_method) const { - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find(p_method); - if (E) { - return E->get().rpc_method_id; - } - - script_data = script_data->base_data; - } - - return UINT16_MAX; -} - -StringName NativeScript::get_rpc_method(uint16_t p_id) const { - ERR_FAIL_COND_V(p_id == UINT16_MAX, StringName()); - - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - for (Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.front(); E; E = E->next()) { - if (E->get().rpc_method_id == p_id) { - return E->key(); - } - } - - script_data = script_data->base_data; - } - - return StringName(); -} - -MultiplayerAPI::RPCMode NativeScript::get_rpc_mode_by_id(uint16_t p_id) const { - ERR_FAIL_COND_V(p_id == UINT16_MAX, MultiplayerAPI::RPC_MODE_DISABLED); - - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - for (Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.front(); E; E = E->next()) { - if (E->get().rpc_method_id == p_id) { - switch (E->get().rpc_mode) { - case GODOT_METHOD_RPC_MODE_DISABLED: - return MultiplayerAPI::RPC_MODE_DISABLED; - case GODOT_METHOD_RPC_MODE_REMOTE: - return MultiplayerAPI::RPC_MODE_REMOTE; - case GODOT_METHOD_RPC_MODE_MASTER: - return MultiplayerAPI::RPC_MODE_MASTER; - case GODOT_METHOD_RPC_MODE_PUPPET: - return MultiplayerAPI::RPC_MODE_PUPPET; - case GODOT_METHOD_RPC_MODE_REMOTESYNC: - return MultiplayerAPI::RPC_MODE_REMOTESYNC; - case GODOT_METHOD_RPC_MODE_MASTERSYNC: - return MultiplayerAPI::RPC_MODE_MASTERSYNC; - case GODOT_METHOD_RPC_MODE_PUPPETSYNC: - return MultiplayerAPI::RPC_MODE_PUPPETSYNC; - default: - return MultiplayerAPI::RPC_MODE_DISABLED; - } - } - } - - script_data = script_data->base_data; - } - - return MultiplayerAPI::RPC_MODE_DISABLED; -} - -MultiplayerAPI::RPCMode NativeScript::get_rpc_mode(const StringName &p_method) const { - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - Map<StringName, NativeScriptDesc::Method>::Element *E = script_data->methods.find(p_method); - if (E) { - switch (E->get().rpc_mode) { - case GODOT_METHOD_RPC_MODE_DISABLED: - return MultiplayerAPI::RPC_MODE_DISABLED; - case GODOT_METHOD_RPC_MODE_REMOTE: - return MultiplayerAPI::RPC_MODE_REMOTE; - case GODOT_METHOD_RPC_MODE_MASTER: - return MultiplayerAPI::RPC_MODE_MASTER; - case GODOT_METHOD_RPC_MODE_PUPPET: - return MultiplayerAPI::RPC_MODE_PUPPET; - case GODOT_METHOD_RPC_MODE_REMOTESYNC: - return MultiplayerAPI::RPC_MODE_REMOTESYNC; - case GODOT_METHOD_RPC_MODE_MASTERSYNC: - return MultiplayerAPI::RPC_MODE_MASTERSYNC; - case GODOT_METHOD_RPC_MODE_PUPPETSYNC: - return MultiplayerAPI::RPC_MODE_PUPPETSYNC; - default: - return MultiplayerAPI::RPC_MODE_DISABLED; - } - } - - script_data = script_data->base_data; - } - - return MultiplayerAPI::RPC_MODE_DISABLED; -} - -Vector<ScriptNetData> NativeScript::get_rset_properties() const { - Vector<ScriptNetData> v; - - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.front(); E; E = E.next()) { - if (E.get().rset_mode != GODOT_METHOD_RPC_MODE_DISABLED) { - ScriptNetData nd; - nd.name = E.key(); - nd.mode = MultiplayerAPI::RPCMode(E.get().rset_mode); - v.push_back(nd); - } - } - script_data = script_data->base_data; - } - - return v; -} - -uint16_t NativeScript::get_rset_property_id(const StringName &p_variable) const { - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.find(p_variable); - if (E) { - return E.get().rset_property_id; - } - - script_data = script_data->base_data; - } - - return UINT16_MAX; -} - -StringName NativeScript::get_rset_property(uint16_t p_id) const { - ERR_FAIL_COND_V(p_id == UINT16_MAX, StringName()); - - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.front(); E; E = E.next()) { - if (E.get().rset_property_id == p_id) { - return E.key(); - } - } - - script_data = script_data->base_data; - } - - return StringName(); -} - -MultiplayerAPI::RPCMode NativeScript::get_rset_mode_by_id(uint16_t p_id) const { - ERR_FAIL_COND_V(p_id == UINT16_MAX, MultiplayerAPI::RPC_MODE_DISABLED); - - NativeScriptDesc *script_data = get_script_desc(); - - while (script_data) { - for (OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.front(); E; E = E.next()) { - if (E.get().rset_property_id == p_id) { - switch (E.get().rset_mode) { - case GODOT_METHOD_RPC_MODE_DISABLED: - return MultiplayerAPI::RPC_MODE_DISABLED; - case GODOT_METHOD_RPC_MODE_REMOTE: - return MultiplayerAPI::RPC_MODE_REMOTE; - case GODOT_METHOD_RPC_MODE_MASTER: - return MultiplayerAPI::RPC_MODE_MASTER; - case GODOT_METHOD_RPC_MODE_PUPPET: - return MultiplayerAPI::RPC_MODE_PUPPET; - case GODOT_METHOD_RPC_MODE_REMOTESYNC: - return MultiplayerAPI::RPC_MODE_REMOTESYNC; - case GODOT_METHOD_RPC_MODE_MASTERSYNC: - return MultiplayerAPI::RPC_MODE_MASTERSYNC; - case GODOT_METHOD_RPC_MODE_PUPPETSYNC: - return MultiplayerAPI::RPC_MODE_PUPPETSYNC; - default: - return MultiplayerAPI::RPC_MODE_DISABLED; - } - } - } - - script_data = script_data->base_data; - } - - return MultiplayerAPI::RPC_MODE_DISABLED; -} - -MultiplayerAPI::RPCMode NativeScript::get_rset_mode(const StringName &p_variable) const { +const Vector<MultiplayerAPI::RPCConfig> NativeScript::get_rpc_methods() const { NativeScriptDesc *script_data = get_script_desc(); + ERR_FAIL_COND_V(!script_data, Vector<MultiplayerAPI::RPCConfig>()); - while (script_data) { - OrderedHashMap<StringName, NativeScriptDesc::Property>::Element E = script_data->properties.find(p_variable); - if (E) { - switch (E.get().rset_mode) { - case GODOT_METHOD_RPC_MODE_DISABLED: - return MultiplayerAPI::RPC_MODE_DISABLED; - case GODOT_METHOD_RPC_MODE_REMOTE: - return MultiplayerAPI::RPC_MODE_REMOTE; - case GODOT_METHOD_RPC_MODE_MASTER: - return MultiplayerAPI::RPC_MODE_MASTER; - case GODOT_METHOD_RPC_MODE_PUPPET: - return MultiplayerAPI::RPC_MODE_PUPPET; - case GODOT_METHOD_RPC_MODE_REMOTESYNC: - return MultiplayerAPI::RPC_MODE_REMOTESYNC; - case GODOT_METHOD_RPC_MODE_MASTERSYNC: - return MultiplayerAPI::RPC_MODE_MASTERSYNC; - case GODOT_METHOD_RPC_MODE_PUPPETSYNC: - return MultiplayerAPI::RPC_MODE_PUPPETSYNC; - default: - return MultiplayerAPI::RPC_MODE_DISABLED; - } - } - - script_data = script_data->base_data; - } - - return MultiplayerAPI::RPC_MODE_DISABLED; + return script_data->rpc_methods; } String NativeScript::get_class_documentation() const { @@ -737,9 +519,9 @@ Variant NativeScript::_new(const Variant **p_args, int p_argcount, Callable::Cal Object *owner = nullptr; if (!(script_data->base_native_type == "")) { - owner = ClassDB::instance(script_data->base_native_type); + owner = ClassDB::instantiate(script_data->base_native_type); } else { - owner = memnew(Reference); + owner = memnew(RefCounted); } if (!owner) { @@ -747,7 +529,7 @@ Variant NativeScript::_new(const Variant **p_args, int p_argcount, Callable::Cal return Variant(); } - Reference *r = Object::cast_to<Reference>(owner); + RefCounted *r = Object::cast_to<RefCounted>(owner); if (r) { ref = REF(r); } @@ -1046,46 +828,10 @@ Ref<Script> NativeScriptInstance::get_script() const { return script; } -Vector<ScriptNetData> NativeScriptInstance::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> NativeScriptInstance::get_rpc_methods() const { return script->get_rpc_methods(); } -uint16_t NativeScriptInstance::get_rpc_method_id(const StringName &p_method) const { - return script->get_rpc_method_id(p_method); -} - -StringName NativeScriptInstance::get_rpc_method(uint16_t p_id) const { - return script->get_rpc_method(p_id); -} - -MultiplayerAPI::RPCMode NativeScriptInstance::get_rpc_mode_by_id(uint16_t p_id) const { - return script->get_rpc_mode_by_id(p_id); -} - -MultiplayerAPI::RPCMode NativeScriptInstance::get_rpc_mode(const StringName &p_method) const { - return script->get_rpc_mode(p_method); -} - -Vector<ScriptNetData> NativeScriptInstance::get_rset_properties() const { - return script->get_rset_properties(); -} - -uint16_t NativeScriptInstance::get_rset_property_id(const StringName &p_variable) const { - return script->get_rset_property_id(p_variable); -} - -StringName NativeScriptInstance::get_rset_property(uint16_t p_id) const { - return script->get_rset_property(p_id); -} - -MultiplayerAPI::RPCMode NativeScriptInstance::get_rset_mode_by_id(uint16_t p_id) const { - return script->get_rset_mode_by_id(p_id); -} - -MultiplayerAPI::RPCMode NativeScriptInstance::get_rset_mode(const StringName &p_variable) const { - return script->get_rset_mode(p_variable); -} - ScriptLanguage *NativeScriptInstance::get_language() { return NativeScriptLanguage::get_singleton(); } @@ -1289,6 +1035,10 @@ void NativeScriptLanguage::finish() { void NativeScriptLanguage::get_reserved_words(List<String> *p_words) const { } +bool NativeScriptLanguage::is_control_flow_keyword(String p_keyword) const { + return false; +} + void NativeScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const { } @@ -1301,7 +1051,7 @@ Ref<Script> NativeScriptLanguage::get_template(const String &p_class_name, const return Ref<NativeScript>(s); } -bool NativeScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { +bool NativeScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { return true; } @@ -1524,6 +1274,8 @@ void NativeScriptLanguage::unregister_binding_functions(int p_idx) { } void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_object) { + return nullptr; +#if 0 ERR_FAIL_INDEX_V(p_idx, binding_functions.size(), nullptr); ERR_FAIL_COND_V_MSG(!binding_functions[p_idx].first, nullptr, "Tried to get binding data for a nativescript binding that does not exist."); @@ -1553,9 +1305,12 @@ void *NativeScriptLanguage::get_instance_binding_data(int p_idx, Object *p_objec } return (*binding_data)[p_idx]; +#endif } void *NativeScriptLanguage::alloc_instance_binding_data(Object *p_object) { + return nullptr; +#if 0 Vector<void *> *binding_data = new Vector<void *>; binding_data->resize(binding_functions.size()); @@ -1567,9 +1322,11 @@ void *NativeScriptLanguage::alloc_instance_binding_data(Object *p_object) { binding_instances.insert(binding_data); return (void *)binding_data; +#endif } void NativeScriptLanguage::free_instance_binding_data(void *p_data) { +#if 0 if (!p_data) { return; } @@ -1589,9 +1346,11 @@ void NativeScriptLanguage::free_instance_binding_data(void *p_data) { binding_instances.erase(&binding_data); delete &binding_data; +#endif } void NativeScriptLanguage::refcount_incremented_instance_binding(Object *p_object) { +#if 0 void *data = p_object->get_script_instance_binding(lang_idx); if (!data) { @@ -1613,9 +1372,11 @@ void NativeScriptLanguage::refcount_incremented_instance_binding(Object *p_objec binding_functions[i].second.refcount_incremented_instance_binding(binding_data[i], p_object); } } +#endif } bool NativeScriptLanguage::refcount_decremented_instance_binding(Object *p_object) { +#if 0 void *data = p_object->get_script_instance_binding(lang_idx); if (!data) { @@ -1641,6 +1402,8 @@ bool NativeScriptLanguage::refcount_decremented_instance_binding(Object *p_objec } return can_die; +#endif + return false; } void NativeScriptLanguage::set_global_type_tag(int p_idx, StringName p_class_name, const void *p_type_tag) { @@ -1688,7 +1451,7 @@ void NativeScriptLanguage::init_library(const Ref<GDNativeLibrary> &lib) { if (!E) { Ref<GDNative> gdn; - gdn.instance(); + gdn.instantiate(); gdn->set_library(lib); // TODO check the return value? diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h index d6ba2bbec1..777a878660 100644 --- a/modules/gdnative/nativescript/nativescript.h +++ b/modules/gdnative/nativescript/nativescript.h @@ -62,8 +62,6 @@ struct NativeScriptDesc { godot_nativescript_property_get_func getter; PropertyInfo info; Variant default_value; - int rset_mode = 0; - uint16_t rset_property_id; String documentation; }; @@ -72,9 +70,8 @@ struct NativeScriptDesc { String documentation; }; - uint16_t rpc_count = 0; Map<StringName, Method> methods; - uint16_t rset_count = 0; + Vector<MultiplayerAPI::RPCConfig> rpc_methods; OrderedHashMap<StringName, Property> properties; Map<StringName, Signal> signals_; // QtCreator doesn't like the name signals StringName base; @@ -90,8 +87,8 @@ struct NativeScriptDesc { bool is_tool = false; inline NativeScriptDesc() { - zeromem(&create_func, sizeof(godot_nativescript_instance_create_func)); - zeromem(&destroy_func, sizeof(godot_nativescript_instance_destroy_func)); + memset(&create_func, 0, sizeof(godot_nativescript_instance_create_func)); + memset(&destroy_func, 0, sizeof(godot_nativescript_instance_destroy_func)); } }; @@ -140,7 +137,7 @@ public: void set_script_class_icon_path(String p_icon_path); String get_script_class_icon_path() const; - virtual bool can_instance() const override; + virtual bool can_instantiate() const override; virtual Ref<Script> get_base_script() const override; //for script inheritance @@ -178,17 +175,7 @@ public: virtual void get_script_method_list(List<MethodInfo> *p_list) const override; virtual void get_script_property_list(List<PropertyInfo> *p_list) const override; - virtual Vector<ScriptNetData> get_rpc_methods() const override; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const override; - virtual StringName get_rpc_method(uint16_t p_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(uint16_t p_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override; - - virtual Vector<ScriptNetData> get_rset_properties() const override; - virtual uint16_t get_rset_property_id(const StringName &p_variable) const override; - virtual StringName get_rset_property(uint16_t p_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(uint16_t p_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const override; String get_class_documentation() const; String get_method_documentation(const StringName &p_method) const; @@ -226,17 +213,7 @@ public: String to_string(bool *r_valid); virtual Ref<Script> get_script() const; - virtual Vector<ScriptNetData> get_rpc_methods() const; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const; - virtual StringName get_rpc_method(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const; - - virtual Vector<ScriptNetData> get_rset_properties() const; - virtual uint16_t get_rset_property_id(const StringName &p_variable) const; - virtual StringName get_rset_property(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const; virtual ScriptLanguage *get_language(); @@ -336,10 +313,11 @@ public: virtual Error execute_file(const String &p_path); virtual void finish(); virtual void get_reserved_words(List<String> *p_words) const; + virtual bool is_control_flow_keyword(String p_keyword) const; virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; + virtual bool validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; diff --git a/modules/gdnative/nativescript/register_types.cpp b/modules/gdnative/nativescript/register_types.cpp index 0353ab2092..82a3459517 100644 --- a/modules/gdnative/nativescript/register_types.cpp +++ b/modules/gdnative/nativescript/register_types.cpp @@ -45,15 +45,15 @@ Ref<ResourceFormatSaverNativeScript> resource_saver_gdns; void register_nativescript_types() { native_script_language = memnew(NativeScriptLanguage); - ClassDB::register_class<NativeScript>(); + GDREGISTER_CLASS(NativeScript); native_script_language->set_language_index(ScriptServer::get_language_count()); ScriptServer::register_language(native_script_language); - resource_saver_gdns.instance(); + resource_saver_gdns.instantiate(); ResourceSaver::add_resource_format_saver(resource_saver_gdns); - resource_loader_gdns.instance(); + resource_loader_gdns.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_gdns); } diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.cpp b/modules/gdnative/net/multiplayer_peer_gdnative.cpp index 8b5fc8db5c..9908ed4533 100644 --- a/modules/gdnative/net/multiplayer_peer_gdnative.cpp +++ b/modules/gdnative/net/multiplayer_peer_gdnative.cpp @@ -61,13 +61,23 @@ int MultiplayerPeerGDNative::get_available_packet_count() const { return interface->get_available_packet_count(interface->data); } -/* NetworkedMultiplayerPeer */ +/* MultiplayerPeer */ +void MultiplayerPeerGDNative::set_transfer_channel(int p_channel) { + ERR_FAIL_COND(interface == nullptr); + return interface->set_transfer_channel(interface->data, p_channel); +} + +int MultiplayerPeerGDNative::get_transfer_channel() const { + ERR_FAIL_COND_V(interface == nullptr, 0); + return interface->get_transfer_channel(interface->data); +} + void MultiplayerPeerGDNative::set_transfer_mode(TransferMode p_mode) { ERR_FAIL_COND(interface == nullptr); interface->set_transfer_mode(interface->data, (godot_int)p_mode); } -NetworkedMultiplayerPeer::TransferMode MultiplayerPeerGDNative::get_transfer_mode() const { +MultiplayerPeer::TransferMode MultiplayerPeerGDNative::get_transfer_mode() const { ERR_FAIL_COND_V(interface == nullptr, TRANSFER_MODE_UNRELIABLE); return (TransferMode)interface->get_transfer_mode(interface->data); } @@ -107,12 +117,13 @@ bool MultiplayerPeerGDNative::is_refusing_new_connections() const { return interface->is_refusing_new_connections(interface->data); } -NetworkedMultiplayerPeer::ConnectionStatus MultiplayerPeerGDNative::get_connection_status() const { +MultiplayerPeer::ConnectionStatus MultiplayerPeerGDNative::get_connection_status() const { ERR_FAIL_COND_V(interface == nullptr, CONNECTION_DISCONNECTED); return (ConnectionStatus)interface->get_connection_status(interface->data); } void MultiplayerPeerGDNative::_bind_methods() { + ADD_PROPERTY_DEFAULT("transfer_channel", 0); ADD_PROPERTY_DEFAULT("transfer_mode", TRANSFER_MODE_UNRELIABLE); ADD_PROPERTY_DEFAULT("refuse_new_connections", true); } diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.h b/modules/gdnative/net/multiplayer_peer_gdnative.h index 593b2534dd..ab084faae6 100644 --- a/modules/gdnative/net/multiplayer_peer_gdnative.h +++ b/modules/gdnative/net/multiplayer_peer_gdnative.h @@ -31,12 +31,12 @@ #ifndef MULTIPLAYER_PEER_GDNATIVE_H #define MULTIPLAYER_PEER_GDNATIVE_H -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "modules/gdnative/gdnative.h" #include "modules/gdnative/include/net/godot_net.h" -class MultiplayerPeerGDNative : public NetworkedMultiplayerPeer { - GDCLASS(MultiplayerPeerGDNative, NetworkedMultiplayerPeer); +class MultiplayerPeerGDNative : public MultiplayerPeer { + GDCLASS(MultiplayerPeerGDNative, MultiplayerPeer); protected: static void _bind_methods(); @@ -55,7 +55,9 @@ public: virtual int get_max_packet_size() const override; virtual int get_available_packet_count() const override; - /* Specific to NetworkedMultiplayerPeer */ + /* Specific to MultiplayerPeer */ + virtual void set_transfer_channel(int p_channel) override; + virtual int get_transfer_channel() const override; virtual void set_transfer_mode(TransferMode p_mode) override; virtual TransferMode get_transfer_mode() const override; virtual void set_target_peer(int p_peer_id) override; diff --git a/modules/gdnative/net/register_types.cpp b/modules/gdnative/net/register_types.cpp index 645c43b7e3..46c383e5ae 100644 --- a/modules/gdnative/net/register_types.cpp +++ b/modules/gdnative/net/register_types.cpp @@ -34,9 +34,9 @@ #include "stream_peer_gdnative.h" void register_net_types() { - ClassDB::register_class<MultiplayerPeerGDNative>(); - ClassDB::register_class<PacketPeerGDNative>(); - ClassDB::register_class<StreamPeerGDNative>(); + GDREGISTER_CLASS(MultiplayerPeerGDNative); + GDREGISTER_CLASS(PacketPeerGDNative); + GDREGISTER_CLASS(StreamPeerGDNative); } void unregister_net_types() { diff --git a/modules/gdnative/pluginscript/pluginscript_instance.cpp b/modules/gdnative/pluginscript/pluginscript_instance.cpp index 7f8dba0906..ed1c0af3ed 100644 --- a/modules/gdnative/pluginscript/pluginscript_instance.cpp +++ b/modules/gdnative/pluginscript/pluginscript_instance.cpp @@ -100,46 +100,10 @@ String PluginScriptInstance::to_string(bool *r_valid) { return str_ret; } -Vector<ScriptNetData> PluginScriptInstance::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> PluginScriptInstance::get_rpc_methods() const { return _script->get_rpc_methods(); } -uint16_t PluginScriptInstance::get_rpc_method_id(const StringName &p_variable) const { - return _script->get_rpc_method_id(p_variable); -} - -StringName PluginScriptInstance::get_rpc_method(uint16_t p_id) const { - return _script->get_rpc_method(p_id); -} - -MultiplayerAPI::RPCMode PluginScriptInstance::get_rpc_mode_by_id(uint16_t p_id) const { - return _script->get_rpc_mode_by_id(p_id); -} - -MultiplayerAPI::RPCMode PluginScriptInstance::get_rpc_mode(const StringName &p_method) const { - return _script->get_rpc_mode(p_method); -} - -Vector<ScriptNetData> PluginScriptInstance::get_rset_properties() const { - return _script->get_rset_properties(); -} - -uint16_t PluginScriptInstance::get_rset_property_id(const StringName &p_variable) const { - return _script->get_rset_property_id(p_variable); -} - -StringName PluginScriptInstance::get_rset_property(uint16_t p_id) const { - return _script->get_rset_property(p_id); -} - -MultiplayerAPI::RPCMode PluginScriptInstance::get_rset_mode_by_id(uint16_t p_id) const { - return _script->get_rset_mode_by_id(p_id); -} - -MultiplayerAPI::RPCMode PluginScriptInstance::get_rset_mode(const StringName &p_variable) const { - return _script->get_rset_mode(p_variable); -} - void PluginScriptInstance::refcount_incremented() { if (_desc->refcount_decremented) { _desc->refcount_incremented(_data); diff --git a/modules/gdnative/pluginscript/pluginscript_instance.h b/modules/gdnative/pluginscript/pluginscript_instance.h index b263c0e62c..25b62ae8ab 100644 --- a/modules/gdnative/pluginscript/pluginscript_instance.h +++ b/modules/gdnative/pluginscript/pluginscript_instance.h @@ -71,17 +71,7 @@ public: void set_path(const String &p_path); - virtual Vector<ScriptNetData> get_rpc_methods() const; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const; - virtual StringName get_rpc_method(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const; - - virtual Vector<ScriptNetData> get_rset_properties() const; - virtual uint16_t get_rset_property_id(const StringName &p_variable) const; - virtual StringName get_rset_property(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(uint16_t p_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const; virtual void refcount_incremented(); virtual bool refcount_decremented(); diff --git a/modules/gdnative/pluginscript/pluginscript_language.cpp b/modules/gdnative/pluginscript/pluginscript_language.cpp index 3ed1dcaca9..79aba342c9 100644 --- a/modules/gdnative/pluginscript/pluginscript_language.cpp +++ b/modules/gdnative/pluginscript/pluginscript_language.cpp @@ -30,7 +30,7 @@ // Godot imports #include "core/config/project_settings.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "core/os/os.h" // PluginScript imports #include "pluginscript_language.h" @@ -77,6 +77,10 @@ void PluginScriptLanguage::get_reserved_words(List<String> *p_words) const { } } +bool PluginScriptLanguage::is_control_flow_keyword(String p_keyword) const { + return false; +} + void PluginScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const { if (_desc.comment_delimiters) { const char **w = _desc.comment_delimiters; @@ -108,20 +112,29 @@ Ref<Script> PluginScriptLanguage::get_template(const String &p_class_name, const return script; } -bool PluginScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { +bool PluginScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { PackedStringArray functions; + Array errors; if (_desc.validate) { bool ret = _desc.validate( _data, (godot_string *)&p_script, - &r_line_error, - &r_col_error, - (godot_string *)&r_test_error, (godot_string *)&p_path, - (godot_packed_string_array *)&functions); + (godot_packed_string_array *)&functions, + (godot_array *)&errors); for (int i = 0; i < functions.size(); i++) { r_functions->push_back(functions[i]); } + if (r_errors) { + for (int i = 0; i < errors.size(); i++) { + Dictionary error = errors[i]; + ScriptLanguage::ScriptError e; + e.line = error["line"]; + e.column = error["column"]; + e.message = error["message"]; + r_errors->push_back(e); + } + } return ret; } return true; diff --git a/modules/gdnative/pluginscript/pluginscript_language.h b/modules/gdnative/pluginscript/pluginscript_language.h index 226b039265..26ab4a95e3 100644 --- a/modules/gdnative/pluginscript/pluginscript_language.h +++ b/modules/gdnative/pluginscript/pluginscript_language.h @@ -71,10 +71,11 @@ public: /* EDITOR FUNCTIONS */ virtual void get_reserved_words(List<String> *p_words) const; + virtual bool is_control_flow_keyword(String p_keyword) const; virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; + virtual bool validate(const String &p_script, const String &p_path = "", List<String> *r_functions = nullptr, List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; diff --git a/modules/gdnative/pluginscript/pluginscript_loader.cpp b/modules/gdnative/pluginscript/pluginscript_loader.cpp index f2165cd225..462452a897 100644 --- a/modules/gdnative/pluginscript/pluginscript_loader.cpp +++ b/modules/gdnative/pluginscript/pluginscript_loader.cpp @@ -29,7 +29,7 @@ /*************************************************************************/ // Godot imports -#include "core/os/file_access.h" +#include "core/io/file_access.h" // Pythonscript imports #include "pluginscript_language.h" #include "pluginscript_loader.h" diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp index 31e6a81975..5380858582 100644 --- a/modules/gdnative/pluginscript/pluginscript_script.cpp +++ b/modules/gdnative/pluginscript/pluginscript_script.cpp @@ -29,7 +29,7 @@ /*************************************************************************/ // Godot imports -#include "core/os/file_access.h" +#include "core/io/file_access.h" // PluginScript imports #include "pluginscript_instance.h" #include "pluginscript_script.h" @@ -38,13 +38,13 @@ #ifdef DEBUG_ENABLED #define __ASSERT_SCRIPT_REASON "Cannot retrieve PluginScript class for this script, is your code correct?" -#define ASSERT_SCRIPT_VALID() \ - { \ - ERR_FAIL_COND_MSG(!can_instance(), __ASSERT_SCRIPT_REASON); \ +#define ASSERT_SCRIPT_VALID() \ + { \ + ERR_FAIL_COND_MSG(!can_instantiate(), __ASSERT_SCRIPT_REASON); \ } -#define ASSERT_SCRIPT_VALID_V(ret) \ - { \ - ERR_FAIL_COND_V_MSG(!can_instance(), ret, __ASSERT_SCRIPT_REASON); \ +#define ASSERT_SCRIPT_VALID_V(ret) \ + { \ + ERR_FAIL_COND_V_MSG(!can_instantiate(), ret, __ASSERT_SCRIPT_REASON); \ } #else #define ASSERT_SCRIPT_VALID() @@ -94,9 +94,9 @@ Variant PluginScript::_new(const Variant **p_args, int p_argcount, Callable::Cal Object *owner = nullptr; if (get_instance_base_type() == "") { - owner = memnew(Reference); + owner = memnew(RefCounted); } else { - owner = ClassDB::instance(get_instance_base_type()); + owner = ClassDB::instantiate(get_instance_base_type()); } if (!owner) { @@ -104,7 +104,7 @@ Variant PluginScript::_new(const Variant **p_args, int p_argcount, Callable::Cal return Variant(); } - Reference *r = Object::cast_to<Reference>(owner); + RefCounted *r = Object::cast_to<RefCounted>(owner); if (r) { ref = REF(r); } @@ -133,15 +133,26 @@ void PluginScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) #endif -bool PluginScript::can_instance() const { +bool PluginScript::can_instantiate() const { bool can = _valid || (!_tool && !ScriptServer::is_scripting_enabled()); return can; } bool PluginScript::inherits_script(const Ref<Script> &p_script) const { -#ifndef _MSC_VER -#warning inheritance needs to be implemented in PluginScript -#endif + Ref<PluginScript> ps = p_script; + if (ps.is_null()) { + return false; + } + + const PluginScript *s = this; + + while (s) { + if (s == p_script.ptr()) { + return true; + } + s = Object::cast_to<PluginScript>(s->_ref_base_parent.ptr()); + } + return false; } @@ -198,7 +209,7 @@ ScriptInstance *PluginScript::instance_create(Object *p_this) { StringName base_type = get_instance_base_type(); if (base_type) { if (!ClassDB::is_parent_class(p_this->get_class_name(), base_type)) { - String msg = "Script inherits from native type '" + String(base_type) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"; + String msg = "Script inherits from native type '" + String(base_type) + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'"; // TODO: implement PluginscriptLanguage::debug_break_parse // if (EngineDebugger::is_active()) { // _language->debug_break_parse(get_path(), 0, msg); @@ -212,6 +223,8 @@ ScriptInstance *PluginScript::instance_create(Object *p_this) { } bool PluginScript::instance_has(const Object *p_this) const { + ERR_FAIL_COND_V(!_language, false); + _language->lock(); bool hasit = _instances.has((Object *)p_this); _language->unlock(); @@ -310,10 +323,9 @@ Error PluginScript::reload(bool p_keep_state) { } Array *methods = (Array *)&manifest.methods; _rpc_methods.clear(); - _rpc_variables.clear(); if (_ref_base_parent.is_valid()) { + /// XXX TODO Should this be _rpc_methods.append_array(...) _rpc_methods = _ref_base_parent->get_rpc_methods(); - _rpc_variables = _ref_base_parent->get_rset_properties(); } for (int i = 0; i < methods->size(); ++i) { Dictionary v = (*methods)[i]; @@ -322,9 +334,10 @@ Error PluginScript::reload(bool p_keep_state) { // rpc_mode is passed as an optional field and is not part of MethodInfo Variant var = v["rpc_mode"]; if (var != Variant()) { - ScriptNetData nd; + MultiplayerAPI::RPCConfig nd; nd.name = mi.name; - nd.mode = MultiplayerAPI::RPCMode(int(var)); + nd.rpc_mode = MultiplayerAPI::RPCMode(int(var)); + // TODO Transfer Channel if (_rpc_methods.find(nd) == -1) { _rpc_methods.push_back(nd); } @@ -332,7 +345,7 @@ Error PluginScript::reload(bool p_keep_state) { } // Sort so we are 100% that they are always the same. - _rpc_methods.sort_custom<SortNetData>(); + _rpc_methods.sort_custom<MultiplayerAPI::SortRPCConfig>(); Array *signals = (Array *)&manifest.signals; for (int i = 0; i < signals->size(); ++i) { @@ -346,21 +359,8 @@ Error PluginScript::reload(bool p_keep_state) { PropertyInfo pi = PropertyInfo::from_dict(v); _properties_info[pi.name] = pi; _properties_default_values[pi.name] = v["default_value"]; - // rset_mode is passed as an optional field and is not part of PropertyInfo - Variant var = v["rset_mode"]; - if (var != Variant()) { - ScriptNetData nd; - nd.name = pi.name; - nd.mode = MultiplayerAPI::RPCMode(int(var)); - if (_rpc_variables.find(nd) == -1) { - _rpc_variables.push_back(nd); - } - } } - // Sort so we are 100% that they are always the same. - _rpc_variables.sort_custom<SortNetData>(); - #ifdef TOOLS_ENABLED /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { @@ -441,10 +441,10 @@ Error PluginScript::load_source_code(const String &p_path) { FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + p_path + "'."); - int len = f->get_len(); + uint64_t len = f->get_length(); sourcef.resize(len + 1); uint8_t *w = sourcef.ptrw(); - int r = f->get_buffer(w, len); + uint64_t r = f->get_buffer(w, len); f->close(); memdelete(f); ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); @@ -484,76 +484,10 @@ int PluginScript::get_member_line(const StringName &p_member) const { return -1; } -Vector<ScriptNetData> PluginScript::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> PluginScript::get_rpc_methods() const { return _rpc_methods; } -uint16_t PluginScript::get_rpc_method_id(const StringName &p_method) const { - ASSERT_SCRIPT_VALID_V(UINT16_MAX); - for (int i = 0; i < _rpc_methods.size(); i++) { - if (_rpc_methods[i].name == p_method) { - return i; - } - } - return UINT16_MAX; -} - -StringName PluginScript::get_rpc_method(const uint16_t p_rpc_method_id) const { - ASSERT_SCRIPT_VALID_V(StringName()); - if (p_rpc_method_id >= _rpc_methods.size()) { - return StringName(); - } - return _rpc_methods[p_rpc_method_id].name; -} - -MultiplayerAPI::RPCMode PluginScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const { - ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED); - if (p_rpc_method_id >= _rpc_methods.size()) { - return MultiplayerAPI::RPC_MODE_DISABLED; - } - return _rpc_methods[p_rpc_method_id].mode; -} - -MultiplayerAPI::RPCMode PluginScript::get_rpc_mode(const StringName &p_method) const { - ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED); - return get_rpc_mode_by_id(get_rpc_method_id(p_method)); -} - -Vector<ScriptNetData> PluginScript::get_rset_properties() const { - return _rpc_variables; -} - -uint16_t PluginScript::get_rset_property_id(const StringName &p_property) const { - ASSERT_SCRIPT_VALID_V(UINT16_MAX); - for (int i = 0; i < _rpc_variables.size(); i++) { - if (_rpc_variables[i].name == p_property) { - return i; - } - } - return UINT16_MAX; -} - -StringName PluginScript::get_rset_property(const uint16_t p_rset_property_id) const { - ASSERT_SCRIPT_VALID_V(StringName()); - if (p_rset_property_id >= _rpc_variables.size()) { - return StringName(); - } - return _rpc_variables[p_rset_property_id].name; -} - -MultiplayerAPI::RPCMode PluginScript::get_rset_mode_by_id(const uint16_t p_rset_property_id) const { - ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED); - if (p_rset_property_id >= _rpc_variables.size()) { - return MultiplayerAPI::RPC_MODE_DISABLED; - } - return _rpc_variables[p_rset_property_id].mode; -} - -MultiplayerAPI::RPCMode PluginScript::get_rset_mode(const StringName &p_variable) const { - ASSERT_SCRIPT_VALID_V(MultiplayerAPI::RPC_MODE_DISABLED); - return get_rset_mode_by_id(get_rset_property_id(p_variable)); -} - PluginScript::PluginScript() : _script_list(this) { } diff --git a/modules/gdnative/pluginscript/pluginscript_script.h b/modules/gdnative/pluginscript/pluginscript_script.h index 1c86f2056d..838195147f 100644 --- a/modules/gdnative/pluginscript/pluginscript_script.h +++ b/modules/gdnative/pluginscript/pluginscript_script.h @@ -61,8 +61,7 @@ private: Map<StringName, PropertyInfo> _properties_info; Map<StringName, MethodInfo> _signals_info; Map<StringName, MethodInfo> _methods_info; - Vector<ScriptNetData> _rpc_methods; - Vector<ScriptNetData> _rpc_variables; + Vector<MultiplayerAPI::RPCConfig> _rpc_methods; Set<Object *> _instances; //exported members @@ -93,7 +92,7 @@ public: return _icon_path; } - virtual bool can_instance() const override; + virtual bool can_instantiate() const override; virtual Ref<Script> get_base_script() const override; //for script inheritance @@ -137,17 +136,7 @@ public: virtual int get_member_line(const StringName &p_member) const override; - virtual Vector<ScriptNetData> get_rpc_methods() const override; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const override; - virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override; - - virtual Vector<ScriptNetData> get_rset_properties() const override; - virtual uint16_t get_rset_property_id(const StringName &p_property) const override; - virtual StringName get_rset_property(const uint16_t p_rset_property_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const override; PluginScript(); void init(PluginScriptLanguage *language); diff --git a/modules/gdnative/pluginscript/register_types.cpp b/modules/gdnative/pluginscript/register_types.cpp index b94538b2f7..7faacfdcb9 100644 --- a/modules/gdnative/pluginscript/register_types.cpp +++ b/modules/gdnative/pluginscript/register_types.cpp @@ -31,9 +31,9 @@ #include "register_types.h" #include "core/config/project_settings.h" +#include "core/io/dir_access.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" -#include "core/os/dir_access.h" #include "core/os/os.h" #include "scene/main/scene_tree.h" @@ -107,7 +107,7 @@ void GDAPI godot_pluginscript_register_language(const godot_pluginscript_languag } void register_pluginscript_types() { - ClassDB::register_class<PluginScript>(); + GDREGISTER_CLASS(PluginScript); } void unregister_pluginscript_types() { diff --git a/modules/gdnative/register_types.cpp b/modules/gdnative/register_types.cpp index d08bde9e23..a41c4f7b19 100644 --- a/modules/gdnative/register_types.cpp +++ b/modules/gdnative/register_types.cpp @@ -79,9 +79,7 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty List<String> entry_keys; config->get_section_keys("entry", &entry_keys); - for (List<String>::Element *E = entry_keys.front(); E; E = E->next()) { - String key = E->get(); - + for (const String &key : entry_keys) { Vector<String> tags = key.split("."); bool skip = false; @@ -112,9 +110,7 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty List<String> dependency_keys; config->get_section_keys("dependencies", &dependency_keys); - for (List<String>::Element *E = dependency_keys.front(); E; E = E->next()) { - String key = E->get(); - + for (const String &key : dependency_keys) { Vector<String> tags = key.split("."); bool skip = false; @@ -149,9 +145,7 @@ void GDNativeExportPlugin::_export_file(const String &p_path, const String &p_ty List<String> entry_keys; config->get_section_keys("entry", &entry_keys); - for (List<String>::Element *E = entry_keys.front(); E; E = E->next()) { - String key = E->get(); - + for (const String &key : entry_keys) { Vector<String> tags = key.split("."); bool skip = false; @@ -230,7 +224,7 @@ static void editor_init_callback() { ProjectSettingsEditor::get_singleton()->get_tabs()->add_child(library_editor); Ref<GDNativeExportPlugin> export_plugin; - export_plugin.instance(); + export_plugin.instantiate(); EditorExport::get_singleton()->add_export_plugin(export_plugin); @@ -259,13 +253,13 @@ void register_gdnative_types() { EditorNode::add_init_callback(editor_init_callback); #endif - ClassDB::register_class<GDNativeLibrary>(); - ClassDB::register_class<GDNative>(); + GDREGISTER_CLASS(GDNativeLibrary); + GDREGISTER_CLASS(GDNative); - resource_loader_gdnlib.instance(); + resource_loader_gdnlib.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_gdnlib); - resource_saver_gdnlib.instance(); + resource_saver_gdnlib.instantiate(); ResourceSaver::add_resource_format_saver(resource_saver_gdnlib); GDNativeCallRegistry::singleton = memnew(GDNativeCallRegistry); @@ -298,7 +292,7 @@ void register_gdnative_types() { Ref<GDNativeLibrary> lib = ResourceLoader::load(path); Ref<GDNative> singleton; - singleton.instance(); + singleton.instantiate(); singleton->set_library(lib); if (!singleton->initialize()) { @@ -363,7 +357,7 @@ void unregister_gdnative_types() { print_line(String("aabb:\t") + itos(sizeof(AABB))); print_line(String("rid:\t") + itos(sizeof(RID))); print_line(String("string:\t") + itos(sizeof(String))); - print_line(String("transform:\t") + itos(sizeof(Transform))); + print_line(String("transform:\t") + itos(sizeof(Transform3D))); print_line(String("transfo2D:\t") + itos(sizeof(Transform2D))); print_line(String("variant:\t") + itos(sizeof(Variant))); print_line(String("vector2:\t") + itos(sizeof(Vector2))); diff --git a/modules/gdnative/tests/test_variant.h b/modules/gdnative/tests/test_variant.h index aeceb6e68f..c506882283 100644 --- a/modules/gdnative/tests/test_variant.h +++ b/modules/gdnative/tests/test_variant.h @@ -107,7 +107,7 @@ TEST_CASE("[GDNative Variant] Variant call") { godot_string_name_new_with_latin1_chars(&method, "is_valid_identifier"); godot_variant_call_error error; - godot_variant_call(&self, &method, NULL, 0, &ret, &error); + godot_variant_call(&self, &method, nullptr, 0, &ret, &error); CHECK(godot_variant_get_type(&ret) == GODOT_VARIANT_TYPE_BOOL); CHECK(godot_variant_as_bool(&ret)); @@ -191,8 +191,8 @@ TEST_CASE("[GDNative Variant] Get utility function list") { godot_string_name *cur = c_list; - for (const List<StringName>::Element *E = cpp_list.front(); E; E = E->next()) { - const StringName &cpp_name = E->get(); + for (const StringName &E : cpp_list) { + const StringName &cpp_name = E; StringName *c_name = (StringName *)cur++; CHECK(*c_name == cpp_name); diff --git a/modules/gdnative/text/text_server_gdnative.cpp b/modules/gdnative/text/text_server_gdnative.cpp index bc4b1ac134..3ed3f5449e 100644 --- a/modules/gdnative/text/text_server_gdnative.cpp +++ b/modules/gdnative/text/text_server_gdnative.cpp @@ -449,12 +449,12 @@ bool TextServerGDNative::shaped_text_add_string(RID p_shaped, const String &p_te return interface->shaped_text_add_string(data, (godot_rid *)&p_shaped, (const godot_string *)&p_text, (const godot_rid **)p_fonts.ptr(), p_size, (const godot_dictionary *)&p_opentype_features, (const godot_string *)&p_language); } -bool TextServerGDNative::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) { +bool TextServerGDNative::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align, int p_length) { ERR_FAIL_COND_V(interface == nullptr, false); return interface->shaped_text_add_object(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key, (const godot_vector2 *)&p_size, (godot_int)p_inline_align, p_length); } -bool TextServerGDNative::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) { +bool TextServerGDNative::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align) { ERR_FAIL_COND_V(interface == nullptr, false); return interface->shaped_text_resize_object(data, (godot_rid *)&p_shaped, (const godot_variant *)&p_key, (const godot_vector2 *)&p_size, (godot_int)p_inline_align); } @@ -498,6 +498,11 @@ bool TextServerGDNative::shaped_text_update_justification_ops(RID p_shaped) { return interface->shaped_text_update_justification_ops(data, (godot_rid *)&p_shaped); } +void TextServerGDNative::shaped_text_overrun_trim_to_width(RID p_shaped_line, float p_width, uint8_t p_trim_flags) { + ERR_FAIL_COND(interface == nullptr); + interface->shaped_text_overrun_trim_to_width(data, (godot_rid *)&p_shaped_line, p_width, p_trim_flags); +}; + bool TextServerGDNative::shaped_text_is_ready(RID p_shaped) const { ERR_FAIL_COND_V(interface == nullptr, false); return interface->shaped_text_is_ready(data, (godot_rid *)&p_shaped); @@ -550,15 +555,15 @@ Vector<Vector2i> TextServerGDNative::shaped_text_get_line_breaks(RID p_shaped, f } } -Vector<Vector2i> TextServerGDNative::shaped_text_get_word_breaks(RID p_shaped) const { +Vector<Vector2i> TextServerGDNative::shaped_text_get_word_breaks(RID p_shaped, int p_grapheme_flags) const { ERR_FAIL_COND_V(interface == nullptr, Vector<Vector2i>()); if (interface->shaped_text_get_word_breaks != nullptr) { - godot_packed_vector2i_array result = interface->shaped_text_get_word_breaks(data, (godot_rid *)&p_shaped); + godot_packed_vector2i_array result = interface->shaped_text_get_word_breaks(data, (godot_rid *)&p_shaped, p_grapheme_flags); Vector<Vector2i> breaks = *(Vector<Vector2i> *)&result; godot_packed_vector2i_array_destroy(&result); return breaks; } else { - return TextServer::shaped_text_get_word_breaks(p_shaped); + return TextServer::shaped_text_get_word_breaks(p_shaped, p_grapheme_flags); } } diff --git a/modules/gdnative/text/text_server_gdnative.h b/modules/gdnative/text/text_server_gdnative.h index 7e42b16fe1..e1b36f4264 100644 --- a/modules/gdnative/text/text_server_gdnative.h +++ b/modules/gdnative/text/text_server_gdnative.h @@ -154,8 +154,8 @@ public: virtual bool shaped_text_get_preserve_control(RID p_shaped) const override; virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override; - virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override; - virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override; + virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align = INLINE_ALIGN_CENTER, int p_length = 1) override; + virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align = INLINE_ALIGN_CENTER) override; virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override; virtual RID shaped_text_get_parent(RID p_shaped) const override; @@ -167,6 +167,8 @@ public: virtual bool shaped_text_update_breaks(RID p_shaped) override; virtual bool shaped_text_update_justification_ops(RID p_shaped) override; + virtual void shaped_text_overrun_trim_to_width(RID p_shaped, float p_width, uint8_t p_trim_flags) override; + virtual bool shaped_text_is_ready(RID p_shaped) const override; virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override; @@ -176,7 +178,7 @@ public: virtual Vector<Glyph> shaped_text_sort_logical(RID p_shaped) override; virtual Vector<Vector2i> shaped_text_get_line_breaks_adv(RID p_shaped, const Vector<float> &p_width, int p_start = 0, bool p_once = true, uint8_t /*TextBreakFlag*/ p_break_flags = BREAK_MANDATORY | BREAK_WORD_BOUND) const override; virtual Vector<Vector2i> shaped_text_get_line_breaks(RID p_shaped, float p_width, int p_start = 0, uint8_t p_break_flags = BREAK_MANDATORY | BREAK_WORD_BOUND) const override; - virtual Vector<Vector2i> shaped_text_get_word_breaks(RID p_shaped) const override; + virtual Vector<Vector2i> shaped_text_get_word_breaks(RID p_shaped, int p_grapheme_flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_PUNCTUATION) const override; virtual Array shaped_text_get_objects(RID p_shaped) const override; virtual Rect2 shaped_text_get_object_rect(RID p_shaped, Variant p_key) const override; diff --git a/modules/gdnative/videodecoder/register_types.cpp b/modules/gdnative/videodecoder/register_types.cpp index 394831daeb..54a577a2b6 100644 --- a/modules/gdnative/videodecoder/register_types.cpp +++ b/modules/gdnative/videodecoder/register_types.cpp @@ -36,10 +36,10 @@ static Ref<ResourceFormatLoaderVideoStreamGDNative> resource_loader_vsgdnative; void register_videodecoder_types() { - resource_loader_vsgdnative.instance(); + resource_loader_vsgdnative.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_vsgdnative, true); - ClassDB::register_class<VideoStreamGDNative>(); + GDREGISTER_CLASS(VideoStreamGDNative); } void unregister_videodecoder_types() { diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.cpp b/modules/gdnative/videodecoder/video_stream_gdnative.cpp index f2fb0a2fdc..4c9bfb395d 100644 --- a/modules/gdnative/videodecoder/video_stream_gdnative.cpp +++ b/modules/gdnative/videodecoder/video_stream_gdnative.cpp @@ -47,11 +47,7 @@ godot_int GDAPI godot_videodecoder_file_read(void *ptr, uint8_t *buf, int buf_si // if file exists if (file) { - long bytes_read = file->get_buffer(buf, buf_size); - // No bytes to read => EOF - if (bytes_read == 0) { - return 0; - } + int64_t bytes_read = file->get_buffer(buf, buf_size); return bytes_read; } return -1; @@ -62,41 +58,35 @@ int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) { FileAccess *file = reinterpret_cast<FileAccess *>(ptr); if (file) { - size_t len = file->get_len(); + int64_t len = file->get_length(); switch (whence) { case SEEK_SET: { - // Just for explicitness - size_t new_pos = static_cast<size_t>(pos); - if (new_pos > len) { + if (pos > len) { return -1; } - file->seek(new_pos); - pos = static_cast<int64_t>(file->get_position()); - return pos; + file->seek(pos); + return file->get_position(); } break; case SEEK_CUR: { // Just in case it doesn't exist - if (pos < 0 && (size_t)-pos > file->get_position()) { + if (pos < 0 && -pos > (int64_t)file->get_position()) { return -1; } - pos = pos + static_cast<int>(file->get_position()); - file->seek(pos); - pos = static_cast<int64_t>(file->get_position()); - return pos; + file->seek(file->get_position() + pos); + return file->get_position(); } break; case SEEK_END: { // Just in case something goes wrong - if ((size_t)-pos > len) { + if (-pos > len) { return -1; } file->seek_end(pos); - pos = static_cast<int64_t>(file->get_position()); - return pos; + return file->get_position(); } break; default: { // Only 4 possible options, hence default = AVSEEK_SIZE // Asks to return the length of file - return static_cast<int64_t>(len); + return len; } break; } } @@ -132,7 +122,7 @@ bool VideoStreamPlaybackGDNative::open_file(const String &p_file) { samples_decoded = 0; Ref<Image> img; - img.instance(); + img.instantiate(); img->create((int)texture_size.width, false, (int)texture_size.height, Image::FORMAT_RGBA8); texture->create_from_image(img); @@ -195,7 +185,7 @@ void VideoStreamPlaybackGDNative::update_texture() { Ref<Image> img = memnew(Image(texture_size.width, texture_size.height, 0, Image::FORMAT_RGBA8, *pba)); - texture->update(img, true); + texture->update(img); } // ctor and dtor diff --git a/modules/gdnative/videodecoder/video_stream_gdnative.h b/modules/gdnative/videodecoder/video_stream_gdnative.h index 140888cd4b..c605dbb433 100644 --- a/modules/gdnative/videodecoder/video_stream_gdnative.h +++ b/modules/gdnative/videodecoder/video_stream_gdnative.h @@ -32,7 +32,7 @@ #define VIDEO_STREAM_GDNATIVE_H #include "../gdnative.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "scene/resources/texture.h" #include "scene/resources/video_stream.h" diff --git a/modules/gdnative/xr/register_types.cpp b/modules/gdnative/xr/register_types.cpp index b60a04f470..cb043debc5 100644 --- a/modules/gdnative/xr/register_types.cpp +++ b/modules/gdnative/xr/register_types.cpp @@ -32,7 +32,7 @@ #include "xr_interface_gdnative.h" void register_xr_types() { - ClassDB::register_class<XRInterfaceGDNative>(); + GDREGISTER_CLASS(XRInterfaceGDNative); ClassDB::add_compatibility_class("ARVRInterfaceGDNative", "XRInterfaceGDNative"); } diff --git a/modules/gdnative/xr/xr_interface_gdnative.cpp b/modules/gdnative/xr/xr_interface_gdnative.cpp index 122cb5849b..e51542e23d 100644 --- a/modules/gdnative/xr/xr_interface_gdnative.cpp +++ b/modules/gdnative/xr/xr_interface_gdnative.cpp @@ -70,8 +70,13 @@ void XRInterfaceGDNative::set_interface(const godot_xr_interface_gdnative *p_int // this should only be called once, just being paranoid.. if (interface) { cleanup(); + interface = NULL; } + // validate + ERR_FAIL_NULL(p_interface); + ERR_FAIL_COND_MSG(p_interface->version.major < 4, "This is an incompatible GDNative XR plugin."); + // bind to our interface interface = p_interface; @@ -119,14 +124,14 @@ int XRInterfaceGDNative::get_camera_feed_id() { return (unsigned int)interface->get_camera_feed_id(data); } -bool XRInterfaceGDNative::is_stereo() { - bool stereo; +uint32_t XRInterfaceGDNative::get_view_count() { + uint32_t view_count; - ERR_FAIL_COND_V(interface == nullptr, false); + ERR_FAIL_COND_V(interface == nullptr, 1); - stereo = interface->is_stereo(data); + view_count = interface->get_view_count(data); - return stereo; + return view_count; } bool XRInterfaceGDNative::is_initialized() const { @@ -173,28 +178,52 @@ Size2 XRInterfaceGDNative::get_render_targetsize() { return *vec; } -Transform XRInterfaceGDNative::get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) { - Transform *ret; +Transform3D XRInterfaceGDNative::get_camera_transform() { + Transform3D *ret; + + ERR_FAIL_COND_V(interface == nullptr, Transform3D()); + + godot_transform3d t = interface->get_camera_transform(data); + + ret = (Transform3D *)&t; + + return *ret; +} + +Transform3D XRInterfaceGDNative::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) { + Transform3D *ret; - ERR_FAIL_COND_V(interface == nullptr, Transform()); + ERR_FAIL_COND_V(interface == nullptr, Transform3D()); - godot_transform t = interface->get_transform_for_eye(data, (int)p_eye, (godot_transform *)&p_cam_transform); + godot_transform3d t = interface->get_transform_for_view(data, (int)p_view, (godot_transform3d *)&p_cam_transform); - ret = (Transform *)&t; + ret = (Transform3D *)&t; return *ret; } -CameraMatrix XRInterfaceGDNative::get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) { +CameraMatrix XRInterfaceGDNative::get_projection_for_view(uint32_t p_view, real_t p_aspect, real_t p_z_near, real_t p_z_far) { CameraMatrix cm; ERR_FAIL_COND_V(interface == nullptr, CameraMatrix()); - interface->fill_projection_for_eye(data, (godot_float *)cm.matrix, (godot_int)p_eye, p_aspect, p_z_near, p_z_far); + interface->fill_projection_for_view(data, (godot_real_t *)cm.matrix, (godot_int)p_view, p_aspect, p_z_near, p_z_far); return cm; } +Vector<BlitToScreen> XRInterfaceGDNative::commit_views(RID p_render_target, const Rect2 &p_screen_rect) { + // possibly move this as a member variable and add a callback to populate? + Vector<BlitToScreen> blit_to_screen; + + ERR_FAIL_COND_V(interface == nullptr, blit_to_screen); + + // must implement + interface->commit_views(data, (godot_rid *)&p_render_target, (godot_rect2 *)&p_screen_rect); + + return blit_to_screen; +} + unsigned int XRInterfaceGDNative::get_external_texture_for_eye(XRInterface::Eyes p_eye) { ERR_FAIL_COND_V(interface == nullptr, 0); @@ -229,27 +258,27 @@ void GDAPI godot_xr_register_interface(const godot_xr_interface_gdnative *p_inte ERR_FAIL_COND_MSG(p_interface->version.major < 4, "GDNative XR interfaces build for Godot 3.x are not supported."); Ref<XRInterfaceGDNative> new_interface; - new_interface.instance(); + new_interface.instantiate(); new_interface->set_interface((const godot_xr_interface_gdnative *)p_interface); XRServer::get_singleton()->add_interface(new_interface); } -godot_float GDAPI godot_xr_get_worldscale() { +godot_real_t GDAPI godot_xr_get_worldscale() { XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL_V(xr_server, 1.0); return xr_server->get_world_scale(); } -godot_transform GDAPI godot_xr_get_reference_frame() { - godot_transform reference_frame; - Transform *reference_frame_ptr = (Transform *)&reference_frame; +godot_transform3d GDAPI godot_xr_get_reference_frame() { + godot_transform3d reference_frame; + Transform3D *reference_frame_ptr = (Transform3D *)&reference_frame; XRServer *xr_server = XRServer::get_singleton(); if (xr_server != nullptr) { *reference_frame_ptr = xr_server->get_reference_frame(); } else { - memnew_placement(&reference_frame, Transform); + memnew_placement(&reference_frame, Transform3D); } return reference_frame; @@ -302,7 +331,7 @@ godot_int GDAPI godot_xr_add_controller(char *p_device_name, godot_int p_hand, g ERR_FAIL_NULL_V(input, 0); Ref<XRPositionalTracker> new_tracker; - new_tracker.instance(); + new_tracker.instantiate(); new_tracker->set_tracker_name(p_device_name); new_tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER); if (p_hand == 1) { @@ -356,13 +385,13 @@ void GDAPI godot_xr_remove_controller(godot_int p_controller_id) { } } -void GDAPI godot_xr_set_controller_transform(godot_int p_controller_id, godot_transform *p_transform, godot_bool p_tracks_orientation, godot_bool p_tracks_position) { +void GDAPI godot_xr_set_controller_transform(godot_int p_controller_id, godot_transform3d *p_transform, godot_bool p_tracks_orientation, godot_bool p_tracks_position) { XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL(xr_server); Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, p_controller_id); if (tracker.is_valid()) { - Transform *transform = (Transform *)p_transform; + Transform3D *transform = (Transform3D *)p_transform; if (p_tracks_orientation) { tracker->set_orientation(transform->basis); } @@ -383,12 +412,12 @@ void GDAPI godot_xr_set_controller_button(godot_int p_controller_id, godot_int p if (tracker.is_valid()) { int joyid = tracker->get_joy_id(); if (joyid != -1) { - input->joy_button(joyid, p_button, p_is_pressed); + input->joy_button(joyid, (JoyButton)p_button, p_is_pressed); } } } -void GDAPI godot_xr_set_controller_axis(godot_int p_controller_id, godot_int p_axis, godot_float p_value, godot_bool p_can_be_negative) { +void GDAPI godot_xr_set_controller_axis(godot_int p_controller_id, godot_int p_axis, godot_real_t p_value, godot_bool p_can_be_negative) { XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL(xr_server); @@ -402,12 +431,12 @@ void GDAPI godot_xr_set_controller_axis(godot_int p_controller_id, godot_int p_a Input::JoyAxisValue jx; jx.min = p_can_be_negative ? -1 : 0; jx.value = p_value; - input->joy_axis(joyid, p_axis, jx); + input->joy_axis(joyid, (JoyAxis)p_axis, jx); } } } -godot_float GDAPI godot_xr_get_controller_rumble(godot_int p_controller_id) { +godot_real_t GDAPI godot_xr_get_controller_rumble(godot_int p_controller_id) { XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL_V(xr_server, 0.0); diff --git a/modules/gdnative/xr/xr_interface_gdnative.h b/modules/gdnative/xr/xr_interface_gdnative.h index 84bd8fc731..42e9206c1f 100644 --- a/modules/gdnative/xr/xr_interface_gdnative.h +++ b/modules/gdnative/xr/xr_interface_gdnative.h @@ -72,20 +72,24 @@ public: /** rendering and internal **/ virtual Size2 get_render_targetsize() override; - virtual bool is_stereo() override; - virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) 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; // we expose a Vector<float> version of this function to GDNative Vector<float> _get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far); // and a CameraMatrix version to XRServer - virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) override; + virtual CameraMatrix get_projection_for_view(uint32_t p_view, real_t p_aspect, real_t p_z_near, real_t p_z_far) override; - virtual unsigned int get_external_texture_for_eye(XRInterface::Eyes p_eye) override; - virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override; + virtual Vector<BlitToScreen> commit_views(RID p_render_target, const Rect2 &p_screen_rect) override; virtual void process() override; virtual void notification(int p_what) override; + + // deprecated + virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override; + virtual unsigned int get_external_texture_for_eye(XRInterface::Eyes p_eye) override; }; #endif // XR_INTERFACE_GDNATIVE_H diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml index 9e974b6fdc..51b3452a3a 100644 --- a/modules/gdscript/doc_classes/@GDScript.xml +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -11,16 +11,11 @@ </tutorials> <methods> <method name="Color8"> - <return type="Color"> - </return> - <argument index="0" name="r8" type="int"> - </argument> - <argument index="1" name="g8" type="int"> - </argument> - <argument index="2" name="b8" type="int"> - </argument> - <argument index="3" name="a8" type="int" default="255"> - </argument> + <return type="Color" /> + <argument index="0" name="r8" type="int" /> + <argument index="1" name="g8" type="int" /> + <argument index="2" name="b8" type="int" /> + <argument 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 @@ -33,12 +28,9 @@ </description> </method> <method name="assert"> - <return type="void"> - </return> - <argument index="0" name="condition" type="bool"> - </argument> - <argument index="1" name="message" type="String" default=""""> - </argument> + <return type="void" /> + <argument index="0" name="condition" type="bool" /> + <argument 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. @@ -54,10 +46,8 @@ </description> </method> <method name="char"> - <return type="String"> - </return> - <argument index="0" name="char" type="int"> - </argument> + <return type="String" /> + <argument 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). [codeblock] @@ -68,12 +58,9 @@ </description> </method> <method name="convert"> - <return type="Variant"> - </return> - <argument index="0" name="what" type="Variant"> - </argument> - <argument index="1" name="type" type="int"> - </argument> + <return type="Variant" /> + <argument index="0" name="what" type="Variant" /> + <argument 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. [codeblock] @@ -87,17 +74,14 @@ </description> </method> <method name="dict2inst"> - <return type="Object"> - </return> - <argument index="0" name="dictionary" type="Dictionary"> - </argument> + <return type="Object" /> + <argument index="0" name="dictionary" type="Dictionary" /> <description> Converts a dictionary (previously created with [method inst2dict]) back to an instance. Useful for deserializing. </description> </method> <method name="get_stack"> - <return type="Array"> - </return> + <return type="Array" /> <description> Returns an array of dictionaries representing the current call stack. [codeblock] @@ -117,10 +101,8 @@ </description> </method> <method name="inst2dict"> - <return type="Dictionary"> - </return> - <argument index="0" name="instance" type="Object"> - </argument> + <return type="Dictionary" /> + <argument index="0" name="instance" type="Object" /> <description> Returns the passed instance converted to a dictionary (useful for serializing). [codeblock] @@ -138,10 +120,8 @@ </description> </method> <method name="len"> - <return type="int"> - </return> - <argument index="0" name="var" type="Variant"> - </argument> + <return type="int" /> + <argument 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. @@ -152,10 +132,8 @@ </description> </method> <method name="load"> - <return type="Resource"> - </return> - <argument index="0" name="path" type="String"> - </argument> + <return type="Resource" /> + <argument 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]. [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. @@ -168,29 +146,25 @@ </description> </method> <method name="preload"> - <return type="Resource"> - </return> - <argument index="0" name="path" type="String"> - </argument> + <return type="Resource" /> + <argument 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]. [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. - var diamond = preload("res://diamond.tscn").instance() + var diamond = preload("res://diamond.tscn").instantiate() [/codeblock] </description> </method> <method name="print_debug" qualifiers="vararg"> - <return type="void"> - </return> + <return type="void" /> <description> Like [method @GlobalScope.print], but prints only when used in debug mode. </description> </method> <method name="print_stack"> - <return type="void"> - </return> + <return type="void" /> <description> Prints a stack track at code location, only works when running with debugger turned on. Output in the console would look something like this: @@ -200,8 +174,7 @@ </description> </method> <method name="range" qualifiers="vararg"> - <return type="Array"> - </return> + <return type="Array" /> <description> Returns an array with the given range. Range can be 1 argument N (0 to N-1), two arguments (initial, final-1) or three arguments (initial, final-1, increment). [codeblock] @@ -218,8 +191,7 @@ </description> </method> <method name="str" qualifiers="vararg"> - <return type="String"> - </return> + <return type="String" /> <description> Converts one or more arguments to string in the best way possible. [codeblock] @@ -231,26 +203,26 @@ </description> </method> <method name="type_exists"> - <return type="bool"> - </return> - <argument index="0" name="type" type="StringName"> - </argument> + <return type="bool" /> + <argument index="0" name="type" type="StringName" /> <description> </description> </method> </methods> <constants> - <constant name="PI" value="3.141593"> - Constant that represents how many times the diameter of a circle fits around its perimeter. This is equivalent to [code]TAU / 2[/code]. + <constant name="PI" value="3.14159265358979"> + Constant that represents how many times the diameter of a circle fits around its perimeter. This is equivalent to [code]TAU / 2[/code], or 180 degrees in rotations. </constant> - <constant name="TAU" value="6.283185"> - The circle constant, the circumference of the unit circle in radians. + <constant name="TAU" value="6.28318530717959"> + The circle constant, the circumference of the unit circle in radians. This is equivalent to [code]PI * 2[/code], or 360 degrees in rotations. </constant> <constant name="INF" value="inf"> - Positive infinity. For negative infinity, use -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. </constant> <constant name="NAN" value="nan"> - "Not a Number", an invalid value. [code]NaN[/code] has special properties, including that it is not equal to itself. It is output by some invalid operations, such as dividing zero by zero. + "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. </constant> </constants> </class> diff --git a/modules/gdscript/doc_classes/GDScript.xml b/modules/gdscript/doc_classes/GDScript.xml index 631a102130..72738f027a 100644 --- a/modules/gdscript/doc_classes/GDScript.xml +++ b/modules/gdscript/doc_classes/GDScript.xml @@ -12,15 +12,13 @@ </tutorials> <methods> <method name="get_as_byte_code" qualifiers="const"> - <return type="PackedByteArray"> - </return> + <return type="PackedByteArray" /> <description> Returns byte code for the script source code. </description> </method> <method name="new" qualifiers="vararg"> - <return type="Variant"> - </return> + <return type="Variant" /> <description> Returns a new instance of the script. For example: diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp index ccc942d86b..ed8b0a4690 100644 --- a/modules/gdscript/editor/gdscript_highlighter.cpp +++ b/modules/gdscript/editor/gdscript_highlighter.cpp @@ -64,6 +64,7 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) bool in_function_args = false; bool in_member_variable = false; bool in_node_path = false; + bool in_annotation = false; bool is_hex_notation = false; bool is_bin_notation = false; bool expect_type = false; @@ -357,9 +358,18 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) in_node_path = false; } + if (!in_annotation && in_region == -1 && str[j] == '@') { + in_annotation = true; + } else if (in_region != -1 || is_a_symbol) { + in_annotation = false; + } + if (in_node_path) { next_type = NODE_PATH; color = node_path_color; + } else if (in_annotation) { + next_type = ANNOTATION; + color = annotation_color; } else if (in_keyword) { next_type = KEYWORD; color = keyword_color; @@ -438,7 +448,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { color_regions.clear(); color_region_cache.clear(); - font_color = text_edit->get_theme_color("font_color"); + font_color = text_edit->get_theme_color(SNAME("font_color")); symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); function_color = EDITOR_GET("text_editor/highlighting/function_color"); number_color = EDITOR_GET("text_editor/highlighting/number_color"); @@ -448,8 +458,8 @@ void GDScriptSyntaxHighlighter::_update_cache() { const Color types_color = EDITOR_GET("text_editor/highlighting/engine_type_color"); List<StringName> types; ClassDB::get_class_list(&types); - for (List<StringName>::Element *E = types.front(); E; E = E->next()) { - String n = E->get(); + for (const StringName &E : types) { + String n = E; if (n.begins_with("_")) { n = n.substr(1, n.length()); } @@ -460,8 +470,8 @@ void GDScriptSyntaxHighlighter::_update_cache() { const Color usertype_color = EDITOR_GET("text_editor/highlighting/user_type_color"); List<StringName> global_classes; ScriptServer::get_global_class_list(&global_classes); - for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) { - keywords[String(E->get())] = usertype_color; + for (const StringName &E : global_classes) { + keywords[String(E)] = usertype_color; } /* Autoloads. */ @@ -479,24 +489,28 @@ void GDScriptSyntaxHighlighter::_update_cache() { const Color basetype_color = EDITOR_GET("text_editor/highlighting/base_type_color"); List<String> core_types; gdscript->get_core_type_words(&core_types); - for (List<String>::Element *E = core_types.front(); E; E = E->next()) { - keywords[E->get()] = basetype_color; + for (const String &E : core_types) { + keywords[E] = basetype_color; } /* Reserved words. */ const Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); + const Color control_flow_keyword_color = EDITOR_GET("text_editor/highlighting/control_flow_keyword_color"); List<String> keyword_list; gdscript->get_reserved_words(&keyword_list); - for (List<String>::Element *E = keyword_list.front(); E; E = E->next()) { - keywords[E->get()] = keyword_color; + for (const String &E : keyword_list) { + if (gdscript->is_control_flow_keyword(E)) { + keywords[E] = control_flow_keyword_color; + } else { + keywords[E] = keyword_color; + } } /* Comments */ const Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); List<String> comments; gdscript->get_comment_delimiters(&comments); - for (List<String>::Element *E = comments.front(); E; E = E->next()) { - String comment = E->get(); + for (const String &comment : comments) { String beg = comment.get_slice(" ", 0); String end = comment.get_slice_count(" ") > 1 ? comment.get_slice(" ", 1) : String(); add_color_region(beg, end, comment_color, end == ""); @@ -506,8 +520,7 @@ void GDScriptSyntaxHighlighter::_update_cache() { const Color string_color = EDITOR_GET("text_editor/highlighting/string_color"); List<String> strings; gdscript->get_string_delimiters(&strings); - for (List<String>::Element *E = strings.front(); E; E = E->next()) { - String string = E->get(); + for (const String &string : strings) { String beg = string.get_slice(" ", 0); String end = string.get_slice_count(" ") > 1 ? string.get_slice(" ", 1) : String(); add_color_region(beg, end, string_color, end == ""); @@ -521,9 +534,9 @@ void GDScriptSyntaxHighlighter::_update_cache() { if (instance_base != StringName()) { List<PropertyInfo> plist; ClassDB::get_property_list(instance_base, &plist); - for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - String name = E->get().name; - if (E->get().usage & PROPERTY_USAGE_CATEGORY || E->get().usage & PROPERTY_USAGE_GROUP || E->get().usage & PROPERTY_USAGE_SUBGROUP) { + for (const PropertyInfo &E : plist) { + String name = E.name; + if (E.usage & PROPERTY_USAGE_CATEGORY || E.usage & PROPERTY_USAGE_GROUP || E.usage & PROPERTY_USAGE_SUBGROUP) { continue; } if (name.find("/") != -1) { @@ -534,26 +547,29 @@ void GDScriptSyntaxHighlighter::_update_cache() { List<String> clist; ClassDB::get_integer_constant_list(instance_base, &clist); - for (List<String>::Element *E = clist.front(); E; E = E->next()) { - member_keywords[E->get()] = member_variable_color; + for (const String &E : clist) { + member_keywords[E] = member_variable_color; } } } const String text_edit_color_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme"); - const bool default_theme = text_edit_color_theme == "Default"; + const bool godot_2_theme = text_edit_color_theme == "Godot 2"; - if (default_theme || EditorSettings::get_singleton()->is_dark_theme()) { + if (godot_2_theme || EditorSettings::get_singleton()->is_dark_theme()) { function_definition_color = Color(0.4, 0.9, 1.0); node_path_color = Color(0.39, 0.76, 0.35); + annotation_color = Color(1.0, 0.7, 0.45); } else { function_definition_color = Color(0.0, 0.65, 0.73); node_path_color = Color(0.32, 0.55, 0.29); + annotation_color = Color(0.8, 0.5, 0.25); } EDITOR_DEF("text_editor/highlighting/gdscript/function_definition_color", function_definition_color); EDITOR_DEF("text_editor/highlighting/gdscript/node_path_color", node_path_color); - if (text_edit_color_theme == "Adaptive" || default_theme) { + EDITOR_DEF("text_editor/highlighting/gdscript/annotation_color", annotation_color); + if (text_edit_color_theme == "Default" || godot_2_theme) { EditorSettings::get_singleton()->set_initial_value( "text_editor/highlighting/gdscript/function_definition_color", function_definition_color, @@ -562,10 +578,15 @@ void GDScriptSyntaxHighlighter::_update_cache() { "text_editor/highlighting/gdscript/node_path_color", node_path_color, true); + EditorSettings::get_singleton()->set_initial_value( + "text_editor/highlighting/gdscript/annotation_color", + annotation_color, + true); } function_definition_color = EDITOR_GET("text_editor/highlighting/gdscript/function_definition_color"); node_path_color = EDITOR_GET("text_editor/highlighting/gdscript/node_path_color"); + annotation_color = EDITOR_GET("text_editor/highlighting/gdscript/annotation_color"); type_color = EDITOR_GET("text_editor/highlighting/base_type_color"); } @@ -599,6 +620,6 @@ void GDScriptSyntaxHighlighter::add_color_region(const String &p_start_key, cons Ref<EditorSyntaxHighlighter> GDScriptSyntaxHighlighter::_create() const { Ref<GDScriptSyntaxHighlighter> syntax_highlighter; - syntax_highlighter.instance(); + syntax_highlighter.instantiate(); return syntax_highlighter; } diff --git a/modules/gdscript/editor/gdscript_highlighter.h b/modules/gdscript/editor/gdscript_highlighter.h index 1b57cb1923..d07c182aa6 100644 --- a/modules/gdscript/editor/gdscript_highlighter.h +++ b/modules/gdscript/editor/gdscript_highlighter.h @@ -54,6 +54,7 @@ private: NONE, REGION, NODE_PATH, + ANNOTATION, SYMBOL, NUMBER, FUNCTION, @@ -72,6 +73,7 @@ private: Color number_color; Color member_color; Color node_path_color; + Color annotation_color; Color type_color; void add_color_region(const String &p_start_key, const String &p_end_key, const Color &p_color, bool p_line_only = false); diff --git a/modules/gdscript/editor/gdscript_translation_parser_plugin.h b/modules/gdscript/editor/gdscript_translation_parser_plugin.h index fcf438422a..caa80fc24c 100644 --- a/modules/gdscript/editor/gdscript_translation_parser_plugin.h +++ b/modules/gdscript/editor/gdscript_translation_parser_plugin.h @@ -34,7 +34,6 @@ #include "core/templates/set.h" #include "editor/editor_translation_parser.h" #include "modules/gdscript/gdscript_parser.h" -#include "modules/regex/regex.h" class GDScriptEditorTranslationParserPlugin : public EditorTranslationParserPlugin { GDCLASS(GDScriptEditorTranslationParserPlugin, EditorTranslationParserPlugin); diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 5f590383d0..8957b00a1b 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -36,8 +36,8 @@ #include "core/config/project_settings.h" #include "core/core_constants.h" #include "core/core_string_names.h" +#include "core/io/file_access.h" #include "core/io/file_access_encrypted.h" -#include "core/os/file_access.h" #include "core/os/os.h" #include "gdscript_analyzer.h" #include "gdscript_cache.h" @@ -72,19 +72,19 @@ void GDScriptNativeClass::_bind_methods() { } Variant GDScriptNativeClass::_new() { - Object *o = instance(); + Object *o = instantiate(); ERR_FAIL_COND_V_MSG(!o, Variant(), "Class type: '" + String(name) + "' is not instantiable."); - Reference *ref = Object::cast_to<Reference>(o); - if (ref) { - return REF(ref); + RefCounted *rc = Object::cast_to<RefCounted>(o); + if (rc) { + return REF(rc); } else { return o; } } -Object *GDScriptNativeClass::instance() { - return ClassDB::instance(name); +Object *GDScriptNativeClass::instantiate() { + return ClassDB::instantiate(name); } void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance *p_instance, Callable::CallError &r_error) { @@ -98,11 +98,11 @@ void GDScript::_super_implicit_constructor(GDScript *p_script, GDScriptInstance p_script->implicit_initializer->call(p_instance, nullptr, 0, r_error); } -GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error) { +GDScriptInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) { /* STEP 1, CREATE */ GDScriptInstance *instance = memnew(GDScriptInstance); - instance->base_ref = p_isref; + instance->base_ref_counted = p_is_ref_counted; instance->members.resize(member_indices.size()); instance->script = Ref<GDScript>(this); instance->owner = p_owner; @@ -170,13 +170,13 @@ Variant GDScript::_new(const Variant **p_args, int p_argcount, Callable::CallErr ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant()); if (_baseptr->native.ptr()) { - owner = _baseptr->native->instance(); + owner = _baseptr->native->instantiate(); } else { - owner = memnew(Reference); //by default, no base means use reference + owner = memnew(RefCounted); //by default, no base means use reference } ERR_FAIL_COND_V_MSG(!owner, Variant(), "Can't inherit from a virtual class."); - Reference *r = Object::cast_to<Reference>(owner); + RefCounted *r = Object::cast_to<RefCounted>(owner); if (r) { ref = REF(r); } @@ -196,7 +196,7 @@ Variant GDScript::_new(const Variant **p_args, int p_argcount, Callable::CallErr } } -bool GDScript::can_instance() const { +bool GDScript::can_instantiate() const { #ifdef TOOLS_ENABLED return valid && (tool || ScriptServer::is_scripting_enabled()); #else @@ -291,8 +291,8 @@ void GDScript::_get_script_property_list(List<PropertyInfo> *r_list, bool p_incl sptr = sptr->_base; } - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - r_list->push_back(E->get()); + for (const PropertyInfo &E : props) { + r_list->push_back(E); } } @@ -346,21 +346,21 @@ 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_path(), 1, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"); + GDScriptLanguage::get_singleton()->debug_break_parse(get_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() + "'"); } - ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced 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 instantiated in object of type '" + p_this->get_class() + "'" + "."); } } Callable::CallError unchecked_error; - return _create_instance(nullptr, 0, p_this, Object::cast_to<Reference>(p_this) != nullptr, unchecked_error); + return _create_instance(nullptr, 0, p_this, Object::cast_to<RefCounted>(p_this) != nullptr, unchecked_error); } PlaceHolderScriptInstance *GDScript::placeholder_instance_create(Object *p_this) { #ifdef TOOLS_ENABLED PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this)); placeholders.insert(si); - _update_exports(); + _update_exports(nullptr, false, si); return si; #else return nullptr; @@ -401,8 +401,8 @@ void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<Pro values[E->key()] = E->get(); } - for (List<PropertyInfo>::Element *E = members_cache.front(); E; E = E->next()) { - propnames.push_back(E->get()); + for (const PropertyInfo &E : members_cache) { + propnames.push_back(E); } } @@ -481,7 +481,7 @@ void GDScript::_update_doc() { methods[i].return_val.class_name = _get_gdscript_reference_class_name(Object::cast_to<GDScript>(return_type.script_type)); } - // Change class name if argumetn is script reference. + // Change class name if argument is script reference. for (int j = 0; j < fn->get_argument_count(); j++) { GDScriptDataType arg_type = fn->get_argument_type(j); if (arg_type.kind == GDScriptDataType::GDSCRIPT) { @@ -584,7 +584,7 @@ void GDScript::_update_doc() { } #endif -bool GDScript::_update_exports(bool *r_err, bool p_recursive_call) { +bool GDScript::_update_exports(bool *r_err, bool p_recursive_call, PlaceHolderScriptInstance *p_instance_to_update) { #ifdef TOOLS_ENABLED static Vector<GDScript *> base_caches; @@ -721,15 +721,19 @@ bool GDScript::_update_exports(bool *r_err, bool p_recursive_call) { } } - if (placeholders.size()) { //hm :( + if ((changed || p_instance_to_update) && placeholders.size()) { //hm :( // update placeholders if any Map<StringName, Variant> values; List<PropertyInfo> propnames; _update_exports_values(values, propnames); - for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { - E->get()->update(propnames, values); + if (changed) { + for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { + E->get()->update(propnames, values); + } + } else { + p_instance_to_update->update(propnames, values); } } @@ -857,8 +861,7 @@ Error GDScript::reload(bool p_keep_state) { } } #ifdef DEBUG_ENABLED - for (const List<GDScriptWarning>::Element *E = parser.get_warnings().front(); E; E = E->next()) { - const GDScriptWarning &warning = E->get(); + for (const GDScriptWarning &warning : parser.get_warnings()) { if (EngineDebugger::is_active()) { Vector<ScriptLanguage::StackInfo> si; EngineDebugger::get_script_debugger()->send_error("", get_path(), warning.start_line, warning.get_name(), warning.get_message(), ERR_HANDLER_WARNING, si); @@ -897,68 +900,10 @@ void GDScript::get_members(Set<StringName> *p_members) { } } -Vector<ScriptNetData> GDScript::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> GDScript::get_rpc_methods() const { return rpc_functions; } -uint16_t GDScript::get_rpc_method_id(const StringName &p_method) const { - for (int i = 0; i < rpc_functions.size(); i++) { - if (rpc_functions[i].name == p_method) { - return i; - } - } - return UINT16_MAX; -} - -StringName GDScript::get_rpc_method(const uint16_t p_rpc_method_id) const { - if (p_rpc_method_id >= rpc_functions.size()) { - return StringName(); - } - return rpc_functions[p_rpc_method_id].name; -} - -MultiplayerAPI::RPCMode GDScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const { - if (p_rpc_method_id >= rpc_functions.size()) { - return MultiplayerAPI::RPC_MODE_DISABLED; - } - return rpc_functions[p_rpc_method_id].mode; -} - -MultiplayerAPI::RPCMode GDScript::get_rpc_mode(const StringName &p_method) const { - return get_rpc_mode_by_id(get_rpc_method_id(p_method)); -} - -Vector<ScriptNetData> GDScript::get_rset_properties() const { - return rpc_variables; -} - -uint16_t GDScript::get_rset_property_id(const StringName &p_variable) const { - for (int i = 0; i < rpc_variables.size(); i++) { - if (rpc_variables[i].name == p_variable) { - return i; - } - } - return UINT16_MAX; -} - -StringName GDScript::get_rset_property(const uint16_t p_rset_member_id) const { - if (p_rset_member_id >= rpc_variables.size()) { - return StringName(); - } - return rpc_variables[p_rset_member_id].name; -} - -MultiplayerAPI::RPCMode GDScript::get_rset_mode_by_id(const uint16_t p_rset_member_id) const { - if (p_rset_member_id >= rpc_variables.size()) { - return MultiplayerAPI::RPC_MODE_DISABLED; - } - return rpc_variables[p_rset_member_id].mode; -} - -MultiplayerAPI::RPCMode GDScript::get_rset_mode(const StringName &p_variable) const { - return get_rset_mode_by_id(get_rset_property_id(p_variable)); -} - Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { GDScript *top = this; while (top) { @@ -1045,10 +990,10 @@ Error GDScript::load_source_code(const String &p_path) { ERR_FAIL_COND_V(err, err); } - int len = f->get_len(); + uint64_t len = f->get_length(); sourcef.resize(len + 1); uint8_t *w = sourcef.ptrw(); - int r = f->get_buffer(w, len); + uint64_t r = f->get_buffer(w, len); f->close(); memdelete(f); ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); @@ -1210,10 +1155,8 @@ void GDScript::_save_orphaned_subclasses() { void GDScript::_init_rpc_methods_properties() { // Copy the base rpc methods so we don't mask their IDs. rpc_functions.clear(); - rpc_variables.clear(); if (base.is_valid()) { rpc_functions = base->rpc_functions; - rpc_variables = base->rpc_variables; } GDScript *cscript = this; @@ -1221,23 +1164,11 @@ void GDScript::_init_rpc_methods_properties() { while (cscript) { // RPC Methods for (Map<StringName, GDScriptFunction *>::Element *E = cscript->member_functions.front(); E; E = E->next()) { - if (E->get()->get_rpc_mode() != MultiplayerAPI::RPC_MODE_DISABLED) { - ScriptNetData nd; - nd.name = E->key(); - nd.mode = E->get()->get_rpc_mode(); - if (-1 == rpc_functions.find(nd)) { - rpc_functions.push_back(nd); - } - } - } - // RSet - for (Map<StringName, MemberInfo>::Element *E = cscript->member_indices.front(); E; E = E->next()) { - if (E->get().rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) { - ScriptNetData nd; - nd.name = E->key(); - nd.mode = E->get().rpc_mode; - if (-1 == rpc_variables.find(nd)) { - rpc_variables.push_back(nd); + MultiplayerAPI::RPCConfig config = E->get()->get_rpc_config(); + if (config.rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) { + config.name = E->get()->get_name(); + if (rpc_functions.find(config) == -1) { + rpc_functions.push_back(config); } } } @@ -1254,8 +1185,7 @@ void GDScript::_init_rpc_methods_properties() { } // Sort so we are 100% that they are always the same. - rpc_functions.sort_custom<SortNetData>(); - rpc_variables.sort_custom<SortNetData>(); + rpc_functions.sort_custom<MultiplayerAPI::SortRPCConfig>(); } GDScript::~GDScript() { @@ -1514,8 +1444,8 @@ void GDScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const sptr = sptr->_base; } - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - p_properties->push_back(E->get()); + for (const PropertyInfo &E : props) { + p_properties->push_back(E); } } @@ -1611,46 +1541,10 @@ ScriptLanguage *GDScriptInstance::get_language() { return GDScriptLanguage::get_singleton(); } -Vector<ScriptNetData> GDScriptInstance::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> GDScriptInstance::get_rpc_methods() const { return script->get_rpc_methods(); } -uint16_t GDScriptInstance::get_rpc_method_id(const StringName &p_method) const { - return script->get_rpc_method_id(p_method); -} - -StringName GDScriptInstance::get_rpc_method(const uint16_t p_rpc_method_id) const { - return script->get_rpc_method(p_rpc_method_id); -} - -MultiplayerAPI::RPCMode GDScriptInstance::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const { - return script->get_rpc_mode_by_id(p_rpc_method_id); -} - -MultiplayerAPI::RPCMode GDScriptInstance::get_rpc_mode(const StringName &p_method) const { - return script->get_rpc_mode(p_method); -} - -Vector<ScriptNetData> GDScriptInstance::get_rset_properties() const { - return script->get_rset_properties(); -} - -uint16_t GDScriptInstance::get_rset_property_id(const StringName &p_variable) const { - return script->get_rset_property_id(p_variable); -} - -StringName GDScriptInstance::get_rset_property(const uint16_t p_rset_member_id) const { - return script->get_rset_property(p_rset_member_id); -} - -MultiplayerAPI::RPCMode GDScriptInstance::get_rset_mode_by_id(const uint16_t p_rset_member_id) const { - return script->get_rset_mode_by_id(p_rset_member_id); -} - -MultiplayerAPI::RPCMode GDScriptInstance::get_rset_mode(const StringName &p_variable) const { - return script->get_rset_mode(p_variable); -} - void GDScriptInstance::reload_members() { #ifdef DEBUG_ENABLED @@ -1681,7 +1575,7 @@ void GDScriptInstance::reload_members() { GDScriptInstance::GDScriptInstance() { owner = nullptr; - base_ref = false; + base_ref_counted = false; } GDScriptInstance::~GDScriptInstance() { @@ -1742,33 +1636,32 @@ void GDScriptLanguage::init() { _add_global(StaticCString::create("PI"), Math_PI); _add_global(StaticCString::create("TAU"), Math_TAU); - _add_global(StaticCString::create("INF"), Math_INF); - _add_global(StaticCString::create("NAN"), Math_NAN); + _add_global(StaticCString::create("INF"), INFINITY); + _add_global(StaticCString::create("NAN"), NAN); //populate native classes List<StringName> class_list; ClassDB::get_class_list(&class_list); - for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) { - StringName n = E->get(); + for (const StringName &n : class_list) { String s = String(n); if (s.begins_with("_")) { - n = s.substr(1, s.length()); + s = s.substr(1, s.length()); } - if (globals.has(n)) { + if (globals.has(s)) { continue; } - Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(E->get())); - _add_global(n, nc); + Ref<GDScriptNativeClass> nc = memnew(GDScriptNativeClass(n)); + _add_global(s, nc); } //populate singletons List<Engine::Singleton> singletons; Engine::get_singleton()->get_singletons(&singletons); - for (List<Engine::Singleton>::Element *E = singletons.front(); E; E = E->next()) { - _add_global(E->get().name, E->get().ptr); + for (const Engine::Singleton &E : singletons) { + _add_global(E.name, E.ptr); } #ifdef TESTS_ENABLED @@ -1911,10 +1804,10 @@ void GDScriptLanguage::reload_all_scripts() { scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for (List<Ref<GDScript>>::Element *E = scripts.front(); E; E = E->next()) { - print_verbose("GDScript: Reloading: " + E->get()->get_path()); - E->get()->load_source_code(E->get()->get_path()); - E->get()->reload(true); + for (Ref<GDScript> &script : scripts) { + print_verbose("GDScript: Reloading: " + script->get_path()); + script->load_source_code(script->get_path()); + script->reload(true); } #endif } @@ -1943,21 +1836,21 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order - for (List<Ref<GDScript>>::Element *E = scripts.front(); E; E = E->next()) { - bool reload = E->get() == p_script || to_reload.has(E->get()->get_base()); + for (Ref<GDScript> &script : scripts) { + bool reload = script == p_script || to_reload.has(script->get_base()); if (!reload) { continue; } - to_reload.insert(E->get(), Map<ObjectID, List<Pair<StringName, Variant>>>()); + to_reload.insert(script, Map<ObjectID, List<Pair<StringName, Variant>>>()); if (!p_soft_reload) { //save state and remove script from instances - Map<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[E->get()]; + Map<ObjectID, List<Pair<StringName, Variant>>> &map = to_reload[script]; - while (E->get()->instances.front()) { - Object *obj = E->get()->instances.front()->get(); + while (script->instances.front()) { + Object *obj = script->instances.front()->get(); //save instance info List<Pair<StringName, Variant>> state; if (obj->get_script_instance()) { @@ -1970,8 +1863,8 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_so //same thing for placeholders #ifdef TOOLS_ENABLED - while (E->get()->placeholders.size()) { - Object *obj = E->get()->placeholders.front()->get()->get_owner(); + while (script->placeholders.size()) { + Object *obj = script->placeholders.front()->get()->get_owner(); //save instance info if (obj->get_script_instance()) { @@ -1981,13 +1874,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 - E->get()->placeholders.erase(E->get()->placeholders.front()->get()); + script->placeholders.erase(script->placeholders.front()->get()); } } #endif - for (Map<ObjectID, List<Pair<StringName, Variant>>>::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) { + for (Map<ObjectID, List<Pair<StringName, Variant>>>::Element *F = script->pending_reload_state.front(); F; F = F->next()) { map[F->key()] = F->get(); //pending to reload, use this one instead } } @@ -2130,11 +2023,24 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const { List<StringName> functions; GDScriptUtilityFunctions::get_function_list(&functions); - for (const List<StringName>::Element *E = functions.front(); E; E = E->next()) { - p_words->push_back(String(E->get())); + for (const StringName &E : functions) { + p_words->push_back(String(E)); } } +bool GDScriptLanguage::is_control_flow_keyword(String p_keyword) const { + return p_keyword == "break" || + p_keyword == "continue" || + p_keyword == "elif" || + p_keyword == "else" || + p_keyword == "if" || + p_keyword == "for" || + p_keyword == "match" || + p_keyword == "pass" || + p_keyword == "return" || + p_keyword == "while"; +} + bool GDScriptLanguage::handles_global_class_type(const String &p_type) const { return p_type == "GDScript"; } @@ -2156,7 +2062,7 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b if (err == OK) { const GDScriptParser::ClassNode *c = parser.get_tree(); if (r_icon_path) { - if (c->icon_path.is_empty() || c->icon_path.is_abs_path()) { + if (c->icon_path.is_empty() || c->icon_path.is_absolute_path()) { *r_icon_path = c->icon_path; } else if (c->icon_path.is_rel_path()) { *r_icon_path = p_path.get_base_dir().plus_file(c->icon_path).simplify_path(); @@ -2224,7 +2130,7 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b break; } } else { - *r_base_type = "Reference"; + *r_base_type = "RefCounted"; subclass = nullptr; } } @@ -2344,7 +2250,7 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_ori if (script.is_null()) { // Don't fail loading because of parsing error. - script.instance(); + script.instantiate(); } if (r_error) { @@ -2388,8 +2294,8 @@ void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<S return; } - for (const List<String>::Element *E = parser.get_dependencies().front(); E; E = E->next()) { - p_dependencies->push_back(E->get()); + for (const String &E : parser.get_dependencies()) { + p_dependencies->push_back(E); } } diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index 12c909fd4f..24809ad5fd 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -39,8 +39,8 @@ #include "core/object/script_language.h" #include "gdscript_function.h" -class GDScriptNativeClass : public Reference { - GDCLASS(GDScriptNativeClass, Reference); +class GDScriptNativeClass : public RefCounted { + GDCLASS(GDScriptNativeClass, RefCounted); StringName name; @@ -51,7 +51,7 @@ protected: public: _FORCE_INLINE_ const StringName &get_name() const { return name; } Variant _new(); - Object *instance(); + Object *instantiate(); GDScriptNativeClass(const StringName &p_name); }; @@ -64,7 +64,6 @@ class GDScript : public Script { int index = 0; StringName setter; StringName getter; - MultiplayerAPI::RPCMode rpc_mode; GDScriptDataType data_type; }; @@ -80,14 +79,13 @@ class GDScript : public Script { GDScript *_base = nullptr; //fast pointer access GDScript *_owner = nullptr; //for subclasses - Set<StringName> members; //members are just indices to the instanced script. + Set<StringName> members; //members are just indices to the instantiated script. Map<StringName, Variant> constants; Map<StringName, GDScriptFunction *> member_functions; - Map<StringName, MemberInfo> member_indices; //members are just indices to the instanced script. + Map<StringName, MemberInfo> member_indices; //members are just indices to the instantiated script. Map<StringName, Ref<GDScript>> subclasses; Map<StringName, Vector<StringName>> _signals; - Vector<ScriptNetData> rpc_functions; - Vector<ScriptNetData> rpc_variables; + Vector<MultiplayerAPI::RPCConfig> rpc_functions; #ifdef TOOLS_ENABLED @@ -133,7 +131,7 @@ class GDScript : public Script { SelfList<GDScriptFunctionState>::List pending_func_states; 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_isref, 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); @@ -149,7 +147,7 @@ class GDScript : public Script { #endif - bool _update_exports(bool *r_err = nullptr, bool p_recursive_call = false); + bool _update_exports(bool *r_err = nullptr, bool p_recursive_call = false, PlaceHolderScriptInstance *p_instance_to_update = nullptr); void _save_orphaned_subclasses(); void _init_rpc_methods_properties(); @@ -158,7 +156,7 @@ class GDScript : public Script { void _get_script_method_list(List<MethodInfo> *r_list, bool p_include_base) const; void _get_script_signal_list(List<MethodInfo> *r_list, bool p_include_base) const; - // This method will map the class name from "Reference" to "MyClass.InnerClass". + // This method will map the class name from "RefCounted" to "MyClass.InnerClass". static String _get_gdscript_reference_class_name(const GDScript *p_gdscript); protected: @@ -197,7 +195,7 @@ public: StringName debug_get_member_by_index(int p_idx) const; Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error); - virtual bool can_instance() const override; + virtual bool can_instantiate() const override; virtual Ref<Script> get_base_script() const override; @@ -247,17 +245,7 @@ public: virtual void get_constants(Map<StringName, Variant> *p_constants) override; virtual void get_members(Set<StringName> *p_members) override; - virtual Vector<ScriptNetData> get_rpc_methods() const override; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const override; - virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override; - - virtual Vector<ScriptNetData> get_rset_properties() const override; - virtual uint16_t get_rset_property_id(const StringName &p_variable) const override; - virtual StringName get_rset_property(const uint16_t p_variable_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const override; #ifdef TOOLS_ENABLED virtual bool is_placeholder_fallback_enabled() const override { return placeholder_fallback_enabled; } @@ -270,6 +258,7 @@ public: class GDScriptInstance : public ScriptInstance { friend class GDScript; friend class GDScriptFunction; + friend class GDScriptLambdaCallable; friend class GDScriptCompiler; friend struct GDScriptUtilityFunctionsDefinitions; @@ -280,7 +269,7 @@ class GDScriptInstance : public ScriptInstance { Map<StringName, int> member_indices_cache; //used only for hot script reloading #endif Vector<Variant> members; - bool base_ref; + bool base_ref_counted; SelfList<GDScriptFunctionState>::List pending_func_states; @@ -309,17 +298,7 @@ public: void reload_members(); - virtual Vector<ScriptNetData> get_rpc_methods() const; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const; - virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const; - - virtual Vector<ScriptNetData> get_rset_properties() const; - virtual uint16_t get_rset_property_id(const StringName &p_variable) const; - virtual StringName get_rset_property(const uint16_t p_variable_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const; GDScriptInstance(); ~GDScriptInstance(); @@ -460,13 +439,14 @@ public: /* EDITOR FUNCTIONS */ virtual void get_reserved_words(List<String> *p_words) const; + virtual bool is_control_flow_keyword(String p_keywords) const; virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; virtual String _get_processed_template(const String &p_template, const String &p_base_class_name) const; virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; virtual bool is_using_templates(); virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script); - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; + virtual bool validate(const String &p_script, const String &p_path = "", List<String> *r_functions = nullptr, List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 5da2bb5cc1..ab37e54cf1 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -31,10 +31,10 @@ #include "gdscript_analyzer.h" #include "core/config/project_settings.h" +#include "core/io/file_access.h" #include "core/io/resource_loader.h" #include "core/object/class_db.h" #include "core/object/script_language.h" -#include "core/os/file_access.h" #include "core/templates/hash_map.h" #include "gdscript.h" #include "gdscript_utility_functions.h" @@ -115,8 +115,8 @@ static GDScriptParser::DataType make_native_enum_type(const StringName &p_native StringName real_native_name = GDScriptParser::get_real_class_name(p_native_class); ClassDB::get_enum_constants(real_native_name, p_enum_name, &enum_values); - for (const List<StringName>::Element *E = enum_values.front(); E != nullptr; E = E->next()) { - type.enum_values[E->get()] = ClassDB::get_integer_constant(real_native_name, E->get()); + for (const StringName &E : enum_values) { + type.enum_values[E] = ClassDB::get_integer_constant(real_native_name, E); } return type; @@ -163,7 +163,7 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, if (!p_class->extends_used) { result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; result.kind = GDScriptParser::DataType::NATIVE; - result.native_type = "Reference"; + result.native_type = "RefCounted"; } else { result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; @@ -229,7 +229,7 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class); return err; } - } else if (class_exists(name) && ClassDB::can_instance(GDScriptParser::get_real_class_name(name))) { + } else if (class_exists(name) && ClassDB::can_instantiate(GDScriptParser::get_real_class_name(name))) { base.kind = GDScriptParser::DataType::NATIVE; base.native_type = name; } else { @@ -543,6 +543,7 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas } else { // TODO: Add warning. mark_node_unsafe(member.variable->initializer); + member.variable->use_conversion_assign = true; } } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) { #ifdef DEBUG_ENABLED @@ -552,6 +553,7 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas if (member.variable->initializer->get_datatype().is_variant()) { // TODO: Warn unsafe assign. mark_node_unsafe(member.variable->initializer); + member.variable->use_conversion_assign = true; } } } else if (member.variable->infer_datatype) { @@ -571,8 +573,8 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas member.variable->set_datatype(datatype); // Apply annotations. - for (List<GDScriptParser::AnnotationNode *>::Element *E = member.variable->annotations.front(); E; E = E->next()) { - E->get()->apply(parser, member.variable); + for (GDScriptParser::AnnotationNode *&E : member.variable->annotations) { + E->apply(parser, member.variable); } } break; case GDScriptParser::ClassNode::Member::CONSTANT: { @@ -620,8 +622,8 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas member.constant->set_datatype(datatype); // Apply annotations. - for (List<GDScriptParser::AnnotationNode *>::Element *E = member.constant->annotations.front(); E; E = E->next()) { - E->get()->apply(parser, member.constant); + for (GDScriptParser::AnnotationNode *&E : member.constant->annotations) { + E->apply(parser, member.constant); } } break; case GDScriptParser::ClassNode::Member::SIGNAL: { @@ -639,8 +641,8 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas member.signal->set_datatype(signal_type); // Apply annotations. - for (List<GDScriptParser::AnnotationNode *>::Element *E = member.signal->annotations.front(); E; E = E->next()) { - E->get()->apply(parser, member.signal); + for (GDScriptParser::AnnotationNode *&E : member.signal->annotations) { + E->apply(parser, member.signal); } } break; case GDScriptParser::ClassNode::Member::ENUM: { @@ -686,8 +688,8 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas member.m_enum->set_datatype(enum_type); // Apply annotations. - for (List<GDScriptParser::AnnotationNode *>::Element *E = member.m_enum->annotations.front(); E; E = E->next()) { - E->get()->apply(parser, member.m_enum); + for (GDScriptParser::AnnotationNode *&E : member.m_enum->annotations) { + E->apply(parser, member.m_enum); } } break; case GDScriptParser::ClassNode::Member::FUNCTION: @@ -759,8 +761,8 @@ void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) { resolve_function_body(member.function); // Apply annotations. - for (List<GDScriptParser::AnnotationNode *>::Element *E = member.function->annotations.front(); E; E = E->next()) { - E->get()->apply(parser, member.function); + for (GDScriptParser::AnnotationNode *&E : member.function->annotations) { + E->apply(parser, member.function); } } @@ -856,6 +858,7 @@ void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) { case GDScriptParser::Node::DICTIONARY: case GDScriptParser::Node::GET_NODE: case GDScriptParser::Node::IDENTIFIER: + case GDScriptParser::Node::LAMBDA: case GDScriptParser::Node::LITERAL: case GDScriptParser::Node::PRELOAD: case GDScriptParser::Node::SELF: @@ -1144,6 +1147,7 @@ void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable } else { // TODO: Add warning. mark_node_unsafe(p_variable->initializer); + p_variable->use_conversion_assign = true; } #ifdef DEBUG_ENABLED } else if (type.builtin_type == Variant::INT && p_variable->initializer->get_datatype().builtin_type == Variant::FLOAT) { @@ -1153,6 +1157,7 @@ void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable if (p_variable->initializer->get_datatype().is_variant()) { // TODO: Warn unsafe assign. mark_node_unsafe(p_variable->initializer); + p_variable->use_conversion_assign = true; } } } else if (p_variable->infer_datatype) { @@ -1458,6 +1463,9 @@ void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expre case GDScriptParser::Node::IDENTIFIER: reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression)); break; + case GDScriptParser::Node::LAMBDA: + reduce_lambda(static_cast<GDScriptParser::LambdaNode *>(p_expression)); + break; case GDScriptParser::Node::LITERAL: reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression)); break; @@ -1604,10 +1612,12 @@ void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assig } else { // TODO: Add warning. mark_node_unsafe(p_assignment); + p_assignment->use_conversion_assign = true; } } else { // TODO: Warning in this case. mark_node_unsafe(p_assignment); + p_assignment->use_conversion_assign = true; } } } else { @@ -1617,6 +1627,9 @@ void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assig if (assignee_type.has_no_type() || assigned_value_type.is_variant()) { mark_node_unsafe(p_assignment); + if (assignee_type.is_hard_type()) { + p_assignment->use_conversion_assign = true; + } } if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) { @@ -1766,10 +1779,10 @@ void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_o } else { if (p_binary_op->variant_op < Variant::OP_MAX) { bool valid = false; - result = get_operation_type(p_binary_op->variant_op, p_binary_op->left_operand->get_datatype(), right_type, valid, p_binary_op); + result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op); if (!valid) { - push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", p_binary_op->left_operand->get_datatype().to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op); + push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", left_type.to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op); } } else { if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) { @@ -1914,9 +1927,7 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_awa Variant::get_constructor_list(builtin_type, &constructors); bool match = false; - for (const List<MethodInfo>::Element *E = constructors.front(); E != nullptr; E = E->next()) { - const MethodInfo &info = E->get(); - + for (const MethodInfo &info : constructors) { if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) { continue; } @@ -2055,12 +2066,20 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_awa if (p_call->is_super) { base_type = parser->current_class->base_type; + base_type.is_meta_type = false; is_self = true; } else if (callee_type == GDScriptParser::Node::IDENTIFIER) { base_type = parser->current_class->get_datatype(); + base_type.is_meta_type = false; is_self = true; } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) { GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee); + if (subscript->base == nullptr) { + // Invalid syntax, error already set on parser. + p_call->set_datatype(call_type); + mark_node_unsafe(p_call); + return; + } if (!subscript->is_attribute) { // Invalid call. Error already sent in parser. // TODO: Could check if Callable here. @@ -2068,9 +2087,23 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_awa mark_node_unsafe(p_call); return; } - reduce_expression(subscript->base); + if (subscript->attribute == nullptr) { + // Invalid call. Error already sent in parser. + p_call->set_datatype(call_type); + mark_node_unsafe(p_call); + return; + } - base_type = subscript->base->get_datatype(); + GDScriptParser::IdentifierNode *base_id = nullptr; + if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) { + base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base); + } + if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) { + base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name)); + } else { + reduce_expression(subscript->base); + base_type = subscript->base->get_datatype(); + } } else { // Invalid call. Error already sent in parser. // TODO: Could check if Callable here too. @@ -2097,6 +2130,8 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_awa if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) { push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parser->current_function->identifier->name), p_call->callee); + } else if (is_self && !is_static && !lambda_stack.is_empty()) { + push_error(vformat(R"*(Cannot call non-static function "%s()" from a lambda function.)*", p_call->function_name), p_call->callee); } call_type = return_type; @@ -2219,6 +2254,8 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) if (!ClassDB::is_parent_class(GDScriptParser::get_real_class_name(parser->current_class->base_type.native_type), result.native_type)) { push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node); + } else if (!lambda_stack.is_empty()) { + push_error(R"*(Cannot use shorthand "get_node()" notation ("$") inside a lambda. Use a captured variable instead.)*", p_get_node); } p_get_node->set_datatype(result); @@ -2287,8 +2324,7 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod Variant::construct(base.builtin_type, dummy, nullptr, 0, temp); List<PropertyInfo> properties; dummy.get_property_list(&properties); - for (const List<PropertyInfo>::Element *E = properties.front(); E != nullptr; E = E->next()) { - const PropertyInfo &prop = E->get(); + for (const PropertyInfo &prop : properties) { if (prop.name == name) { p_identifier->set_datatype(type_from_property(prop)); return; @@ -2310,6 +2346,7 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod GDScriptParser::DataType result; result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; result.kind = GDScriptParser::DataType::ENUM_VALUE; + result.builtin_type = base.builtin_type; result.native_type = base.native_type; result.enum_type = name; p_identifier->set_datatype(result); @@ -2346,6 +2383,7 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod case GDScriptParser::ClassNode::Member::ENUM_VALUE: p_identifier->is_constant = true; p_identifier->reduced_value = member.enum_value.value; + p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT; break; case GDScriptParser::ClassNode::Member::VARIABLE: p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE; @@ -2446,42 +2484,65 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident } } + bool found_source = false; // Check if identifier is local. // If that's the case, the declaration already was solved before. switch (p_identifier->source) { case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER: p_identifier->set_datatype(p_identifier->parameter_source->get_datatype()); - return; + found_source = true; + break; case GDScriptParser::IdentifierNode::LOCAL_CONSTANT: case GDScriptParser::IdentifierNode::MEMBER_CONSTANT: p_identifier->set_datatype(p_identifier->constant_source->get_datatype()); p_identifier->is_constant = true; // TODO: Constant should have a value on the node itself. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value; - return; + found_source = true; + break; case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: p_identifier->variable_source->usages++; [[fallthrough]]; case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: p_identifier->set_datatype(p_identifier->variable_source->get_datatype()); - return; + found_source = true; + break; case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: p_identifier->set_datatype(p_identifier->bind_source->get_datatype()); - return; + found_source = true; + break; case GDScriptParser::IdentifierNode::LOCAL_BIND: { GDScriptParser::DataType result = p_identifier->bind_source->get_datatype(); result.is_constant = true; p_identifier->set_datatype(result); - return; - } + found_source = true; + } break; case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE: break; } // Not a local, so check members. - reduce_identifier_from_base(p_identifier); - if (p_identifier->get_datatype().is_set()) { - // Found. + if (!found_source) { + reduce_identifier_from_base(p_identifier); + if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) { + // Found. + found_source = true; + } + } + + if (found_source) { + // If the identifier is local, check if it's any kind of capture by comparing their source function. + // Only capture locals and members and enum values. Constants are still accessible from the lambda using the script reference. + if (p_identifier->source == GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_CONSTANT || lambda_stack.is_empty()) { + return; + } + + GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function; + while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) { + function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size(); + function_test->source_lambda->captures.push_back(p_identifier); + function_test = function_test->source_lambda->parent_function; + } return; } @@ -2563,6 +2624,57 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident p_identifier->set_datatype(dummy); // Just so type is set to something. } +void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) { + // Lambda is always a Callable. + GDScriptParser::DataType lambda_type; + lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; + lambda_type.kind = GDScriptParser::DataType::BUILTIN; + lambda_type.builtin_type = Variant::CALLABLE; + p_lambda->set_datatype(lambda_type); + + if (p_lambda->function == nullptr) { + return; + } + + GDScriptParser::FunctionNode *previous_function = parser->current_function; + parser->current_function = p_lambda->function; + + lambda_stack.push_back(p_lambda); + + for (int i = 0; i < p_lambda->function->parameters.size(); i++) { + resolve_parameter(p_lambda->function->parameters[i]); + } + + resolve_suite(p_lambda->function->body); + + int captures_amount = p_lambda->captures.size(); + if (captures_amount > 0) { + // Create space for lambda parameters. + // At the beginning to not mess with optional parameters. + int param_count = p_lambda->function->parameters.size(); + p_lambda->function->parameters.resize(param_count + captures_amount); + for (int i = param_count - 1; i >= 0; i--) { + p_lambda->function->parameters.write[i + captures_amount] = p_lambda->function->parameters[i]; + p_lambda->function->parameters_indices[p_lambda->function->parameters[i]->identifier->name] = i + captures_amount; + } + + // Add captures as extra parameters at the beginning. + for (int i = 0; i < p_lambda->captures.size(); i++) { + GDScriptParser::IdentifierNode *capture = p_lambda->captures[i]; + GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>(); + capture_param->identifier = capture; + capture_param->usages = capture->usages; + capture_param->set_datatype(capture->get_datatype()); + + p_lambda->function->parameters.write[i] = capture_param; + p_lambda->function->parameters_indices[capture->name] = i; + } + } + + lambda_stack.pop_back(); + parser->current_function = previous_function; +} + void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) { p_literal->reduced_value = p_literal->value; p_literal->is_constant = true; @@ -2711,7 +2823,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri case Variant::RECT2: case Variant::RECT2I: case Variant::PLANE: - case Variant::QUAT: + case Variant::QUATERNION: case Variant::AABB: case Variant::OBJECT: error = index_type.builtin_type != Variant::STRING; @@ -2722,8 +2834,8 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri case Variant::VECTOR2I: case Variant::VECTOR3: case Variant::VECTOR3I: - case Variant::TRANSFORM: case Variant::TRANSFORM2D: + case Variant::TRANSFORM3D: error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT && index_type.builtin_type != Variant::STRING; break; @@ -2790,7 +2902,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri case Variant::PACKED_FLOAT64_ARRAY: case Variant::VECTOR2: case Variant::VECTOR3: - case Variant::QUAT: + case Variant::QUATERNION: result_type.builtin_type = Variant::FLOAT; break; // Return Color. @@ -2819,7 +2931,7 @@ void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscri result_type.builtin_type = Variant::VECTOR3; break; // Depends on the index. - case Variant::TRANSFORM: + case Variant::TRANSFORM3D: case Variant::PLANE: case Variant::COLOR: case Variant::DICTIONARY: @@ -3010,8 +3122,8 @@ GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_va GDScriptParser::ClassNode *found = ref->get_parser()->head; // It should be okay to assume this exists, since we have a complete script already. - for (const List<StringName>::Element *E = class_chain.front(); E; E = E->next()) { - found = found->get_member(E->get()).m_class; + for (const StringName &E : class_chain) { + found = found->get_member(E).m_class; } result.class_type = found; @@ -3107,9 +3219,9 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, GD List<MethodInfo> methods; dummy.get_method_list(&methods); - for (const List<MethodInfo>::Element *E = methods.front(); E != nullptr; E = E->next()) { - if (E->get().name == p_function) { - return function_signature_from_info(E->get(), r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg); + for (const MethodInfo &E : methods) { + if (E.name == p_function) { + return function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg); } } @@ -3206,8 +3318,8 @@ bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GD r_default_arg_count = p_info.default_arguments.size(); r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0; - for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E != nullptr; E = E->next()) { - r_par_types.push_back(type_from_property(E->get())); + for (const PropertyInfo &E : p_info.arguments) { + r_par_types.push_back(type_from_property(E)); } return true; } @@ -3215,8 +3327,8 @@ bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GD bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) { List<GDScriptParser::DataType> arg_types; - for (const List<PropertyInfo>::Element *E = p_method.arguments.front(); E != nullptr; E = E->next()) { - arg_types.push_back(type_from_property(E->get())); + for (const PropertyInfo &E : p_method.arguments) { + arg_types.push_back(type_from_property(E)); } return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call); @@ -3332,6 +3444,7 @@ GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator } r_valid = true; + result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED; result.kind = GDScriptParser::DataType::BUILTIN; result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type); @@ -3542,11 +3655,11 @@ Error GDScriptAnalyzer::resolve_program() { List<String> parser_keys; depended_parsers.get_key_list(&parser_keys); - for (const List<String>::Element *E = parser_keys.front(); E != nullptr; E = E->next()) { - if (depended_parsers[E->get()].is_null()) { + for (const String &E : parser_keys) { + if (depended_parsers[E].is_null()) { return ERR_PARSE_ERROR; } - depended_parsers[E->get()]->raise_status(GDScriptParserRef::FULLY_SOLVED); + depended_parsers[E]->raise_status(GDScriptParserRef::FULLY_SOLVED); } return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR; } diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index 8430d3f4a5..8cd3fcf837 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -32,7 +32,7 @@ #define GDSCRIPT_ANALYZER_H #include "core/object/object.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/templates/set.h" #include "gdscript_cache.h" #include "gdscript_parser.h" @@ -42,6 +42,7 @@ class GDScriptAnalyzer { HashMap<String, Ref<GDScriptParserRef>> depended_parsers; const GDScriptParser::EnumNode *current_enum = nullptr; + List<const GDScriptParser::LambdaNode *> lambda_stack; Error resolve_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive = true); GDScriptParser::DataType resolve_datatype(GDScriptParser::TypeNode *p_type); @@ -82,6 +83,7 @@ class GDScriptAnalyzer { void reduce_get_node(GDScriptParser::GetNodeNode *p_get_node); void reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin = false); void reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base = nullptr); + void reduce_lambda(GDScriptParser::LambdaNode *p_lambda); void reduce_literal(GDScriptParser::LiteralNode *p_literal); void reduce_preload(GDScriptParser::PreloadNode *p_preload); void reduce_self(GDScriptParser::SelfNode *p_self); diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp index 89c5f5482b..5958326315 100644 --- a/modules/gdscript/gdscript_byte_codegen.cpp +++ b/modules/gdscript/gdscript_byte_codegen.cpp @@ -85,10 +85,10 @@ uint32_t GDScriptByteCodeGenerator::add_temporary(const GDScriptDataType &p_type case Variant::VECTOR3I: case Variant::TRANSFORM2D: case Variant::PLANE: - case Variant::QUAT: + case Variant::QUATERNION: case Variant::AABB: case Variant::BASIS: - case Variant::TRANSFORM: + case Variant::TRANSFORM3D: case Variant::COLOR: case Variant::STRING_NAME: case Variant::NODE_PATH: @@ -129,12 +129,6 @@ uint32_t GDScriptByteCodeGenerator::add_temporary(const GDScriptDataType &p_type int idx = temporaries.size(); pool.push_back(idx); temporaries.push_back(new_temp); - - // First time using this, so adjust to the proper type. - if (temp_type != Variant::NIL) { - Address addr(Address::TEMPORARY, idx, p_type); - write_type_adjust(addr, temp_type); - } } int slot = pool.front()->get(); pool.pop_front(); @@ -161,7 +155,7 @@ void GDScriptByteCodeGenerator::end_parameters() { function->default_arguments.reverse(); } -void GDScriptByteCodeGenerator::write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCMode p_rpc_mode, const GDScriptDataType &p_return_type) { +void GDScriptByteCodeGenerator::write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCConfig p_rpc_config, const GDScriptDataType &p_return_type) { function = memnew(GDScriptFunction); debug_stack = EngineDebugger::is_active(); @@ -176,7 +170,7 @@ void GDScriptByteCodeGenerator::write_start(GDScript *p_script, const StringName function->_static = p_static; function->return_type = p_return_type; - function->rpc_mode = p_rpc_mode; + function->rpc_config = p_rpc_config; function->_argument_count = 0; } @@ -189,8 +183,12 @@ GDScriptFunction *GDScriptByteCodeGenerator::write_end() { append(GDScriptFunction::OPCODE_END, 0); for (int i = 0; i < temporaries.size(); i++) { + int stack_index = i + max_locals + RESERVED_STACK; for (int j = 0; j < temporaries[i].bytecode_indices.size(); j++) { - opcodes.write[temporaries[i].bytecode_indices[j]] = (i + max_locals + RESERVED_STACK) | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS); + opcodes.write[temporaries[i].bytecode_indices[j]] = stack_index | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS); + } + if (temporaries[i].type != Variant::NIL) { + function->temporary_slots[stack_index] = temporaries[i].type; } } @@ -383,6 +381,18 @@ GDScriptFunction *GDScriptByteCodeGenerator::write_end() { function->_methods_count = 0; } + if (lambdas_map.size()) { + function->lambdas.resize(lambdas_map.size()); + function->_lambdas_ptr = function->lambdas.ptrw(); + function->_lambdas_count = lambdas_map.size(); + for (const Map<GDScriptFunction *, int>::Element *E = lambdas_map.front(); E; E = E->next()) { + function->lambdas.write[E->get()] = E->key(); + } + } else { + function->_lambdas_ptr = nullptr; + function->_lambdas_count = 0; + } + if (debug_stack) { function->stack_debug = stack_debug; } @@ -448,8 +458,8 @@ void GDScriptByteCodeGenerator::write_type_adjust(const Address &p_target, Varia case Variant::PLANE: append(GDScriptFunction::OPCODE_TYPE_ADJUST_PLANE, 1); break; - case Variant::QUAT: - append(GDScriptFunction::OPCODE_TYPE_ADJUST_QUAT, 1); + case Variant::QUATERNION: + append(GDScriptFunction::OPCODE_TYPE_ADJUST_QUATERNION, 1); break; case Variant::AABB: append(GDScriptFunction::OPCODE_TYPE_ADJUST_AABB, 1); @@ -457,7 +467,7 @@ void GDScriptByteCodeGenerator::write_type_adjust(const Address &p_target, Varia case Variant::BASIS: append(GDScriptFunction::OPCODE_TYPE_ADJUST_BASIS, 1); break; - case Variant::TRANSFORM: + case Variant::TRANSFORM3D: append(GDScriptFunction::OPCODE_TYPE_ADJUST_TRANSFORM, 1); break; case Variant::COLOR: @@ -544,6 +554,14 @@ void GDScriptByteCodeGenerator::write_unary_operator(const Address &p_target, Va void GDScriptByteCodeGenerator::write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) { if (HAS_BUILTIN_TYPE(p_left_operand) && HAS_BUILTIN_TYPE(p_right_operand)) { + if (p_target.mode == Address::TEMPORARY) { + Variant::Type result_type = Variant::get_operator_return_type(p_operator, p_left_operand.type.builtin_type, p_right_operand.type.builtin_type); + Variant::Type temp_type = temporaries[p_target.address].type; + if (result_type != temp_type) { + write_type_adjust(p_target, result_type); + } + } + // Gather specific operator. Variant::ValidatedOperatorEvaluator op_func = Variant::get_validated_operator_evaluator(p_operator, p_left_operand.type.builtin_type, p_right_operand.type.builtin_type); @@ -769,63 +787,43 @@ void GDScriptByteCodeGenerator::write_get_member(const Address &p_target, const append(p_name); } -void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Address &p_source) { - if (p_target.type.has_type && !p_source.type.has_type) { - // Typed assignment. - switch (p_target.type.kind) { - case GDScriptDataType::BUILTIN: { - if (p_target.type.builtin_type == Variant::ARRAY && p_target.type.has_container_element_type()) { - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_ARRAY, 2); - append(p_target); - append(p_source); - } else { - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2); - append(p_target); - append(p_source); - append(p_target.type.builtin_type); - } - } break; - case GDScriptDataType::NATIVE: { - int class_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_target.type.native_type]; - Variant nc = GDScriptLanguage::get_singleton()->get_global_array()[class_idx]; - class_idx = get_constant_pos(nc) | (GDScriptFunction::ADDR_TYPE_CONSTANT << GDScriptFunction::ADDR_BITS); - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE, 3); - append(p_target); - append(p_source); - append(class_idx); - } break; - case GDScriptDataType::SCRIPT: - case GDScriptDataType::GDSCRIPT: { - Variant script = p_target.type.script_type; - int idx = get_constant_pos(script) | (GDScriptFunction::ADDR_TYPE_CONSTANT << GDScriptFunction::ADDR_BITS); - - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT, 3); +void GDScriptByteCodeGenerator::write_assign_with_conversion(const Address &p_target, const Address &p_source) { + switch (p_target.type.kind) { + case GDScriptDataType::BUILTIN: { + if (p_target.type.builtin_type == Variant::ARRAY && p_target.type.has_container_element_type()) { + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_ARRAY, 2); append(p_target); append(p_source); - append(idx); - } break; - default: { - ERR_PRINT("Compiler bug: unresolved assign."); - - // Shouldn't get here, but fail-safe to a regular assignment - append(GDScriptFunction::OPCODE_ASSIGN, 2); + } else { + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2); append(p_target); append(p_source); + append(p_target.type.builtin_type); } - } - } else { - if (p_target.type.kind == GDScriptDataType::BUILTIN && p_target.type.builtin_type == Variant::ARRAY && p_target.type.has_container_element_type()) { - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_ARRAY, 2); + } break; + case GDScriptDataType::NATIVE: { + int class_idx = GDScriptLanguage::get_singleton()->get_global_map()[p_target.type.native_type]; + Variant nc = GDScriptLanguage::get_singleton()->get_global_array()[class_idx]; + class_idx = get_constant_pos(nc) | (GDScriptFunction::ADDR_TYPE_CONSTANT << GDScriptFunction::ADDR_BITS); + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_NATIVE, 3); append(p_target); append(p_source); - } else if (p_target.type.kind == GDScriptDataType::BUILTIN && p_source.type.kind == GDScriptDataType::BUILTIN && p_target.type.builtin_type != p_source.type.builtin_type) { - // Need conversion.. - append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2); + append(class_idx); + } break; + case GDScriptDataType::SCRIPT: + case GDScriptDataType::GDSCRIPT: { + Variant script = p_target.type.script_type; + int idx = get_constant_pos(script) | (GDScriptFunction::ADDR_TYPE_CONSTANT << GDScriptFunction::ADDR_BITS); + + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_SCRIPT, 3); append(p_target); append(p_source); - append(p_target.type.builtin_type); - } else { - // Either untyped assignment or already type-checked by the parser + append(idx); + } break; + default: { + ERR_PRINT("Compiler bug: unresolved assign."); + + // Shouldn't get here, but fail-safe to a regular assignment append(GDScriptFunction::OPCODE_ASSIGN, 2); append(p_target); append(p_source); @@ -833,6 +831,24 @@ void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Addr } } +void GDScriptByteCodeGenerator::write_assign(const Address &p_target, const Address &p_source) { + if (p_target.type.kind == GDScriptDataType::BUILTIN && p_target.type.builtin_type == Variant::ARRAY && p_target.type.has_container_element_type()) { + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_ARRAY, 2); + append(p_target); + append(p_source); + } else if (p_target.type.kind == GDScriptDataType::BUILTIN && p_source.type.kind == GDScriptDataType::BUILTIN && p_target.type.builtin_type != p_source.type.builtin_type) { + // Need conversion. + append(GDScriptFunction::OPCODE_ASSIGN_TYPED_BUILTIN, 2); + append(p_target); + append(p_source); + append(p_target.type.builtin_type); + } else { + append(GDScriptFunction::OPCODE_ASSIGN, 2); + append(p_target); + append(p_source); + } +} + void GDScriptByteCodeGenerator::write_assign_true(const Address &p_target) { append(GDScriptFunction::OPCODE_ASSIGN_TRUE, 1); append(p_target); @@ -1005,6 +1021,56 @@ void GDScriptByteCodeGenerator::write_call_builtin_type(const Address &p_target, append(Variant::get_validated_builtin_method(p_type, p_method)); } +void GDScriptByteCodeGenerator::write_call_builtin_type_static(const Address &p_target, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) { + bool is_validated = false; + + // Check if all types are correct. + if (Variant::is_builtin_method_vararg(p_type, p_method)) { + is_validated = true; // Vararg works fine with any argument, since they can be any type. + } else if (p_arguments.size() == Variant::get_builtin_method_argument_count(p_type, p_method)) { + bool all_types_exact = true; + for (int i = 0; i < p_arguments.size(); i++) { + if (!IS_BUILTIN_TYPE(p_arguments[i], Variant::get_builtin_method_argument_type(p_type, p_method, i))) { + all_types_exact = false; + break; + } + } + + is_validated = all_types_exact; + } + + if (!is_validated) { + // Perform regular call. + append(GDScriptFunction::OPCODE_CALL_BUILTIN_STATIC, p_arguments.size() + 1); + for (int i = 0; i < p_arguments.size(); i++) { + append(p_arguments[i]); + } + append(p_target); + append(p_type); + append(p_method); + append(p_arguments.size()); + return; + } + + if (p_target.mode == Address::TEMPORARY) { + Variant::Type result_type = Variant::get_builtin_method_return_type(p_type, p_method); + Variant::Type temp_type = temporaries[p_target.address].type; + if (result_type != temp_type) { + write_type_adjust(p_target, result_type); + } + } + + append(GDScriptFunction::OPCODE_CALL_BUILTIN_TYPE_VALIDATED, 2 + p_arguments.size()); + + for (int i = 0; i < p_arguments.size(); i++) { + append(p_arguments[i]); + } + append(Address()); // No base since it's static. + append(p_target); + append(p_arguments.size()); + append(Variant::get_validated_builtin_method(p_type, p_method)); +} + void GDScriptByteCodeGenerator::write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) { append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL_METHOD_BIND : GDScriptFunction::OPCODE_CALL_METHOD_BIND_RET, 2 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { @@ -1042,12 +1108,12 @@ void GDScriptByteCodeGenerator::write_call_ptrcall(const Address &p_target, cons CASE_TYPE(PLANE); CASE_TYPE(AABB); CASE_TYPE(BASIS); - CASE_TYPE(TRANSFORM); + CASE_TYPE(TRANSFORM3D); CASE_TYPE(COLOR); CASE_TYPE(STRING_NAME); CASE_TYPE(NODE_PATH); CASE_TYPE(RID); - CASE_TYPE(QUAT); + CASE_TYPE(QUATERNION); CASE_TYPE(OBJECT); CASE_TYPE(CALLABLE); CASE_TYPE(SIGNAL); @@ -1118,6 +1184,17 @@ void GDScriptByteCodeGenerator::write_call_script_function(const Address &p_targ append(p_function_name); } +void GDScriptByteCodeGenerator::write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures) { + append(GDScriptFunction::OPCODE_CREATE_LAMBDA, 1 + p_captures.size()); + for (int i = 0; i < p_captures.size(); i++) { + append(p_captures[i]); + } + + append(p_target); + append(p_captures.size()); + append(p_function); +} + void GDScriptByteCodeGenerator::write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) { // Try to find an appropriate constructor. bool all_have_type = true; @@ -1382,8 +1459,8 @@ void GDScriptByteCodeGenerator::write_endfor() { } // Patch break statements. - for (const List<int>::Element *E = current_breaks_to_patch.back()->get().front(); E; E = E->next()) { - patch_jump(E->get()); + for (const int &E : current_breaks_to_patch.back()->get()) { + patch_jump(E); } current_breaks_to_patch.pop_back(); @@ -1417,8 +1494,8 @@ void GDScriptByteCodeGenerator::write_endwhile() { while_jmp_addrs.pop_back(); // Patch break statements. - for (const List<int>::Element *E = current_breaks_to_patch.back()->get().front(); E; E = E->next()) { - patch_jump(E->get()); + for (const int &E : current_breaks_to_patch.back()->get()) { + patch_jump(E); } current_breaks_to_patch.pop_back(); } @@ -1429,8 +1506,8 @@ void GDScriptByteCodeGenerator::start_match() { void GDScriptByteCodeGenerator::start_match_branch() { // Patch continue statements. - for (const List<int>::Element *E = match_continues_to_patch.back()->get().front(); E; E = E->next()) { - patch_jump(E->get()); + for (const int &E : match_continues_to_patch.back()->get()) { + patch_jump(E); } match_continues_to_patch.pop_back(); // Start a new list for next branch. @@ -1439,8 +1516,8 @@ void GDScriptByteCodeGenerator::start_match_branch() { void GDScriptByteCodeGenerator::end_match() { // Patch continue statements. - for (const List<int>::Element *E = match_continues_to_patch.back()->get().front(); E; E = E->next()) { - patch_jump(E->get()); + for (const int &E : match_continues_to_patch.back()->get()) { + patch_jump(E); } match_continues_to_patch.pop_back(); } diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h index 17d681d7bb..3d6fb291ad 100644 --- a/modules/gdscript/gdscript_byte_codegen.h +++ b/modules/gdscript/gdscript_byte_codegen.h @@ -93,6 +93,7 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { Map<Variant::ValidatedUtilityFunction, int> utilities_map; Map<GDScriptUtilityFunctions::FunctionPtr, int> gds_utilities_map; Map<MethodBind *, int> method_bind_map; + Map<GDScriptFunction *, int> lambdas_map; // Lists since these can be nested. List<int> if_jmp_addrs; @@ -293,6 +294,15 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { return pos; } + int get_lambda_function_pos(GDScriptFunction *p_lambda_function) { + if (lambdas_map.has(p_lambda_function)) { + return lambdas_map[p_lambda_function]; + } + int pos = lambdas_map.size(); + lambdas_map[p_lambda_function] = pos; + return pos; + } + void alloc_ptrcall(int p_params) { if (p_params >= ptrcall_max) { ptrcall_max = p_params; @@ -386,6 +396,10 @@ class GDScriptByteCodeGenerator : public GDScriptCodeGenerator { opcodes.push_back(get_method_bind_pos(p_method)); } + void append(GDScriptFunction *p_lambda_function) { + opcodes.push_back(get_lambda_function_pos(p_lambda_function)); + } + void patch_jump(int p_address) { opcodes.write[p_address] = opcodes.size(); } @@ -405,7 +419,7 @@ public: virtual void start_block() override; virtual void end_block() override; - virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCMode p_rpc_mode, const GDScriptDataType &p_return_type) override; + virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCConfig p_rpc_config, const GDScriptDataType &p_return_type) override; virtual GDScriptFunction *write_end() override; #ifdef DEBUG_ENABLED @@ -436,6 +450,7 @@ public: virtual void write_set_member(const Address &p_value, const StringName &p_name) override; virtual void write_get_member(const Address &p_target, const StringName &p_name) override; virtual void write_assign(const Address &p_target, const Address &p_source) override; + virtual void write_assign_with_conversion(const Address &p_target, const Address &p_source) override; virtual void write_assign_true(const Address &p_target) override; virtual void write_assign_false(const Address &p_target) override; virtual void write_assign_default_parameter(const Address &p_dst, const Address &p_src) override; @@ -447,11 +462,13 @@ public: virtual void write_call_utility(const Address &p_target, const StringName &p_function, const Vector<Address> &p_arguments) override; virtual void write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) override; virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) override; + virtual void write_call_builtin_type_static(const Address &p_target, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) override; virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override; virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override; virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override; virtual void write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override; virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override; + virtual void write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures) override; virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) override; virtual void write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) override; virtual void write_construct_typed_array(const Address &p_target, const GDScriptDataType &p_element_type, const Vector<Address> &p_arguments) override; diff --git a/modules/gdscript/gdscript_cache.cpp b/modules/gdscript/gdscript_cache.cpp index 113d36be98..1a844bf241 100644 --- a/modules/gdscript/gdscript_cache.cpp +++ b/modules/gdscript/gdscript_cache.cpp @@ -30,7 +30,7 @@ #include "gdscript_cache.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "core/templates/vector.h" #include "gdscript.h" #include "gdscript_analyzer.h" @@ -134,7 +134,7 @@ Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptP return ref; } GDScriptParser *parser = memnew(GDScriptParser); - ref.instance(); + ref.instantiate(); ref->parser = parser; ref->path = p_path; singleton->parser_map[p_path] = ref.ptr(); @@ -153,9 +153,9 @@ String GDScriptCache::get_source_code(const String &p_path) { ERR_FAIL_COND_V(err, ""); } - int len = f->get_len(); + uint64_t len = f->get_length(); source_file.resize(len + 1); - int r = f->get_buffer(source_file.ptrw(), len); + uint64_t r = f->get_buffer(source_file.ptrw(), len); f->close(); ERR_FAIL_COND_V(r != len, ""); source_file.write[len] = 0; @@ -180,7 +180,7 @@ Ref<GDScript> GDScriptCache::get_shallow_script(const String &p_path, const Stri } Ref<GDScript> script; - script.instance(); + script.instantiate(); script->set_path(p_path, true); script->set_script_path(p_path); script->load_source_code(p_path); diff --git a/modules/gdscript/gdscript_cache.h b/modules/gdscript/gdscript_cache.h index d1d2a2abbf..943638d29f 100644 --- a/modules/gdscript/gdscript_cache.h +++ b/modules/gdscript/gdscript_cache.h @@ -31,7 +31,7 @@ #ifndef GDSCRIPT_CACHE_H #define GDSCRIPT_CACHE_H -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/os/mutex.h" #include "core/templates/hash_map.h" #include "core/templates/set.h" @@ -40,7 +40,7 @@ class GDScriptAnalyzer; class GDScriptParser; -class GDScriptParserRef : public Reference { +class GDScriptParserRef : public RefCounted { public: enum Status { EMPTY, diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h index b377beefdb..ecc86c37f3 100644 --- a/modules/gdscript/gdscript_codegen.h +++ b/modules/gdscript/gdscript_codegen.h @@ -80,7 +80,7 @@ public: virtual void start_block() = 0; virtual void end_block() = 0; - virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCMode p_rpc_mode, const GDScriptDataType &p_return_type) = 0; + virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCConfig p_rpc_config, const GDScriptDataType &p_return_type) = 0; virtual GDScriptFunction *write_end() = 0; #ifdef DEBUG_ENABLED @@ -111,6 +111,7 @@ public: virtual void write_set_member(const Address &p_value, const StringName &p_name) = 0; virtual void write_get_member(const Address &p_target, const StringName &p_name) = 0; virtual void write_assign(const Address &p_target, const Address &p_source) = 0; + virtual void write_assign_with_conversion(const Address &p_target, const Address &p_source) = 0; virtual void write_assign_true(const Address &p_target) = 0; virtual void write_assign_false(const Address &p_target) = 0; virtual void write_assign_default_parameter(const Address &dst, const Address &src) = 0; @@ -122,11 +123,13 @@ public: virtual void write_call_utility(const Address &p_target, const StringName &p_function, const Vector<Address> &p_arguments) = 0; virtual void write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) = 0; virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) = 0; + virtual void write_call_builtin_type_static(const Address &p_target, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; virtual void write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; + virtual void write_lambda(const Address &p_target, GDScriptFunction *p_function, const Vector<Address> &p_captures) = 0; virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) = 0; virtual void write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) = 0; virtual void write_construct_typed_array(const Address &p_target, const GDScriptDataType &p_element_type, const Vector<Address> &p_arguments) = 0; diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 9b718db7cf..fe827a5b72 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -107,7 +107,7 @@ GDScriptDataType GDScriptCompiler::_gdtype_from_datatype(const GDScriptParser::D // Locate class by constructing the path to it and following that path GDScriptParser::ClassNode *class_type = p_datatype.class_type; if (class_type) { - if (class_type->fqcn.begins_with(main_script->path) || (!main_script->name.is_empty() && class_type->fqcn.begins_with(main_script->name))) { + if ((!main_script->path.is_empty() && class_type->fqcn.begins_with(main_script->path)) || (!main_script->name.is_empty() && class_type->fqcn.begins_with(main_script->name))) { // Local class. List<StringName> names; while (class_type->outer) { @@ -537,39 +537,44 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee); if (subscript->is_attribute) { - GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base); - if (r_error) { - return GDScriptCodeGenerator::Address(); - } - if (within_await) { - gen->write_call_async(result, base, call->function_name, arguments); - } else if (base.type.has_type && base.type.kind != GDScriptDataType::BUILTIN) { - // Native method, use faster path. - StringName class_name; - if (base.type.kind == GDScriptDataType::NATIVE) { - class_name = base.type.native_type; - } else { - class_name = base.type.native_type == StringName() ? base.type.script_type->get_instance_base_type() : base.type.native_type; + // May be static built-in method call. + if (!call->is_super && subscript->base->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name) < Variant::VARIANT_MAX) { + gen->write_call_builtin_type_static(result, GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name), subscript->attribute->name, arguments); + } else { + GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base); + if (r_error) { + return GDScriptCodeGenerator::Address(); } - if (ClassDB::class_exists(class_name) && ClassDB::has_method(class_name, call->function_name)) { - MethodBind *method = ClassDB::get_method(class_name, call->function_name); - if (_have_exact_arguments(method, arguments)) { - // Exact arguments, use ptrcall. - gen->write_call_ptrcall(result, base, method, arguments); + if (within_await) { + gen->write_call_async(result, base, call->function_name, arguments); + } else if (base.type.has_type && base.type.kind != GDScriptDataType::BUILTIN) { + // Native method, use faster path. + StringName class_name; + if (base.type.kind == GDScriptDataType::NATIVE) { + class_name = base.type.native_type; } else { - // Not exact arguments, but still can use method bind call. - gen->write_call_method_bind(result, base, method, arguments); + class_name = base.type.native_type == StringName() ? base.type.script_type->get_instance_base_type() : base.type.native_type; } + if (ClassDB::class_exists(class_name) && ClassDB::has_method(class_name, call->function_name)) { + MethodBind *method = ClassDB::get_method(class_name, call->function_name); + if (_have_exact_arguments(method, arguments)) { + // Exact arguments, use ptrcall. + gen->write_call_ptrcall(result, base, method, arguments); + } else { + // Not exact arguments, but still can use method bind call. + gen->write_call_method_bind(result, base, method, arguments); + } + } else { + gen->write_call(result, base, call->function_name, arguments); + } + } else if (base.type.has_type && base.type.kind == GDScriptDataType::BUILTIN) { + gen->write_call_builtin_type(result, base, base.type.builtin_type, call->function_name, arguments); } else { gen->write_call(result, base, call->function_name, arguments); } - } else if (base.type.has_type && base.type.kind == GDScriptDataType::BUILTIN) { - gen->write_call_builtin_type(result, base, base.type.builtin_type, call->function_name, arguments); - } else { - gen->write_call(result, base, call->function_name, arguments); - } - if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) { - gen->pop_temporary(); + if (base.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + gen->pop_temporary(); + } } } else { _set_error("Cannot call something that isn't a function.", call->callee); @@ -966,6 +971,9 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } else { gen->write_set(prev_base, key, assigned); } + if (key.mode == GDScriptCodeGenerator::Address::TEMPORARY) { + gen->pop_temporary(); + } if (assigned.mode == GDScriptCodeGenerator::Address::TEMPORARY) { gen->pop_temporary(); } @@ -973,8 +981,7 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code assigned = prev_base; // Set back the values into their bases. - for (List<ChainInfo>::Element *E = set_chain.front(); E; E = E->next()) { - const ChainInfo &info = E->get(); + for (const ChainInfo &info : set_chain) { if (!info.is_named) { gen->write_set(info.base, info.key, assigned); if (info.key.mode == GDScriptCodeGenerator::Address::TEMPORARY) { @@ -1076,7 +1083,11 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code gen->write_call(GDScriptCodeGenerator::Address(), GDScriptCodeGenerator::Address(GDScriptCodeGenerator::Address::SELF), setter_function, args); } else { // Just assign. - gen->write_assign(target, op_result); + if (assignment->use_conversion_assign) { + gen->write_assign_with_conversion(target, op_result); + } else { + gen->write_assign(target, op_result); + } } if (op_result.mode == GDScriptCodeGenerator::Address::TEMPORARY) { @@ -1091,6 +1102,34 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code } return GDScriptCodeGenerator::Address(); // Assignment does not return a value. } 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())); + + Vector<GDScriptCodeGenerator::Address> captures; + captures.resize(lambda->captures.size()); + for (int i = 0; i < lambda->captures.size(); i++) { + captures.write[i] = _parse_expression(codegen, r_error, lambda->captures[i]); + if (r_error) { + return GDScriptCodeGenerator::Address(); + } + } + + GDScriptFunction *function = _parse_function(r_error, codegen.script, codegen.class_node, lambda->function, false, true); + if (r_error) { + return GDScriptCodeGenerator::Address(); + } + + gen->write_lambda(result, function, captures); + + for (int i = 0; i < captures.size(); i++) { + if (captures[i].mode == GDScriptCodeGenerator::Address::TEMPORARY) { + gen->pop_temporary(); + } + } + + return result; + } break; default: { ERR_FAIL_V_MSG(GDScriptCodeGenerator::Address(), "Bug in bytecode compiler, unexpected node in parse tree while parsing expression."); // Unreachable code. } break; @@ -1756,7 +1795,11 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui if (error) { return error; } - gen->write_assign(local, src_address); + if (lv->use_conversion_assign) { + gen->write_assign_with_conversion(local, src_address); + } else { + gen->write_assign(local, src_address); + } if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) { codegen.generator->pop_temporary(); } @@ -1804,8 +1847,8 @@ Error GDScriptCompiler::_parse_block(CodeGen &codegen, const GDScriptParser::Sui return OK; } -Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready) { - Error error = OK; +GDScriptFunction *GDScriptCompiler::_parse_function(Error &r_error, GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready, bool p_for_lambda) { + r_error = OK; CodeGen codegen; codegen.generator = memnew(GDScriptByteCodeGenerator); @@ -1815,16 +1858,20 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser StringName func_name; bool is_static = false; - MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; + MultiplayerAPI::RPCConfig rpc_config; GDScriptDataType return_type; return_type.has_type = true; return_type.kind = GDScriptDataType::BUILTIN; return_type.builtin_type = Variant::NIL; if (p_func) { - func_name = p_func->identifier->name; + if (p_func->identifier) { + func_name = p_func->identifier->name; + } else { + func_name = "<anonymous lambda>"; + } is_static = p_func->is_static; - rpc_mode = p_func->rpc_mode; + rpc_config = p_func->rpc_config; return_type = _gdtype_from_datatype(p_func->get_datatype(), p_script); } else { if (p_for_ready) { @@ -1835,7 +1882,7 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser } codegen.function_name = func_name; - codegen.generator->write_start(p_script, func_name, is_static, rpc_mode, return_type); + codegen.generator->write_start(p_script, func_name, is_static, rpc_config, return_type); int optional_parameters = 0; @@ -1853,11 +1900,11 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser } // Parse initializer if applies. - bool is_implicit_initializer = !p_for_ready && !p_func; - bool is_initializer = p_func && String(p_func->identifier->name) == GDScriptLanguage::get_singleton()->strings._init; - bool is_for_ready = p_for_ready || (p_func && String(p_func->identifier->name) == "_ready"); + bool is_implicit_initializer = !p_for_ready && !p_func && !p_for_lambda; + bool is_initializer = p_func && !p_for_lambda && String(p_func->identifier->name) == GDScriptLanguage::get_singleton()->strings._init; + bool is_for_ready = p_for_ready || (p_func && !p_for_lambda && String(p_func->identifier->name) == "_ready"); - if (is_implicit_initializer || is_for_ready) { + if (!p_for_lambda && (is_implicit_initializer || is_for_ready)) { // Initialize class fields. for (int i = 0; i < p_class->members.size(); i++) { if (p_class->members[i].type != GDScriptParser::ClassNode::Member::VARIABLE) { @@ -1884,13 +1931,17 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser codegen.generator->write_construct_array(dst_address, Vector<GDScriptCodeGenerator::Address>()); } } - GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, error, field->initializer, false, true); - if (error) { + GDScriptCodeGenerator::Address src_address = _parse_expression(codegen, r_error, field->initializer, false, true); + if (r_error) { memdelete(codegen.generator); - return error; + return nullptr; } - codegen.generator->write_assign(dst_address, src_address); + if (field->use_conversion_assign) { + codegen.generator->write_assign_with_conversion(dst_address, src_address); + } else { + codegen.generator->write_assign(dst_address, src_address); + } if (src_address.mode == GDScriptCodeGenerator::Address::TEMPORARY) { codegen.generator->pop_temporary(); } @@ -1914,10 +1965,10 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser codegen.generator->start_parameters(); for (int i = p_func->parameters.size() - optional_parameters; i < p_func->parameters.size(); i++) { const GDScriptParser::ParameterNode *parameter = p_func->parameters[i]; - GDScriptCodeGenerator::Address src_addr = _parse_expression(codegen, error, parameter->default_value, true); - if (error) { + GDScriptCodeGenerator::Address src_addr = _parse_expression(codegen, r_error, parameter->default_value, true); + if (r_error) { memdelete(codegen.generator); - return error; + return nullptr; } GDScriptCodeGenerator::Address dst_addr = codegen.parameters[parameter->identifier->name]; codegen.generator->write_assign_default_parameter(dst_addr, src_addr); @@ -1928,10 +1979,10 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser codegen.generator->end_parameters(); } - Error err = _parse_block(codegen, p_func->body); - if (err) { + r_error = _parse_block(codegen, p_func->body); + if (r_error) { memdelete(codegen.generator); - return err; + return nullptr; } } @@ -1957,6 +2008,10 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser signature += "::" + String(func_name); } + if (p_for_lambda) { + signature += "(lambda)"; + } + codegen.generator->set_signature(signature); } #endif @@ -1964,8 +2019,10 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser if (p_func) { codegen.generator->set_initial_line(p_func->start_line); #ifdef TOOLS_ENABLED - p_script->member_lines[func_name] = p_func->start_line; - p_script->doc_functions[func_name] = p_func->doc_description; + if (!p_for_lambda) { + p_script->member_lines[func_name] = p_func->start_line; + p_script->doc_functions[func_name] = p_func->doc_description; + } #endif } else { codegen.generator->set_initial_line(0); @@ -1994,11 +2051,13 @@ Error GDScriptCompiler::_parse_function(GDScript *p_script, const GDScriptParser #endif } - p_script->member_functions[func_name] = gd_function; + if (!p_for_lambda) { + p_script->member_functions[func_name] = gd_function; + } memdelete(codegen.generator); - return OK; + return gd_function; } Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::VariableNode *p_variable, bool p_is_setter) { @@ -2028,7 +2087,7 @@ Error GDScriptCompiler::_parse_setter_getter(GDScript *p_script, const GDScriptP return_type = _gdtype_from_datatype(p_variable->get_datatype(), p_script); } - codegen.generator->write_start(p_script, func_name, false, p_variable->rpc_mode, return_type); + codegen.generator->write_start(p_script, func_name, false, MultiplayerAPI::RPCConfig(), return_type); if (p_is_setter) { uint32_t par_addr = codegen.generator->add_parameter(p_variable->setter_parameter->name, false, _gdtype_from_datatype(p_variable->get_datatype())); @@ -2163,7 +2222,7 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar if (err) { return err; } - if (base.is_null() && !base->is_valid()) { + if (base.is_null() || !base->is_valid()) { return ERR_COMPILATION_FAILED; } } @@ -2208,7 +2267,6 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar } break; } - minfo.rpc_mode = variable->rpc_mode; minfo.data_type = _gdtype_from_datatype(variable->get_datatype(), p_script); PropertyInfo prop_info = minfo.data_type; @@ -2222,9 +2280,10 @@ Error GDScriptCompiler::_parse_class_level(GDScript *p_script, const GDScriptPar } prop_info.hint = export_info.hint; prop_info.hint_string = export_info.hint_string; - prop_info.usage = export_info.usage; + prop_info.usage = export_info.usage | PROPERTY_USAGE_SCRIPT_VARIABLE; + } else { + prop_info.usage = PROPERTY_USAGE_SCRIPT_VARIABLE; } - prop_info.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; #ifdef TOOLS_ENABLED p_script->doc_variables[name] = variable->doc_description; #endif @@ -2391,7 +2450,8 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa if (!has_ready && function->identifier->name == "_ready") { has_ready = true; } - Error err = _parse_function(p_script, p_class, function); + Error err = OK; + _parse_function(err, p_script, p_class, function); if (err) { return err; } @@ -2416,7 +2476,8 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa { // Create an implicit constructor in any case. - Error err = _parse_function(p_script, p_class, nullptr); + Error err = OK; + _parse_function(err, p_script, p_class, nullptr); if (err) { return err; } @@ -2424,7 +2485,8 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa if (!has_ready && p_class->onready_used) { //create a _ready constructor - Error err = _parse_function(p_script, p_class, nullptr, true); + Error err = OK; + _parse_function(err, p_script, p_class, nullptr, true); if (err) { return err; } @@ -2448,7 +2510,7 @@ Error GDScriptCompiler::_parse_class_blocks(GDScript *p_script, const GDScriptPa p_script->placeholders.erase(psi); //remove placeholder GDScriptInstance *instance = memnew(GDScriptInstance); - instance->base_ref = Object::cast_to<Reference>(E->get()); + instance->base_ref_counted = Object::cast_to<RefCounted>(E->get()); instance->members.resize(p_script->member_indices.size()); instance->script = Ref<GDScript>(p_script); instance->owner = E->get(); @@ -2523,7 +2585,7 @@ void GDScriptCompiler::_make_scripts(GDScript *p_script, const GDScriptParser::C if (orphan_subclass.is_valid()) { subclass = orphan_subclass; } else { - subclass.instance(); + subclass.instantiate(); } } diff --git a/modules/gdscript/gdscript_compiler.h b/modules/gdscript/gdscript_compiler.h index c405eadb07..7d5bee93ac 100644 --- a/modules/gdscript/gdscript_compiler.h +++ b/modules/gdscript/gdscript_compiler.h @@ -128,7 +128,7 @@ class GDScriptCompiler { GDScriptCodeGenerator::Address _parse_match_pattern(CodeGen &codegen, Error &r_error, const GDScriptParser::PatternNode *p_pattern, const GDScriptCodeGenerator::Address &p_value_addr, const GDScriptCodeGenerator::Address &p_type_addr, const GDScriptCodeGenerator::Address &p_previous_test, bool p_is_first, bool p_is_nested); void _add_locals_in_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block); Error _parse_block(CodeGen &codegen, const GDScriptParser::SuiteNode *p_block, bool p_add_locals = true); - Error _parse_function(GDScript *p_script, const GDScriptParser::ClassNode *p_class, const GDScriptParser::FunctionNode *p_func, bool p_for_ready = false); + 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); diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp index 0d0afcc741..1acb9ceddc 100644 --- a/modules/gdscript/gdscript_disassembler.cpp +++ b/modules/gdscript/gdscript_disassembler.cpp @@ -397,7 +397,7 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { text += DADDR(1 + argc); text += " = "; - text += "<unkown type>("; + text += "<unknown type>("; for (int i = 0; i < argc; i++) { if (i > 0) { text += ", "; @@ -542,6 +542,28 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { incr = 5 + argc; } break; + case OPCODE_CALL_BUILTIN_STATIC: { + Variant::Type type = (Variant::Type)_code_ptr[ip + 1 + instr_var_args]; + int argc = _code_ptr[ip + 3 + instr_var_args]; + + text += "call built-in method static "; + text += DADDR(1 + argc); + text += " = "; + text += Variant::get_type_name(type); + text += "."; + text += _global_names_ptr[_code_ptr[ip + 2 + instr_var_args]].operator String(); + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) { + text += ", "; + } + text += DADDR(1 + i); + } + text += ")"; + + incr += 5 + argc; + } break; case OPCODE_CALL_PTRCALL_NO_RETURN: { text += "call-ptrcall (no return) "; @@ -598,12 +620,12 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { DISASSEMBLE_PTRCALL(PLANE); DISASSEMBLE_PTRCALL(AABB); DISASSEMBLE_PTRCALL(BASIS); - DISASSEMBLE_PTRCALL(TRANSFORM); + DISASSEMBLE_PTRCALL(TRANSFORM3D); DISASSEMBLE_PTRCALL(COLOR); DISASSEMBLE_PTRCALL(STRING_NAME); DISASSEMBLE_PTRCALL(NODE_PATH); DISASSEMBLE_PTRCALL(RID); - DISASSEMBLE_PTRCALL(QUAT); + DISASSEMBLE_PTRCALL(QUATERNION); DISASSEMBLE_PTRCALL(OBJECT); DISASSEMBLE_PTRCALL(CALLABLE); DISASSEMBLE_PTRCALL(SIGNAL); @@ -666,7 +688,7 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { int argc = _code_ptr[ip + 1 + instr_var_args]; text += DADDR(1 + argc) + " = "; - text += "<unkown function>"; + text += "<unknown function>"; text += "("; for (int i = 0; i < argc; i++) { @@ -721,7 +743,7 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { text += "await "; text += DADDR(1); - incr += 2; + incr = 2; } break; case OPCODE_AWAIT_RESUME: { text += "await resume "; @@ -729,6 +751,25 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { incr = 2; } break; + case OPCODE_CREATE_LAMBDA: { + int captures_count = _code_ptr[ip + 1 + instr_var_args]; + GDScriptFunction *lambda = _lambdas_ptr[_code_ptr[ip + 2 + instr_var_args]]; + + text += DADDR(1 + captures_count); + text += "create lambda from "; + text += lambda->name.operator String(); + text += "function, captures ("; + + for (int i = 0; i < captures_count; i++) { + if (i > 0) { + text += ", "; + } + text += DADDR(1 + i); + } + text += ")"; + + incr = 3 + captures_count; + } break; case OPCODE_JUMP: { text += "jump "; text += itos(_code_ptr[ip + 1]); @@ -916,7 +957,7 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { DISASSEMBLE_TYPE_ADJUST(VECTOR3I); DISASSEMBLE_TYPE_ADJUST(TRANSFORM2D); DISASSEMBLE_TYPE_ADJUST(PLANE); - DISASSEMBLE_TYPE_ADJUST(QUAT); + DISASSEMBLE_TYPE_ADJUST(QUATERNION); DISASSEMBLE_TYPE_ADJUST(AABB); DISASSEMBLE_TYPE_ADJUST(BASIS); DISASSEMBLE_TYPE_ADJUST(TRANSFORM); diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index ae3b16a9d7..2e570d5a5b 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -32,7 +32,7 @@ #include "core/config/engine.h" #include "core/core_constants.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "gdscript_analyzer.h" #include "gdscript_compiler.h" #include "gdscript_parser.h" @@ -104,7 +104,7 @@ Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const Str _template = _get_processed_template(_template, p_base_class_name); Ref<GDScript> script; - script.instance(); + script.instantiate(); script->set_source_code(_template); return script; @@ -131,7 +131,7 @@ static void get_function_names_recursively(const GDScriptParser::ClassNode *p_cl } } -bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { +bool GDScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { GDScriptParser parser; GDScriptAnalyzer analyzer(&parser); @@ -141,8 +141,8 @@ bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int & } #ifdef DEBUG_ENABLED if (r_warnings) { - for (const List<GDScriptWarning>::Element *E = parser.get_warnings().front(); E; E = E->next()) { - const GDScriptWarning &warn = E->get(); + for (const GDScriptWarning &E : parser.get_warnings()) { + const GDScriptWarning &warn = E; ScriptLanguage::Warning w; w.start_line = warn.start_line; w.end_line = warn.end_line; @@ -156,10 +156,16 @@ bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int & } #endif if (err) { - GDScriptParser::ParserError parse_error = parser.get_errors().front()->get(); - r_line_error = parse_error.line; - r_col_error = parse_error.column; - r_test_error = parse_error.message; + if (r_errors) { + for (const GDScriptParser::ParserError &E : parser.get_errors()) { + const GDScriptParser::ParserError &pe = E; + ScriptLanguage::ScriptError e; + e.line = pe.line; + e.column = pe.column; + e.message = pe.message; + r_errors->push_back(e); + } + } return false; } else { const GDScriptParser::ClassNode *cl = parser.get_tree(); @@ -313,9 +319,9 @@ void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p List<Pair<StringName, int>> locals; f->debug_get_stack_member_state(*_call_stack[l].line, &locals); - for (List<Pair<StringName, int>>::Element *E = locals.front(); E; E = E->next()) { - p_locals->push_back(E->get().first); - p_values->push_back(_call_stack[l].stack[E->get().second]); + for (const Pair<StringName, int> &E : locals) { + p_locals->push_back(E.first); + p_values->push_back(_call_stack[l].stack[E.second]); } } @@ -415,8 +421,8 @@ void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const List<StringName> functions; GDScriptUtilityFunctions::get_function_list(&functions); - for (const List<StringName>::Element *E = functions.front(); E; E = E->next()) { - p_functions->push_back(GDScriptUtilityFunctions::get_function_info(E->get())); + for (const StringName &E : functions) { + p_functions->push_back(GDScriptUtilityFunctions::get_function_info(E)); } // Not really "functions", but show in documentation. @@ -451,12 +457,12 @@ void GDScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_const Pair<String, Variant> infinity; infinity.first = "INF"; - infinity.second = Math_INF; + infinity.second = INFINITY; p_constants->push_back(infinity); Pair<String, Variant> nan; nan.first = "NAN"; - nan.second = Math_NAN; + nan.second = NAN; p_constants->push_back(nan); } @@ -542,7 +548,7 @@ static String _make_arguments_hint(const MethodInfo &p_info, int p_arg_idx, bool int def_args = p_info.arguments.size() - p_info.default_arguments.size(); int i = 0; - for (const List<PropertyInfo>::Element *E = p_info.arguments.front(); E; E = E->next()) { + for (const PropertyInfo &E : p_info.arguments) { if (i > 0) { arghint += ", "; } @@ -550,7 +556,7 @@ static String _make_arguments_hint(const MethodInfo &p_info, int p_arg_idx, bool if (i == p_arg_idx) { arghint += String::chr(0xFFFF); } - arghint += E->get().name + ": " + _get_visual_datatype(E->get(), true); + arghint += E.name + ": " + _get_visual_datatype(E, true); if (i - def_args >= 0) { arghint += String(" = ") + p_info.default_arguments[i - def_args].get_construct_string(); @@ -656,11 +662,11 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a r_result.insert(node.display, node); List<StringName> node_types; ClassDB::get_inheriters_from_class("Node", &node_types); - for (const List<StringName>::Element *E = node_types.front(); E != nullptr; E = E->next()) { - if (!ClassDB::is_class_exposed(E->get())) { + for (const StringName &E : node_types) { + if (!ClassDB::is_class_exposed(E)) { continue; } - ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CLASS); + ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CLASS); r_result.insert(option.display, option); } } @@ -669,9 +675,9 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a static void _list_available_types(bool p_inherit_only, GDScriptParser::CompletionContext &p_context, Map<String, ScriptCodeCompletionOption> &r_result) { List<StringName> native_types; ClassDB::get_class_list(&native_types); - for (const List<StringName>::Element *E = native_types.front(); E != nullptr; E = E->next()) { - if (ClassDB::is_class_exposed(E->get()) && !Engine::get_singleton()->has_singleton(E->get())) { - ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CLASS); + for (const StringName &E : native_types) { + if (ClassDB::is_class_exposed(E) && !Engine::get_singleton()->has_singleton(E)) { + ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CLASS); r_result.insert(option.display, option); } } @@ -681,8 +687,8 @@ static void _list_available_types(bool p_inherit_only, GDScriptParser::Completio // Native enums from base class List<StringName> enums; ClassDB::get_enum_list(p_context.current_class->base_type.native_type, &enums); - for (const List<StringName>::Element *E = enums.front(); E != nullptr; E = E->next()) { - ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_ENUM); + for (const StringName &E : enums) { + ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_ENUM); r_result.insert(option.display, option); } } @@ -719,8 +725,8 @@ static void _list_available_types(bool p_inherit_only, GDScriptParser::Completio // Global scripts List<StringName> global_classes; ScriptServer::get_global_class_list(&global_classes); - for (const List<StringName>::Element *E = global_classes.front(); E != nullptr; E = E->next()) { - ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CLASS); + for (const StringName &E : global_classes) { + ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CLASS); r_result.insert(option.display, option); } @@ -738,7 +744,13 @@ static void _list_available_types(bool p_inherit_only, GDScriptParser::Completio static void _find_identifiers_in_suite(const GDScriptParser::SuiteNode *p_suite, Map<String, ScriptCodeCompletionOption> &r_result) { for (int i = 0; i < p_suite->locals.size(); i++) { - ScriptCodeCompletionOption option(p_suite->locals[i].name, ScriptCodeCompletionOption::KIND_VARIABLE); + ScriptCodeCompletionOption option; + if (p_suite->locals[i].type == GDScriptParser::SuiteNode::Local::CONSTANT) { + option = ScriptCodeCompletionOption(p_suite->locals[i].name, ScriptCodeCompletionOption::KIND_CONSTANT); + option.default_value = p_suite->locals[i].constant->initializer->reduced_value; + } else { + option = ScriptCodeCompletionOption(p_suite->locals[i].name, ScriptCodeCompletionOption::KIND_VARIABLE); + } r_result.insert(option.display, option); } if (p_suite->parent_block) { @@ -853,8 +865,8 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base if (!_static) { List<PropertyInfo> members; scr->get_script_property_list(&members); - for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { - ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER); + for (const PropertyInfo &E : members) { + ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_MEMBER); r_result.insert(option.display, option); } } @@ -867,20 +879,20 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base List<MethodInfo> signals; scr->get_script_signal_list(&signals); - for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { - ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_SIGNAL); + for (const MethodInfo &E : signals) { + ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_SIGNAL); r_result.insert(option.display, option); } } List<MethodInfo> methods; scr->get_script_method_list(&methods); - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().name.begins_with("@")) { + for (const MethodInfo &E : methods) { + if (E.name.begins_with("@")) { continue; } - ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION); - if (E->get().arguments.size()) { + ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_FUNCTION); + if (E.arguments.size()) { option.insert_text += "("; } else { option.insert_text += "()"; @@ -908,22 +920,22 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base if (!p_only_functions) { List<String> constants; ClassDB::get_integer_constant_list(type, &constants); - for (List<String>::Element *E = constants.front(); E; E = E->next()) { - ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CONSTANT); + for (const String &E : constants) { + ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CONSTANT); r_result.insert(option.display, option); } if (!_static || Engine::get_singleton()->has_singleton(type)) { List<PropertyInfo> pinfo; ClassDB::get_property_list(type, &pinfo); - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) { + for (const PropertyInfo &E : pinfo) { + if (E.usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) { continue; } - if (E->get().name.find("/") != -1) { + if (E.name.find("/") != -1) { continue; } - ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER); + ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_MEMBER); r_result.insert(option.display, option); } } @@ -933,12 +945,12 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base List<MethodInfo> methods; bool is_autocompleting_getters = GLOBAL_GET("debug/gdscript/completion/autocomplete_setters_and_getters").booleanize(); ClassDB::get_method_list(type, &methods, false, !is_autocompleting_getters); - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().name.begins_with("_")) { + for (const MethodInfo &E : methods) { + if (E.name.begins_with("_")) { continue; } - ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION); - if (E->get().arguments.size()) { + ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_FUNCTION); + if (E.arguments.size()) { option.insert_text += "("; } else { option.insert_text += "()"; @@ -965,9 +977,9 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base tmp.get_property_list(&members); } - for (List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { - if (String(E->get().name).find("/") == -1) { - ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_MEMBER); + for (const PropertyInfo &E : members) { + if (String(E.name).find("/") == -1) { + ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_MEMBER); r_result.insert(option.display, option); } } @@ -975,9 +987,9 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base List<MethodInfo> methods; tmp.get_method_list(&methods); - for (const List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - ScriptCodeCompletionOption option(E->get().name, ScriptCodeCompletionOption::KIND_FUNCTION); - if (E->get().arguments.size()) { + for (const MethodInfo &E : methods) { + ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_FUNCTION); + if (E.arguments.size()) { option.insert_text += "("; } else { option.insert_text += "()"; @@ -1007,9 +1019,9 @@ static void _find_identifiers(GDScriptParser::CompletionContext &p_context, bool List<StringName> functions; GDScriptUtilityFunctions::get_function_list(&functions); - for (const List<StringName>::Element *E = functions.front(); E; E = E->next()) { - MethodInfo function = GDScriptUtilityFunctions::get_function_info(E->get()); - ScriptCodeCompletionOption option(String(E->get()), ScriptCodeCompletionOption::KIND_FUNCTION); + for (const StringName &E : functions) { + MethodInfo function = GDScriptUtilityFunctions::get_function_info(E); + ScriptCodeCompletionOption option(String(E), ScriptCodeCompletionOption::KIND_FUNCTION); if (function.arguments.size() || (function.flags & METHOD_FLAG_VARARG)) { option.insert_text += "("; } else { @@ -1023,7 +1035,7 @@ static void _find_identifiers(GDScriptParser::CompletionContext &p_context, bool } static const char *_type_names[Variant::VARIANT_MAX] = { - "null", "bool", "int", "float", "String", "StringName", "Vector2", "Vector2i", "Rect2", "Rect2i", "Vector3", "Vector3i", "Transform2D", "Plane", "Quat", "AABB", "Basis", "Transform", + "null", "bool", "int", "float", "String", "StringName", "Vector2", "Vector2i", "Rect2", "Rect2i", "Vector3", "Vector3i", "Transform2D", "Plane", "Quaternion", "AABB", "Basis", "Transform3D", "Color", "NodePath", "RID", "Signal", "Callable", "Object", "Dictionary", "Array", "PackedByteArray", "PackedInt32Array", "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray", "PackedVector2Array", "PackedVector3Array", "PackedColorArray" }; @@ -1756,9 +1768,9 @@ static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, StringName real_native = GDScriptParser::get_real_class_name(base_type.native_type); MethodInfo info; if (ClassDB::get_method_info(real_native, p_context.current_function->identifier->name, &info)) { - for (const List<PropertyInfo>::Element *E = info.arguments.front(); E; E = E->next()) { - if (E->get().name == p_identifier) { - r_type = _type_from_property(E->get()); + for (const PropertyInfo &E : info.arguments) { + if (E.name == p_identifier) { + r_type = _type_from_property(E); return true; } } @@ -1920,8 +1932,7 @@ static bool _guess_identifier_type_from_base(GDScriptParser::CompletionContext & if (!is_static) { List<PropertyInfo> members; scr->get_script_property_list(&members); - for (const List<PropertyInfo>::Element *E = members.front(); E; E = E->next()) { - const PropertyInfo &prop = E->get(); + for (const PropertyInfo &prop : members) { if (prop.name == p_identifier) { r_type = _type_from_property(prop); return true; @@ -2084,8 +2095,7 @@ static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContex if (scr.is_valid()) { List<MethodInfo> methods; scr->get_script_method_list(&methods); - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - MethodInfo &mi = E->get(); + for (const MethodInfo &mi : methods) { if (mi.name == p_method) { r_type = _type_from_property(mi.return_val); return true; @@ -2125,8 +2135,7 @@ static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContex List<MethodInfo> methods; tmp.get_method_list(&methods); - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - MethodInfo &mi = E->get(); + for (const MethodInfo &mi : methods) { if (mi.name == p_method) { r_type = _type_from_property(mi.return_val); return true; @@ -2171,8 +2180,8 @@ static void _find_enumeration_candidates(GDScriptParser::CompletionContext &p_co List<StringName> enum_constants; ClassDB::get_enum_constants(class_name, enum_name, &enum_constants); - for (List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) { - String candidate = class_name + "." + E->get(); + for (const StringName &E : enum_constants) { + String candidate = class_name + "." + E; ScriptCodeCompletionOption option(candidate, ScriptCodeCompletionOption::KIND_ENUM); r_result.insert(option.display, option); } @@ -2216,8 +2225,8 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c if (obj) { List<String> options; obj->get_argument_options(p_method, p_argidx, &options); - for (List<String>::Element *F = options.front(); F; F = F->next()) { - ScriptCodeCompletionOption option(F->get(), ScriptCodeCompletionOption::KIND_FUNCTION); + for (const String &F : options) { + ScriptCodeCompletionOption option(F, ScriptCodeCompletionOption::KIND_FUNCTION); r_result.insert(option.display, option); } } @@ -2238,8 +2247,8 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - String s = E->get().name; + for (const PropertyInfo &E : props) { + String s = E.name; if (!s.begins_with("autoload/")) { continue; } @@ -2254,8 +2263,8 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c // Get input actions List<PropertyInfo> props; ProjectSettings::get_singleton()->get_property_list(&props); - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - String s = E->get().name; + for (const PropertyInfo &E : props) { + String s = E.name; if (!s.begins_with("input/")) { continue; } @@ -2279,9 +2288,9 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c List<MethodInfo> methods; base.get_method_list(&methods); - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().name == p_method) { - r_arghint = _make_arguments_hint(E->get(), p_argidx); + for (const MethodInfo &E : methods) { + if (E.name == p_method) { + r_arghint = _make_arguments_hint(E, p_argidx); return; } } @@ -2328,14 +2337,14 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c Variant::get_constructor_list(GDScriptParser::get_builtin_type(call->function_name), &constructors); int i = 0; - for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) { - if (p_argidx >= E->get().arguments.size()) { + for (const MethodInfo &E : constructors) { + if (p_argidx >= E.arguments.size()) { continue; } if (i > 0) { r_arghint += "\n"; } - r_arghint += _make_arguments_hint(E->get(), p_argidx); + r_arghint += _make_arguments_hint(E, p_argidx); i++; } return; @@ -2372,7 +2381,7 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c r_forced = r_result.size() > 0; } -Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) { +::Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) { const String quote_style = EDITOR_DEF("text_editor/completion/use_single_quotes", false) ? "'" : "\""; GDScriptParser parser; @@ -2394,9 +2403,9 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path case GDScriptParser::COMPLETION_ANNOTATION: { List<MethodInfo> annotations; parser.get_annotation_list(&annotations); - for (const List<MethodInfo>::Element *E = annotations.front(); E != nullptr; E = E->next()) { - ScriptCodeCompletionOption option(E->get().name.substr(1), ScriptCodeCompletionOption::KIND_PLAIN_TEXT); - if (E->get().arguments.size() > 0) { + for (const MethodInfo &E : annotations) { + ScriptCodeCompletionOption option(E.name.substr(1), ScriptCodeCompletionOption::KIND_PLAIN_TEXT); + if (E.arguments.size() > 0) { option.insert_text += "("; } options.insert(option.display, option); @@ -2414,10 +2423,10 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path case GDScriptParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: { List<StringName> constants; Variant::get_constants_for_type(completion_context.builtin_type, &constants); - for (const List<StringName>::Element *E = constants.front(); E != nullptr; E = E->next()) { - ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_CONSTANT); + for (const StringName &E : constants) { + ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CONSTANT); bool valid = false; - Variant default_value = Variant::get_constant_value(completion_context.builtin_type, E->get(), &valid); + Variant default_value = Variant::get_constant_value(completion_context.builtin_type, E, &valid); if (valid) { option.default_value = default_value; } @@ -2594,8 +2603,7 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path List<MethodInfo> virtual_methods; ClassDB::get_virtual_methods(class_name, &virtual_methods); - for (List<MethodInfo>::Element *E = virtual_methods.front(); E; E = E->next()) { - MethodInfo &mi = E->get(); + for (const MethodInfo &mi : virtual_methods) { String method_hint = mi.name; if (method_hint.find(":") != -1) { method_hint = method_hint.get_slice(":", 0); @@ -2644,8 +2652,8 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path List<String> opts; p_owner->get_argument_options("get_node", 0, &opts); - for (List<String>::Element *E = opts.front(); E; E = E->next()) { - String opt = E->get().strip_edges(); + for (const String &E : opts) { + String opt = E.strip_edges(); if (opt.is_quoted()) { r_forced = true; String idopt = opt.unquote(); @@ -2787,6 +2795,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co if (base_type.class_type->has_member(p_symbol)) { r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION; r_result.location = base_type.class_type->get_member(p_symbol).get_line(); + r_result.class_path = base_type.script_path; return OK; } base_type = base_type.class_type->base_type; @@ -2829,8 +2838,8 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co List<MethodInfo> virtual_methods; ClassDB::get_virtual_methods(class_name, &virtual_methods, true); - for (List<MethodInfo>::Element *E = virtual_methods.front(); E; E = E->next()) { - if (E->get().name == p_symbol) { + for (const MethodInfo &E : virtual_methods) { + if (E.name == p_symbol) { r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD; r_result.class_name = base_type.native_type; r_result.class_member = p_symbol; @@ -2848,8 +2857,8 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co List<String> constants; ClassDB::get_integer_constant_list(class_name, &constants, true); - for (List<String>::Element *E = constants.front(); E; E = E->next()) { - if (E->get() == p_symbol) { + for (const String &E : constants) { + if (E == p_symbol) { r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT; r_result.class_name = base_type.native_type; r_result.class_member = p_symbol; @@ -2867,7 +2876,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co StringName parent = ClassDB::get_parent_class(class_name); if (parent != StringName()) { if (String(parent).begins_with("_")) { - base_type.native_type = String(parent).right(1); + base_type.native_type = String(parent).substr(1); } else { base_type.native_type = parent; } @@ -2888,7 +2897,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co Variant v; REF v_ref; if (base_type.builtin_type == Variant::OBJECT) { - v_ref.instance(); + v_ref.instantiate(); v = v_ref; } else { Callable::CallError err; @@ -2923,7 +2932,7 @@ static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, co return ERR_CANT_RESOLVE; } -Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result) { +::Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result) { //before parsing, try the usual stuff if (ClassDB::class_exists(p_symbol)) { r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS; @@ -2993,6 +3002,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol is_function = true; [[fallthrough]]; } + case GDScriptParser::COMPLETION_CALL_ARGUMENTS: case GDScriptParser::COMPLETION_IDENTIFIER: { GDScriptParser::DataType base_type; if (context.current_class) { @@ -3025,9 +3035,9 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol if (!is_function) { // Guess in autoloads as singletons. if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) { - const ProjectSettings::AutoloadInfo &singleton = ProjectSettings::get_singleton()->get_autoload(p_symbol); - if (singleton.is_singleton) { - String script = singleton.path; + const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(p_symbol); + if (autoload.is_singleton) { + String script = autoload.path; if (!script.ends_with(".gd")) { // Not a script, try find the script anyway, // may have some success. @@ -3060,7 +3070,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol // proxy class remove the underscore. if (r_result.class_name.begins_with("_")) { - r_result.class_name = r_result.class_name.right(1); + r_result.class_name = r_result.class_name.substr(1); } return OK; } @@ -3070,7 +3080,7 @@ Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol // We cannot determine the exact nature of the identifier here // Otherwise these codes would work StringName enumName = ClassDB::get_integer_constant_enum("@GlobalScope", p_symbol, true); - if (enumName != NULL) { + if (enumName != nullptr) { r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_ENUM; r_result.class_name = "@GlobalScope"; r_result.class_member = enumName; diff --git a/modules/gdscript/gdscript_function.cpp b/modules/gdscript/gdscript_function.cpp index 7b37aa40a2..876c508689 100644 --- a/modules/gdscript/gdscript_function.cpp +++ b/modules/gdscript/gdscript_function.cpp @@ -94,8 +94,7 @@ struct _GDFKCS { void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<StringName, int>> *r_stackvars) const { int oc = 0; Map<StringName, _GDFKC> sdmap; - for (const List<StackDebug>::Element *E = stack_debug.front(); E; E = E->next()) { - const StackDebug &sd = E->get(); + for (const StackDebug &sd : stack_debug) { if (sd.line > p_line) { break; } @@ -131,10 +130,10 @@ void GDScriptFunction::debug_get_stack_member_state(int p_line, List<Pair<String stackpositions.sort(); - for (List<_GDFKCS>::Element *E = stackpositions.front(); E; E = E->next()) { + for (_GDFKCS &E : stackpositions) { Pair<StringName, int> p; - p.first = E->get().id; - p.second = E->get().pos; + p.first = E.id; + p.second = E.pos; r_stackvars->push_back(p); } } @@ -150,6 +149,10 @@ GDScriptFunction::GDScriptFunction() { } GDScriptFunction::~GDScriptFunction() { + for (int i = 0; i < lambdas.size(); i++) { + memdelete(lambdas[i]); + } + #ifdef DEBUG_ENABLED MutexLock lock(GDScriptLanguage::get_singleton()->lock); @@ -258,9 +261,9 @@ Variant GDScriptFunctionState::resume(const Variant &p_arg) { if (completed) { if (first_state.is_valid()) { - first_state->emit_signal("completed", ret); + first_state->emit_signal(SNAME("completed"), ret); } else { - emit_signal("completed", ret); + emit_signal(SNAME("completed"), ret); } #ifdef DEBUG_ENABLED diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h index fbec734a28..9e5ef0f632 100644 --- a/modules/gdscript/gdscript_function.h +++ b/modules/gdscript/gdscript_function.h @@ -31,7 +31,7 @@ #ifndef GDSCRIPT_FUNCTION_H #define GDSCRIPT_FUNCTION_H -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/object/script_language.h" #include "core/os/thread.h" #include "core/string/string_name.h" @@ -263,6 +263,7 @@ public: OPCODE_CALL_SELF_BASE, OPCODE_CALL_METHOD_BIND, OPCODE_CALL_METHOD_BIND_RET, + OPCODE_CALL_BUILTIN_STATIC, // ptrcall have one instruction per return type. OPCODE_CALL_PTRCALL_NO_RETURN, OPCODE_CALL_PTRCALL_BOOL, @@ -277,10 +278,10 @@ public: OPCODE_CALL_PTRCALL_VECTOR3I, OPCODE_CALL_PTRCALL_TRANSFORM2D, OPCODE_CALL_PTRCALL_PLANE, - OPCODE_CALL_PTRCALL_QUAT, + OPCODE_CALL_PTRCALL_QUATERNION, OPCODE_CALL_PTRCALL_AABB, OPCODE_CALL_PTRCALL_BASIS, - OPCODE_CALL_PTRCALL_TRANSFORM, + OPCODE_CALL_PTRCALL_TRANSFORM3D, OPCODE_CALL_PTRCALL_COLOR, OPCODE_CALL_PTRCALL_STRING_NAME, OPCODE_CALL_PTRCALL_NODE_PATH, @@ -301,6 +302,7 @@ public: OPCODE_CALL_PTRCALL_PACKED_COLOR_ARRAY, OPCODE_AWAIT, OPCODE_AWAIT_RESUME, + OPCODE_CREATE_LAMBDA, OPCODE_JUMP, OPCODE_JUMP_IF, OPCODE_JUMP_IF_NOT, @@ -363,7 +365,7 @@ public: OPCODE_TYPE_ADJUST_VECTOR3I, OPCODE_TYPE_ADJUST_TRANSFORM2D, OPCODE_TYPE_ADJUST_PLANE, - OPCODE_TYPE_ADJUST_QUAT, + OPCODE_TYPE_ADJUST_QUATERNION, OPCODE_TYPE_ADJUST_AABB, OPCODE_TYPE_ADJUST_BASIS, OPCODE_TYPE_ADJUST_TRANSFORM, @@ -459,6 +461,8 @@ private: const GDScriptUtilityFunctions::FunctionPtr *_gds_utilities_ptr = nullptr; int _methods_count = 0; MethodBind **_methods_ptr = nullptr; + int _lambdas_count = 0; + GDScriptFunction **_lambdas_ptr = nullptr; const int *_code_ptr = nullptr; int _code_size = 0; int _argument_count = 0; @@ -468,7 +472,7 @@ private: int _initial_line = 0; bool _static = false; - MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; + MultiplayerAPI::RPCConfig rpc_config; GDScript *_script = nullptr; @@ -488,10 +492,13 @@ private: Vector<Variant::ValidatedUtilityFunction> utilities; Vector<GDScriptUtilityFunctions::FunctionPtr> gds_utilities; Vector<MethodBind *> methods; + Vector<GDScriptFunction *> lambdas; Vector<int> code; Vector<GDScriptDataType> argument_types; GDScriptDataType return_type; + Map<int, Variant::Type> temporary_slots; + #ifdef TOOLS_ENABLED Vector<StringName> arg_names; Vector<Variant> default_arg_values; @@ -585,13 +592,13 @@ public: void disassemble(const Vector<String> &p_code_lines) const; #endif - _FORCE_INLINE_ MultiplayerAPI::RPCMode get_rpc_mode() const { return rpc_mode; } + _FORCE_INLINE_ MultiplayerAPI::RPCConfig get_rpc_config() const { return rpc_config; } GDScriptFunction(); ~GDScriptFunction(); }; -class GDScriptFunctionState : public Reference { - GDCLASS(GDScriptFunctionState, Reference); +class GDScriptFunctionState : public RefCounted { + GDCLASS(GDScriptFunctionState, RefCounted); friend class GDScriptFunction; GDScriptFunction *function = nullptr; GDScriptFunction::CallState state; diff --git a/modules/gdscript/gdscript_lambda_callable.cpp b/modules/gdscript/gdscript_lambda_callable.cpp new file mode 100644 index 0000000000..0bc109b6e1 --- /dev/null +++ b/modules/gdscript/gdscript_lambda_callable.cpp @@ -0,0 +1,95 @@ +/*************************************************************************/ +/* gdscript_lambda_callable.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "gdscript_lambda_callable.h" + +#include "core/templates/hashfuncs.h" +#include "gdscript.h" + +bool GDScriptLambdaCallable::compare_equal(const CallableCustom *p_a, const CallableCustom *p_b) { + // Lambda callables are only compared by reference. + return p_a == p_b; +} + +bool GDScriptLambdaCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) { + // Lambda callables are only compared by reference. + return p_a < p_b; +} + +uint32_t GDScriptLambdaCallable::hash() const { + return h; +} + +String GDScriptLambdaCallable::get_as_text() const { + if (function->get_name() != StringName()) { + return function->get_name().operator String() + "(lambda)"; + } + return "(anonymous lambda)"; +} + +CallableCustom::CompareEqualFunc GDScriptLambdaCallable::get_compare_equal_func() const { + return compare_equal; +} + +CallableCustom::CompareLessFunc GDScriptLambdaCallable::get_compare_less_func() const { + return compare_less; +} + +ObjectID GDScriptLambdaCallable::get_object() const { + return script->get_instance_id(); +} + +void GDScriptLambdaCallable::call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const { + int captures_amount = captures.size(); + + if (captures_amount > 0) { + Vector<const Variant *> args; + args.resize(p_argcount + captures_amount); + for (int i = 0; i < captures_amount; i++) { + args.write[i] = &captures[i]; + } + for (int i = 0; i < p_argcount; i++) { + args.write[i + captures_amount] = p_arguments[i]; + } + + r_return_value = function->call(nullptr, args.ptrw(), args.size(), r_call_error); + r_call_error.argument -= captures_amount; + } else { + r_return_value = function->call(nullptr, p_arguments, p_argcount, r_call_error); + } +} + +GDScriptLambdaCallable::GDScriptLambdaCallable(Ref<GDScript> p_script, GDScriptFunction *p_function, const Vector<Variant> &p_captures) { + script = p_script; + function = p_function; + captures = p_captures; + + h = (uint32_t)hash_djb2_one_64((uint64_t)this); +} diff --git a/modules/gdscript/gdscript_lambda_callable.h b/modules/gdscript/gdscript_lambda_callable.h new file mode 100644 index 0000000000..336778d549 --- /dev/null +++ b/modules/gdscript/gdscript_lambda_callable.h @@ -0,0 +1,65 @@ +/*************************************************************************/ +/* gdscript_lambda_callable.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 GDSCRIPT_LAMBDA_CALLABLE +#define GDSCRIPT_LAMBDA_CALLABLE + +#include "core/object/ref_counted.h" +#include "core/templates/vector.h" +#include "core/variant/callable.h" +#include "core/variant/variant.h" + +class GDScript; +class GDScriptFunction; +class GDScriptInstance; + +class GDScriptLambdaCallable : public CallableCustom { + GDScriptFunction *function = nullptr; + Ref<GDScript> script; + uint32_t h; + + Vector<Variant> captures; + + static bool compare_equal(const CallableCustom *p_a, const CallableCustom *p_b); + static bool compare_less(const CallableCustom *p_a, const CallableCustom *p_b); + +public: + uint32_t hash() const override; + String get_as_text() const override; + CompareEqualFunc get_compare_equal_func() const override; + CompareLessFunc get_compare_less_func() const override; + ObjectID get_object() const override; + void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override; + + GDScriptLambdaCallable(Ref<GDScript> p_script, GDScriptFunction *p_function, const Vector<Variant> &p_captures); + virtual ~GDScriptLambdaCallable() = default; +}; + +#endif // GDSCRIPT_LAMBDA_CALLABLE diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index d910137510..a21167ad95 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -31,9 +31,9 @@ #include "gdscript_parser.h" #include "core/config/project_settings.h" +#include "core/io/file_access.h" #include "core/io/resource_loader.h" #include "core/math/math_defs.h" -#include "core/os/file_access.h" #include "gdscript.h" #ifdef DEBUG_ENABLED @@ -61,9 +61,9 @@ Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) { builtin_types["Vector3i"] = Variant::VECTOR3I; builtin_types["AABB"] = Variant::AABB; builtin_types["Plane"] = Variant::PLANE; - builtin_types["Quat"] = Variant::QUAT; + builtin_types["Quaternion"] = Variant::QUATERNION; builtin_types["Basis"] = Variant::BASIS; - builtin_types["Transform"] = Variant::TRANSFORM; + builtin_types["Transform3D"] = Variant::TRANSFORM3D; builtin_types["Color"] = Variant::COLOR; builtin_types["RID"] = Variant::RID; builtin_types["Object"] = Variant::OBJECT; @@ -136,8 +136,8 @@ void GDScriptParser::cleanup() { void GDScriptParser::get_annotation_list(List<MethodInfo> *r_annotations) const { List<StringName> keys; valid_annotations.get_key_list(&keys); - for (const List<StringName>::Element *E = keys.front(); E != nullptr; E = E->next()) { - r_annotations->push_back(valid_annotations[E->get()].info); + for (const StringName &E : keys) { + r_annotations->push_back(valid_annotations[E].info); } } @@ -157,7 +157,6 @@ GDScriptParser::GDScriptParser() { register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>); register_annotation(MethodInfo("@export_placeholder"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>); register_annotation(MethodInfo("@export_range", { Variant::FLOAT, "min" }, { Variant::FLOAT, "max" }, { Variant::FLOAT, "step" }, { Variant::STRING, "slider1" }, { Variant::STRING, "slider2" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_RANGE, Variant::FLOAT>, 3); - register_annotation(MethodInfo("@export_exp_range", { Variant::FLOAT, "min" }, { Variant::FLOAT, "max" }, { Variant::FLOAT, "step" }, { Variant::STRING, "slider1" }, { Variant::STRING, "slider2" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_RANGE, Variant::FLOAT>, 3); register_annotation(MethodInfo("@export_exp_easing", { Variant::STRING, "hint1" }, { Variant::STRING, "hint2" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, 2); register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>); register_annotation(MethodInfo("@export_node_path", { Variant::STRING, "type" }), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NODE_PATH_VALID_TYPES, Variant::NODE_PATH>, 1, true); @@ -169,12 +168,7 @@ GDScriptParser::GDScriptParser() { register_annotation(MethodInfo("@export_flags_3d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_PHYSICS, Variant::INT>); register_annotation(MethodInfo("@export_flags_3d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_NAVIGATION, Variant::INT>); // Networking. - register_annotation(MethodInfo("@remote"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_REMOTE>); - register_annotation(MethodInfo("@master"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_MASTER>); - register_annotation(MethodInfo("@puppet"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_PUPPET>); - register_annotation(MethodInfo("@remotesync"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_REMOTESYNC>); - register_annotation(MethodInfo("@mastersync"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_MASTERSYNC>); - register_annotation(MethodInfo("@puppetsync"), AnnotationInfo::VARIABLE | AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_PUPPETSYNC>); + register_annotation(MethodInfo("@rpc", { Variant::STRING, "mode" }, { Variant::STRING, "sync" }, { Variant::STRING, "transfer_mode" }, { Variant::INT, "transfer_channel" }), AnnotationInfo::FUNCTION, &GDScriptParser::network_annotations<MultiplayerAPI::RPC_MODE_PUPPET>, 4, true); // TODO: Warning annotations. } @@ -254,7 +248,7 @@ void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_ warning.rightmost_column = p_source->rightmost_column; List<GDScriptWarning>::Element *before = nullptr; - for (List<GDScriptWarning>::Element *E = warnings.front(); E != nullptr; E = E->next()) { + for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) { if (E->get().start_line > warning.start_line) { break; } @@ -402,6 +396,8 @@ Error GDScriptParser::parse(const String &p_source_code, const String &p_script_ } GDScriptTokenizer::Token GDScriptParser::advance() { + lambda_ended = false; // Empty marker since we're past the end in any case. + if (current.type == GDScriptTokenizer::Token::TK_EOF) { ERR_FAIL_COND_V_MSG(current.type == GDScriptTokenizer::Token::TK_EOF, current, "GDScript parser bug: Trying to advance past the end of stream."); } @@ -428,7 +424,7 @@ bool GDScriptParser::match(GDScriptTokenizer::Token::Type p_token_type) { return true; } -bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) { +bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) const { if (p_token_type == GDScriptTokenizer::Token::IDENTIFIER) { return current.is_identifier(); } @@ -443,7 +439,7 @@ bool GDScriptParser::consume(GDScriptTokenizer::Token::Type p_token_type, const return false; } -bool GDScriptParser::is_at_end() { +bool GDScriptParser::is_at_end() const { return check(GDScriptTokenizer::Token::TK_EOF); } @@ -494,16 +490,34 @@ void GDScriptParser::pop_multiline() { tokenizer.set_multiline_mode(multiline_stack.size() > 0 ? multiline_stack.back()->get() : false); } -bool GDScriptParser::is_statement_end() { +bool GDScriptParser::is_statement_end_token() const { return check(GDScriptTokenizer::Token::NEWLINE) || check(GDScriptTokenizer::Token::SEMICOLON) || check(GDScriptTokenizer::Token::TK_EOF); } +bool GDScriptParser::is_statement_end() const { + return lambda_ended || in_lambda || is_statement_end_token(); +} + void GDScriptParser::end_statement(const String &p_context) { bool found = false; while (is_statement_end() && !is_at_end()) { // Remove sequential newlines/semicolons. + if (is_statement_end_token()) { + // Only consume if this is an actual token. + advance(); + } else if (lambda_ended) { + lambda_ended = false; // Consume this "token". + found = true; + break; + } else { + if (!found) { + lambda_ended = true; // Mark the lambda as done since we found something else to end the statement. + found = true; + } + break; + } + found = true; - advance(); } if (!found && !is_at_end()) { push_error(vformat(R"(Expected end of statement after %s, found "%s" instead.)", p_context, current.get_name())); @@ -1153,7 +1167,7 @@ GDScriptParser::EnumNode *GDScriptParser::parse_enum() { consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)"); #ifdef TOOLS_ENABLED - // Enum values documentaion. + // Enum values documentation. for (int i = 0; i < enum_node->values.size(); i++) { if (i == enum_node->values.size() - 1) { // If close bracket is same line as last value. @@ -1182,36 +1196,7 @@ GDScriptParser::EnumNode *GDScriptParser::parse_enum() { return enum_node; } -GDScriptParser::FunctionNode *GDScriptParser::parse_function() { - bool _static = false; - if (previous.type == GDScriptTokenizer::Token::STATIC) { - // TODO: Improve message if user uses "static" with "var" or "const" - if (!consume(GDScriptTokenizer::Token::FUNC, R"(Expected "func" after "static".)")) { - return nullptr; - } - _static = true; - } - - FunctionNode *function = alloc_node<FunctionNode>(); - make_completion_context(COMPLETION_OVERRIDE_METHOD, function); - - if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) { - return nullptr; - } - - FunctionNode *previous_function = current_function; - current_function = function; - - function->identifier = parse_identifier(); - function->is_static = _static; - - push_multiline(true); - consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)"); - - SuiteNode *body = alloc_node<SuiteNode>(); - SuiteNode *previous_suite = current_suite; - current_suite = body; - +void GDScriptParser::parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type) { if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) { bool default_used = false; do { @@ -1231,29 +1216,61 @@ GDScriptParser::FunctionNode *GDScriptParser::parse_function() { continue; } } - if (function->parameters_indices.has(parameter->identifier->name)) { - push_error(vformat(R"(Parameter with name "%s" was already declared for this function.)", parameter->identifier->name)); + if (p_function->parameters_indices.has(parameter->identifier->name)) { + push_error(vformat(R"(Parameter with name "%s" was already declared for this %s.)", parameter->identifier->name, p_type)); } else { - function->parameters_indices[parameter->identifier->name] = function->parameters.size(); - function->parameters.push_back(parameter); - body->add_local(parameter); + p_function->parameters_indices[parameter->identifier->name] = p_function->parameters.size(); + p_function->parameters.push_back(parameter); + p_body->add_local(parameter, current_function); } } while (match(GDScriptTokenizer::Token::COMMA)); } pop_multiline(); - consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after function parameters.)*"); + consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, vformat(R"*(Expected closing ")" after %s parameters.)*", p_type)); if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) { - make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, function); - function->return_type = parse_type(true); - if (function->return_type == nullptr) { + make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, p_function); + p_function->return_type = parse_type(true); + if (p_function->return_type == nullptr) { push_error(R"(Expected return type or "void" after "->".)"); } } // TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens. - consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after function declaration.)"); + consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after %s declaration.)", p_type)); +} + +GDScriptParser::FunctionNode *GDScriptParser::parse_function() { + bool _static = false; + if (previous.type == GDScriptTokenizer::Token::STATIC) { + // TODO: Improve message if user uses "static" with "var" or "const" + if (!consume(GDScriptTokenizer::Token::FUNC, R"(Expected "func" after "static".)")) { + return nullptr; + } + _static = true; + } + + FunctionNode *function = alloc_node<FunctionNode>(); + make_completion_context(COMPLETION_OVERRIDE_METHOD, function); + + if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) { + return nullptr; + } + + FunctionNode *previous_function = current_function; + current_function = function; + + function->identifier = parse_identifier(); + function->is_static = _static; + + SuiteNode *body = alloc_node<SuiteNode>(); + SuiteNode *previous_suite = current_suite; + current_suite = body; + + push_multiline(true); + consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)"); + parse_function_signature(function, body, "function"); current_suite = previous_suite; function->body = parse_suite("function declaration", body); @@ -1315,8 +1332,7 @@ GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_vali } void GDScriptParser::clear_unused_annotations() { - for (const List<AnnotationNode *>::Element *E = annotation_stack.front(); E != nullptr; E = E->next()) { - AnnotationNode *annotation = E->get(); + for (const AnnotationNode *annotation : annotation_stack) { push_error(vformat(R"(Annotation "%s" does not precedes a valid target, so it will have no effect.)", annotation->name), annotation); } @@ -1339,29 +1355,34 @@ bool GDScriptParser::register_annotation(const MethodInfo &p_info, uint32_t p_ta return true; } -GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite) { +GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) { SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>(); suite->parent_block = current_suite; + suite->parent_function = current_function; current_suite = suite; bool multiline = false; - if (check(GDScriptTokenizer::Token::NEWLINE)) { + if (match(GDScriptTokenizer::Token::NEWLINE)) { multiline = true; } if (multiline) { - consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after %s.)", p_context)); - if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) { current_suite = suite->parent_block; return suite; } } + int error_count = 0; + do { Node *statement = parse_statement(); if (statement == nullptr) { + if (error_count++ > 100) { + push_error("Too many statement errors.", suite); + break; + } continue; } suite->statements.push_back(statement); @@ -1374,7 +1395,7 @@ GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, if (local.type != SuiteNode::Local::UNDEFINED) { push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name)); } - current_suite->add_local(variable); + current_suite->add_local(variable, current_function); break; } case Node::CONSTANT: { @@ -1389,19 +1410,29 @@ GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, } push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name)); } - current_suite->add_local(constant); + current_suite->add_local(constant, current_function); break; } default: break; } - } while (multiline && !check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()); + } while (multiline && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end()); if (multiline) { - consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context)); + if (!lambda_ended) { + consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context)); + + } else { + match(GDScriptTokenizer::Token::DEDENT); + } + } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) { + consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context)); } + if (p_for_lambda) { + lambda_ended = true; + } current_suite = suite->parent_block; return suite; } @@ -1458,6 +1489,10 @@ GDScriptParser::Node *GDScriptParser::parse_statement() { push_error(R"(Constructor cannot return a value.)"); } n_return->return_value = parse_expression(false); + } else if (in_lambda && !is_statement_end_token()) { + // Try to parse it anyway as this might not be the statement end in a lambda. + // If this fails the expression will be nullptr, but that's the same as no return, so it's fine. + n_return->return_value = parse_expression(false); } result = n_return; @@ -1486,10 +1521,18 @@ GDScriptParser::Node *GDScriptParser::parse_statement() { default: { // Expression statement. ExpressionNode *expression = parse_expression(true); // Allow assignment here. + bool has_ended_lambda = false; if (expression == nullptr) { - push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name())); + if (in_lambda) { + // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is. + lambda_ended = true; + has_ended_lambda = true; + } else { + push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name())); + } } end_statement("expression"); + lambda_ended = lambda_ended || has_ended_lambda; result = expression; #ifdef DEBUG_ENABLED @@ -1513,7 +1556,7 @@ GDScriptParser::Node *GDScriptParser::parse_statement() { if (unreachable && result != nullptr) { current_suite->has_unreachable_code = true; if (current_function) { - push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier->name); + push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>"); } else { // TODO: Properties setters and getters with unreachable code are not being warned } @@ -1598,7 +1641,7 @@ GDScriptParser::ForNode *GDScriptParser::parse_for() { SuiteNode *suite = alloc_node<SuiteNode>(); if (n_for->variable) { - suite->add_local(SuiteNode::Local(n_for->variable)); + suite->add_local(SuiteNode::Local(n_for->variable, current_function)); } suite->parent_for = n_for; @@ -1752,8 +1795,8 @@ GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() { List<StringName> binds; branch->patterns[0]->binds.get_key_list(&binds); - for (List<StringName>::Element *E = binds.front(); E != nullptr; E = E->next()) { - SuiteNode::Local local(branch->patterns[0]->binds[E->get()]); + for (const StringName &E : binds) { + SuiteNode::Local local(branch->patterns[0]->binds[E], current_function); suite->add_local(local); } } @@ -1953,7 +1996,7 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_pr // Completion can appear whenever an expression is expected. make_completion_context(COMPLETION_IDENTIFIER, nullptr); - GDScriptTokenizer::Token token = advance(); + GDScriptTokenizer::Token token = current; ParseFunction prefix_rule = get_rule(token.type)->prefix; if (prefix_rule == nullptr) { @@ -1961,6 +2004,8 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_pr return nullptr; } + advance(); // Only consume the token if there's a valid rule. + ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign); while (p_precedence <= get_rule(current.type)->precedence) { @@ -2002,6 +2047,8 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode if (current_suite != nullptr && current_suite->has_local(identifier->name)) { const SuiteNode::Local &declaration = current_suite->get_local(identifier->name); + + identifier->source_function = declaration.source_function; switch (declaration.type) { case SuiteNode::Local::CONSTANT: identifier->source = IdentifierNode::LOCAL_CONSTANT; @@ -2055,6 +2102,9 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_pre if (current_function && current_function->is_static) { push_error(R"(Cannot use "self" inside a static function.)"); } + if (in_lambda) { + push_error(R"(Cannot use "self" inside a lambda.)"); + } SelfNode *self = alloc_node<SelfNode>(); self->current_class = current_class; return self; @@ -2072,10 +2122,10 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(Expressio constant->value = Math_TAU; break; case GDScriptTokenizer::Token::CONST_INF: - constant->value = Math_INF; + constant->value = INFINITY; break; case GDScriptTokenizer::Token::CONST_NAN: - constant->value = Math_NAN; + constant->value = NAN; break; default: return nullptr; // Unreachable. @@ -2430,7 +2480,9 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode switch (dictionary->style) { case DictionaryNode::LUA_TABLE: if (key != nullptr && key->type != Node::IDENTIFIER) { - push_error("Expected identifier as dictionary key."); + push_error("Expected identifier as LUA-style dictionary key."); + advance(); + break; } if (!match(GDScriptTokenizer::Token::EQUAL)) { if (match(GDScriptTokenizer::Token::COLON)) { @@ -2488,7 +2540,7 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode * if (for_completion) { bool is_builtin = false; - if (p_previous_operand->type == Node::IDENTIFIER) { + if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) { const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand); Variant::Type builtin_type = get_builtin_type(id->name); if (builtin_type < Variant::VARIANT_MAX) { @@ -2675,6 +2727,65 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_ return preload; } +GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) { + LambdaNode *lambda = alloc_node<LambdaNode>(); + lambda->parent_function = current_function; + FunctionNode *function = alloc_node<FunctionNode>(); + function->source_lambda = lambda; + + function->is_static = current_function != nullptr ? current_function->is_static : false; + + if (match(GDScriptTokenizer::Token::IDENTIFIER)) { + function->identifier = parse_identifier(); + } + + bool multiline_context = multiline_stack.back()->get(); + + // Reset the multiline stack since we don't want the multiline mode one in the lambda body. + push_multiline(false); + if (multiline_context) { + tokenizer.push_expression_indented_block(); + } + + push_multiline(true); // For the parameters. + if (function->identifier) { + consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)"); + } else { + consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)"); + } + + FunctionNode *previous_function = current_function; + current_function = function; + + SuiteNode *body = alloc_node<SuiteNode>(); + SuiteNode *previous_suite = current_suite; + current_suite = body; + + parse_function_signature(function, body, "lambda"); + + current_suite = previous_suite; + + bool previous_in_lambda = in_lambda; + in_lambda = true; + + function->body = parse_suite("lambda declaration", body, true); + + pop_multiline(); + + if (multiline_context) { + // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens. + while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) { + current = tokenizer.scan(); // Not advance() since we don't want to change the previous token. + } + tokenizer.pop_expression_indented_block(); + } + + current_function = previous_function; + in_lambda = previous_in_lambda; + lambda->function = function; + return lambda; +} + GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) { // Just for better error messages. GDScriptTokenizer::Token::Type invalid = previous.type; @@ -3019,7 +3130,7 @@ GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Ty { nullptr, nullptr, PREC_NONE }, // CONST, { nullptr, nullptr, PREC_NONE }, // ENUM, { nullptr, nullptr, PREC_NONE }, // EXTENDS, - { nullptr, nullptr, PREC_NONE }, // FUNC, + { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC, { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN, { nullptr, &GDScriptParser::parse_binary_operator, PREC_TYPE_TEST }, // IS, { nullptr, nullptr, PREC_NONE }, // NAMESPACE, @@ -3315,27 +3426,60 @@ template <MultiplayerAPI::RPCMode t_mode> bool GDScriptParser::network_annotations(const AnnotationNode *p_annotation, Node *p_node) { ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE && p_node->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to variables and functions.)", p_annotation->name)); - switch (p_node->type) { - case Node::VARIABLE: { - VariableNode *variable = static_cast<VariableNode *>(p_node); - if (variable->rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) { - push_error(R"(RPC annotations can only be used once per variable.)", p_annotation); + MultiplayerAPI::RPCConfig rpc_config; + rpc_config.rpc_mode = t_mode; + for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) { + if (i == 0) { + String mode = p_annotation->resolved_arguments[i].operator String(); + if (mode == "any") { + rpc_config.rpc_mode = MultiplayerAPI::RPC_MODE_REMOTE; + } else if (mode == "master") { + rpc_config.rpc_mode = MultiplayerAPI::RPC_MODE_MASTER; + } else if (mode == "puppet") { + rpc_config.rpc_mode = MultiplayerAPI::RPC_MODE_PUPPET; + } else { + push_error(R"(Invalid RPC mode. Must be one of: 'any', 'master', or 'puppet')", p_annotation); + return false; } - variable->rpc_mode = t_mode; - break; + } else if (i == 1) { + String sync = p_annotation->resolved_arguments[i].operator String(); + if (sync == "sync") { + rpc_config.sync = true; + } else if (sync == "nosync") { + rpc_config.sync = false; + } else { + push_error(R"(Invalid RPC sync mode. Must be one of: 'sync' or 'nosync')", p_annotation); + return false; + } + } else if (i == 2) { + String mode = p_annotation->resolved_arguments[i].operator String(); + if (mode == "reliable") { + rpc_config.transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE; + } else if (mode == "unreliable") { + rpc_config.transfer_mode = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE; + } else if (mode == "ordered") { + rpc_config.transfer_mode = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED; + } else { + push_error(R"(Invalid RPC transfer mode. Must be one of: 'reliable', 'unreliable', 'ordered')", p_annotation); + return false; + } + } else if (i == 3) { + rpc_config.channel = p_annotation->resolved_arguments[i].operator int(); } + } + switch (p_node->type) { case Node::FUNCTION: { FunctionNode *function = static_cast<FunctionNode *>(p_node); - if (function->rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) { + if (function->rpc_config.rpc_mode != MultiplayerAPI::RPC_MODE_DISABLED) { push_error(R"(RPC annotations can only be used once per function.)", p_annotation); + return false; } - function->rpc_mode = t_mode; + function->rpc_config = rpc_config; break; } default: return false; // Unreachable. } - return true; } @@ -3475,7 +3619,7 @@ void GDScriptParser::TreePrinter::push_text(const String &p_text) { printed += p_text; } -void GDScriptParser::TreePrinter::print_annotation(AnnotationNode *p_annotation) { +void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) { push_text(p_annotation->name); push_text(" ("); for (int i = 0; i < p_annotation->arguments.size(); i++) { @@ -3755,6 +3899,10 @@ void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) } void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) { + if (p_expression == nullptr) { + push_text("<invalid expression>"); + return; + } switch (p_expression->type) { case Node::ARRAY: print_array(static_cast<ArrayNode *>(p_expression)); @@ -3783,6 +3931,9 @@ void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) case Node::IDENTIFIER: print_identifier(static_cast<IdentifierNode *>(p_expression)); break; + case Node::LAMBDA: + print_lambda(static_cast<LambdaNode *>(p_expression)); + break; case Node::LITERAL: print_literal(static_cast<LiteralNode *>(p_expression)); break; @@ -3842,12 +3993,17 @@ void GDScriptParser::TreePrinter::print_for(ForNode *p_for) { decrease_indent(); } -void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function) { - for (const List<AnnotationNode *>::Element *E = p_function->annotations.front(); E != nullptr; E = E->next()) { - print_annotation(E->get()); +void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) { + for (const AnnotationNode *E : p_function->annotations) { + print_annotation(E); + } + push_text(p_context); + push_text(" "); + if (p_function->identifier) { + print_identifier(p_function->identifier); + } else { + push_text("<anonymous>"); } - push_text("Function "); - print_identifier(p_function->identifier); push_text("( "); for (int i = 0; i < p_function->parameters.size(); i++) { if (i > 0) { @@ -3901,6 +4057,18 @@ void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) { } } +void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) { + print_function(p_lambda->function, "Lambda"); + push_text("| captures [ "); + for (int i = 0; i < p_lambda->captures.size(); i++) { + if (i > 0) { + push_text(" , "); + } + push_text(p_lambda->captures[i]->name.operator String()); + } + push_line(" ]"); +} + void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) { // Prefix for string types. switch (p_literal->value.get_type()) { @@ -4166,8 +4334,8 @@ void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) { } void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) { - for (const List<AnnotationNode *>::Element *E = p_variable->annotations.front(); E != nullptr; E = E->next()) { - print_annotation(E->get()); + for (const AnnotationNode *E : p_variable->annotations) { + print_annotation(E); } push_text("Variable "); diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index 272d21ffce..6a227a55e5 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -33,7 +33,7 @@ #include "core/io/multiplayer_api.h" #include "core/io/resource.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/object/script_language.h" #include "core/string/string_name.h" #include "core/string/ustring.h" @@ -76,6 +76,7 @@ public: struct GetNodeNode; struct IdentifierNode; struct IfNode; + struct LambdaNode; struct LiteralNode; struct MatchNode; struct MatchBranchNode; @@ -267,6 +268,7 @@ public: GET_NODE, IDENTIFIER, IF, + LAMBDA, LITERAL, MATCH, MATCH_BRANCH, @@ -368,6 +370,7 @@ public: Variant::Operator variant_op = Variant::OP_MAX; ExpressionNode *assignee = nullptr; ExpressionNode *assigned_value = nullptr; + bool use_conversion_assign = false; AssignmentNode() { type = ASSIGNMENT; @@ -726,8 +729,9 @@ public: SuiteNode *body = nullptr; bool is_static = false; bool is_coroutine = false; - MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; + MultiplayerAPI::RPCConfig rpc_config; MethodInfo info; + LambdaNode *source_lambda = nullptr; #ifdef TOOLS_ENABLED Vector<Variant> default_arg_values; String doc_description; @@ -771,6 +775,7 @@ public: VariableNode *variable_source; IdentifierNode *bind_source; }; + FunctionNode *source_function = nullptr; int usages = 0; // Useful for binds/iterator variable. @@ -789,6 +794,21 @@ public: } }; + struct LambdaNode : public ExpressionNode { + FunctionNode *function = nullptr; + FunctionNode *parent_function = nullptr; + Vector<IdentifierNode *> captures; + Map<StringName, int> captures_indices; + + bool has_name() const { + return function && function->identifier; + } + + LambdaNode() { + type = LAMBDA; + } + }; + struct LiteralNode : public ExpressionNode { Variant value; @@ -942,6 +962,7 @@ public: IdentifierNode *bind; }; StringName name; + FunctionNode *source_function = nullptr; int start_line = 0, end_line = 0; int start_column = 0, end_column = 0; @@ -951,10 +972,11 @@ public: String get_name() const; Local() {} - Local(ConstantNode *p_constant) { + Local(ConstantNode *p_constant, FunctionNode *p_source_function) { type = CONSTANT; constant = p_constant; name = p_constant->identifier->name; + source_function = p_source_function; start_line = p_constant->start_line; end_line = p_constant->end_line; @@ -963,10 +985,11 @@ public: leftmost_column = p_constant->leftmost_column; rightmost_column = p_constant->rightmost_column; } - Local(VariableNode *p_variable) { + Local(VariableNode *p_variable, FunctionNode *p_source_function) { type = VARIABLE; variable = p_variable; name = p_variable->identifier->name; + source_function = p_source_function; start_line = p_variable->start_line; end_line = p_variable->end_line; @@ -975,10 +998,11 @@ public: leftmost_column = p_variable->leftmost_column; rightmost_column = p_variable->rightmost_column; } - Local(ParameterNode *p_parameter) { + Local(ParameterNode *p_parameter, FunctionNode *p_source_function) { type = PARAMETER; parameter = p_parameter; name = p_parameter->identifier->name; + source_function = p_source_function; start_line = p_parameter->start_line; end_line = p_parameter->end_line; @@ -987,10 +1011,11 @@ public: leftmost_column = p_parameter->leftmost_column; rightmost_column = p_parameter->rightmost_column; } - Local(IdentifierNode *p_identifier) { + Local(IdentifierNode *p_identifier, FunctionNode *p_source_function) { type = FOR_VARIABLE; bind = p_identifier; name = p_identifier->name; + source_function = p_source_function; start_line = p_identifier->start_line; end_line = p_identifier->end_line; @@ -1015,9 +1040,9 @@ public: bool has_local(const StringName &p_name) const; const Local &get_local(const StringName &p_name) const; template <class T> - void add_local(T *p_local) { + void add_local(T *p_local, FunctionNode *p_source_function) { locals_indices[p_local->identifier->name] = locals.size(); - locals.push_back(Local(p_local)); + locals.push_back(Local(p_local, p_source_function)); } void add_local(const Local &p_local) { locals_indices[p_local.name] = locals.size(); @@ -1092,9 +1117,9 @@ public: bool exported = false; bool onready = false; PropertyInfo export_info; - MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED; int assignments = 0; int usages = 0; + bool use_conversion_assign = false; #ifdef TOOLS_ENABLED String doc_description; #endif // TOOLS_ENABLED @@ -1191,6 +1216,8 @@ private: CompletionCall completion_call; List<CompletionCall> completion_call_stack; bool passed_cursor = false; + bool in_lambda = false; + bool lambda_ended = false; // Marker for when a lambda ends, to apply an end of statement if needed. typedef bool (GDScriptParser::*AnnotationAction)(const AnnotationNode *p_annotation, Node *p_target); struct AnnotationInfo { @@ -1278,10 +1305,11 @@ private: GDScriptTokenizer::Token advance(); bool match(GDScriptTokenizer::Token::Type p_token_type); - bool check(GDScriptTokenizer::Token::Type p_token_type); + bool check(GDScriptTokenizer::Token::Type p_token_type) const; bool consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message); - bool is_at_end(); - bool is_statement_end(); + bool is_at_end() const; + bool is_statement_end_token() const; + bool is_statement_end() const; void end_statement(const String &p_context); void synchronize(); void push_multiline(bool p_state); @@ -1299,7 +1327,8 @@ private: EnumNode *parse_enum(); ParameterNode *parse_parameter(); FunctionNode *parse_function(); - SuiteNode *parse_suite(const String &p_context, SuiteNode *p_suite = nullptr); + void parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type); + SuiteNode *parse_suite(const String &p_context, SuiteNode *p_suite = nullptr, bool p_for_lambda = false); // Annotations AnnotationNode *parse_annotation(uint32_t p_valid_targets); bool register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, int p_optional_arguments = 0, bool p_is_vararg = false); @@ -1354,6 +1383,7 @@ private: ExpressionNode *parse_await(ExpressionNode *p_previous_operand, bool p_can_assign); ExpressionNode *parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign); ExpressionNode *parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign); + ExpressionNode *parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign); ExpressionNode *parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign); TypeNode *parse_type(bool p_allow_void = false); #ifdef TOOLS_ENABLED @@ -1401,7 +1431,7 @@ public: void push_line(const String &p_line = String()); void push_text(const String &p_text); - void print_annotation(AnnotationNode *p_annotation); + void print_annotation(const AnnotationNode *p_annotation); void print_array(ArrayNode *p_array); void print_assert(AssertNode *p_assert); void print_assignment(AssignmentNode *p_assignment); @@ -1415,10 +1445,11 @@ public: void print_expression(ExpressionNode *p_expression); void print_enum(EnumNode *p_enum); void print_for(ForNode *p_for); - void print_function(FunctionNode *p_function); + void print_function(FunctionNode *p_function, const String &p_context = "Function"); void print_get_node(GetNodeNode *p_get_node); void print_if(IfNode *p_if, bool p_is_elif = false); void print_identifier(IdentifierNode *p_identifier); + void print_lambda(LambdaNode *p_lambda); void print_literal(LiteralNode *p_literal); void print_match(MatchNode *p_match); void print_match_branch(MatchBranchNode *p_match_branch); diff --git a/modules/gdscript/gdscript_tokenizer.cpp b/modules/gdscript/gdscript_tokenizer.cpp index e432dfc891..3f14156dfa 100644 --- a/modules/gdscript/gdscript_tokenizer.cpp +++ b/modules/gdscript/gdscript_tokenizer.cpp @@ -242,6 +242,16 @@ void GDScriptTokenizer::set_multiline_mode(bool p_state) { multiline_mode = p_state; } +void GDScriptTokenizer::push_expression_indented_block() { + indent_stack_stack.push_back(indent_stack); +} + +void GDScriptTokenizer::pop_expression_indented_block() { + ERR_FAIL_COND(indent_stack_stack.size() == 0); + indent_stack = indent_stack_stack.back()->get(); + indent_stack_stack.pop_back(); +} + int GDScriptTokenizer::get_cursor_line() const { return cursor_line; } @@ -633,6 +643,8 @@ GDScriptTokenizer::Token GDScriptTokenizer::number() { push_error(error); } previous_was_underscore = true; + } else { + previous_was_underscore = false; } _advance(); } @@ -704,6 +716,8 @@ GDScriptTokenizer::Token GDScriptTokenizer::number() { push_error(error); } previous_was_underscore = true; + } else { + previous_was_underscore = false; } _advance(); } diff --git a/modules/gdscript/gdscript_tokenizer.h b/modules/gdscript/gdscript_tokenizer.h index bea4b14019..84b82c07f0 100644 --- a/modules/gdscript/gdscript_tokenizer.h +++ b/modules/gdscript/gdscript_tokenizer.h @@ -217,6 +217,7 @@ private: Token last_newline; int pending_indents = 0; List<int> indent_stack; + List<List<int>> indent_stack_stack; // For lambdas, which require manipulating the indentation point. List<char32_t> paren_stack; char32_t indent_char = '\0'; int position = 0; @@ -263,6 +264,8 @@ public: void set_multiline_mode(bool p_state); bool is_past_cursor() const; static String get_token_name(Token::Type p_token_type); + void push_expression_indented_block(); // For lambdas, or blocks inside expressions. + void pop_expression_indented_block(); // For lambdas, or blocks inside expressions. GDScriptTokenizer(); }; diff --git a/modules/gdscript/gdscript_utility_functions.cpp b/modules/gdscript/gdscript_utility_functions.cpp index 64c629662c..62531473c3 100644 --- a/modules/gdscript/gdscript_utility_functions.cpp +++ b/modules/gdscript/gdscript_utility_functions.cpp @@ -706,8 +706,8 @@ bool GDScriptUtilityFunctions::function_exists(const StringName &p_function) { } void GDScriptUtilityFunctions::get_function_list(List<StringName> *r_functions) { - for (const List<StringName>::Element *E = utility_function_name_table.front(); E; E = E->next()) { - r_functions->push_back(E->get()); + for (const StringName &E : utility_function_name_table) { + r_functions->push_back(E); } } diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp index b47a4eb992..8a261a88e3 100644 --- a/modules/gdscript/gdscript_vm.cpp +++ b/modules/gdscript/gdscript_vm.cpp @@ -33,6 +33,7 @@ #include "core/core_string_names.h" #include "core/os/os.h" #include "gdscript.h" +#include "gdscript_lambda_callable.h" Variant *GDScriptFunction::_get_variant(int p_address, GDScriptInstance *p_instance, Variant *p_stack, String &r_error) const { int address = p_address & ADDR_MASK; @@ -151,6 +152,44 @@ String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const return err_text; } +void (*type_init_function_table[])(Variant *) = { + nullptr, // NIL (shouldn't be called). + &VariantInitializer<bool>::init, // BOOL. + &VariantInitializer<int64_t>::init, // INT. + &VariantInitializer<double>::init, // FLOAT. + &VariantInitializer<String>::init, // STRING. + &VariantInitializer<Vector2>::init, // VECTOR2. + &VariantInitializer<Vector2i>::init, // VECTOR2I. + &VariantInitializer<Rect2>::init, // RECT2. + &VariantInitializer<Rect2i>::init, // RECT2I. + &VariantInitializer<Vector3>::init, // VECTOR3. + &VariantInitializer<Vector3i>::init, // VECTOR3I. + &VariantInitializer<Transform2D>::init, // TRANSFORM2D. + &VariantInitializer<Plane>::init, // PLANE. + &VariantInitializer<Quaternion>::init, // QUATERNION. + &VariantInitializer<AABB>::init, // AABB. + &VariantInitializer<Basis>::init, // BASIS. + &VariantInitializer<Transform3D>::init, // TRANSFORM3D. + &VariantInitializer<Color>::init, // COLOR. + &VariantInitializer<StringName>::init, // STRING_NAME. + &VariantInitializer<NodePath>::init, // NODE_PATH. + &VariantInitializer<RID>::init, // RID. + &VariantTypeAdjust<Object *>::adjust, // OBJECT. + &VariantInitializer<Callable>::init, // CALLABLE. + &VariantInitializer<Signal>::init, // SIGNAL. + &VariantInitializer<Dictionary>::init, // DICTIONARY. + &VariantInitializer<Array>::init, // ARRAY. + &VariantInitializer<PackedByteArray>::init, // PACKED_BYTE_ARRAY. + &VariantInitializer<PackedInt32Array>::init, // PACKED_INT32_ARRAY. + &VariantInitializer<PackedInt64Array>::init, // PACKED_INT64_ARRAY. + &VariantInitializer<PackedFloat32Array>::init, // PACKED_FLOAT32_ARRAY. + &VariantInitializer<PackedFloat64Array>::init, // PACKED_FLOAT64_ARRAY. + &VariantInitializer<PackedStringArray>::init, // PACKED_STRING_ARRAY. + &VariantInitializer<PackedVector2Array>::init, // PACKED_VECTOR2_ARRAY. + &VariantInitializer<PackedVector3Array>::init, // PACKED_VECTOR3_ARRAY. + &VariantInitializer<PackedColorArray>::init, // PACKED_COLOR_ARRAY. +}; + #if defined(__GNUC__) #define OPCODES_TABLE \ static const void *switch_table_ops[] = { \ @@ -195,6 +234,7 @@ String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const &&OPCODE_CALL_SELF_BASE, \ &&OPCODE_CALL_METHOD_BIND, \ &&OPCODE_CALL_METHOD_BIND_RET, \ + &&OPCODE_CALL_BUILTIN_STATIC, \ &&OPCODE_CALL_PTRCALL_NO_RETURN, \ &&OPCODE_CALL_PTRCALL_BOOL, \ &&OPCODE_CALL_PTRCALL_INT, \ @@ -208,10 +248,10 @@ String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const &&OPCODE_CALL_PTRCALL_VECTOR3I, \ &&OPCODE_CALL_PTRCALL_TRANSFORM2D, \ &&OPCODE_CALL_PTRCALL_PLANE, \ - &&OPCODE_CALL_PTRCALL_QUAT, \ + &&OPCODE_CALL_PTRCALL_QUATERNION, \ &&OPCODE_CALL_PTRCALL_AABB, \ &&OPCODE_CALL_PTRCALL_BASIS, \ - &&OPCODE_CALL_PTRCALL_TRANSFORM, \ + &&OPCODE_CALL_PTRCALL_TRANSFORM3D, \ &&OPCODE_CALL_PTRCALL_COLOR, \ &&OPCODE_CALL_PTRCALL_STRING_NAME, \ &&OPCODE_CALL_PTRCALL_NODE_PATH, \ @@ -232,6 +272,7 @@ String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const &&OPCODE_CALL_PTRCALL_PACKED_COLOR_ARRAY, \ &&OPCODE_AWAIT, \ &&OPCODE_AWAIT_RESUME, \ + &&OPCODE_CREATE_LAMBDA, \ &&OPCODE_JUMP, \ &&OPCODE_JUMP_IF, \ &&OPCODE_JUMP_IF_NOT, \ @@ -294,7 +335,7 @@ String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const &&OPCODE_TYPE_ADJUST_VECTOR3I, \ &&OPCODE_TYPE_ADJUST_TRANSFORM2D, \ &&OPCODE_TYPE_ADJUST_PLANE, \ - &&OPCODE_TYPE_ADJUST_QUAT, \ + &&OPCODE_TYPE_ADJUST_QUATERNION, \ &&OPCODE_TYPE_ADJUST_AABB, \ &&OPCODE_TYPE_ADJUST_BASIS, \ &&OPCODE_TYPE_ADJUST_TRANSFORM, \ @@ -357,7 +398,7 @@ String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const #define OP_GET_VECTOR3I get_vector3i #define OP_GET_RECT2 get_rect2 #define OP_GET_RECT2I get_rect2i -#define OP_GET_QUAT get_quat +#define OP_GET_QUATERNION get_quaternion #define OP_GET_COLOR get_color #define OP_GET_STRING get_string #define OP_GET_STRING_NAME get_string_name @@ -375,7 +416,7 @@ String GDScriptFunction::_get_call_error(const Callable::CallError &p_err, const #define OP_GET_PACKED_VECTOR2_ARRAY get_vector2_array #define OP_GET_PACKED_VECTOR3_ARRAY get_vector3_array #define OP_GET_PACKED_COLOR_ARRAY get_color_array -#define OP_GET_TRANSFORM get_transform +#define OP_GET_TRANSFORM3D get_transform #define OP_GET_TRANSFORM2D get_transform2d #define OP_GET_PLANE get_plane #define OP_GET_AABB get_aabb @@ -489,6 +530,10 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a memnew_placement(&stack[ADDR_STACK_CLASS], Variant(script)); + for (const Map<int, Variant::Type>::Element *E = temporary_slots.front(); E; E = E->next()) { + type_init_function_table[E->get()](&stack[E->key()]); + } + String err_text; #ifdef DEBUG_ENABLED @@ -1452,13 +1497,17 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a if (err.error != Callable::CallError::CALL_OK) { String methodstr = *methodname; String basestr = _get_var_type(base); + bool is_callable = false; if (methodstr == "call") { - if (argc >= 1) { + if (argc >= 1 && base->get_type() != Variant::CALLABLE) { methodstr = String(*argptrs[0]) + " (via call)"; if (err.error == Callable::CallError::CALL_ERROR_INVALID_ARGUMENT) { err.argument += 1; } + } else { + methodstr = base->operator String() + " (Callable)"; + is_callable = true; } } else if (methodstr == "free") { if (err.error == Callable::CallError::CALL_ERROR_INVALID_METHOD) { @@ -1478,7 +1527,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } } } - err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs); + err_text = _get_call_error(err, "function '" + methodstr + (is_callable ? "" : "' in base '" + basestr) + "'", (const Variant **)argptrs); OPCODE_BREAK; } #endif @@ -1567,6 +1616,51 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } DISPATCH_OPCODE; + OPCODE(OPCODE_CALL_BUILTIN_STATIC) { + CHECK_SPACE(4 + instr_arg_count); + + ip += instr_arg_count; + + GD_ERR_BREAK(_code_ptr[ip + 1] < 0 || _code_ptr[ip + 1] >= Variant::VARIANT_MAX); + Variant::Type builtin_type = (Variant::Type)_code_ptr[ip + 1]; + + int methodname_idx = _code_ptr[ip + 2]; + GD_ERR_BREAK(methodname_idx < 0 || methodname_idx >= _global_names_count); + const StringName *methodname = &_global_names_ptr[methodname_idx]; + + int argc = _code_ptr[ip + 3]; + GD_ERR_BREAK(argc < 0); + + GET_INSTRUCTION_ARG(ret, argc); + + const Variant **argptrs = const_cast<const Variant **>(instruction_args); + +#ifdef DEBUG_ENABLED + uint64_t call_time = 0; + + if (GDScriptLanguage::get_singleton()->profiling) { + call_time = OS::get_singleton()->get_ticks_usec(); + } +#endif + + Callable::CallError err; + Variant::call_static(builtin_type, *methodname, argptrs, argc, *ret, err); + +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; + } + + if (err.error != Callable::CallError::CALL_OK) { + err_text = _get_call_error(err, "static function '" + methodname->operator String() + "' in type '" + Variant::get_type_name(builtin_type) + "'", argptrs); + OPCODE_BREAK; + } +#endif + + ip += 4; + } + DISPATCH_OPCODE; + #ifdef DEBUG_ENABLED #define OPCODE_CALL_PTR(m_type) \ OPCODE(OPCODE_CALL_PTRCALL_##m_type) { \ @@ -1639,10 +1733,10 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a OPCODE_CALL_PTR(VECTOR3I); OPCODE_CALL_PTR(TRANSFORM2D); OPCODE_CALL_PTR(PLANE); - OPCODE_CALL_PTR(QUAT); + OPCODE_CALL_PTR(QUATERNION); OPCODE_CALL_PTR(AABB); OPCODE_CALL_PTR(BASIS); - OPCODE_CALL_PTR(TRANSFORM); + OPCODE_CALL_PTR(TRANSFORM3D); OPCODE_CALL_PTR(COLOR); OPCODE_CALL_PTR(STRING_NAME); OPCODE_CALL_PTR(NODE_PATH); @@ -1876,7 +1970,7 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a #ifdef DEBUG_ENABLED if (err.error != Callable::CallError::CALL_OK) { // TODO: Add this information in debug. - String methodstr = "<unkown function>"; + String methodstr = "<unknown function>"; if (dst->get_type() == Variant::STRING) { // Call provided error string. err_text = "Error calling GDScript utility function '" + methodstr + "': " + String(*dst); @@ -1895,7 +1989,10 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a ip += instr_arg_count; - int self_fun = _code_ptr[ip + 1]; + int argc = _code_ptr[ip + 1]; + GD_ERR_BREAK(argc < 0); + + int self_fun = _code_ptr[ip + 2]; #ifdef DEBUG_ENABLED if (self_fun < 0 || self_fun >= _global_names_count) { err_text = "compiler bug, function name not found"; @@ -1904,9 +2001,6 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a #endif const StringName *methodname = &_global_names_ptr[self_fun]; - int argc = _code_ptr[ip + 2]; - GD_ERR_BREAK(argc < 0); - Variant **argptrs = instruction_args; GET_INSTRUCTION_ARG(dst, argc); @@ -2057,6 +2151,34 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } DISPATCH_OPCODE; + OPCODE(OPCODE_CREATE_LAMBDA) { + CHECK_SPACE(2 + instr_arg_count); + + ip += instr_arg_count; + + int captures_count = _code_ptr[ip + 1]; + GD_ERR_BREAK(captures_count < 0); + + int lambda_index = _code_ptr[ip + 2]; + GD_ERR_BREAK(lambda_index < 0 || lambda_index >= _lambdas_count); + GDScriptFunction *lambda = _lambdas_ptr[lambda_index]; + + Vector<Variant> captures; + captures.resize(captures_count); + for (int i = 0; i < captures_count; i++) { + GET_INSTRUCTION_ARG(arg, i); + captures.write[i] = *arg; + } + + GDScriptLambdaCallable *callable = memnew(GDScriptLambdaCallable(Ref<GDScript>(script), lambda, captures)); + + GET_INSTRUCTION_ARG(result, captures_count); + *result = Callable(callable); + + ip += 3; + } + DISPATCH_OPCODE; + OPCODE(OPCODE_JUMP) { CHECK_SPACE(2); int to = _code_ptr[ip + 1]; @@ -3028,10 +3150,10 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a OPCODE_TYPE_ADJUST(VECTOR3I, Vector3i); OPCODE_TYPE_ADJUST(TRANSFORM2D, Transform2D); OPCODE_TYPE_ADJUST(PLANE, Plane); - OPCODE_TYPE_ADJUST(QUAT, Quat); + OPCODE_TYPE_ADJUST(QUATERNION, Quaternion); OPCODE_TYPE_ADJUST(AABB, AABB); OPCODE_TYPE_ADJUST(BASIS, Basis); - OPCODE_TYPE_ADJUST(TRANSFORM, Transform); + OPCODE_TYPE_ADJUST(TRANSFORM, Transform3D); OPCODE_TYPE_ADJUST(COLOR, Color); OPCODE_TYPE_ADJUST(STRING_NAME, StringName); OPCODE_TYPE_ADJUST(NODE_PATH, NodePath); diff --git a/modules/gdscript/language_server/gdscript_extend_parser.cpp b/modules/gdscript/language_server/gdscript_extend_parser.cpp index e63b6ab20e..d106b3b541 100644 --- a/modules/gdscript/language_server/gdscript_extend_parser.cpp +++ b/modules/gdscript/language_server/gdscript_extend_parser.cpp @@ -32,7 +32,6 @@ #include "../gdscript.h" #include "../gdscript_analyzer.h" -#include "core/io/json.h" #include "gdscript_language_protocol.h" #include "gdscript_workspace.h" @@ -40,8 +39,7 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostics.clear(); const List<ParserError> &errors = get_errors(); - for (const List<ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) { - const ParserError &error = E->get(); + for (const ParserError &error : errors) { lsp::Diagnostic diagnostic; diagnostic.severity = lsp::DiagnosticSeverity::Error; diagnostic.message = error.message; @@ -49,8 +47,9 @@ void ExtendGDScriptParser::update_diagnostics() { diagnostic.code = -1; lsp::Range range; lsp::Position pos; - int line = LINE_NUMBER_TO_INDEX(error.line); - const String &line_text = get_lines()[line]; + const PackedStringArray lines = get_lines(); + int line = CLAMP(LINE_NUMBER_TO_INDEX(error.line), 0, lines.size() - 1); + const String &line_text = lines[line]; pos.line = line; pos.character = line_text.length() - line_text.strip_edges(true, false).length(); range.start = pos; @@ -61,8 +60,7 @@ void ExtendGDScriptParser::update_diagnostics() { } const List<GDScriptWarning> &warnings = get_warnings(); - for (const List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) { - const GDScriptWarning &warning = E->get(); + for (const GDScriptWarning &warning : warnings) { lsp::Diagnostic diagnostic; diagnostic.severity = lsp::DiagnosticSeverity::Warning; diagnostic.message = "(" + warning.get_name() + "): " + warning.get_message(); @@ -152,9 +150,9 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p } r_symbol.kind = lsp::SymbolKind::Class; r_symbol.deprecated = false; - r_symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_class->start_line); - r_symbol.range.start.character = LINE_NUMBER_TO_INDEX(p_class->start_column); - r_symbol.range.end.line = LINE_NUMBER_TO_INDEX(p_class->end_line); + r_symbol.range.start.line = p_class->start_line; + r_symbol.range.start.character = p_class->start_column; + r_symbol.range.end.line = lines.size(); r_symbol.selectionRange.start.line = r_symbol.range.start.line; r_symbol.detail = "class " + r_symbol.name; bool is_root_class = &r_symbol == &class_symbol; @@ -167,7 +165,7 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p case ClassNode::Member::VARIABLE: { lsp::DocumentSymbol symbol; symbol.name = m.variable->identifier->name; - symbol.kind = lsp::SymbolKind::Variable; + symbol.kind = m.variable->property == VariableNode::PropertyStyle::PROP_NONE ? lsp::SymbolKind::Variable : lsp::SymbolKind::Property; symbol.deprecated = false; symbol.range.start.line = LINE_NUMBER_TO_INDEX(m.variable->start_line); symbol.range.start.character = LINE_NUMBER_TO_INDEX(m.variable->start_column); @@ -182,7 +180,7 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p symbol.detail += ": " + m.get_datatype().to_string(); } if (m.variable->initializer != nullptr && m.variable->initializer->is_constant) { - symbol.detail += " = " + JSON::print(m.variable->initializer->reduced_value); + symbol.detail += " = " + m.variable->initializer->reduced_value.to_json_string(); } symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(m.variable->start_line)); @@ -223,10 +221,10 @@ void ExtendGDScriptParser::parse_class_symbol(const GDScriptParser::ClassNode *p } } } else { - value_text = JSON::print(default_value); + value_text = default_value.to_json_string(); } } else { - value_text = JSON::print(default_value); + value_text = default_value.to_json_string(); } if (!value_text.is_empty()) { symbol.detail += " = " + value_text; @@ -319,7 +317,7 @@ void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionN const String uri = get_uri(); r_symbol.name = p_func->identifier->name; - r_symbol.kind = lsp::SymbolKind::Function; + r_symbol.kind = p_func->is_static ? lsp::SymbolKind::Function : lsp::SymbolKind::Method; r_symbol.detail = "func " + String(p_func->identifier->name) + "("; r_symbol.deprecated = false; r_symbol.range.start.line = LINE_NUMBER_TO_INDEX(p_func->start_line); @@ -352,8 +350,7 @@ void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionN parameters += ": " + parameter->get_datatype().to_string(); } if (parameter->default_value != nullptr) { - String value = JSON::print(parameter->default_value->reduced_value); - parameters += " = " + value; + parameters += " = " + parameter->default_value->reduced_value.to_json_string(); } } r_symbol.detail += parameters + ")"; @@ -361,24 +358,73 @@ void ExtendGDScriptParser::parse_function_symbol(const GDScriptParser::FunctionN r_symbol.detail += " -> " + p_func->get_datatype().to_string(); } - for (int i = 0; i < p_func->body->locals.size(); i++) { - const SuiteNode::Local &local = p_func->body->locals[i]; - lsp::DocumentSymbol symbol; - symbol.name = local.name; - symbol.kind = local.type == SuiteNode::Local::CONSTANT ? lsp::SymbolKind::Constant : lsp::SymbolKind::Variable; - symbol.range.start.line = LINE_NUMBER_TO_INDEX(local.start_line); - symbol.range.start.character = LINE_NUMBER_TO_INDEX(local.start_column); - symbol.range.end.line = LINE_NUMBER_TO_INDEX(local.end_line); - symbol.range.end.character = LINE_NUMBER_TO_INDEX(local.end_column); - symbol.uri = uri; - symbol.script_path = path; - symbol.detail = SuiteNode::Local::CONSTANT ? "const " : "var "; - symbol.detail += symbol.name; - if (local.get_datatype().is_hard_type()) { - symbol.detail += ": " + local.get_datatype().to_string(); + List<GDScriptParser::SuiteNode *> function_nodes; + + List<GDScriptParser::Node *> node_stack; + node_stack.push_back(p_func->body); + + while (!node_stack.is_empty()) { + GDScriptParser::Node *node = node_stack[0]; + node_stack.pop_front(); + + switch (node->type) { + case GDScriptParser::TypeNode::IF: { + GDScriptParser::IfNode *if_node = (GDScriptParser::IfNode *)node; + node_stack.push_back(if_node->true_block); + if (if_node->false_block) { + node_stack.push_back(if_node->false_block); + } + } break; + + case GDScriptParser::TypeNode::FOR: { + GDScriptParser::ForNode *for_node = (GDScriptParser::ForNode *)node; + node_stack.push_back(for_node->loop); + } break; + + case GDScriptParser::TypeNode::WHILE: { + GDScriptParser::WhileNode *while_node = (GDScriptParser::WhileNode *)node; + node_stack.push_back(while_node->loop); + } break; + + case GDScriptParser::TypeNode::MATCH_BRANCH: { + GDScriptParser::MatchBranchNode *match_node = (GDScriptParser::MatchBranchNode *)node; + node_stack.push_back(match_node->block); + } break; + + case GDScriptParser::TypeNode::SUITE: { + GDScriptParser::SuiteNode *suite_node = (GDScriptParser::SuiteNode *)node; + function_nodes.push_back(suite_node); + for (int i = 0; i < suite_node->statements.size(); ++i) { + node_stack.push_back(suite_node->statements[i]); + } + } break; + + default: + continue; + } + } + + for (List<GDScriptParser::SuiteNode *>::Element *N = function_nodes.front(); N; N = N->next()) { + const GDScriptParser::SuiteNode *suite_node = N->get(); + for (int i = 0; i < suite_node->locals.size(); i++) { + const SuiteNode::Local &local = suite_node->locals[i]; + lsp::DocumentSymbol symbol; + symbol.name = local.name; + symbol.kind = local.type == SuiteNode::Local::CONSTANT ? lsp::SymbolKind::Constant : lsp::SymbolKind::Variable; + symbol.range.start.line = LINE_NUMBER_TO_INDEX(local.start_line); + symbol.range.start.character = LINE_NUMBER_TO_INDEX(local.start_column); + symbol.range.end.line = LINE_NUMBER_TO_INDEX(local.end_line); + symbol.range.end.character = LINE_NUMBER_TO_INDEX(local.end_column); + symbol.uri = uri; + symbol.script_path = path; + symbol.detail = local.type == SuiteNode::Local::CONSTANT ? "const " : "var "; + symbol.detail += symbol.name; + if (local.get_datatype().is_hard_type()) { + symbol.detail += ": " + local.get_datatype().to_string(); + } + symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(local.start_line)); + r_symbol.children.push_back(symbol); } - symbol.documentation = parse_documentation(LINE_NUMBER_TO_INDEX(local.start_line)); - r_symbol.children.push_back(symbol); } } @@ -419,8 +465,8 @@ String ExtendGDScriptParser::parse_documentation(int p_line, bool p_docs_down) { } String doc; - for (List<String>::Element *E = doc_lines.front(); E; E = E->next()) { - doc += E->get() + "\n"; + for (const String &E : doc_lines) { + doc += E + "\n"; } return doc; } @@ -647,7 +693,9 @@ Dictionary ExtendGDScriptParser::dump_function_api(const GDScriptParser::Functio ERR_FAIL_NULL_V(p_func, func); func["name"] = p_func->identifier->name; func["return_type"] = p_func->get_datatype().to_string(); - func["rpc_mode"] = p_func->rpc_mode; + func["rpc_mode"] = p_func->rpc_config.rpc_mode; + func["rpc_transfer_mode"] = p_func->rpc_config.transfer_mode; + func["rpc_transfer_channel"] = p_func->rpc_config.channel; Array parameters; for (int i = 0; i < p_func->parameters.size(); i++) { Dictionary arg; diff --git a/modules/gdscript/language_server/gdscript_language_protocol.cpp b/modules/gdscript/language_server/gdscript_language_protocol.cpp index 912c9a174e..b6c48468f5 100644 --- a/modules/gdscript/language_server/gdscript_language_protocol.cpp +++ b/modules/gdscript/language_server/gdscript_language_protocol.cpp @@ -31,8 +31,6 @@ #include "gdscript_language_protocol.h" #include "core/config/project_settings.h" -#include "core/io/json.h" -#include "core/os/copymem.h" #include "editor/doc_tools.h" #include "editor/editor_log.h" #include "editor/editor_node.h" @@ -130,13 +128,13 @@ Error GDScriptLanguageProtocol::on_client_connected() { peer->connection = tcp_peer; clients.set(next_client_id, peer); next_client_id++; - EditorNode::get_log()->add_message("Connection Taken", EditorLog::MSG_TYPE_EDITOR); + EditorNode::get_log()->add_message("[LSP] Connection Taken", EditorLog::MSG_TYPE_EDITOR); return OK; } void GDScriptLanguageProtocol::on_client_disconnected(const int &p_client_id) { clients.erase(p_client_id); - EditorNode::get_log()->add_message("Disconnected", EditorLog::MSG_TYPE_EDITOR); + EditorNode::get_log()->add_message("[LSP] Disconnected", EditorLog::MSG_TYPE_EDITOR); } String GDScriptLanguageProtocol::process_message(const String &p_text) { @@ -195,7 +193,7 @@ Dictionary GDScriptLanguageProtocol::initialize(const Dictionary &p_params) { vformat("GDScriptLanguageProtocol: Can't initialize invalid peer '%d'.", latest_client_id)); Ref<LSPeer> peer = clients.get(latest_client_id); if (peer != nullptr) { - String msg = JSON::print(request); + String msg = Variant(request).to_json_string(); msg = format_output(msg); (*peer)->res_queue.push_back(msg.utf8()); } @@ -256,7 +254,7 @@ void GDScriptLanguageProtocol::poll() { } } -Error GDScriptLanguageProtocol::start(int p_port, const IP_Address &p_bind_ip) { +Error GDScriptLanguageProtocol::start(int p_port, const IPAddress &p_bind_ip) { return server->listen(p_port, p_bind_ip); } @@ -281,7 +279,7 @@ void GDScriptLanguageProtocol::notify_client(const String &p_method, const Varia ERR_FAIL_COND(peer == nullptr); Dictionary message = make_notification(p_method, p_params); - String msg = JSON::print(message); + String msg = Variant(message).to_json_string(); msg = format_output(msg); peer->res_queue.push_back(msg.utf8()); } @@ -295,10 +293,10 @@ bool GDScriptLanguageProtocol::is_goto_native_symbols_enabled() const { } GDScriptLanguageProtocol::GDScriptLanguageProtocol() { - server.instance(); + server.instantiate(); singleton = this; - workspace.instance(); - text_document.instance(); + workspace.instantiate(); + text_document.instantiate(); set_scope("textDocument", text_document.ptr()); set_scope("completionItem", text_document.ptr()); set_scope("workspace", workspace.ptr()); diff --git a/modules/gdscript/language_server/gdscript_language_protocol.h b/modules/gdscript/language_server/gdscript_language_protocol.h index 8b08ae0655..5a2dd55c46 100644 --- a/modules/gdscript/language_server/gdscript_language_protocol.h +++ b/modules/gdscript/language_server/gdscript_language_protocol.h @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GDSCRIPT_PROTOCAL_SERVER_H -#define GDSCRIPT_PROTOCAL_SERVER_H +#ifndef GDSCRIPT_LANGUAGE_PROTOCOL_H +#define GDSCRIPT_LANGUAGE_PROTOCOL_H #include "core/io/stream_peer.h" #include "core/io/stream_peer_tcp.h" @@ -37,7 +37,13 @@ #include "gdscript_text_document.h" #include "gdscript_workspace.h" #include "lsp.hpp" + +#include "modules/modules_enabled.gen.h" +#ifdef MODULE_JSONRPC_ENABLED #include "modules/jsonrpc/jsonrpc.h" +#else +#error "Can't build GDScript LSP without JSONRPC module." +#endif #define LSP_MAX_BUFFER_SIZE 4194304 #define LSP_MAX_CLIENTS 8 @@ -46,7 +52,7 @@ class GDScriptLanguageProtocol : public JSONRPC { GDCLASS(GDScriptLanguageProtocol, JSONRPC) private: - struct LSPeer : Reference { + struct LSPeer : RefCounted { Ref<StreamPeerTCP> connection; uint8_t req_buf[LSP_MAX_BUFFER_SIZE]; @@ -69,7 +75,7 @@ private: static GDScriptLanguageProtocol *singleton; HashMap<int, Ref<LSPeer>> clients; - Ref<TCP_Server> server; + Ref<TCPServer> server; int latest_client_id = 0; int next_client_id = 0; @@ -97,7 +103,7 @@ public: _FORCE_INLINE_ bool is_initialized() const { return _initialized; } void poll(); - Error start(int p_port, const IP_Address &p_bind_ip); + Error start(int p_port, const IPAddress &p_bind_ip); void stop(); void notify_client(const String &p_method, const Variant &p_params = Variant(), int p_client_id = -1); @@ -108,4 +114,4 @@ public: GDScriptLanguageProtocol(); }; -#endif +#endif // GDSCRIPT_LANGUAGE_PROTOCOL_H diff --git a/modules/gdscript/language_server/gdscript_language_server.cpp b/modules/gdscript/language_server/gdscript_language_server.cpp index 98ada9de4d..c47164d95b 100644 --- a/modules/gdscript/language_server/gdscript_language_server.cpp +++ b/modules/gdscript/language_server/gdscript_language_server.cpp @@ -30,7 +30,7 @@ #include "gdscript_language_server.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "core/os/os.h" #include "editor/editor_log.h" #include "editor/editor_node.h" @@ -78,7 +78,7 @@ void GDScriptLanguageServer::thread_main(void *p_userdata) { void GDScriptLanguageServer::start() { port = (int)_EDITOR_GET("network/language_server/remote_port"); use_thread = (bool)_EDITOR_GET("network/language_server/use_thread"); - if (protocol.start(port, IP_Address("127.0.0.1")) == OK) { + if (protocol.start(port, IPAddress("127.0.0.1")) == OK) { EditorNode::get_log()->add_message("--- GDScript language server started ---", EditorLog::MSG_TYPE_EDITOR); if (use_thread) { thread_running = true; @@ -101,7 +101,7 @@ void GDScriptLanguageServer::stop() { } void register_lsp_types() { - ClassDB::register_class<GDScriptLanguageProtocol>(); - ClassDB::register_class<GDScriptTextDocument>(); - ClassDB::register_class<GDScriptWorkspace>(); + GDREGISTER_CLASS(GDScriptLanguageProtocol); + GDREGISTER_CLASS(GDScriptTextDocument); + GDREGISTER_CLASS(GDScriptWorkspace); } diff --git a/modules/gdscript/language_server/gdscript_text_document.cpp b/modules/gdscript/language_server/gdscript_text_document.cpp index 030633274c..9574c765bc 100644 --- a/modules/gdscript/language_server/gdscript_text_document.cpp +++ b/modules/gdscript/language_server/gdscript_text_document.cpp @@ -40,11 +40,14 @@ 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("didSave"), &GDScriptTextDocument::didSave); ClassDB::bind_method(D_METHOD("nativeSymbol"), &GDScriptTextDocument::nativeSymbol); ClassDB::bind_method(D_METHOD("documentSymbol"), &GDScriptTextDocument::documentSymbol); ClassDB::bind_method(D_METHOD("completion"), &GDScriptTextDocument::completion); ClassDB::bind_method(D_METHOD("resolve"), &GDScriptTextDocument::resolve); + ClassDB::bind_method(D_METHOD("rename"), &GDScriptTextDocument::rename); ClassDB::bind_method(D_METHOD("foldingRange"), &GDScriptTextDocument::foldingRange); ClassDB::bind_method(D_METHOD("codeLens"), &GDScriptTextDocument::codeLens); ClassDB::bind_method(D_METHOD("documentLink"), &GDScriptTextDocument::documentLink); @@ -61,6 +64,11 @@ void GDScriptTextDocument::didOpen(const Variant &p_param) { sync_script_content(doc.uri, doc.text); } +void GDScriptTextDocument::didClose(const Variant &p_param) { + // Left empty on purpose. Godot does nothing special on closing a document, + // but it satisfies LSP clients that require didClose be implemented. +} + void GDScriptTextDocument::didChange(const Variant &p_param) { lsp::TextDocumentItem doc = load_document_item(p_param); Dictionary dict = p_param; @@ -73,6 +81,20 @@ void GDScriptTextDocument::didChange(const Variant &p_param) { sync_script_content(doc.uri, doc.text); } +void GDScriptTextDocument::didSave(const Variant &p_param) { + lsp::TextDocumentItem doc = load_document_item(p_param); + Dictionary dict = p_param; + String text = dict["text"]; + + 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);*/ +} + lsp::TextDocumentItem GDScriptTextDocument::load_document_item(const Variant &p_param) { lsp::TextDocumentItem doc; Dictionary params = p_param; @@ -151,8 +173,7 @@ Array GDScriptTextDocument::completion(const Dictionary &p_params) { int i = 0; arr.resize(options.size()); - for (const List<ScriptCodeCompletionOption>::Element *E = options.front(); E; E = E->next()) { - const ScriptCodeCompletionOption &option = E->get(); + for (const ScriptCodeCompletionOption &option : options) { lsp::CompletionItem item; item.label = option.display; item.data = request_data; @@ -210,6 +231,14 @@ Array GDScriptTextDocument::completion(const Dictionary &p_params) { return arr; } +Dictionary GDScriptTextDocument::rename(const Dictionary &p_params) { + lsp::TextDocumentPositionParams params; + params.load(p_params); + String new_name = p_params["newName"]; + + return GDScriptLanguageProtocol::get_singleton()->get_workspace()->rename(params, new_name); +} + Dictionary GDScriptTextDocument::resolve(const Dictionary &p_params) { lsp::CompletionItem item; item.load(p_params); @@ -288,8 +317,8 @@ Array GDScriptTextDocument::documentLink(const Dictionary &p_params) { List<lsp::DocumentLink> links; GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_document_links(params.textDocument.uri, links); - for (const List<lsp::DocumentLink>::Element *E = links.front(); E; E = E->next()) { - ret.push_back(E->get().to_json()); + for (const lsp::DocumentLink &E : links) { + ret.push_back(E.to_json()); } return ret; } @@ -316,8 +345,8 @@ Variant GDScriptTextDocument::hover(const Dictionary &p_params) { Array contents; List<const lsp::DocumentSymbol *> list; GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(params, list); - for (List<const lsp::DocumentSymbol *>::Element *E = list.front(); E; E = E->next()) { - if (const lsp::DocumentSymbol *s = E->get()) { + for (const lsp::DocumentSymbol *&E : list) { + if (const lsp::DocumentSymbol *s = E) { contents.push_back(s->render().value); } } @@ -367,7 +396,7 @@ Variant GDScriptTextDocument::declaration(const Dictionary &p_params) { id = "class_global:" + symbol->native_class + ":" + symbol->name; break; } - call_deferred("show_native_symbol_in_editor", id); + call_deferred(SNAME("show_native_symbol_in_editor"), id); } else { notify_client_show_symbol(symbol); } @@ -400,11 +429,19 @@ GDScriptTextDocument::~GDScriptTextDocument() { void GDScriptTextDocument::sync_script_content(const String &p_path, const String &p_content) { String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(p_path); 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) { - ScriptEditor::get_singleton()->call_deferred("_help_class_goto", p_symbol_id); + ScriptEditor::get_singleton()->call_deferred(SNAME("_help_class_goto"), p_symbol_id); DisplayServer::get_singleton()->window_move_to_foreground(); } @@ -424,8 +461,8 @@ Array GDScriptTextDocument::find_symbols(const lsp::TextDocumentPositionParams & } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) { List<const lsp::DocumentSymbol *> list; GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(p_location, list); - for (List<const lsp::DocumentSymbol *>::Element *E = list.front(); E; E = E->next()) { - if (const lsp::DocumentSymbol *s = E->get()) { + for (const lsp::DocumentSymbol *&E : list) { + if (const lsp::DocumentSymbol *s = E) { if (!s->uri.is_empty()) { lsp::Location location; location.uri = s->uri; diff --git a/modules/gdscript/language_server/gdscript_text_document.h b/modules/gdscript/language_server/gdscript_text_document.h index 792e601bc1..9021c84a3f 100644 --- a/modules/gdscript/language_server/gdscript_text_document.h +++ b/modules/gdscript/language_server/gdscript_text_document.h @@ -31,19 +31,21 @@ #ifndef GDSCRIPT_TEXT_DOCUMENT_H #define GDSCRIPT_TEXT_DOCUMENT_H -#include "core/object/reference.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" +#include "core/object/ref_counted.h" #include "lsp.hpp" -class GDScriptTextDocument : public Reference { - GDCLASS(GDScriptTextDocument, Reference) +class GDScriptTextDocument : public RefCounted { + GDCLASS(GDScriptTextDocument, RefCounted) protected: static void _bind_methods(); FileAccess *file_checker; void didOpen(const Variant &p_param); + void didClose(const Variant &p_param); void didChange(const Variant &p_param); + void didSave(const Variant &p_param); void sync_script_content(const String &p_path, const String &p_content); void show_native_symbol_in_editor(const String &p_symbol_id); @@ -60,6 +62,7 @@ public: Array documentSymbol(const Dictionary &p_params); Array completion(const Dictionary &p_params); Dictionary resolve(const Dictionary &p_params); + Dictionary rename(const Dictionary &p_params); Array foldingRange(const Dictionary &p_params); Array codeLens(const Dictionary &p_params); Array documentLink(const Dictionary &p_params); diff --git a/modules/gdscript/language_server/gdscript_workspace.cpp b/modules/gdscript/language_server/gdscript_workspace.cpp index 69cad1a335..1512b4bb89 100644 --- a/modules/gdscript/language_server/gdscript_workspace.cpp +++ b/modules/gdscript/language_server/gdscript_workspace.cpp @@ -42,6 +42,7 @@ #include "scene/resources/packed_scene.h" void GDScriptWorkspace::_bind_methods() { + ClassDB::bind_method(D_METHOD("didDeleteFiles"), &GDScriptWorkspace::did_delete_files); ClassDB::bind_method(D_METHOD("symbol"), &GDScriptWorkspace::symbol); ClassDB::bind_method(D_METHOD("parse_script", "path", "content"), &GDScriptWorkspace::parse_script); ClassDB::bind_method(D_METHOD("parse_local_script", "path"), &GDScriptWorkspace::parse_local_script); @@ -51,6 +52,16 @@ void GDScriptWorkspace::_bind_methods() { ClassDB::bind_method(D_METHOD("generate_script_api", "path"), &GDScriptWorkspace::generate_script_api); } +void GDScriptWorkspace::did_delete_files(const Dictionary &p_params) { + Array files = p_params["files"]; + for (int i = 0; i < files.size(); ++i) { + Dictionary file = files[i]; + String uri = file["uri"]; + String path = get_file_path(uri); + parse_script(path, ""); + } +} + void GDScriptWorkspace::remove_cache_parser(const String &p_path) { Map<String, ExtendGDScriptParser *>::Element *parser = parse_results.find(p_path); Map<String, ExtendGDScriptParser *>::Element *script = scripts.find(p_path); @@ -105,11 +116,40 @@ const lsp::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_ return nullptr; } +const lsp::DocumentSymbol *GDScriptWorkspace::get_parameter_symbol(const lsp::DocumentSymbol *p_parent, const String &symbol_identifier) { + for (int i = 0; i < p_parent->children.size(); ++i) { + const lsp::DocumentSymbol *parameter_symbol = &p_parent->children[i]; + if (!parameter_symbol->detail.is_empty() && parameter_symbol->name == symbol_identifier) { + return parameter_symbol; + } + } + + return nullptr; +} + +const lsp::DocumentSymbol *GDScriptWorkspace::get_local_symbol(const ExtendGDScriptParser *p_parser, const String &p_symbol_identifier) { + const lsp::DocumentSymbol *class_symbol = &p_parser->get_symbols(); + + for (int i = 0; i < class_symbol->children.size(); ++i) { + if (class_symbol->children[i].kind == lsp::SymbolKind::Function || class_symbol->children[i].kind == lsp::SymbolKind::Class) { + const lsp::DocumentSymbol *function_symbol = &class_symbol->children[i]; + + for (int l = 0; l < function_symbol->children.size(); ++l) { + const lsp::DocumentSymbol *local = &function_symbol->children[l]; + if (!local->detail.is_empty() && local->name == p_symbol_identifier) { + return local; + } + } + } + } + + return nullptr; +} + void GDScriptWorkspace::reload_all_workspace_scripts() { List<String> paths; list_script_files("res://", paths); - for (List<String>::Element *E = paths.front(); E; E = E->next()) { - const String &path = E->get(); + for (const String &path : paths) { Error err; String content = FileAccess::get_file_as_string(path, &err); ERR_CONTINUE(err != OK); @@ -177,7 +217,9 @@ Array GDScriptWorkspace::symbol(const Dictionary &p_params) { E->get()->get_symbols().symbol_tree_as_list(E->key(), script_symbols); for (int i = 0; i < script_symbols.size(); ++i) { if (query.is_subsequence_ofi(script_symbols[i].name)) { - arr.push_back(script_symbols[i].to_json()); + lsp::DocumentedSymbolInformation symbol = script_symbols[i]; + symbol.location.uri = get_file_uri(symbol.location.uri); + arr.push_back(symbol.to_json()); } } } @@ -219,18 +261,13 @@ Error GDScriptWorkspace::initialize() { class_symbol.children.push_back(symbol); } - Vector<DocData::PropertyDoc> properties; - properties.append_array(class_data.properties); - const int theme_prop_start_idx = properties.size(); - properties.append_array(class_data.theme_properties); - for (int i = 0; i < class_data.properties.size(); i++) { const DocData::PropertyDoc &data = class_data.properties[i]; lsp::DocumentSymbol symbol; symbol.name = data.name; symbol.native_class = class_name; symbol.kind = lsp::SymbolKind::Property; - symbol.detail = String(i >= theme_prop_start_idx ? "<Theme> var" : "var") + " " + class_name + "." + data.name; + symbol.detail = "var " + class_name + "." + data.name; if (data.enumeration.length()) { symbol.detail += ": " + data.enumeration; } else { @@ -240,6 +277,17 @@ Error GDScriptWorkspace::initialize() { class_symbol.children.push_back(symbol); } + for (int i = 0; i < class_data.theme_properties.size(); i++) { + const DocData::ThemeItemDoc &data = class_data.theme_properties[i]; + lsp::DocumentSymbol symbol; + symbol.name = data.name; + symbol.native_class = class_name; + symbol.kind = lsp::SymbolKind::Property; + symbol.detail = "<Theme> var " + class_name + "." + data.name + ": " + data.type; + symbol.documentation = data.description; + class_symbol.children.push_back(symbol); + } + Vector<DocData::MethodDoc> methods_signals; methods_signals.append_array(class_data.methods); const int signal_start_idx = methods_signals.size(); @@ -338,6 +386,50 @@ Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_cont return err; } +Dictionary GDScriptWorkspace::rename(const lsp::TextDocumentPositionParams &p_doc_pos, const String &new_name) { + Error err; + String path = get_file_path(p_doc_pos.textDocument.uri); + + lsp::WorkspaceEdit edit; + + List<String> paths; + list_script_files("res://", paths); + + const lsp::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos); + if (reference_symbol) { + String identifier = reference_symbol->name; + + for (List<String>::Element *PE = paths.front(); PE; PE = PE->next()) { + PackedStringArray content = FileAccess::get_file_as_string(PE->get(), &err).split("\n"); + for (int i = 0; i < content.size(); ++i) { + String line = content[i]; + + int character = line.find(identifier); + while (character > -1) { + lsp::TextDocumentPositionParams params; + + lsp::TextDocumentIdentifier text_doc; + text_doc.uri = get_file_uri(PE->get()); + + params.textDocument = text_doc; + params.position.line = i; + params.position.character = character; + + const lsp::DocumentSymbol *other_symbol = resolve_symbol(params); + + if (other_symbol == reference_symbol) { + edit.add_change(text_doc.uri, i, character, character + identifier.length(), new_name); + } + + character = line.find(identifier, character + 1); + } + } + } + } + + return edit.to_json(); +} + Error GDScriptWorkspace::parse_local_script(const String &p_path) { Error err; String content = FileAccess::get_file_as_string(p_path, &err); @@ -413,7 +505,7 @@ Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) { RES owner_res = ResourceLoader::load(owner_path); if (Object::cast_to<PackedScene>(owner_res.ptr())) { Ref<PackedScene> owner_packed_scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*owner_res)); - owner_scene_node = owner_packed_scene->instance(); + owner_scene_node = owner_packed_scene->instantiate(); break; } } @@ -428,8 +520,31 @@ void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<S if (const ExtendGDScriptParser *parser = get_parse_result(path)) { Node *owner_scene_node = _get_owner_scene_node(path); + + Array stack; + Node *current = nullptr; + if (owner_scene_node != nullptr) { + stack.push_back(owner_scene_node); + + while (!stack.is_empty()) { + current = stack.pop_back(); + Ref<GDScript> script = current->get_script(); + if (script.is_valid() && script->get_path() == path) { + break; + } + for (int i = 0; i < current->get_child_count(); ++i) { + stack.push_back(current->get_child(i)); + } + } + + Ref<GDScript> script = current->get_script(); + if (!script.is_valid() || script->get_path() != path) { + current = owner_scene_node; + } + } + String code = parser->get_text_for_completion(p_params.position); - GDScriptLanguage::get_singleton()->complete_code(code, path, owner_scene_node, r_options, forced, call_hint); + GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint); if (owner_scene_node) { memdelete(owner_scene_node); } @@ -466,10 +581,16 @@ const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocu String target_script_path = path; if (!ret.script.is_null()) { target_script_path = ret.script->get_path(); + } else if (!ret.class_path.is_empty()) { + target_script_path = ret.class_path; } if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) { symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location)); + + if (symbol && symbol->kind == lsp::SymbolKind::Function && symbol->name != symbol_identifier) { + symbol = get_parameter_symbol(symbol, symbol_identifier); + } } } else { @@ -481,6 +602,10 @@ const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocu } } else { symbol = parser->get_member_symbol(symbol_identifier); + + if (!symbol) { + symbol = get_local_symbol(parser, symbol_identifier); + } } } } @@ -546,8 +671,8 @@ const lsp::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const lsp::N void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<lsp::DocumentLink> &r_list) { if (const ExtendGDScriptParser *parser = get_parse_successed_script(get_file_path(p_uri))) { const List<lsp::DocumentLink> &links = parser->get_document_links(); - for (const List<lsp::DocumentLink>::Element *E = links.front(); E; E = E->next()) { - r_list.push_back(E->get()); + for (const lsp::DocumentLink &E : links) { + r_list.push_back(E); } } } @@ -574,8 +699,7 @@ Error GDScriptWorkspace::resolve_signature(const lsp::TextDocumentPositionParams GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(text_pos, symbols); } - for (List<const lsp::DocumentSymbol *>::Element *E = symbols.front(); E; E = E->next()) { - const lsp::DocumentSymbol *symbol = E->get(); + for (const lsp::DocumentSymbol *const &symbol : symbols) { if (symbol->kind == lsp::SymbolKind::Method || symbol->kind == lsp::SymbolKind::Function) { lsp::SignatureInformation signature_info; signature_info.label = symbol->detail; diff --git a/modules/gdscript/language_server/gdscript_workspace.h b/modules/gdscript/language_server/gdscript_workspace.h index 7fd8bfcf20..9496677449 100644 --- a/modules/gdscript/language_server/gdscript_workspace.h +++ b/modules/gdscript/language_server/gdscript_workspace.h @@ -37,8 +37,8 @@ #include "gdscript_extend_parser.h" #include "lsp.hpp" -class GDScriptWorkspace : public Reference { - GDCLASS(GDScriptWorkspace, Reference); +class GDScriptWorkspace : public RefCounted { + GDCLASS(GDScriptWorkspace, RefCounted); private: void _get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners); @@ -52,6 +52,8 @@ protected: const lsp::DocumentSymbol *get_native_symbol(const String &p_class, const String &p_member = "") const; const lsp::DocumentSymbol *get_script_symbol(const String &p_path) const; + const lsp::DocumentSymbol *get_parameter_symbol(const lsp::DocumentSymbol *p_parent, const String &symbol_identifier); + const lsp::DocumentSymbol *get_local_symbol(const ExtendGDScriptParser *p_parser, const String &p_symbol_identifier); void reload_all_workspace_scripts(); @@ -89,6 +91,8 @@ public: void resolve_document_links(const String &p_uri, List<lsp::DocumentLink> &r_list); Dictionary generate_script_api(const String &p_path); Error resolve_signature(const lsp::TextDocumentPositionParams &p_doc_pos, lsp::SignatureHelp &r_signature); + void did_delete_files(const Dictionary &p_params); + Dictionary rename(const lsp::TextDocumentPositionParams &p_doc_pos, const String &new_name); GDScriptWorkspace(); ~GDScriptWorkspace(); diff --git a/modules/gdscript/language_server/lsp.hpp b/modules/gdscript/language_server/lsp.hpp index 6635098be2..9ac6c6bd4e 100644 --- a/modules/gdscript/language_server/lsp.hpp +++ b/modules/gdscript/language_server/lsp.hpp @@ -255,6 +255,62 @@ struct TextEdit { }; /** + * The edits to be applied. + */ +struct WorkspaceEdit { + /** + * Holds changes to existing resources. + */ + Map<String, Vector<TextEdit>> changes; + + _FORCE_INLINE_ Dictionary to_json() const { + Dictionary dict; + + Dictionary out_changes; + for (Map<String, Vector<TextEdit>>::Element *E = changes.front(); E; E = E->next()) { + Array edits; + for (int i = 0; i < E->get().size(); ++i) { + Dictionary text_edit; + text_edit["range"] = E->get()[i].range.to_json(); + text_edit["newText"] = E->get()[i].newText; + edits.push_back(text_edit); + } + out_changes[E->key()] = edits; + } + dict["changes"] = out_changes; + + return dict; + } + + _FORCE_INLINE_ void add_change(const String &uri, const int &line, const int &start_character, const int &end_character, const String &new_text) { + if (Map<String, Vector<TextEdit>>::Element *E = changes.find(uri)) { + Vector<TextEdit> edit_list = E->value(); + for (int i = 0; i < edit_list.size(); ++i) { + TextEdit edit = edit_list[i]; + if (edit.range.start.character == start_character) { + return; + } + } + } + + TextEdit new_edit; + new_edit.newText = new_text; + new_edit.range.start.line = line; + new_edit.range.start.character = start_character; + new_edit.range.end.line = line; + new_edit.range.end.character = end_character; + + if (Map<String, Vector<TextEdit>>::Element *E = changes.find(uri)) { + E->value().push_back(new_edit); + } else { + Vector<TextEdit> edit_list; + edit_list.push_back(new_edit); + changes.insert(uri, edit_list); + } + } +}; + +/** * Represents a reference to a command. * Provides a title which will be used to represent a command in the UI. * Commands are identified by a string identifier. @@ -486,7 +542,7 @@ struct TextDocumentSyncOptions { * If present save notifications are sent to the server. If omitted the notification should not be * sent. */ - bool save = false; + SaveOptions save; Dictionary to_json() { Dictionary dict; @@ -494,7 +550,7 @@ struct TextDocumentSyncOptions { dict["willSave"] = willSave; dict["openClose"] = openClose; dict["change"] = change; - dict["save"] = save; + dict["save"] = save.to_json(); return dict; } }; @@ -766,7 +822,7 @@ struct MarkupContent { // Use namespace instead of enumeration to follow the LSP specifications // lsp::EnumName::EnumValue is OK but lsp::EnumValue is not -// And here C++ compilers are unhappy with our enumeration name like Color, File, Reference etc. +// And here C++ compilers are unhappy with our enumeration name like Color, File, RefCounted etc. /** * The kind of a completion entry. */ @@ -788,7 +844,7 @@ static const int Keyword = 14; static const int Snippet = 15; static const int Color = 16; static const int File = 17; -static const int Reference = 18; +static const int RefCounted = 18; static const int Folder = 19; static const int EnumMember = 20; static const int Constant = 21; @@ -1018,32 +1074,32 @@ struct CompletionList { * A symbol kind. */ namespace SymbolKind { -static const int File = 0; -static const int Module = 1; -static const int Namespace = 2; -static const int Package = 3; -static const int Class = 4; -static const int Method = 5; -static const int Property = 6; -static const int Field = 7; -static const int Constructor = 8; -static const int Enum = 9; -static const int Interface = 10; -static const int Function = 11; -static const int Variable = 12; -static const int Constant = 13; -static const int String = 14; -static const int Number = 15; -static const int Boolean = 16; -static const int Array = 17; -static const int Object = 18; -static const int Key = 19; -static const int Null = 20; -static const int EnumMember = 21; -static const int Struct = 22; -static const int Event = 23; -static const int Operator = 24; -static const int TypeParameter = 25; +static const int File = 1; +static const int Module = 2; +static const int Namespace = 3; +static const int Package = 4; +static const int Class = 5; +static const int Method = 6; +static const int Property = 7; +static const int Field = 8; +static const int Constructor = 9; +static const int Enum = 10; +static const int Interface = 11; +static const int Function = 12; +static const int Variable = 13; +static const int Constant = 14; +static const int String = 15; +static const int Number = 16; +static const int Boolean = 17; +static const int Array = 18; +static const int Object = 19; +static const int Key = 20; +static const int Null = 21; +static const int EnumMember = 22; +static const int Struct = 23; +static const int Event = 24; +static const int Operator = 25; +static const int TypeParameter = 26; }; // namespace SymbolKind /** @@ -1528,6 +1584,114 @@ struct SignatureHelp { } }; +/** + * A pattern to describe in which file operation requests or notifications + * the server is interested in. + */ +struct FileOperationPattern { + /** + * The glob pattern to match. + */ + String glob = "**/*.gd"; + + /** + * Whether to match `file`s or `folder`s with this pattern. + * + * Matches both if undefined. + */ + String matches = "file"; + + Dictionary to_json() const { + Dictionary dict; + + dict["glob"] = glob; + dict["matches"] = matches; + + return dict; + } +}; + +/** + * A filter to describe in which file operation requests or notifications + * the server is interested in. + */ +struct FileOperationFilter { + /** + * The actual file operation pattern. + */ + FileOperationPattern pattern; + + Dictionary to_json() const { + Dictionary dict; + + dict["pattern"] = pattern.to_json(); + + return dict; + } +}; + +/** + * The options to register for file operations. + */ +struct FileOperationRegistrationOptions { + /** + * The actual filters. + */ + Vector<FileOperationFilter> filters; + + FileOperationRegistrationOptions() { + filters.push_back(FileOperationFilter()); + } + + Dictionary to_json() const { + Dictionary dict; + + Array filts; + for (int i = 0; i < filters.size(); i++) { + filts.push_back(filters[i].to_json()); + } + dict["filters"] = filts; + + return dict; + } +}; + +/** + * The server is interested in file notifications/requests. + */ +struct FileOperations { + /** + * The server is interested in receiving didDeleteFiles file notifications. + */ + FileOperationRegistrationOptions didDelete; + + Dictionary to_json() const { + Dictionary dict; + + dict["didDelete"] = didDelete.to_json(); + + return dict; + } +}; + +/** + * Workspace specific server capabilities + */ +struct Workspace { + /** + * The server is interested in file notifications/requests. + */ + FileOperations fileOperations; + + Dictionary to_json() const { + Dictionary dict; + + dict["fileOperations"] = fileOperations.to_json(); + + return dict; + } +}; + struct ServerCapabilities { /** * Defines how text documents are synced. Is either a detailed structure defining each notification or @@ -1590,6 +1754,11 @@ struct ServerCapabilities { bool workspaceSymbolProvider = true; /** + * The server supports workspace folder. + */ + Workspace workspace; + + /** * The server provides code actions. The `CodeActionOptions` return type is only * valid if the client signals code action literal support via the property * `textDocument.codeAction.codeActionLiteralSupport`. @@ -1676,6 +1845,7 @@ struct ServerCapabilities { dict["documentHighlightProvider"] = documentHighlightProvider; dict["documentSymbolProvider"] = documentSymbolProvider; dict["workspaceSymbolProvider"] = workspaceSymbolProvider; + dict["workspace"] = workspace.to_json(); dict["codeActionProvider"] = codeActionProvider; dict["documentFormattingProvider"] = documentFormattingProvider; dict["documentRangeFormattingProvider"] = documentRangeFormattingProvider; diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp index 2d2f94f5e0..c2b1981f31 100644 --- a/modules/gdscript/register_types.cpp +++ b/modules/gdscript/register_types.cpp @@ -30,10 +30,10 @@ #include "register_types.h" +#include "core/io/dir_access.h" +#include "core/io/file_access.h" #include "core/io/file_access_encrypted.h" #include "core/io/resource_loader.h" -#include "core/os/dir_access.h" -#include "core/os/file_access.h" #include "gdscript.h" #include "gdscript_analyzer.h" #include "gdscript_cache.h" @@ -92,12 +92,12 @@ public: static void _editor_init() { Ref<EditorExportGDScript> gd_export; - gd_export.instance(); + gd_export.instantiate(); EditorExport::get_singleton()->add_export_plugin(gd_export); #ifdef TOOLS_ENABLED Ref<GDScriptSyntaxHighlighter> gdscript_syntax_highlighter; - gdscript_syntax_highlighter.instance(); + gdscript_syntax_highlighter.instantiate(); ScriptEditor::get_singleton()->register_syntax_highlighter(gdscript_syntax_highlighter); #endif @@ -112,15 +112,15 @@ static void _editor_init() { #endif // TOOLS_ENABLED void register_gdscript_types() { - ClassDB::register_class<GDScript>(); + GDREGISTER_CLASS(GDScript); script_language_gd = memnew(GDScriptLanguage); ScriptServer::register_language(script_language_gd); - resource_loader_gd.instance(); + resource_loader_gd.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_gd); - resource_saver_gd.instance(); + resource_saver_gd.instantiate(); ResourceSaver::add_resource_format_saver(resource_saver_gd); gdscript_cache = memnew(GDScriptCache); @@ -128,7 +128,7 @@ void register_gdscript_types() { #ifdef TOOLS_ENABLED EditorNode::add_init_callback(_editor_init); - gdscript_translation_parser_plugin.instance(); + gdscript_translation_parser_plugin.instantiate(); EditorTranslationParser::get_singleton()->add_parser(gdscript_translation_parser_plugin, EditorTranslationParser::STANDARD); #endif // TOOLS_ENABLED diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp index 76ae43e792..03a48bf071 100644 --- a/modules/gdscript/tests/gdscript_test_runner.cpp +++ b/modules/gdscript/tests/gdscript_test_runner.cpp @@ -37,8 +37,8 @@ #include "core/config/project_settings.h" #include "core/core_string_names.h" +#include "core/io/dir_access.h" #include "core/io/file_access_pack.h" -#include "core/os/dir_access.h" #include "core/os/os.h" #include "core/string/string_builder.h" #include "scene/resources/packed_scene.h" @@ -75,14 +75,14 @@ void init_autoloads() { Node *n = nullptr; if (res->is_class("PackedScene")) { Ref<PackedScene> ps = res; - n = ps->instance(); + n = ps->instantiate(); } else if (res->is_class("Script")) { Ref<Script> script_res = res; StringName ibt = script_res->get_instance_base_type(); bool valid_type = ClassDB::is_parent_class(ibt, "Node"); ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path); - Object *obj = ClassDB::instance(ibt); + Object *obj = ClassDB::instantiate(ibt); ERR_CONTINUE_MSG(obj == nullptr, "Cannot instance script for autoload, expected 'Node' inheritance, got: " + @@ -257,6 +257,7 @@ bool GDScriptTestRunner::make_tests() { ERR_FAIL_COND_V_MSG(err != OK, false, "Could not open specified test directory."); + source_dir = dir->get_current_dir() + "/"; // Make it absolute path. return make_tests_for_dir(dir->get_current_dir()); } @@ -294,7 +295,7 @@ void GDScriptTestRunner::handle_cmdline() { String test_cmd = "--gdscript-test"; String gen_cmd = "--gdscript-generate-tests"; - for (List<String>::Element *E = cmdline_args.front(); E != nullptr; E = E->next()) { + for (List<String>::Element *E = cmdline_args.front(); E; E = E->next()) { String &cmd = E->get(); if (cmd == test_cmd || cmd == gen_cmd) { if (E->next() == nullptr) { @@ -361,11 +362,9 @@ void GDScriptTest::error_handler(void *p_this, const char *p_function, const cha break; } - builder.append("\n>> "); - builder.append(p_function); - builder.append("\n>> "); + builder.append("\n>> on function: "); builder.append(p_function); - builder.append("\n>> "); + builder.append("()\n>> "); builder.append(String(p_file).trim_prefix(self->base_dir)); builder.append("\n>> "); builder.append(itos(p_line)); @@ -421,7 +420,7 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { // Create script. Ref<GDScript> script; - script.instance(); + script.instantiate(); script->set_path(source_file); script->set_script_path(source_file); err = script->load_source_code(source_file); @@ -441,8 +440,8 @@ 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 List<GDScriptParser::ParserError>::Element *E = errors.front(); E; E = E->next()) { - result.output += E->get().message + "\n"; // TODO: line, column? + 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 (!p_is_generating) { @@ -460,8 +459,8 @@ 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 List<GDScriptParser::ParserError>::Element *E = errors.front(); E; E = E->next()) { - result.output += E->get().message + "\n"; // TODO: line, column? + 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 (!p_is_generating) { @@ -471,8 +470,8 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { } StringBuilder warning_string; - for (const List<GDScriptWarning>::Element *E = parser.get_warnings().front(); E != nullptr; E = E->next()) { - const GDScriptWarning warning = E->get(); + for (const GDScriptWarning &E : parser.get_warnings()) { + const GDScriptWarning warning = E; warning_string.append(">> WARNING"); warning_string.append("\n>> Line: "); warning_string.append(itos(warning.start_line)); @@ -511,10 +510,10 @@ GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) { script->reload(); // Create object instance for test. - Object *obj = ClassDB::instance(script->get_native()->get_name()); - Ref<Reference> obj_ref; - if (obj->is_reference()) { - obj_ref = Ref<Reference>(Object::cast_to<Reference>(obj)); + Object *obj = ClassDB::instantiate(script->get_native()->get_name()); + Ref<RefCounted> obj_ref; + if (obj->is_ref_counted()) { + obj_ref = Ref<RefCounted>(Object::cast_to<RefCounted>(obj)); } obj->set_script(script); GDScriptInstance *instance = static_cast<GDScriptInstance *>(obj->get_script_instance()); diff --git a/modules/gdscript/tests/gdscript_test_runner_suite.h b/modules/gdscript/tests/gdscript_test_runner_suite.h index 136907b316..cf4e61f07d 100644 --- a/modules/gdscript/tests/gdscript_test_runner_suite.h +++ b/modules/gdscript/tests/gdscript_test_runner_suite.h @@ -48,6 +48,27 @@ TEST_SUITE("[Modules][GDScript]") { } } +TEST_CASE("[Modules][GDScript] Load source code dynamically and run it") { + Ref<GDScript> gdscript = memnew(GDScript); + gdscript->set_source_code(R"( +extends RefCounted + +func _init(): + set_meta("result", 42) +)"); + // A spurious `Condition "err" is true` message is printed (despite parsing being successful and returning `OK`). + // Silence it. + ERR_PRINT_OFF; + const Error error = gdscript->reload(); + ERR_PRINT_ON; + CHECK_MESSAGE(error == OK, "The script should parse successfully."); + + // Run the script by assigning it to a reference-counted object. + Ref<RefCounted> ref_counted = memnew(RefCounted); + ref_counted->set_script(gdscript); + CHECK_MESSAGE(int(ref_counted->get_meta("result")) == 42, "The script should assign object metadata successfully."); +} + } // namespace GDScriptTests #endif // GDSCRIPT_TEST_RUNNER_SUITE_H diff --git a/modules/gdscript/tests/scripts/analyzer/features/call_self_get_name.gd b/modules/gdscript/tests/scripts/analyzer/features/call_self_get_name.gd new file mode 100644 index 0000000000..d21d8bce96 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/call_self_get_name.gd @@ -0,0 +1,9 @@ +extends Node + +func test(): + set_name("TestNodeName") + if get_name() == &"TestNodeName": + print("Name is equal") + else: + print("Name is not equal") + print(get_name() is StringName) diff --git a/modules/gdscript/tests/scripts/analyzer/features/call_self_get_name.out b/modules/gdscript/tests/scripts/analyzer/features/call_self_get_name.out new file mode 100644 index 0000000000..dc4348d9c3 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/call_self_get_name.out @@ -0,0 +1,3 @@ +GDTEST_OK +Name is equal +True diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-argument.gd b/modules/gdscript/tests/scripts/parser/errors/missing_argument.gd index c56ad94095..c56ad94095 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-argument.gd +++ b/modules/gdscript/tests/scripts/parser/errors/missing_argument.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-argument.out b/modules/gdscript/tests/scripts/parser/errors/missing_argument.out index fc2a891109..fc2a891109 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-argument.out +++ b/modules/gdscript/tests/scripts/parser/errors/missing_argument.out diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-closing-expr-paren.gd b/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.gd index a1077e1985..a1077e1985 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-closing-expr-paren.gd +++ b/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-closing-expr-paren.out b/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.out index 7326afa33d..7326afa33d 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-closing-expr-paren.out +++ b/modules/gdscript/tests/scripts/parser/errors/missing_closing_expr_paren.out diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-colon.gd b/modules/gdscript/tests/scripts/parser/errors/missing_colon.gd index 62cb633e9e..62cb633e9e 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-colon.gd +++ b/modules/gdscript/tests/scripts/parser/errors/missing_colon.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-colon.out b/modules/gdscript/tests/scripts/parser/errors/missing_colon.out index 687b963bc8..687b963bc8 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-colon.out +++ b/modules/gdscript/tests/scripts/parser/errors/missing_colon.out diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-paren-after-args.gd b/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.gd index 116b0151da..116b0151da 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-paren-after-args.gd +++ b/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/missing-paren-after-args.out b/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.out index 34ea7ac323..34ea7ac323 100644 --- a/modules/gdscript/tests/scripts/parser-errors/missing-paren-after-args.out +++ b/modules/gdscript/tests/scripts/parser/errors/missing_paren_after_args.out diff --git a/modules/gdscript/tests/scripts/parser-errors/mixing-tabs-spaces.gd b/modules/gdscript/tests/scripts/parser/errors/mixing_tabs_spaces.gd index 9ad77f1432..9ad77f1432 100644 --- a/modules/gdscript/tests/scripts/parser-errors/mixing-tabs-spaces.gd +++ b/modules/gdscript/tests/scripts/parser/errors/mixing_tabs_spaces.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/mixing-tabs-spaces.out b/modules/gdscript/tests/scripts/parser/errors/mixing_tabs_spaces.out index 6390de9788..6390de9788 100644 --- a/modules/gdscript/tests/scripts/parser-errors/mixing-tabs-spaces.out +++ b/modules/gdscript/tests/scripts/parser/errors/mixing_tabs_spaces.out diff --git a/modules/gdscript/tests/scripts/parser-errors/nothing-after-dollar.gd b/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.gd index 3875ce3936..3875ce3936 100644 --- a/modules/gdscript/tests/scripts/parser-errors/nothing-after-dollar.gd +++ b/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/nothing-after-dollar.out b/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.out index b3dc181a22..b3dc181a22 100644 --- a/modules/gdscript/tests/scripts/parser-errors/nothing-after-dollar.out +++ b/modules/gdscript/tests/scripts/parser/errors/nothing_after_dollar.out diff --git a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar.gd b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.gd index 6fd2692d47..6fd2692d47 100644 --- a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar.gd +++ b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar.out b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.out index b3dc181a22..b3dc181a22 100644 --- a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar.out +++ b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar.out diff --git a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar-slash.gd b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.gd index 1836d42226..1836d42226 100644 --- a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar-slash.gd +++ b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.gd diff --git a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar-slash.out b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.out index dcb4ccecb0..dcb4ccecb0 100644 --- a/modules/gdscript/tests/scripts/parser-errors/wrong-value-after-dollar-slash.out +++ b/modules/gdscript/tests/scripts/parser/errors/wrong_value_after_dollar_slash.out diff --git a/modules/gdscript/tests/scripts/parser-features/semicolon-as-end-statement.gd b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.gd index 08f2eedb2d..08f2eedb2d 100644 --- a/modules/gdscript/tests/scripts/parser-features/semicolon-as-end-statement.gd +++ b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.gd diff --git a/modules/gdscript/tests/scripts/parser-features/semicolon-as-end-statement.out b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.out index fc03f3efe8..fc03f3efe8 100644 --- a/modules/gdscript/tests/scripts/parser-features/semicolon-as-end-statement.out +++ b/modules/gdscript/tests/scripts/parser/features/semicolon_as_end_statement.out diff --git a/modules/gdscript/tests/scripts/parser-features/trailing-comma-in-function-args.gd b/modules/gdscript/tests/scripts/parser/features/trailing_comma_in_function_args.gd index 6097b11b10..6097b11b10 100644 --- a/modules/gdscript/tests/scripts/parser-features/trailing-comma-in-function-args.gd +++ b/modules/gdscript/tests/scripts/parser/features/trailing_comma_in_function_args.gd diff --git a/modules/gdscript/tests/scripts/parser-features/trailing-comma-in-function-args.out b/modules/gdscript/tests/scripts/parser/features/trailing_comma_in_function_args.out index 94e2ec2af8..94e2ec2af8 100644 --- a/modules/gdscript/tests/scripts/parser-features/trailing-comma-in-function-args.out +++ b/modules/gdscript/tests/scripts/parser/features/trailing_comma_in_function_args.out diff --git a/modules/gdscript/tests/scripts/parser-features/variable-declaration.gd b/modules/gdscript/tests/scripts/parser/features/variable_declaration.gd index 3b48f10ca7..3b48f10ca7 100644 --- a/modules/gdscript/tests/scripts/parser-features/variable-declaration.gd +++ b/modules/gdscript/tests/scripts/parser/features/variable_declaration.gd diff --git a/modules/gdscript/tests/scripts/parser-features/variable-declaration.out b/modules/gdscript/tests/scripts/parser/features/variable_declaration.out index 2e0a63c024..2e0a63c024 100644 --- a/modules/gdscript/tests/scripts/parser-features/variable-declaration.out +++ b/modules/gdscript/tests/scripts/parser/features/variable_declaration.out diff --git a/modules/gdscript/tests/scripts/parser-warnings/unused-variable.gd b/modules/gdscript/tests/scripts/parser/warnings/unused_variable.gd index 68e3bd424f..68e3bd424f 100644 --- a/modules/gdscript/tests/scripts/parser-warnings/unused-variable.gd +++ b/modules/gdscript/tests/scripts/parser/warnings/unused_variable.gd diff --git a/modules/gdscript/tests/scripts/parser-warnings/unused-variable.out b/modules/gdscript/tests/scripts/parser/warnings/unused_variable.out index 270e0e69c0..270e0e69c0 100644 --- a/modules/gdscript/tests/scripts/parser-warnings/unused-variable.out +++ b/modules/gdscript/tests/scripts/parser/warnings/unused_variable.out diff --git a/modules/gdscript/tests/scripts/runtime/errors/callable_call_after_free_object.gd b/modules/gdscript/tests/scripts/runtime/errors/callable_call_after_free_object.gd new file mode 100644 index 0000000000..10780b5379 --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/errors/callable_call_after_free_object.gd @@ -0,0 +1,5 @@ +func test(): + var node := Node.new() + var inside_tree = node.is_inside_tree + node.free() + inside_tree.call() diff --git a/modules/gdscript/tests/scripts/runtime/errors/callable_call_after_free_object.out b/modules/gdscript/tests/scripts/runtime/errors/callable_call_after_free_object.out new file mode 100644 index 0000000000..e585c374e2 --- /dev/null +++ b/modules/gdscript/tests/scripts/runtime/errors/callable_call_after_free_object.out @@ -0,0 +1,6 @@ +GDTEST_RUNTIME_ERROR +>> SCRIPT ERROR +>> on function: test() +>> runtime/errors/callable_call_after_free_object.gd +>> 5 +>> Attempt to call function 'null::is_inside_tree (Callable)' on a null instance. diff --git a/modules/gdscript/tests/test_gdscript.cpp b/modules/gdscript/tests/test_gdscript.cpp index e70f221c0a..52e9d92223 100644 --- a/modules/gdscript/tests/test_gdscript.cpp +++ b/modules/gdscript/tests/test_gdscript.cpp @@ -31,8 +31,8 @@ #include "test_gdscript.h" #include "core/config/project_settings.h" +#include "core/io/file_access.h" #include "core/io/file_access_pack.h" -#include "core/os/file_access.h" #include "core/os/main_loop.h" #include "core/os/os.h" #include "core/string/string_builder.h" @@ -66,7 +66,7 @@ static void test_tokenizer(const String &p_code, const Vector<String> &p_lines) StringBuilder token; token += " --> "; // Padding for line number. - for (int l = current.start_line; l <= current.end_line; l++) { + for (int l = current.start_line; l <= current.end_line && l <= p_lines.size(); l++) { print_line(vformat("%04d %s", l, p_lines[l - 1]).replace("\t", tab)); } @@ -113,11 +113,21 @@ static void test_parser(const String &p_code, const String &p_script_path, const if (err != OK) { const List<GDScriptParser::ParserError> &errors = parser.get_errors(); - for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) { - const GDScriptParser::ParserError &error = E->get(); + for (const GDScriptParser::ParserError &error : errors) { print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message)); } } + + GDScriptAnalyzer analyzer(&parser); + analyzer.analyze(); + + if (err != OK) { + const List<GDScriptParser::ParserError> &errors = parser.get_errors(); + for (const GDScriptParser::ParserError &error : errors) { + print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message)); + } + } + #ifdef TOOLS_ENABLED GDScriptParser::TreePrinter printer; printer.print_tree(parser); @@ -131,8 +141,7 @@ static void test_compiler(const String &p_code, const String &p_script_path, con if (err != OK) { print_line("Error in parser:"); const List<GDScriptParser::ParserError> &errors = parser.get_errors(); - for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) { - const GDScriptParser::ParserError &error = E->get(); + for (const GDScriptParser::ParserError &error : errors) { print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message)); } return; @@ -144,8 +153,7 @@ static void test_compiler(const String &p_code, const String &p_script_path, con if (err != OK) { print_line("Error in analyzer:"); const List<GDScriptParser::ParserError> &errors = parser.get_errors(); - for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) { - const GDScriptParser::ParserError &error = E->get(); + for (const GDScriptParser::ParserError &error : errors) { print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message)); } return; @@ -153,7 +161,7 @@ static void test_compiler(const String &p_code, const String &p_script_path, con GDScriptCompiler compiler; Ref<GDScript> script; - script.instance(); + script.instantiate(); script->set_path(p_script_path); err = compiler.compile(&parser, script.ptr(), false); @@ -203,8 +211,8 @@ void test(TestType p_type) { init_language(fa->get_path_absolute().get_base_dir()); Vector<uint8_t> buf; - int flen = fa->get_len(); - buf.resize(fa->get_len() + 1); + uint64_t flen = fa->get_length(); + buf.resize(flen + 1); fa->get_buffer(buf.ptrw(), flen); buf.write[flen] = 0; diff --git a/modules/glslang/register_types.cpp b/modules/glslang/register_types.cpp index 14135265b9..dd545ff431 100644 --- a/modules/glslang/register_types.cpp +++ b/modules/glslang/register_types.cpp @@ -116,6 +116,10 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage } } + if (p_capabilities->supports_multiview) { + preamble += "#define has_VK_KHR_multiview 1\n"; + } + if (preamble != "") { shader.setPreamble(preamble.c_str()); } @@ -173,17 +177,24 @@ static Vector<uint8_t> _compile_shader_glsl(RenderingDevice::ShaderStage p_stage ret.resize(SpirV.size() * sizeof(uint32_t)); { uint8_t *w = ret.ptrw(); - copymem(w, &SpirV[0], SpirV.size() * sizeof(uint32_t)); + memcpy(w, &SpirV[0], SpirV.size() * sizeof(uint32_t)); } return ret; } +static String _get_cache_key_function_glsl(const RenderingDevice::Capabilities *p_capabilities) { + String version; + version = "SpirVGen=" + itos(glslang::GetSpirvGeneratorVersion()) + ", major=" + itos(p_capabilities->version_major) + ", minor=" + itos(p_capabilities->version_minor) + " , subgroup_size=" + itos(p_capabilities->subgroup_operations) + " , subgroup_ops=" + itos(p_capabilities->subgroup_operations) + " , subgroup_in_shaders=" + itos(p_capabilities->subgroup_in_shaders); + return version; +} + void preregister_glslang_types() { // initialize in case it's not initialized. This is done once per thread // and it's safe to call multiple times glslang::InitializeProcess(); - RenderingDevice::shader_set_compile_function(_compile_shader_glsl); + RenderingDevice::shader_set_compile_to_spirv_function(_compile_shader_glsl); + RenderingDevice::shader_set_get_cache_key_function(_get_cache_key_function_glsl); } void register_glslang_types() { diff --git a/modules/gltf/doc_classes/GLTFAccessor.xml b/modules/gltf/doc_classes/GLTFAccessor.xml index a1f596f7dd..41a318ce19 100644 --- a/modules/gltf/doc_classes/GLTFAccessor.xml +++ b/modules/gltf/doc_classes/GLTFAccessor.xml @@ -17,9 +17,9 @@ </member> <member name="count" type="int" setter="set_count" getter="get_count" default="0"> </member> - <member name="max" type="PackedFloat64Array" setter="set_max" getter="get_max" default="PackedFloat64Array( )"> + <member name="max" type="PackedFloat64Array" setter="set_max" getter="get_max" default="PackedFloat64Array()"> </member> - <member name="min" type="PackedFloat64Array" setter="set_min" getter="get_min" default="PackedFloat64Array( )"> + <member name="min" type="PackedFloat64Array" setter="set_min" getter="get_min" default="PackedFloat64Array()"> </member> <member name="normalized" type="bool" setter="set_normalized" getter="get_normalized" default="false"> </member> diff --git a/modules/gltf/doc_classes/GLTFLight.xml b/modules/gltf/doc_classes/GLTFLight.xml index bfeaf9a86e..f51d287685 100644 --- a/modules/gltf/doc_classes/GLTFLight.xml +++ b/modules/gltf/doc_classes/GLTFLight.xml @@ -9,7 +9,7 @@ <methods> </methods> <members> - <member name="color" type="Color" setter="set_color" getter="get_color" default="Color( 0, 0, 0, 1 )"> + <member name="color" type="Color" setter="set_color" getter="get_color" default="Color(0, 0, 0, 1)"> </member> <member name="inner_cone_angle" type="float" setter="set_inner_cone_angle" getter="get_inner_cone_angle" default="0.0"> </member> diff --git a/modules/gltf/doc_classes/GLTFMesh.xml b/modules/gltf/doc_classes/GLTFMesh.xml index 55f79d2c55..fd7e4a169e 100644 --- a/modules/gltf/doc_classes/GLTFMesh.xml +++ b/modules/gltf/doc_classes/GLTFMesh.xml @@ -9,7 +9,7 @@ <methods> </methods> <members> - <member name="blend_weights" type="PackedFloat32Array" setter="set_blend_weights" getter="get_blend_weights" default="PackedFloat32Array( )"> + <member name="blend_weights" type="PackedFloat32Array" setter="set_blend_weights" getter="get_blend_weights" default="PackedFloat32Array()"> </member> <member name="mesh" type="EditorSceneImporterMesh" setter="set_mesh" getter="get_mesh"> </member> diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml index 5b7d4fadec..bfbb12df4d 100644 --- a/modules/gltf/doc_classes/GLTFNode.xml +++ b/modules/gltf/doc_classes/GLTFNode.xml @@ -11,9 +11,7 @@ <members> <member name="camera" type="int" setter="set_camera" getter="get_camera" default="-1"> </member> - <member name="children" type="PackedInt32Array" setter="set_children" getter="get_children" default="PackedInt32Array( )"> - </member> - <member name="fake_joint_parent" type="int" setter="set_fake_joint_parent" getter="get_fake_joint_parent" default="-1"> + <member name="children" type="PackedInt32Array" setter="set_children" getter="get_children" default="PackedInt32Array()"> </member> <member name="height" type="int" setter="set_height" getter="get_height" default="-1"> </member> @@ -25,17 +23,17 @@ </member> <member name="parent" type="int" setter="set_parent" getter="get_parent" default="-1"> </member> - <member name="rotation" type="Quat" setter="set_rotation" getter="get_rotation" default="Quat( 0, 0, 0, 1 )"> + <member name="rotation" type="Quaternion" setter="set_rotation" getter="get_rotation" default="Quaternion(0, 0, 0, 1)"> </member> - <member name="scale" type="Vector3" setter="set_scale" getter="get_scale" default="Vector3( 1, 1, 1 )"> + <member name="scale" type="Vector3" setter="set_scale" getter="get_scale" default="Vector3(1, 1, 1)"> </member> <member name="skeleton" type="int" setter="set_skeleton" getter="get_skeleton" default="-1"> </member> <member name="skin" type="int" setter="set_skin" getter="get_skin" default="-1"> </member> - <member name="translation" type="Vector3" setter="set_translation" getter="get_translation" default="Vector3( 0, 0, 0 )"> + <member name="translation" type="Vector3" setter="set_translation" getter="get_translation" default="Vector3(0, 0, 0)"> </member> - <member name="xform" type="Transform" setter="set_xform" getter="get_xform" default="Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )"> + <member name="xform" type="Transform3D" setter="set_xform" getter="get_xform" default="Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)"> </member> </members> <constants> diff --git a/modules/gltf/doc_classes/GLTFSkeleton.xml b/modules/gltf/doc_classes/GLTFSkeleton.xml index 9680c27705..6e83cec252 100644 --- a/modules/gltf/doc_classes/GLTFSkeleton.xml +++ b/modules/gltf/doc_classes/GLTFSkeleton.xml @@ -8,58 +8,48 @@ </tutorials> <methods> <method name="get_bone_attachment"> - <return type="BoneAttachment3D"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="BoneAttachment3D" /> + <argument index="0" name="idx" type="int" /> <description> </description> </method> <method name="get_bone_attachment_count"> - <return type="int"> - </return> + <return type="int" /> <description> </description> </method> <method name="get_godot_bone_node"> - <return type="Dictionary"> - </return> + <return type="Dictionary" /> <description> </description> </method> <method name="get_godot_skeleton"> - <return type="Skeleton3D"> - </return> + <return type="Skeleton3D" /> <description> </description> </method> <method name="get_unique_names"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="set_godot_bone_node"> - <return type="void"> - </return> - <argument index="0" name="godot_bone_node" type="Dictionary"> - </argument> + <return type="void" /> + <argument index="0" name="godot_bone_node" type="Dictionary" /> <description> </description> </method> <method name="set_unique_names"> - <return type="void"> - </return> - <argument index="0" name="unique_names" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="unique_names" type="Array" /> <description> </description> </method> </methods> <members> - <member name="joints" type="PackedInt32Array" setter="set_joints" getter="get_joints" default="PackedInt32Array( )"> + <member name="joints" type="PackedInt32Array" setter="set_joints" getter="get_joints" default="PackedInt32Array()"> </member> - <member name="roots" type="PackedInt32Array" setter="set_roots" getter="get_roots" default="PackedInt32Array( )"> + <member name="roots" type="PackedInt32Array" setter="set_roots" getter="get_roots" default="PackedInt32Array()"> </member> </members> <constants> diff --git a/modules/gltf/doc_classes/GLTFSkin.xml b/modules/gltf/doc_classes/GLTFSkin.xml index 5a80c7097a..107ca960cd 100644 --- a/modules/gltf/doc_classes/GLTFSkin.xml +++ b/modules/gltf/doc_classes/GLTFSkin.xml @@ -8,44 +8,35 @@ </tutorials> <methods> <method name="get_inverse_binds"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_joint_i_to_bone_i"> - <return type="Dictionary"> - </return> + <return type="Dictionary" /> <description> </description> </method> <method name="get_joint_i_to_name"> - <return type="Dictionary"> - </return> + <return type="Dictionary" /> <description> </description> </method> <method name="set_inverse_binds"> - <return type="void"> - </return> - <argument index="0" name="inverse_binds" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="inverse_binds" type="Array" /> <description> </description> </method> <method name="set_joint_i_to_bone_i"> - <return type="void"> - </return> - <argument index="0" name="joint_i_to_bone_i" type="Dictionary"> - </argument> + <return type="void" /> + <argument index="0" name="joint_i_to_bone_i" type="Dictionary" /> <description> </description> </method> <method name="set_joint_i_to_name"> - <return type="void"> - </return> - <argument index="0" name="joint_i_to_name" type="Dictionary"> - </argument> + <return type="void" /> + <argument index="0" name="joint_i_to_name" type="Dictionary" /> <description> </description> </method> @@ -53,13 +44,13 @@ <members> <member name="godot_skin" type="Skin" setter="set_godot_skin" getter="get_godot_skin"> </member> - <member name="joints" type="PackedInt32Array" setter="set_joints" getter="get_joints" default="PackedInt32Array( )"> + <member name="joints" type="PackedInt32Array" setter="set_joints" getter="get_joints" default="PackedInt32Array()"> </member> - <member name="joints_original" type="PackedInt32Array" setter="set_joints_original" getter="get_joints_original" default="PackedInt32Array( )"> + <member name="joints_original" type="PackedInt32Array" setter="set_joints_original" getter="get_joints_original" default="PackedInt32Array()"> </member> - <member name="non_joints" type="PackedInt32Array" setter="set_non_joints" getter="get_non_joints" default="PackedInt32Array( )"> + <member name="non_joints" type="PackedInt32Array" setter="set_non_joints" getter="get_non_joints" default="PackedInt32Array()"> </member> - <member name="roots" type="PackedInt32Array" setter="set_roots" getter="get_roots" default="PackedInt32Array( )"> + <member name="roots" type="PackedInt32Array" setter="set_roots" getter="get_roots" default="PackedInt32Array()"> </member> <member name="skeleton" type="int" setter="set_skeleton" getter="get_skeleton" default="-1"> </member> diff --git a/modules/gltf/doc_classes/GLTFSpecGloss.xml b/modules/gltf/doc_classes/GLTFSpecGloss.xml index 68cc7c845d..6e9c419649 100644 --- a/modules/gltf/doc_classes/GLTFSpecGloss.xml +++ b/modules/gltf/doc_classes/GLTFSpecGloss.xml @@ -9,7 +9,7 @@ <methods> </methods> <members> - <member name="diffuse_factor" type="Color" setter="set_diffuse_factor" getter="get_diffuse_factor" default="Color( 1, 1, 1, 1 )"> + <member name="diffuse_factor" type="Color" setter="set_diffuse_factor" getter="get_diffuse_factor" default="Color(1, 1, 1, 1)"> </member> <member name="diffuse_img" type="Image" setter="set_diffuse_img" getter="get_diffuse_img"> </member> @@ -17,7 +17,7 @@ </member> <member name="spec_gloss_img" type="Image" setter="set_spec_gloss_img" getter="get_spec_gloss_img"> </member> - <member name="specular_factor" type="Color" setter="set_specular_factor" getter="get_specular_factor" default="Color( 1, 1, 1, 1 )"> + <member name="specular_factor" type="Color" setter="set_specular_factor" getter="get_specular_factor" default="Color(1, 1, 1, 1)"> </member> </members> <constants> diff --git a/modules/gltf/doc_classes/GLTFState.xml b/modules/gltf/doc_classes/GLTFState.xml index 8255cd73d0..ae976fc04c 100644 --- a/modules/gltf/doc_classes/GLTFState.xml +++ b/modules/gltf/doc_classes/GLTFState.xml @@ -8,244 +8,193 @@ </tutorials> <methods> <method name="get_accessors"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_animation_player"> - <return type="AnimationPlayer"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="AnimationPlayer" /> + <argument index="0" name="idx" type="int" /> <description> </description> </method> <method name="get_animation_players_count"> - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="int" /> + <argument index="0" name="idx" type="int" /> <description> </description> </method> <method name="get_animations"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_buffer_views"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_cameras"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_images"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_lights"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_materials"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_meshes"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_nodes"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_scene_node"> - <return type="Node"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="Node" /> + <argument index="0" name="idx" type="int" /> <description> </description> </method> <method name="get_skeleton_to_node"> - <return type="Dictionary"> - </return> + <return type="Dictionary" /> <description> </description> </method> <method name="get_skeletons"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_skins"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_textures"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_unique_animation_names"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="get_unique_names"> - <return type="Array"> - </return> + <return type="Array" /> <description> </description> </method> <method name="set_accessors"> - <return type="void"> - </return> - <argument index="0" name="accessors" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="accessors" type="Array" /> <description> </description> </method> <method name="set_animations"> - <return type="void"> - </return> - <argument index="0" name="animations" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="animations" type="Array" /> <description> </description> </method> <method name="set_buffer_views"> - <return type="void"> - </return> - <argument index="0" name="buffer_views" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="buffer_views" type="Array" /> <description> </description> </method> <method name="set_cameras"> - <return type="void"> - </return> - <argument index="0" name="cameras" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="cameras" type="Array" /> <description> </description> </method> <method name="set_images"> - <return type="void"> - </return> - <argument index="0" name="images" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="images" type="Array" /> <description> </description> </method> <method name="set_lights"> - <return type="void"> - </return> - <argument index="0" name="lights" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="lights" type="Array" /> <description> </description> </method> <method name="set_materials"> - <return type="void"> - </return> - <argument index="0" name="materials" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="materials" type="Array" /> <description> </description> </method> <method name="set_meshes"> - <return type="void"> - </return> - <argument index="0" name="meshes" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="meshes" type="Array" /> <description> </description> </method> <method name="set_nodes"> - <return type="void"> - </return> - <argument index="0" name="nodes" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="nodes" type="Array" /> <description> </description> </method> <method name="set_skeleton_to_node"> - <return type="void"> - </return> - <argument index="0" name="skeleton_to_node" type="Dictionary"> - </argument> + <return type="void" /> + <argument index="0" name="skeleton_to_node" type="Dictionary" /> <description> </description> </method> <method name="set_skeletons"> - <return type="void"> - </return> - <argument index="0" name="skeletons" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="skeletons" type="Array" /> <description> </description> </method> <method name="set_skins"> - <return type="void"> - </return> - <argument index="0" name="skins" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="skins" type="Array" /> <description> </description> </method> <method name="set_textures"> - <return type="void"> - </return> - <argument index="0" name="textures" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="textures" type="Array" /> <description> </description> </method> <method name="set_unique_animation_names"> - <return type="void"> - </return> - <argument index="0" name="unique_animation_names" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="unique_animation_names" type="Array" /> <description> </description> </method> <method name="set_unique_names"> - <return type="void"> - </return> - <argument index="0" name="unique_names" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="unique_names" type="Array" /> <description> </description> </method> </methods> <members> - <member name="buffers" type="Array" setter="set_buffers" getter="get_buffers" default="[ ]"> + <member name="buffers" type="Array" setter="set_buffers" getter="get_buffers" default="[]"> </member> - <member name="glb_data" type="PackedByteArray" setter="set_glb_data" getter="get_glb_data" default="PackedByteArray( )"> + <member name="glb_data" type="PackedByteArray" setter="set_glb_data" getter="get_glb_data" default="PackedByteArray()"> </member> <member name="json" type="Dictionary" setter="set_json" getter="get_json" default="{}"> </member> @@ -253,7 +202,7 @@ </member> <member name="minor_version" type="int" setter="set_minor_version" getter="get_minor_version" default="0"> </member> - <member name="root_nodes" type="Array" setter="set_root_nodes" getter="get_root_nodes" default="[ ]"> + <member name="root_nodes" type="Array" setter="set_root_nodes" getter="get_root_nodes" default="[]"> </member> <member name="scene_name" type="String" setter="set_scene_name" getter="get_scene_name" default=""""> </member> diff --git a/modules/gltf/doc_classes/PackedSceneGLTF.xml b/modules/gltf/doc_classes/PackedSceneGLTF.xml index a04c6ef0b6..d0136c6402 100644 --- a/modules/gltf/doc_classes/PackedSceneGLTF.xml +++ b/modules/gltf/doc_classes/PackedSceneGLTF.xml @@ -8,50 +8,35 @@ </tutorials> <methods> <method name="export_gltf"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="node" type="Node"> - </argument> - <argument index="1" name="path" type="String"> - </argument> - <argument index="2" name="flags" type="int" default="0"> - </argument> - <argument index="3" name="bake_fps" type="float" default="1000.0"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="node" type="Node" /> + <argument index="1" name="path" type="String" /> + <argument index="2" name="flags" type="int" default="0" /> + <argument index="3" name="bake_fps" type="float" default="1000.0" /> <description> </description> </method> <method name="import_gltf_scene"> - <return type="Node"> - </return> - <argument index="0" name="path" type="String"> - </argument> - <argument index="1" name="flags" type="int" default="0"> - </argument> - <argument index="2" name="bake_fps" type="float" default="1000.0"> - </argument> - <argument index="3" name="state" type="GLTFState" default="null"> - </argument> + <return type="Node" /> + <argument index="0" name="path" type="String" /> + <argument index="1" name="flags" type="int" default="0" /> + <argument index="2" name="bake_fps" type="float" default="1000.0" /> + <argument index="3" name="state" type="GLTFState" default="null" /> <description> </description> </method> <method name="pack_gltf"> - <return type="void"> - </return> - <argument index="0" name="path" type="String"> - </argument> - <argument index="1" name="flags" type="int" default="0"> - </argument> - <argument index="2" name="bake_fps" type="float" default="1000.0"> - </argument> - <argument index="3" name="state" type="GLTFState" default="null"> - </argument> + <return type="void" /> + <argument index="0" name="path" type="String" /> + <argument index="1" name="flags" type="int" default="0" /> + <argument index="2" name="bake_fps" type="float" default="1000.0" /> + <argument index="3" name="state" type="GLTFState" default="null" /> <description> </description> </method> </methods> <members> - <member name="_bundled" type="Dictionary" setter="_set_bundled_scene" getter="_get_bundled_scene" override="true" default="{"conn_count": 0,"conns": PackedInt32Array( ),"editable_instances": [ ],"names": PackedStringArray( ),"node_count": 0,"node_paths": [ ],"nodes": PackedInt32Array( ),"variants": [ ],"version": 2}" /> + <member name="_bundled" type="Dictionary" setter="_set_bundled_scene" getter="_get_bundled_scene" override="true" default="{"conn_count": 0,"conns": PackedInt32Array(),"editable_instances": [],"names": PackedStringArray(),"node_count": 0,"node_paths": [],"nodes": PackedInt32Array(),"variants": [],"version": 2}" /> </members> <constants> </constants> diff --git a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp index 4cdaccde6f..ae080bcc9a 100644 --- a/modules/gltf/editor_scene_exporter_gltf_plugin.cpp +++ b/modules/gltf/editor_scene_exporter_gltf_plugin.cpp @@ -49,7 +49,7 @@ bool SceneExporterGLTFPlugin::has_main_screen() const { SceneExporterGLTFPlugin::SceneExporterGLTFPlugin(EditorNode *p_node) { editor = p_node; - convert_gltf2.instance(); + convert_gltf2.instantiate(); file_export_lib = memnew(EditorFileDialog); editor->get_gui_base()->add_child(file_export_lib); file_export_lib->connect("file_selected", callable_mp(this, &SceneExporterGLTFPlugin::_gltf2_dialog_action)); diff --git a/modules/gltf/editor_scene_importer_gltf.cpp b/modules/gltf/editor_scene_importer_gltf.cpp index 35f44ca122..eca1c85bf3 100644 --- a/modules/gltf/editor_scene_importer_gltf.cpp +++ b/modules/gltf/editor_scene_importer_gltf.cpp @@ -28,23 +28,14 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "core/crypto/crypto_core.h" -#include "core/io/json.h" -#include "core/math/disjoint_set.h" -#include "core/math/math_defs.h" -#include "core/os/file_access.h" -#include "core/os/os.h" -#include "editor/import/resource_importer_scene.h" -#include "modules/gltf/gltf_state.h" -#include "modules/regex/regex.h" -#include "scene/3d/bone_attachment_3d.h" -#include "scene/3d/camera_3d.h" -#include "scene/3d/mesh_instance_3d.h" -#include "scene/animation/animation_player.h" -#include "scene/resources/packed_scene.h" -#include "scene/resources/surface_tool.h" +#include "editor_scene_importer_gltf.h" + +#include "gltf_document.h" +#include "gltf_state.h" -#include "modules/gltf/editor_scene_importer_gltf.h" +#include "scene/3d/node_3d.h" +#include "scene/animation/animation_player.h" +#include "scene/resources/animation.h" uint32_t EditorSceneImporterGLTF::get_import_flags() const { return ImportFlags::IMPORT_SCENE | ImportFlags::IMPORT_ANIMATION; @@ -60,7 +51,7 @@ Node *EditorSceneImporterGLTF::import_scene(const String &p_path, List<String> *r_missing_deps, Error *r_err) { Ref<PackedSceneGLTF> importer; - importer.instance(); + importer.instantiate(); return importer->import_scene(p_path, p_flags, p_bake_fps, r_missing_deps, r_err, Ref<GLTFState>()); } @@ -91,13 +82,13 @@ Node *PackedSceneGLTF::import_scene(const String &p_path, uint32_t p_flags, Error *r_err, Ref<GLTFState> r_state) { if (r_state == Ref<GLTFState>()) { - r_state.instance(); + r_state.instantiate(); } r_state->use_named_skin_binds = p_flags & EditorSceneImporter::IMPORT_USE_NAMED_SKIN_BINDS; Ref<GLTFDocument> gltf_document; - gltf_document.instance(); + gltf_document.instantiate(); Error err = gltf_document->parse(r_state, p_path); if (r_err) { *r_err = err; @@ -139,9 +130,9 @@ void PackedSceneGLTF::save_scene(Node *p_node, const String &p_path, *r_err = err; } Ref<GLTFDocument> gltf_document; - gltf_document.instance(); + gltf_document.instantiate(); Ref<GLTFState> state; - state.instance(); + state.instantiate(); err = gltf_document->serialize(state, p_node, p_path); if (r_err) { *r_err = err; @@ -172,7 +163,7 @@ Error PackedSceneGLTF::export_gltf(Node *p_root, String p_path, int32_t flags = p_flags; real_t baked_fps = p_bake_fps; Ref<PackedSceneGLTF> exporter; - exporter.instance(); + exporter.instantiate(); exporter->save_scene(p_root, path, "", flags, baked_fps, &deps, &err); int32_t error_code = err; if (error_code != 0) { diff --git a/modules/gltf/editor_scene_importer_gltf.h b/modules/gltf/editor_scene_importer_gltf.h index af1a885f2b..7bc5f594ed 100644 --- a/modules/gltf/editor_scene_importer_gltf.h +++ b/modules/gltf/editor_scene_importer_gltf.h @@ -31,29 +31,13 @@ #ifndef EDITOR_SCENE_IMPORTER_GLTF_H #define EDITOR_SCENE_IMPORTER_GLTF_H -#include "core/config/project_settings.h" -#include "core/io/json.h" -#include "core/object/object.h" -#include "core/templates/vector.h" +#include "gltf_state.h" + #include "editor/import/resource_importer_scene.h" -#include "modules/csg/csg_shape.h" -#include "modules/gridmap/grid_map.h" -#include "scene/3d/mesh_instance_3d.h" -#include "scene/3d/multimesh_instance_3d.h" -#include "scene/3d/node_3d.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/animation/animation_player.h" -#include "scene/gui/check_box.h" #include "scene/main/node.h" #include "scene/resources/packed_scene.h" -#include "scene/resources/surface_tool.h" - -#include "gltf_document.h" -#include "gltf_state.h" -class AnimationPlayer; -class BoneAttachment; -class EditorSceneImporterMeshNode3D; +class Animation; #ifdef TOOLS_ENABLED class EditorSceneImporterGLTF : public EditorSceneImporter { diff --git a/modules/gltf/gltf_animation.h b/modules/gltf/gltf_animation.h index a494e6bd67..216d2161c4 100644 --- a/modules/gltf/gltf_animation.h +++ b/modules/gltf/gltf_animation.h @@ -56,7 +56,7 @@ public: struct Track { Channel<Vector3> translation_track; - Channel<Quat> rotation_track; + Channel<Quaternion> rotation_track; Channel<Vector3> scale_track; Vector<Channel<float>> weight_tracks; }; diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index 027a054b70..ff0579a11c 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -29,9 +29,7 @@ /*************************************************************************/ #include "gltf_document.h" -#include "core/error/error_list.h" -#include "core/error/error_macros.h" -#include "core/variant/variant.h" + #include "gltf_accessor.h" #include "gltf_animation.h" #include "gltf_camera.h" @@ -44,35 +42,34 @@ #include "gltf_state.h" #include "gltf_texture.h" -#include <stdio.h> -#include <stdlib.h> - -#include "core/core_bind.h" #include "core/crypto/crypto_core.h" +#include "core/error/error_macros.h" +#include "core/io/dir_access.h" +#include "core/io/file_access.h" #include "core/io/json.h" #include "core/math/disjoint_set.h" -#include "core/os/file_access.h" #include "core/variant/typed_array.h" +#include "core/variant/variant.h" #include "core/version.h" #include "core/version_hash.gen.h" #include "drivers/png/png_driver_common.h" #include "editor/import/resource_importer_scene.h" +#include "scene/2d/node_2d.h" +#include "scene/3d/camera_3d.h" +#include "scene/3d/multimesh_instance_3d.h" +#include "scene/animation/animation_player.h" +#include "scene/resources/surface_tool.h" + +#include "modules/modules_enabled.gen.h" #ifdef MODULE_CSG_ENABLED #include "modules/csg/csg_shape.h" #endif // MODULE_CSG_ENABLED #ifdef MODULE_GRIDMAP_ENABLED #include "modules/gridmap/grid_map.h" #endif // MODULE_GRIDMAP_ENABLED -#include "scene/2d/node_2d.h" -#include "scene/3d/bone_attachment_3d.h" -#include "scene/3d/camera_3d.h" -#include "scene/3d/mesh_instance_3d.h" -#include "scene/3d/multimesh_instance_3d.h" -#include "scene/3d/node_3d.h" -#include "scene/3d/skeleton_3d.h" -#include "scene/animation/animation_player.h" -#include "scene/main/node.h" -#include "scene/resources/surface_tool.h" + +#include <stdio.h> +#include <stdlib.h> #include <limits> Error GLTFDocument::serialize(Ref<GLTFState> state, Node *p_root, const String &p_path) { @@ -233,20 +230,18 @@ Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> state) { } Vector<uint8_t> array; - array.resize(f->get_len()); + array.resize(f->get_length()); f->get_buffer(array.ptrw(), array.size()); String text; text.parse_utf8((const char *)array.ptr(), array.size()); - String err_txt; - int err_line; - Variant v; - err = JSON::parse(text, v, err_txt, err_line); + JSON json; + err = json.parse(text); if (err != OK) { - _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT); + _err_print_error("", p_path.utf8().get_data(), json.get_error_line(), json.get_error_message().utf8().get_data(), ERR_HANDLER_SCRIPT); return err; } - state->json = v; + state->json = json.get_data(); return OK; } @@ -299,16 +294,14 @@ Error GLTFDocument::_parse_glb(const String &p_path, Ref<GLTFState> state) { String text; text.parse_utf8((const char *)json_data.ptr(), json_data.size()); - String err_txt; - int err_line; - Variant v; - err = JSON::parse(text, v, err_txt, err_line); + JSON json; + err = json.parse(text); if (err != OK) { - _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT); + _err_print_error("", p_path.utf8().get_data(), json.get_error_line(), json.get_error_message().utf8().get_data(), ERR_HANDLER_SCRIPT); return err; } - state->json = v; + state->json = json.get_data(); //data? @@ -342,25 +335,25 @@ static Vector3 _arr_to_vec3(const Array &p_array) { return Vector3(p_array[0], p_array[1], p_array[2]); } -static Array _quat_to_array(const Quat &p_quat) { +static Array _quaternion_to_array(const Quaternion &p_quaternion) { Array array; array.resize(4); - array[0] = p_quat.x; - array[1] = p_quat.y; - array[2] = p_quat.z; - array[3] = p_quat.w; + array[0] = p_quaternion.x; + array[1] = p_quaternion.y; + array[2] = p_quaternion.z; + array[3] = p_quaternion.w; return array; } -static Quat _arr_to_quat(const Array &p_array) { - ERR_FAIL_COND_V(p_array.size() != 4, Quat()); - return Quat(p_array[0], p_array[1], p_array[2], p_array[3]); +static Quaternion _arr_to_quaternion(const Array &p_array) { + ERR_FAIL_COND_V(p_array.size() != 4, Quaternion()); + return Quaternion(p_array[0], p_array[1], p_array[2], p_array[3]); } -static Transform _arr_to_xform(const Array &p_array) { - ERR_FAIL_COND_V(p_array.size() != 16, Transform()); +static Transform3D _arr_to_xform(const Array &p_array) { + ERR_FAIL_COND_V(p_array.size() != 16, Transform3D()); - Transform xform; + Transform3D xform; xform.basis.set_axis(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2])); xform.basis.set_axis(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6])); xform.basis.set_axis(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10])); @@ -369,7 +362,7 @@ static Transform _arr_to_xform(const Array &p_array) { return xform; } -static Vector<real_t> _xform_to_array(const Transform p_transform) { +static Vector<real_t> _xform_to_array(const Transform3D p_transform) { Vector<real_t> array; array.resize(16); Vector3 axis_x = p_transform.get_basis().get_axis(Vector3::AXIS_X); @@ -421,12 +414,12 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { } if (n->skeleton != -1 && n->skin < 0) { } - if (n->xform != Transform()) { + if (n->xform != Transform3D()) { node["matrix"] = _xform_to_array(n->xform); } - if (!n->rotation.is_equal_approx(Quat())) { - node["rotation"] = _quat_to_array(n->rotation); + if (!n->rotation.is_equal_approx(Quaternion())) { + node["rotation"] = _quaternion_to_array(n->rotation); } if (!n->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) { @@ -569,7 +562,7 @@ Error GLTFDocument::_parse_nodes(Ref<GLTFState> state) { const Array &nodes = state->json["nodes"]; for (int i = 0; i < nodes.size(); i++) { Ref<GLTFNode> node; - node.instance(); + node.instantiate(); const Dictionary &n = nodes[i]; if (n.has("name")) { @@ -591,13 +584,13 @@ Error GLTFDocument::_parse_nodes(Ref<GLTFState> state) { node->translation = _arr_to_vec3(n["translation"]); } if (n.has("rotation")) { - node->rotation = _arr_to_quat(n["rotation"]); + node->rotation = _arr_to_quaternion(n["rotation"]); } if (n.has("scale")) { node->scale = _arr_to_vec3(n["scale"]); } - node->xform.basis.set_quat_scale(node->rotation, node->scale); + node->xform.basis.set_quaternion_scale(node->rotation, node->scale); node->xform.origin = node->translation; } @@ -664,7 +657,7 @@ static Vector<uint8_t> _parse_base64_uri(const String &uri) { int start = uri.find(","); ERR_FAIL_COND_V(start == -1, Vector<uint8_t>()); - CharString substr = uri.right(start + 1).ascii(); + CharString substr = uri.substr(start + 1).ascii(); int strlen = substr.length(); @@ -830,7 +823,7 @@ Error GLTFDocument::_parse_buffer_views(Ref<GLTFState> state) { const Dictionary &d = buffers[i]; Ref<GLTFBufferView> buffer_view; - buffer_view.instance(); + buffer_view.instantiate(); ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR); buffer_view->buffer = d["buffer"]; @@ -976,7 +969,7 @@ Error GLTFDocument::_parse_accessors(Ref<GLTFState> state) { const Dictionary &d = accessors[i]; Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR); accessor->component_type = d["componentType"]; @@ -1118,7 +1111,7 @@ Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> state, const double *src, } Ref<GLTFBufferView> bv; - bv.instance(); + bv.instantiate(); const uint32_t offset = bv->byte_offset = byte_offset; Vector<uint8_t> &gltf_buffer = state->buffers.write[0]; @@ -1157,7 +1150,7 @@ Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> state, const double *src, } int64_t old_size = gltf_buffer.size(); gltf_buffer.resize(old_size + (buffer.size() * sizeof(int8_t))); - copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int8_t)); + memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int8_t)); bv->byte_length = buffer.size() * sizeof(int8_t); } break; case COMPONENT_TYPE_UNSIGNED_BYTE: { @@ -1203,7 +1196,7 @@ Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> state, const double *src, } int64_t old_size = gltf_buffer.size(); gltf_buffer.resize(old_size + (buffer.size() * sizeof(int16_t))); - copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int16_t)); + memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int16_t)); bv->byte_length = buffer.size() * sizeof(int16_t); } break; case COMPONENT_TYPE_UNSIGNED_SHORT: { @@ -1227,7 +1220,7 @@ Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> state, const double *src, } int64_t old_size = gltf_buffer.size(); gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint16_t))); - copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint16_t)); + memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint16_t)); bv->byte_length = buffer.size() * sizeof(uint16_t); } break; case COMPONENT_TYPE_INT: { @@ -1247,7 +1240,7 @@ Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> state, const double *src, } int64_t old_size = gltf_buffer.size(); gltf_buffer.resize(old_size + (buffer.size() * sizeof(int32_t))); - copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int32_t)); + memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int32_t)); bv->byte_length = buffer.size() * sizeof(int32_t); } break; case COMPONENT_TYPE_FLOAT: { @@ -1267,7 +1260,7 @@ Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> state, const double *src, } int64_t old_size = gltf_buffer.size(); gltf_buffer.resize(old_size + (buffer.size() * sizeof(float))); - copymem(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(float)); + memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(float)); bv->byte_length = buffer.size() * sizeof(float); } break; } @@ -1512,7 +1505,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_ints(Ref<GLTFState> state, c ERR_FAIL_COND_V(attribs.size() == 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_SCALAR; @@ -1596,7 +1589,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec2(Ref<GLTFState> state, c ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC2; @@ -1645,7 +1638,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_color(Ref<GLTFState> state, ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4; @@ -1710,7 +1703,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_weights(Ref<GLTFState> state ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4; @@ -1757,7 +1750,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_joints(Ref<GLTFState> state, ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4; @@ -1779,7 +1772,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_joints(Ref<GLTFState> state, return state->accessors.size() - 1; } -GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quats(Ref<GLTFState> state, const Vector<Quat> p_attribs, const bool p_for_vertex) { +GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quaternions(Ref<GLTFState> state, const Vector<Quaternion> p_attribs, const bool p_for_vertex) { if (p_attribs.size() == 0) { return -1; } @@ -1794,11 +1787,11 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quats(Ref<GLTFState> state, Vector<double> type_min; type_min.resize(element_count); for (int i = 0; i < p_attribs.size(); i++) { - Quat quat = p_attribs[i]; - attribs.write[(i * element_count) + 0] = Math::snapped(quat.x, CMP_NORMALIZE_TOLERANCE); - attribs.write[(i * element_count) + 1] = Math::snapped(quat.y, CMP_NORMALIZE_TOLERANCE); - attribs.write[(i * element_count) + 2] = Math::snapped(quat.z, CMP_NORMALIZE_TOLERANCE); - attribs.write[(i * element_count) + 3] = Math::snapped(quat.w, CMP_NORMALIZE_TOLERANCE); + Quaternion quaternion = p_attribs[i]; + attribs.write[(i * element_count) + 0] = Math::snapped(quaternion.x, CMP_NORMALIZE_TOLERANCE); + attribs.write[(i * element_count) + 1] = Math::snapped(quaternion.y, CMP_NORMALIZE_TOLERANCE); + attribs.write[(i * element_count) + 2] = Math::snapped(quaternion.z, CMP_NORMALIZE_TOLERANCE); + attribs.write[(i * element_count) + 3] = Math::snapped(quaternion.w, CMP_NORMALIZE_TOLERANCE); _calc_accessor_min_max(i, element_count, type_max, attribs, type_min); } @@ -1806,7 +1799,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quats(Ref<GLTFState> state, ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC4; @@ -1871,7 +1864,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_floats(Ref<GLTFState> state, ERR_FAIL_COND_V(!attribs.size(), -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_SCALAR; @@ -1917,7 +1910,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec3(Ref<GLTFState> state, c ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_VEC3; @@ -1939,7 +1932,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec3(Ref<GLTFState> state, c return state->accessors.size() - 1; } -GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> state, const Vector<Transform> p_attribs, const bool p_for_vertex) { +GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> state, const Vector<Transform3D> p_attribs, const bool p_for_vertex) { if (p_attribs.size() == 0) { return -1; } @@ -1953,7 +1946,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> state, Vector<double> type_min; type_min.resize(element_count); for (int i = 0; i < p_attribs.size(); i++) { - Transform attrib = p_attribs[i]; + Transform3D attrib = p_attribs[i]; Basis basis = attrib.get_basis(); Vector3 axis_0 = basis.get_axis(Vector3::AXIS_X); @@ -1985,7 +1978,7 @@ GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> state, ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1); Ref<GLTFAccessor> accessor; - accessor.instance(); + accessor.instantiate(); GLTFBufferIndex buffer_view_i; int64_t size = state->buffers[0].size(); const GLTFDocument::GLTFType type = GLTFDocument::TYPE_MAT4; @@ -2053,9 +2046,9 @@ Vector<Color> GLTFDocument::_decode_accessor_as_color(Ref<GLTFState> state, cons } return ret; } -Vector<Quat> GLTFDocument::_decode_accessor_as_quat(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) { +Vector<Quaternion> GLTFDocument::_decode_accessor_as_quaternion(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) { const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); - Vector<Quat> ret; + Vector<Quaternion> ret; if (attribs.size() == 0) { return ret; @@ -2067,7 +2060,7 @@ Vector<Quat> GLTFDocument::_decode_accessor_as_quat(Ref<GLTFState> state, const ret.resize(ret_size); { for (int i = 0; i < ret_size; i++) { - ret.write[i] = Quat(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized(); + ret.write[i] = Quaternion(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized(); } } return ret; @@ -2107,9 +2100,9 @@ Vector<Basis> GLTFDocument::_decode_accessor_as_basis(Ref<GLTFState> state, cons return ret; } -Vector<Transform> GLTFDocument::_decode_accessor_as_xform(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) { +Vector<Transform3D> GLTFDocument::_decode_accessor_as_xform(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) { const Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex); - Vector<Transform> ret; + Vector<Transform3D> ret; if (attribs.size() == 0) { return ret; @@ -2335,7 +2328,7 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { //generate indices because they need to be swapped for CW/CCW const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX]; Ref<SurfaceTool> st; - st.instance(); + st.instantiate(); st->create_from_triangle_arrays(array); st->index(); Vector<int32_t> generated_indices = st->commit_to_arrays()[Mesh::ARRAY_INDEX]; @@ -2389,9 +2382,9 @@ Error GLTFDocument::_serialize_meshes(Ref<GLTFState> state) { for (int i = 0; i < ret_size; i++) { Color tangent; tangent.r = tarr[(i * 4) + 0]; - tangent.r = tarr[(i * 4) + 1]; - tangent.r = tarr[(i * 4) + 2]; - tangent.r = tarr[(i * 4) + 3]; + tangent.g = tarr[(i * 4) + 1]; + tangent.b = tarr[(i * 4) + 2]; + tangent.a = tarr[(i * 4) + 3]; } t["TANGENT"] = _encode_accessor_as_color(state, attribs, true); } @@ -2459,7 +2452,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { Dictionary d = meshes[i]; Ref<GLTFMesh> mesh; - mesh.instance(); + mesh.instantiate(); bool has_vertex_color = false; ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR); @@ -2467,7 +2460,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { Array primitives = d["primitives"]; const Dictionary &extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary(); Ref<EditorSceneImporterMesh> import_mesh; - import_mesh.instance(); + import_mesh.instantiate(); String mesh_name = "mesh"; if (d.has("name") && !String(d["name"]).is_empty()) { mesh_name = d["name"]; @@ -2652,11 +2645,11 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { if (generate_tangents) { //must generate mikktspace tangents.. ergh.. Ref<SurfaceTool> st; - st.instance(); + st.instantiate(); + st->create_from_triangle_arrays(array); if (a.has("JOINTS_0") && a.has("JOINTS_1")) { st->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS); } - st->create_from_triangle_arrays(array); st->generate_tangents(); array = st->commit_to_arrays(); } @@ -2771,11 +2764,11 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { if (generate_tangents) { Ref<SurfaceTool> st; - st.instance(); + st.instantiate(); + st->create_from_triangle_arrays(array_copy); if (a.has("JOINTS_0") && a.has("JOINTS_1")) { st->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS); } - st->create_from_triangle_arrays(array_copy); st->deindex(); st->generate_tangents(); array_copy = st->commit_to_arrays(); @@ -2799,12 +2792,12 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { } else if (has_vertex_color) { Ref<StandardMaterial3D> mat3d; - mat3d.instance(); + mat3d.instantiate(); mat3d->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); mat = mat3d; } - import_mesh->add_surface(primitive, array, morphs, Dictionary(), mat); + import_mesh->add_surface(primitive, array, morphs, Dictionary(), mat, mat.is_valid() ? mat->get_name() : String()); } Vector<float> blend_weights; @@ -2821,8 +2814,8 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { } blend_weights.write[j] = weights[j]; } - mesh->set_blend_weights(blend_weights); } + mesh->set_blend_weights(blend_weights); mesh->set_mesh(import_mesh); state->meshes.push_back(mesh); @@ -2847,7 +2840,7 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path GLTFBufferViewIndex bvi; Ref<GLTFBufferView> bv; - bv.instance(); + bv.instantiate(); const GLTFBufferIndex bi = 0; bv->buffer = bi; @@ -2864,7 +2857,7 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path bv->byte_length = buffer.size(); state->buffers.write[bi].resize(state->buffers[bi].size() + bv->byte_length); - copymem(&state->buffers.write[bi].write[bv->byte_offset], buffer.ptr(), buffer.size()); + memcpy(&state->buffers.write[bi].write[bv->byte_offset], buffer.ptr(), buffer.size()); ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > state->buffers[bi].size(), ERR_FILE_CORRUPT); state->buffer_views.push_back(bv); @@ -2877,16 +2870,13 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path name = itos(i); } name = _gen_unique_name(state, name); - name = name.pad_zeros(3); - Ref<_Directory> dir; - dir.instance(); + name = name.pad_zeros(3) + ".png"; String texture_dir = "textures"; String new_texture_dir = p_path.get_base_dir() + "/" + texture_dir; - dir->open(p_path.get_base_dir()); - if (!dir->dir_exists(new_texture_dir)) { - dir->make_dir(new_texture_dir); + DirAccessRef da = DirAccess::open(p_path.get_base_dir()); + if (!da->dir_exists(new_texture_dir)) { + da->make_dir(new_texture_dir); } - name = name + ".png"; image->save_png(new_texture_dir.plus_file(name)); d["uri"] = texture_dir.plus_file(name); } @@ -3013,29 +3003,39 @@ Error GLTFDocument::_parse_images(Ref<GLTFState> state, const String &p_base_pat Ref<Image> img; + // First we honor the mime types if they were defined. if (mimetype == "image/png") { // Load buffer as PNG. ERR_FAIL_COND_V(Image::_png_mem_loader_func == nullptr, ERR_UNAVAILABLE); img = Image::_png_mem_loader_func(data_ptr, data_size); } else if (mimetype == "image/jpeg") { // Loader buffer as JPEG. ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, ERR_UNAVAILABLE); img = Image::_jpg_mem_loader_func(data_ptr, data_size); - } else { - // We can land here if we got an URI with base64-encoded data with application/* MIME type, - // and the optional mimeType property was not defined to tell us how to handle this data (or was invalid). - // So let's try PNG first, then JPEG. + } + + // If we didn't pass the above tests, we attempt loading as PNG and then + // JPEG directly. + // This covers URIs with base64-encoded data with application/* type but + // no optional mimeType property, or bufferViews with a bogus mimeType + // (e.g. `image/jpeg` but the data is actually PNG). + // That's not *exactly* what the spec mandates but this lets us be + // lenient with bogus glb files which do exist in production. + if (img.is_null()) { // Try PNG first. ERR_FAIL_COND_V(Image::_png_mem_loader_func == nullptr, ERR_UNAVAILABLE); img = Image::_png_mem_loader_func(data_ptr, data_size); - if (img.is_null()) { - ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, ERR_UNAVAILABLE); - img = Image::_jpg_mem_loader_func(data_ptr, data_size); - } } - - ERR_FAIL_COND_V_MSG(img.is_null(), ERR_FILE_CORRUPT, - vformat("glTF: Couldn't load image index '%d' with its given mimetype: %s.", i, mimetype)); + if (img.is_null()) { // And then JPEG. + ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, ERR_UNAVAILABLE); + img = Image::_jpg_mem_loader_func(data_ptr, data_size); + } + // Now we've done our best, fix your scenes. + if (img.is_null()) { + ERR_PRINT(vformat("glTF: Couldn't load image index '%d' with its given mimetype: %s.", i, mimetype)); + state->images.push_back(Ref<Texture2D>()); + continue; + } Ref<ImageTexture> t; - t.instance(); + t.instantiate(); t->create_from_image(img); state->images.push_back(t); @@ -3076,7 +3076,7 @@ Error GLTFDocument::_parse_textures(Ref<GLTFState> state) { ERR_FAIL_COND_V(!d.has("source"), ERR_PARSE_ERROR); Ref<GLTFTexture> t; - t.instance(); + t.instantiate(); t->set_src_image(d["source"]); state->textures.push_back(t); } @@ -3087,7 +3087,7 @@ Error GLTFDocument::_parse_textures(Ref<GLTFState> state) { GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> state, Ref<Texture2D> p_texture) { ERR_FAIL_COND_V(p_texture.is_null(), -1); Ref<GLTFTexture> gltf_texture; - gltf_texture.instance(); + gltf_texture.instantiate(); ERR_FAIL_COND_V(p_texture->get_image().is_null(), -1); GLTFImageIndex gltf_src_image_i = state->images.size(); state->images.push_back(p_texture); @@ -3160,9 +3160,9 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { Ref<Texture2D> ao_texture = material->get_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION); BaseMaterial3D::TextureChannel ao_channel = material->get_ao_texture_channel(); Ref<ImageTexture> orm_texture; - orm_texture.instance(); + orm_texture.instantiate(); Ref<Image> orm_image; - orm_image.instance(); + orm_image.instantiate(); int32_t height = 0; int32_t width = 0; Ref<Image> ao_image; @@ -3282,7 +3282,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { if (material->get_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING)) { Dictionary nt; Ref<ImageTexture> tex; - tex.instance(); + tex.instantiate(); { Ref<Texture2D> normal_texture = material->get_texture(BaseMaterial3D::TEXTURE_NORMAL); // Code for uncompressing RG normal maps @@ -3370,7 +3370,7 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { const Dictionary &d = materials[i]; Ref<StandardMaterial3D> material; - material.instance(); + material.instantiate(); if (d.has("name") && !String(d["name"]).is_empty()) { material->set_name(d["name"]); } else { @@ -3386,7 +3386,7 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { Dictionary sgm = pbr_spec_gloss_extensions["KHR_materials_pbrSpecularGlossiness"]; Ref<GLTFSpecGloss> spec_gloss; - spec_gloss.instance(); + spec_gloss.instantiate(); if (sgm.has("diffuseTexture")) { const Dictionary &diffuse_texture_dict = sgm["diffuseTexture"]; if (diffuse_texture_dict.has("index")) { @@ -3569,7 +3569,7 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re return; } Ref<Image> rm_img; - rm_img.instance(); + rm_img.instantiate(); bool has_roughness = false; bool has_metal = false; p_material->set_roughness(1.0f); @@ -3597,7 +3597,7 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re if (!Math::is_equal_approx(mr.g, 1.0f)) { has_roughness = true; } - if (!Math::is_equal_approx(mr.b, 0.0f)) { + if (!Math::is_zero_approx(mr.b)) { has_metal = true; } mr.g *= r_spec_gloss->gloss_factor; @@ -3611,11 +3611,11 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re rm_img->generate_mipmaps(); r_spec_gloss->diffuse_img->generate_mipmaps(); Ref<ImageTexture> diffuse_image_texture; - diffuse_image_texture.instance(); + diffuse_image_texture.instantiate(); diffuse_image_texture->create_from_image(r_spec_gloss->diffuse_img); p_material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, diffuse_image_texture); Ref<ImageTexture> rm_image_texture; - rm_image_texture.instance(); + rm_image_texture.instantiate(); rm_image_texture->create_from_image(rm_img); if (has_roughness) { p_material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, rm_image_texture); @@ -3891,7 +3891,7 @@ Error GLTFDocument::_parse_skins(Ref<GLTFState> state) { const Dictionary &d = skins[i]; Ref<GLTFSkin> skin; - skin.instance(); + skin.instantiate(); ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR); @@ -4019,7 +4019,7 @@ Error GLTFDocument::_determine_skeletons(Ref<GLTFState> state) { for (GLTFSkeletonIndex skel_i = 0; skel_i < skeleton_owners.size(); ++skel_i) { const GLTFNodeIndex skeleton_owner = skeleton_owners[skel_i]; Ref<GLTFSkeleton> skeleton; - skeleton.instance(); + skeleton.instantiate(); Vector<GLTFNodeIndex> skeleton_nodes; skeleton_sets.get_members(skeleton_nodes, skeleton_owner); @@ -4105,81 +4105,10 @@ Error GLTFDocument::_reparent_non_joint_skeleton_subtrees(Ref<GLTFState> state, subtree_set.get_members(subtree_nodes, subtree_root); for (int subtree_i = 0; subtree_i < subtree_nodes.size(); ++subtree_i) { - ERR_FAIL_COND_V(_reparent_to_fake_joint(state, skeleton, subtree_nodes[subtree_i]), FAILED); - - // We modified the tree, recompute all the heights - _compute_node_heights(state); - } - } - - return OK; -} - -Error GLTFDocument::_reparent_to_fake_joint(Ref<GLTFState> state, Ref<GLTFSkeleton> skeleton, const GLTFNodeIndex node_index) { - Ref<GLTFNode> node = state->nodes[node_index]; - - // Can we just "steal" this joint if it is just a spatial node? - if (node->skin < 0 && node->mesh < 0 && node->camera < 0) { - node->joint = true; - // Add the joint to the skeletons joints - skeleton->joints.push_back(node_index); - return OK; - } - - GLTFNode *fake_joint = memnew(GLTFNode); - const GLTFNodeIndex fake_joint_index = state->nodes.size(); - state->nodes.push_back(fake_joint); - - // We better not be a joint, or we messed up in our logic - if (node->joint) { - return FAILED; - } - - fake_joint->translation = node->translation; - fake_joint->rotation = node->rotation; - fake_joint->scale = node->scale; - fake_joint->xform = node->xform; - fake_joint->joint = true; - - // We can use the exact same name here, because the joint will be inside a skeleton and not the scene - fake_joint->set_name(node->get_name()); - - // Clear the nodes transforms, since it will be parented to the fake joint - node->translation = Vector3(0, 0, 0); - node->rotation = Quat(); - node->scale = Vector3(1, 1, 1); - node->xform = Transform(); - - // Transfer the node children to the fake joint - for (int child_i = 0; child_i < node->children.size(); ++child_i) { - Ref<GLTFNode> child = state->nodes[node->children[child_i]]; - child->parent = fake_joint_index; - } - - fake_joint->children = node->children; - node->children.clear(); - - // add the fake joint to the parent and remove the original joint - if (node->parent >= 0) { - Ref<GLTFNode> parent = state->nodes[node->parent]; - parent->children.erase(node_index); - parent->children.push_back(fake_joint_index); - fake_joint->parent = node->parent; - } - - // Add the node to the fake joint - fake_joint->children.push_back(node_index); - node->parent = fake_joint_index; - node->fake_joint_parent = fake_joint_index; - - // Add the fake joint to the skeletons joints - skeleton->joints.push_back(fake_joint_index); - - // Replace skin_skeletons with fake joints if we must. - for (GLTFSkinIndex skin_i = 0; skin_i < state->skins.size(); ++skin_i) { - Ref<GLTFSkin> skin = state->skins.write[skin_i]; - if (skin->skin_root == node_index) { - skin->skin_root = fake_joint_index; + Ref<GLTFNode> node = state->nodes[subtree_nodes[subtree_i]]; + node->joint = true; + // Add the joint to the skeletons joints + skeleton->joints.push_back(subtree_nodes[subtree_i]); } } @@ -4338,7 +4267,7 @@ Error GLTFDocument::_create_skins(Ref<GLTFState> state) { Ref<GLTFSkin> gltf_skin = state->skins.write[skin_i]; Ref<Skin> skin; - skin.instance(); + skin.instantiate(); // Some skins don't have IBM's! What absolute monsters! const bool has_ibms = !gltf_skin->inverse_binds.is_empty(); @@ -4347,7 +4276,7 @@ Error GLTFDocument::_create_skins(Ref<GLTFState> state) { GLTFNodeIndex node = gltf_skin->joints_original[joint_i]; String bone_name = state->nodes[node]->get_name(); - Transform xform; + Transform3D xform; if (has_ibms) { xform = gltf_skin->inverse_binds[joint_i]; } @@ -4387,9 +4316,12 @@ bool GLTFDocument::_skins_are_same(const Ref<Skin> skin_a, const Ref<Skin> skin_ if (skin_a->get_bind_bone(i) != skin_b->get_bind_bone(i)) { return false; } + if (skin_a->get_bind_name(i) != skin_b->get_bind_name(i)) { + return false; + } - Transform a_xform = skin_a->get_bind_pose(i); - Transform b_xform = skin_b->get_bind_pose(i); + Transform3D a_xform = skin_a->get_bind_pose(i); + Transform3D b_xform = skin_b->get_bind_pose(i); if (a_xform != b_xform) { return false; @@ -4517,7 +4449,7 @@ Error GLTFDocument::_parse_lights(Ref<GLTFState> state) { const Dictionary &d = lights[light_i]; Ref<GLTFLight> light; - light.instance(); + light.instantiate(); ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR); const String &type = d["type"]; light->type = type; @@ -4538,9 +4470,9 @@ Error GLTFDocument::_parse_lights(Ref<GLTFState> state) { const Dictionary &spot = d["spot"]; light->inner_cone_angle = spot["innerConeAngle"]; light->outer_cone_angle = spot["outerConeAngle"]; - ERR_FAIL_COND_V_MSG(light->inner_cone_angle >= light->outer_cone_angle, ERR_PARSE_ERROR, "The inner angle must be smaller than the outer angle."); + ERR_CONTINUE_MSG(light->inner_cone_angle >= light->outer_cone_angle, "The inner angle must be smaller than the outer angle."); } else if (type != "point" && type != "directional") { - ERR_FAIL_V_MSG(ERR_PARSE_ERROR, "Light type is unknown."); + ERR_CONTINUE_MSG(ERR_PARSE_ERROR, "Light type is unknown."); } state->lights.push_back(light); @@ -4562,7 +4494,7 @@ Error GLTFDocument::_parse_cameras(Ref<GLTFState> state) { const Dictionary &d = cameras[i]; Ref<GLTFCamera> camera; - camera.instance(); + camera.instantiate(); ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR); const String &type = d["type"]; if (type == "orthographic") { @@ -4672,8 +4604,8 @@ Error GLTFDocument::_serialize_animations(Ref<GLTFState> state) { s["interpolation"] = interpolation_to_string(track.rotation_track.interpolation); Vector<real_t> times = Variant(track.rotation_track.times); s["input"] = _encode_accessor_as_floats(state, times, false); - Vector<Quat> values = track.rotation_track.values; - s["output"] = _encode_accessor_as_quats(state, values, false); + Vector<Quaternion> values = track.rotation_track.values; + s["output"] = _encode_accessor_as_quaternions(state, values, false); samplers.push_back(s); @@ -4765,7 +4697,7 @@ Error GLTFDocument::_parse_animations(Ref<GLTFState> state) { const Dictionary &d = animations[i]; Ref<GLTFAnimation> animation; - animation.instance(); + animation.instantiate(); if (!d.has("channels") || !d.has("samplers")) { continue; @@ -4842,7 +4774,7 @@ Error GLTFDocument::_parse_animations(Ref<GLTFState> state) { track->translation_track.times = Variant(times); //convert via variant track->translation_track.values = Variant(translations); //convert via variant } else if (path == "rotation") { - const Vector<Quat> rotations = _decode_accessor_as_quat(state, output, false); + const Vector<Quaternion> rotations = _decode_accessor_as_quaternion(state, output, false); track->rotation_track.interpolation = interp; track->rotation_track.times = Variant(times); //convert via variant track->rotation_track.values = rotations; @@ -4914,10 +4846,9 @@ void GLTFDocument::_assign_scene_names(Ref<GLTFState> state) { } } -BoneAttachment3D *GLTFDocument::_generate_bone_attachment(Ref<GLTFState> state, Skeleton3D *skeleton, const GLTFNodeIndex node_index) { +BoneAttachment3D *GLTFDocument::_generate_bone_attachment(Ref<GLTFState> state, Skeleton3D *skeleton, const GLTFNodeIndex node_index, const GLTFNodeIndex bone_index) { Ref<GLTFNode> gltf_node = state->nodes[node_index]; - Ref<GLTFNode> bone_node = state->nodes[gltf_node->parent]; - + Ref<GLTFNode> bone_node = state->nodes[bone_index]; BoneAttachment3D *bone_attachment = memnew(BoneAttachment3D); print_verbose("glTF: Creating bone attachment for: " + gltf_node->get_name()); @@ -4934,7 +4865,7 @@ GLTFMeshIndex GLTFDocument::_convert_mesh_instance(Ref<GLTFState> state, MeshIns return -1; } Ref<EditorSceneImporterMesh> import_mesh; - import_mesh.instance(); + import_mesh.instantiate(); Ref<Mesh> godot_mesh = p_mesh_instance->get_mesh(); if (godot_mesh.is_null()) { return -1; @@ -4971,7 +4902,7 @@ GLTFMeshIndex GLTFDocument::_convert_mesh_instance(Ref<GLTFState> state, MeshIns blend_weights.write[blend_i] = 0.0f; } Ref<GLTFMesh> gltf_mesh; - gltf_mesh.instance(); + gltf_mesh.instantiate(); gltf_mesh->set_mesh(import_mesh); gltf_mesh->set_blend_weights(blend_weights); GLTFMeshIndex mesh_i = state->meshes.size(); @@ -5002,7 +4933,7 @@ EditorSceneImporterMeshNode3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFSta return mi; } -Light3D *GLTFDocument::_generate_light(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) { +Node3D *GLTFDocument::_generate_light(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) { Ref<GLTFNode> gltf_node = state->nodes[node_index]; ERR_FAIL_INDEX_V(gltf_node->light, state->lights.size(), nullptr); @@ -5051,7 +4982,7 @@ Light3D *GLTFDocument::_generate_light(Ref<GLTFState> state, Node *scene_parent, light->set_param(SpotLight3D::PARAM_SPOT_ATTENUATION, angle_attenuation); return light; } - return nullptr; + return memnew(Node3D); } Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index) { @@ -5076,7 +5007,7 @@ GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> state, Camera3D *p_ print_verbose("glTF: Converting camera: " + p_camera->get_name()); Ref<GLTFCamera> c; - c.instance(); + c.instantiate(); if (p_camera->get_projection() == Camera3D::Projection::PROJECTION_PERSPECTIVE) { c->set_perspective(true); @@ -5097,7 +5028,7 @@ GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> state, Light3D *p_lig print_verbose("glTF: Converting light: " + p_light->get_name()); Ref<GLTFLight> l; - l.instance(); + l.instantiate(); l->color = p_light->get_color(); if (cast_to<DirectionalLight3D>(p_light)) { l->type = "directional"; @@ -5132,7 +5063,7 @@ GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> state, Light3D *p_lig GLTFSkeletonIndex GLTFDocument::_convert_skeleton(Ref<GLTFState> state, Skeleton3D *p_skeleton) { print_verbose("glTF: Converting skeleton: " + p_skeleton->get_name()); Ref<GLTFSkeleton> gltf_skeleton; - gltf_skeleton.instance(); + gltf_skeleton.instantiate(); gltf_skeleton->set_name(_gen_unique_name(state, p_skeleton->get_name())); gltf_skeleton->godot_skeleton = p_skeleton; GLTFSkeletonIndex skeleton_i = state->skeletons.size(); @@ -5141,9 +5072,9 @@ GLTFSkeletonIndex GLTFDocument::_convert_skeleton(Ref<GLTFState> state, Skeleton } void GLTFDocument::_convert_spatial(Ref<GLTFState> state, Node3D *p_spatial, Ref<GLTFNode> p_node) { - Transform xform = p_spatial->get_transform(); + Transform3D xform = p_spatial->get_transform(); p_node->scale = xform.basis.get_scale(); - p_node->rotation = xform.basis.get_rotation_quat(); + p_node->rotation = xform.basis.get_rotation_quaternion(); p_node->translation = xform.origin; } @@ -5162,7 +5093,7 @@ void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, No return; } Ref<GLTFNode> gltf_node; - gltf_node.instance(); + gltf_node.instantiate(); gltf_node->set_name(_gen_unique_name(state, p_current->get_name())); if (cast_to<Node3D>(p_current)) { Node3D *spatial = cast_to<Node3D>(p_current); @@ -5228,9 +5159,9 @@ void GLTFDocument::_convert_csg_shape_to_gltf(Node *p_current, GLTFNodeIndex p_g mat = csg->get_material_override(); } Ref<GLTFMesh> gltf_mesh; - gltf_mesh.instance(); + gltf_mesh.instantiate(); Ref<EditorSceneImporterMesh> import_mesh; - import_mesh.instance(); + import_mesh.instantiate(); Ref<ArrayMesh> array_mesh = csg->get_meshes()[1]; for (int32_t surface_i = 0; surface_i < array_mesh->get_surface_count(); surface_i++) { import_mesh->add_surface(Mesh::PrimitiveType::PRIMITIVE_TRIANGLES, array_mesh->surface_get_arrays(surface_i), Array(), Dictionary(), mat, array_mesh->surface_get_name(surface_i)); @@ -5306,7 +5237,7 @@ void GLTFDocument::_convert_grid_map_to_gltf(Node *p_scene_parent, const GLTFNod Vector3(cell_location.x, cell_location.y, cell_location.z)); EditorSceneImporterMeshNode3D *import_mesh_node = memnew(EditorSceneImporterMeshNode3D); import_mesh_node->set_mesh(grid_map->get_mesh_library()->get_item_mesh(cell)); - Transform cell_xform; + Transform3D cell_xform; cell_xform.basis.set_orthogonal_index( grid_map->get_cell_item_orientation( Vector3(cell_location.x, cell_location.y, cell_location.z))); @@ -5316,7 +5247,7 @@ void GLTFDocument::_convert_grid_map_to_gltf(Node *p_scene_parent, const GLTFNod cell_xform.set_origin(grid_map->map_to_world( Vector3(cell_location.x, cell_location.y, cell_location.z))); Ref<GLTFMesh> gltf_mesh; - gltf_mesh.instance(); + gltf_mesh.instantiate(); gltf_mesh = import_mesh_node; new_gltf_node->mesh = state->meshes.size(); state->meshes.push_back(gltf_mesh); @@ -5334,15 +5265,15 @@ void GLTFDocument::_convert_mult_mesh_instance_to_gltf(Node *p_scene_parent, con for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count(); instance_i++) { GLTFNode *new_gltf_node = memnew(GLTFNode); - Transform transform; + Transform3D transform; if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_2D) { Transform2D xform_2d = multi_mesh->get_instance_transform_2d(instance_i); transform.origin = Vector3(xform_2d.get_origin().x, 0, xform_2d.get_origin().y); real_t rotation = xform_2d.get_rotation(); - Quat quat(Vector3(0, 1, 0), rotation); + Quaternion quaternion(Vector3(0, 1, 0), rotation); Size2 scale = xform_2d.get_scale(); - transform.basis.set_quat_scale(quat, + transform.basis.set_quaternion_scale(quaternion, Vector3(scale.x, 0, scale.y)); transform = multi_mesh_instance->get_transform() * transform; @@ -5353,14 +5284,14 @@ void GLTFDocument::_convert_mult_mesh_instance_to_gltf(Node *p_scene_parent, con Ref<ArrayMesh> mm = multi_mesh->get_mesh(); if (mm.is_valid()) { Ref<EditorSceneImporterMesh> mesh; - mesh.instance(); + mesh.instantiate(); for (int32_t surface_i = 0; surface_i < mm->get_surface_count(); surface_i++) { Array surface = mm->surface_get_arrays(surface_i); mesh->add_surface(mm->surface_get_primitive_type(surface_i), surface, Array(), Dictionary(), mm->surface_get_material(surface_i), mm->get_name()); } Ref<GLTFMesh> gltf_mesh; - gltf_mesh.instance(); + gltf_mesh.instantiate(); gltf_mesh->set_name(multi_mesh->get_name()); gltf_mesh->set_mesh(mesh); new_gltf_node->mesh = state->meshes.size(); @@ -5423,31 +5354,22 @@ void GLTFDocument::_convert_mesh_to_gltf(Node *p_scene_parent, Ref<GLTFState> st void GLTFDocument::_generate_scene_node(Ref<GLTFState> state, Node *scene_parent, Node3D *scene_root, const GLTFNodeIndex node_index) { Ref<GLTFNode> gltf_node = state->nodes[node_index]; + if (gltf_node->skeleton >= 0) { + _generate_skeleton_bone_node(state, scene_parent, scene_root, node_index); + return; + } + Node3D *current_node = nullptr; // Is our parent a skeleton Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(scene_parent); - if (gltf_node->skeleton >= 0) { - Skeleton3D *skeleton = state->skeletons[gltf_node->skeleton]->godot_skeleton; + const bool non_bone_parented_to_skeleton = active_skeleton; - if (active_skeleton != skeleton) { - ERR_FAIL_COND_MSG(active_skeleton != nullptr, "glTF: Generating scene detected direct parented Skeletons"); - - // Add it to the scene if it has not already been added - if (skeleton->get_parent() == nullptr) { - scene_parent->add_child(skeleton); - skeleton->set_owner(scene_root); - } - } - - active_skeleton = skeleton; - current_node = skeleton; - } - - // If we have an active skeleton, and the node is node skinned, we need to create a bone attachment - if (current_node == nullptr && active_skeleton != nullptr && gltf_node->skin < 0) { - BoneAttachment3D *bone_attachment = _generate_bone_attachment(state, active_skeleton, node_index); + // skinned meshes must not be placed in a bone attachment. + if (non_bone_parented_to_skeleton && gltf_node->skin < 0) { + // Bone Attachment - Parent Case + BoneAttachment3D *bone_attachment = _generate_bone_attachment(state, active_skeleton, node_index, gltf_node->parent); scene_parent->add_child(bone_attachment); bone_attachment->set_owner(scene_root); @@ -5459,9 +5381,89 @@ void GLTFDocument::_generate_scene_node(Ref<GLTFState> state, Node *scene_parent // and attach it to the bone_attachment scene_parent = bone_attachment; } + if (gltf_node->mesh >= 0) { + current_node = _generate_mesh_instance(state, scene_parent, node_index); + } else if (gltf_node->camera >= 0) { + current_node = _generate_camera(state, scene_parent, node_index); + } else if (gltf_node->light >= 0) { + current_node = _generate_light(state, scene_parent, node_index); + } + + // We still have not managed to make a node. + if (!current_node) { + current_node = _generate_spatial(state, scene_parent, node_index); + } + + scene_parent->add_child(current_node); + if (current_node != scene_root) { + current_node->set_owner(scene_root); + } + current_node->set_transform(gltf_node->xform); + current_node->set_name(gltf_node->get_name()); + + state->scene_nodes.insert(node_index, current_node); + + for (int i = 0; i < gltf_node->children.size(); ++i) { + _generate_scene_node(state, current_node, scene_root, gltf_node->children[i]); + } +} + +void GLTFDocument::_generate_skeleton_bone_node(Ref<GLTFState> state, Node *scene_parent, Node3D *scene_root, const GLTFNodeIndex node_index) { + Ref<GLTFNode> gltf_node = state->nodes[node_index]; - // We still have not managed to make a node - if (current_node == nullptr) { + Node3D *current_node = nullptr; + + Skeleton3D *skeleton = state->skeletons[gltf_node->skeleton]->godot_skeleton; + // In this case, this node is already a bone in skeleton. + const bool is_skinned_mesh = (gltf_node->skin >= 0 && gltf_node->mesh >= 0); + const bool requires_extra_node = (gltf_node->mesh >= 0 || gltf_node->camera >= 0 || gltf_node->light >= 0); + + Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(scene_parent); + if (active_skeleton != skeleton) { + if (active_skeleton) { + // Bone Attachment - Direct Parented Skeleton Case + BoneAttachment3D *bone_attachment = _generate_bone_attachment(state, active_skeleton, node_index, gltf_node->parent); + + scene_parent->add_child(bone_attachment); + bone_attachment->set_owner(scene_root); + + // There is no gltf_node that represent this, so just directly create a unique name + bone_attachment->set_name(_gen_unique_name(state, "BoneAttachment3D")); + + // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node + // and attach it to the bone_attachment + scene_parent = bone_attachment; + WARN_PRINT(vformat("glTF: Generating scene detected direct parented Skeletons at node %d", node_index)); + } + + // Add it to the scene if it has not already been added + if (skeleton->get_parent() == nullptr) { + scene_parent->add_child(skeleton); + skeleton->set_owner(scene_root); + } + } + + active_skeleton = skeleton; + current_node = skeleton; + + if (requires_extra_node) { + // skinned meshes must not be placed in a bone attachment. + if (!is_skinned_mesh) { + // Bone Attachment - Same Node Case + BoneAttachment3D *bone_attachment = _generate_bone_attachment(state, active_skeleton, node_index, node_index); + + scene_parent->add_child(bone_attachment); + bone_attachment->set_owner(scene_root); + + // There is no gltf_node that represent this, so just directly create a unique name + bone_attachment->set_name(_gen_unique_name(state, "BoneAttachment3D")); + + // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node + // and attach it to the bone_attachment + scene_parent = bone_attachment; + } + + // We still have not managed to make a node if (gltf_node->mesh >= 0) { current_node = _generate_mesh_instance(state, scene_parent, node_index); } else if (gltf_node->camera >= 0) { @@ -5470,22 +5472,18 @@ void GLTFDocument::_generate_scene_node(Ref<GLTFState> state, Node *scene_parent current_node = _generate_light(state, scene_parent, node_index); } - if (!current_node) { - current_node = _generate_spatial(state, scene_parent, node_index); - } - scene_parent->add_child(current_node); if (current_node != scene_root) { current_node->set_owner(scene_root); } - current_node->set_transform(gltf_node->xform); + // Do not set transform here. Transform is already applied to our bone. current_node->set_name(gltf_node->get_name()); } state->scene_nodes.insert(node_index, current_node); for (int i = 0; i < gltf_node->children.size(); ++i) { - _generate_scene_node(state, current_node, scene_root, gltf_node->children[i]); + _generate_scene_node(state, active_skeleton, scene_root, gltf_node->children[i]); } } @@ -5516,24 +5514,24 @@ struct EditorSceneImporterGLTFInterpolate { // thank you for existing, partial specialization template <> -struct EditorSceneImporterGLTFInterpolate<Quat> { - Quat lerp(const Quat &a, const Quat &b, const float c) const { - ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quat(), "The quaternion \"a\" must be normalized."); - ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quat(), "The quaternion \"b\" must be normalized."); +struct EditorSceneImporterGLTFInterpolate<Quaternion> { + Quaternion lerp(const Quaternion &a, const Quaternion &b, const float c) const { + ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quaternion(), "The quaternion \"a\" must be normalized."); + ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quaternion(), "The quaternion \"b\" must be normalized."); return a.slerp(b, c).normalized(); } - Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, const float c) { - ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quat(), "The quaternion \"p1\" must be normalized."); - ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quat(), "The quaternion \"p2\" must be normalized."); + Quaternion catmull_rom(const Quaternion &p0, const Quaternion &p1, const Quaternion &p2, const Quaternion &p3, const float c) { + ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quaternion(), "The quaternion \"p1\" must be normalized."); + ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quaternion(), "The quaternion \"p2\" must be normalized."); return p1.slerp(p2, c).normalized(); } - Quat bezier(const Quat start, const Quat control_1, const Quat control_2, const Quat end, const float t) { - ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quat(), "The start quaternion must be normalized."); - ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quat(), "The end quaternion must be normalized."); + Quaternion bezier(const Quaternion start, const Quaternion control_1, const Quaternion control_2, const Quaternion end, const float t) { + ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quaternion(), "The start quaternion must be normalized."); + ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quaternion(), "The end quaternion must be normalized."); return start.slerp(end, t).normalized(); } @@ -5541,6 +5539,11 @@ struct EditorSceneImporterGLTFInterpolate<Quat> { template <class T> T GLTFDocument::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, const float p_time, const GLTFAnimation::Interpolation p_interp) { + ERR_FAIL_COND_V(!p_values.size(), T()); + if (p_times.size() != p_values.size()) { + ERR_PRINT_ONCE("The interpolated values are not corresponding to its times."); + return p_values[0]; + } //could use binary search, worth it? int idx = -1; for (int i = 0; i < p_times.size(); i++) { @@ -5615,7 +5618,7 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, } Ref<Animation> animation; - animation.instance(); + animation.instantiate(); animation->set_name(name); if (anim->get_loop()) { @@ -5626,28 +5629,30 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, for (Map<int, GLTFAnimation::Track>::Element *track_i = anim->get_tracks().front(); track_i; track_i = track_i->next()) { const GLTFAnimation::Track &track = track_i->get(); - //need to find the path + //need to find the path: for skeletons, weight tracks will affect the mesh NodePath node_path; + //for skeletons, transform tracks always affect bones + NodePath transform_node_path; GLTFNodeIndex node_index = track_i->key(); - if (state->nodes[node_index]->fake_joint_parent >= 0) { - // Should be same as parent - node_index = state->nodes[node_index]->fake_joint_parent; - } const Ref<GLTFNode> gltf_node = state->nodes[track_i->key()]; + Node *root = ap->get_parent(); + ERR_FAIL_COND(root == nullptr); + Map<GLTFNodeIndex, Node *>::Element *node_element = state->scene_nodes.find(node_index); + ERR_CONTINUE_MSG(node_element == nullptr, vformat("Unable to find node %d for animation", node_index)); + node_path = root->get_path_to(node_element->get()); + if (gltf_node->skeleton >= 0) { - const Skeleton3D *sk = Object::cast_to<Skeleton3D>(state->scene_nodes.find(node_index)->get()); + const Skeleton3D *sk = state->skeletons[gltf_node->skeleton]->godot_skeleton; ERR_FAIL_COND(sk == nullptr); const String path = ap->get_parent()->get_path_to(sk); const String bone = gltf_node->get_name(); - node_path = path + ":" + bone; + transform_node_path = path + ":" + bone; } else { - Node *root = ap->get_parent(); - Node *godot_node = state->scene_nodes.find(node_index)->get(); - node_path = root->get_path_to(godot_node); + transform_node_path = node_path; } for (int i = 0; i < track.rotation_track.times.size(); i++) { @@ -5666,18 +5671,20 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, } } - if (track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) { + // Animated TRS properties will not affect a skinned mesh. + const bool transform_affects_skinned_mesh_instance = gltf_node->skeleton < 0 && gltf_node->skin >= 0; + if ((track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) && !transform_affects_skinned_mesh_instance) { //make transform track int track_idx = animation->get_track_count(); - animation->add_track(Animation::TYPE_TRANSFORM); - animation->track_set_path(track_idx, node_path); + animation->add_track(Animation::TYPE_TRANSFORM3D); + animation->track_set_path(track_idx, transform_node_path); //first determine animation length const double increment = 1.0 / bake_fps; double time = 0.0; Vector3 base_pos; - Quat base_rot; + Quaternion base_rot; Vector3 base_scale = Vector3(1, 1, 1); if (!track.rotation_track.values.size()) { @@ -5695,7 +5702,7 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, bool last = false; while (true) { Vector3 pos = base_pos; - Quat rot = base_rot; + Quaternion rot = base_rot; Vector3 scale = base_scale; if (track.translation_track.times.size()) { @@ -5703,7 +5710,7 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, } if (track.rotation_track.times.size()) { - rot = _interpolate_track<Quat>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation); + rot = _interpolate_track<Quaternion>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation); } if (track.scale_track.times.size()) { @@ -5711,15 +5718,15 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, } if (gltf_node->skeleton >= 0) { - Transform xform; - xform.basis.set_quat_scale(rot, scale); + Transform3D xform; + xform.basis.set_quaternion_scale(rot, scale); xform.origin = pos; const Skeleton3D *skeleton = state->skeletons[gltf_node->skeleton]->godot_skeleton; const int bone_idx = skeleton->find_bone(gltf_node->get_name()); xform = skeleton->get_bone_rest(bone_idx).affine_inverse() * xform; - rot = xform.basis.get_rotation_quat(); + rot = xform.basis.get_rotation_quaternion(); rot.normalize(); scale = xform.basis.get_scale(); pos = xform.origin; @@ -5804,9 +5811,9 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { } MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(mi_element->get()); ERR_CONTINUE(!mi); - Transform mi_xform = mi->get_transform(); + Transform3D mi_xform = mi->get_transform(); node->scale = mi_xform.basis.get_scale(); - node->rotation = mi_xform.basis.get_rotation_quat(); + node->rotation = mi_xform.basis.get_rotation_quaternion(); node->translation = mi_xform.origin; Dictionary json_skin; @@ -5822,7 +5829,7 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { skin = skeleton->register_skin(nullptr)->get_skin(); } Ref<GLTFSkin> gltf_skin; - gltf_skin.instance(); + gltf_skin.instantiate(); Array json_joints; GLTFSkeletonIndex skeleton_gltf_i = -1; @@ -5864,13 +5871,13 @@ void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { BoneId bone_index = skeleton->find_bone(godot_bone_name); ERR_CONTINUE(bone_index == -1); Ref<GLTFNode> joint_node; - joint_node.instance(); + joint_node.instantiate(); String gltf_bone_name = _gen_unique_bone_name(state, skeleton_gltf_i, godot_bone_name); joint_node->set_name(gltf_bone_name); - Transform bone_rest_xform = skeleton->get_bone_rest(bone_index); + Transform3D bone_rest_xform = skeleton->get_bone_rest(bone_index); joint_node->scale = bone_rest_xform.basis.get_scale(); - joint_node->rotation = bone_rest_xform.basis.get_rotation_quat(); + joint_node->rotation = bone_rest_xform.basis.get_rotation_quaternion(); joint_node->translation = bone_rest_xform.origin; joint_node->joint = true; @@ -5975,13 +5982,15 @@ void GLTFDocument::_process_mesh_instances(Ref<GLTFState> state, Node *scene_roo const GLTFSkinIndex skin_i = node->skin; Map<GLTFNodeIndex, Node *>::Element *mi_element = state->scene_nodes.find(node_i); + ERR_CONTINUE_MSG(mi_element == nullptr, vformat("Unable to find node %d", node_i)); + EditorSceneImporterMeshNode3D *mi = Object::cast_to<EditorSceneImporterMeshNode3D>(mi_element->get()); - ERR_FAIL_COND(mi == nullptr); + ERR_CONTINUE_MSG(mi == nullptr, vformat("Unable to cast node %d of type %s to EditorSceneImporterMeshNode3D", node_i, mi_element->get()->get_class_name())); const GLTFSkeletonIndex skel_i = state->skins.write[node->skin]->skeleton; Ref<GLTFSkeleton> gltf_skeleton = state->skeletons.write[skel_i]; Skeleton3D *skeleton = gltf_skeleton->godot_skeleton; - ERR_FAIL_COND(skeleton == nullptr); + ERR_CONTINUE_MSG(skeleton == nullptr, vformat("Unable to find Skeleton for node %d skin %d", node_i, skin_i)); mi->get_parent()->remove_child(mi); skeleton->add_child(mi); @@ -5989,12 +5998,12 @@ void GLTFDocument::_process_mesh_instances(Ref<GLTFState> state, Node *scene_roo mi->set_skin(state->skins.write[skin_i]->godot_skin); mi->set_skeleton_path(mi->get_path_to(skeleton)); - mi->set_transform(Transform()); + mi->set_transform(Transform3D()); } } } -GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state, GLTFAnimation::Track p_track, Ref<Animation> p_animation, Transform p_bone_rest, int32_t p_track_i, GLTFNodeIndex p_node_i) { +GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state, GLTFAnimation::Track p_track, Ref<Animation> p_animation, Transform3D p_bone_rest, int32_t p_track_i, GLTFNodeIndex p_node_i) { Animation::InterpolationType interpolation = p_animation->track_get_interpolation_type(p_track_i); GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR; @@ -6014,7 +6023,7 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state times.write[key_i] = p_animation->track_get_key_time(p_track_i, key_i); } const float BAKE_FPS = 30.0f; - if (track_type == Animation::TYPE_TRANSFORM) { + if (track_type == Animation::TYPE_TRANSFORM3D) { p_track.translation_track.times = times; p_track.translation_track.interpolation = gltf_interpolation; p_track.rotation_track.times = times; @@ -6030,16 +6039,16 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state p_track.rotation_track.interpolation = gltf_interpolation; for (int32_t key_i = 0; key_i < key_count; key_i++) { Vector3 translation; - Quat rotation; + Quaternion rotation; Vector3 scale; Error err = p_animation->transform_track_get_key(p_track_i, key_i, &translation, &rotation, &scale); ERR_CONTINUE(err != OK); - Transform xform; - xform.basis.set_quat_scale(rotation, scale); + Transform3D xform; + xform.basis.set_quaternion_scale(rotation, scale); xform.origin = translation; xform = p_bone_rest * xform; p_track.translation_track.values.write[key_i] = xform.get_origin(); - p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quat(); + p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quaternion(); p_track.scale_track.values.write[key_i] = xform.basis.get_scale(); } } else if (path.find(":transform") != -1) { @@ -6057,9 +6066,9 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state p_track.rotation_track.values.resize(key_count); p_track.rotation_track.interpolation = gltf_interpolation; for (int32_t key_i = 0; key_i < key_count; key_i++) { - Transform xform = p_animation->track_get_key_value(p_track_i, key_i); + Transform3D xform = p_animation->track_get_key_value(p_track_i, key_i); p_track.translation_track.values.write[key_i] = xform.get_origin(); - p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quat(); + p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quaternion(); p_track.scale_track.values.write[key_i] = xform.basis.get_scale(); } } else if (track_type == Animation::TYPE_VALUE) { @@ -6071,7 +6080,7 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state p_track.rotation_track.interpolation = gltf_interpolation; for (int32_t key_i = 0; key_i < key_count; key_i++) { - Quat rotation_track = p_animation->track_get_key_value(p_track_i, key_i); + Quaternion rotation_track = p_animation->track_get_key_value(p_track_i, key_i); p_track.rotation_track.values.write[key_i] = rotation_track; } } else if (path.find(":translation") != -1) { @@ -6085,7 +6094,7 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state Vector3 translation = p_animation->track_get_key_value(p_track_i, key_i); p_track.translation_track.values.write[key_i] = translation; } - } else if (path.find(":rotation_degrees") != -1) { + } else if (path.find(":rotation") != -1) { p_track.rotation_track.times = times; p_track.rotation_track.interpolation = gltf_interpolation; @@ -6093,12 +6102,8 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state p_track.rotation_track.interpolation = gltf_interpolation; for (int32_t key_i = 0; key_i < key_count; key_i++) { - Vector3 rotation_degrees = p_animation->track_get_key_value(p_track_i, key_i); - Vector3 rotation_radian; - rotation_radian.x = Math::deg2rad(rotation_degrees.x); - rotation_radian.y = Math::deg2rad(rotation_degrees.y); - rotation_radian.z = Math::deg2rad(rotation_degrees.z); - p_track.rotation_track.values.write[key_i] = Quat(rotation_radian); + 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); } } else if (path.find(":scale") != -1) { p_track.scale_track.times = times; @@ -6184,7 +6189,7 @@ GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> state void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, String p_animation_track_name) { Ref<Animation> animation = ap->get_animation(p_animation_track_name); Ref<GLTFAnimation> gltf_animation; - gltf_animation.instance(); + gltf_animation.instantiate(); gltf_animation->set_name(_gen_unique_name(state, p_animation_track_name)); for (int32_t track_i = 0; track_i < animation->get_track_count(); track_i++) { @@ -6204,7 +6209,7 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, if (translation_track_i) { track = translation_track_i->get(); } - track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index); + track = _convert_animation_track(state, track, animation, Transform3D(), track_i, node_index); gltf_animation->get_tracks().insert(node_index, track); } } @@ -6220,7 +6225,7 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, if (rotation_degree_track_i) { track = rotation_degree_track_i->get(); } - track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index); + track = _convert_animation_track(state, track, animation, Transform3D(), track_i, node_index); gltf_animation->get_tracks().insert(node_index, track); } } @@ -6236,7 +6241,7 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, if (scale_track_i) { track = scale_track_i->get(); } - track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index); + track = _convert_animation_track(state, track, animation, Transform3D(), track_i, node_index); gltf_animation->get_tracks().insert(node_index, track); } } @@ -6247,7 +6252,7 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, for (Map<GLTFNodeIndex, Node *>::Element *transform_track_i = state->scene_nodes.front(); transform_track_i; transform_track_i = transform_track_i->next()) { if (transform_track_i->get() == node) { GLTFAnimation::Track track; - track = _convert_animation_track(state, track, animation, Transform(), track_i, transform_track_i->key()); + track = _convert_animation_track(state, track, animation, Transform3D(), track_i, transform_track_i->key()); gltf_animation->get_tracks().insert(transform_track_i->key(), track); } } @@ -6335,7 +6340,7 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, Ref<GLTFSkeleton> skeleton_gltf = state->skeletons[skeleton_gltf_i]; int32_t bone = skeleton->find_bone(suffix); ERR_CONTINUE(bone == -1); - Transform xform = skeleton->get_bone_rest(bone); + Transform3D xform = skeleton->get_bone_rest(bone); if (!skeleton_gltf->godot_bone_node.has(bone)) { continue; } @@ -6362,7 +6367,7 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, if (node_track_i) { track = node_track_i->get(); } - track = _convert_animation_track(state, track, animation, Transform(), track_i, node_index); + track = _convert_animation_track(state, track, animation, Transform3D(), track_i, node_index); gltf_animation->get_tracks().insert(node_index, track); break; } @@ -6578,7 +6583,7 @@ Error GLTFDocument::_serialize_file(Ref<GLTFState> state, const String p_path) { FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE, &err); ERR_FAIL_COND_V(!f, FAILED); - String json = JSON::print(state->json); + String json = Variant(state->json).to_json_string(); const uint32_t magic = 0x46546C67; // GLTF const int32_t header_size = 12; @@ -6619,7 +6624,7 @@ Error GLTFDocument::_serialize_file(Ref<GLTFState> state, const String p_path) { ERR_FAIL_COND_V(!f, FAILED); f->create(FileAccess::ACCESS_RESOURCES); - String json = JSON::print(state->json); + String json = Variant(state->json).to_json_string(); f->store_string(json); f->close(); } diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h index bda1ce87d6..3e8ea19045 100644 --- a/modules/gltf/gltf_document.h +++ b/modules/gltf/gltf_document.h @@ -31,11 +31,9 @@ #ifndef GLTF_DOCUMENT_H #define GLTF_DOCUMENT_H -#include "editor/import/resource_importer_scene.h" -#include "editor/import/scene_importer_mesh_node_3d.h" #include "gltf_animation.h" -#include "modules/modules_enabled.gen.h" -#include "scene/2d/node_2d.h" + +#include "editor/import/scene_importer_mesh_node_3d.h" #include "scene/3d/bone_attachment_3d.h" #include "scene/3d/light_3d.h" #include "scene/3d/mesh_instance_3d.h" @@ -45,6 +43,8 @@ #include "scene/resources/material.h" #include "scene/resources/texture.h" +#include "modules/modules_enabled.gen.h" + class GLTFState; class GLTFSkin; class GLTFNode; @@ -205,7 +205,7 @@ private: Vector<Color> _decode_accessor_as_color(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex); - Vector<Quat> _decode_accessor_as_quat(Ref<GLTFState> state, + Vector<Quaternion> _decode_accessor_as_quaternion(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex); Vector<Transform2D> _decode_accessor_as_xform2d(Ref<GLTFState> state, @@ -214,7 +214,7 @@ private: Vector<Basis> _decode_accessor_as_basis(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex); - Vector<Transform> _decode_accessor_as_xform(Ref<GLTFState> state, + Vector<Transform3D> _decode_accessor_as_xform(Ref<GLTFState> state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex); Error _parse_meshes(Ref<GLTFState> state); @@ -260,11 +260,12 @@ private: Error _serialize_animations(Ref<GLTFState> state); BoneAttachment3D *_generate_bone_attachment(Ref<GLTFState> state, Skeleton3D *skeleton, - const GLTFNodeIndex node_index); + const GLTFNodeIndex node_index, + const GLTFNodeIndex bone_index); EditorSceneImporterMeshNode3D *_generate_mesh_instance(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index); Camera3D *_generate_camera(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index); - Light3D *_generate_light(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index); + Node3D *_generate_light(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index); Node3D *_generate_spatial(Ref<GLTFState> state, Node *scene_parent, const GLTFNodeIndex node_index); void _assign_scene_names(Ref<GLTFState> state); @@ -272,8 +273,8 @@ private: T _interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, const float p_time, const GLTFAnimation::Interpolation p_interp); - GLTFAccessorIndex _encode_accessor_as_quats(Ref<GLTFState> state, - const Vector<Quat> p_attribs, + GLTFAccessorIndex _encode_accessor_as_quaternions(Ref<GLTFState> state, + const Vector<Quaternion> p_attribs, const bool p_for_vertex); GLTFAccessorIndex _encode_accessor_as_weights(Ref<GLTFState> state, const Vector<Color> p_attribs, @@ -316,7 +317,7 @@ private: const Vector<int32_t> p_attribs, const bool p_for_vertex); GLTFAccessorIndex _encode_accessor_as_xform(Ref<GLTFState> state, - const Vector<Transform> p_attribs, + const Vector<Transform3D> p_attribs, const bool p_for_vertex); Error _encode_buffer_view(Ref<GLTFState> state, const double *src, const int count, const GLTFType type, @@ -332,7 +333,7 @@ private: String interpolation_to_string(const GLTFAnimation::Interpolation p_interp); GLTFAnimation::Track _convert_animation_track(Ref<GLTFState> state, GLTFAnimation::Track p_track, - Ref<Animation> p_animation, Transform p_bone_rest, + Ref<Animation> p_animation, Transform3D p_bone_rest, int32_t p_track_i, GLTFNodeIndex p_node_i); Error _encode_buffer_bins(Ref<GLTFState> state, const String &p_path); @@ -365,6 +366,7 @@ public: void _generate_scene_node(Ref<GLTFState> state, Node *scene_parent, Node3D *scene_root, const GLTFNodeIndex node_index); + void _generate_skeleton_bone_node(Ref<GLTFState> state, Node *scene_parent, Node3D *scene_root, const GLTFNodeIndex node_index); void _import_animation(Ref<GLTFState> state, AnimationPlayer *ap, const GLTFAnimationIndex index, const int bake_fps); GLTFMeshIndex _convert_mesh_instance(Ref<GLTFState> state, diff --git a/modules/gltf/gltf_node.cpp b/modules/gltf/gltf_node.cpp index 777c6fbd9a..5db7ad66c3 100644 --- a/modules/gltf/gltf_node.cpp +++ b/modules/gltf/gltf_node.cpp @@ -55,24 +55,21 @@ void GLTFNode::_bind_methods() { ClassDB::bind_method(D_METHOD("set_scale", "scale"), &GLTFNode::set_scale); ClassDB::bind_method(D_METHOD("get_children"), &GLTFNode::get_children); ClassDB::bind_method(D_METHOD("set_children", "children"), &GLTFNode::set_children); - ClassDB::bind_method(D_METHOD("get_fake_joint_parent"), &GLTFNode::get_fake_joint_parent); - ClassDB::bind_method(D_METHOD("set_fake_joint_parent", "fake_joint_parent"), &GLTFNode::set_fake_joint_parent); ClassDB::bind_method(D_METHOD("get_light"), &GLTFNode::get_light); ClassDB::bind_method(D_METHOD("set_light", "light"), &GLTFNode::set_light); ADD_PROPERTY(PropertyInfo(Variant::INT, "parent"), "set_parent", "get_parent"); // GLTFNodeIndex ADD_PROPERTY(PropertyInfo(Variant::INT, "height"), "set_height", "get_height"); // int - ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "xform"), "set_xform", "get_xform"); // Transform + ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "xform"), "set_xform", "get_xform"); // Transform3D ADD_PROPERTY(PropertyInfo(Variant::INT, "mesh"), "set_mesh", "get_mesh"); // GLTFMeshIndex ADD_PROPERTY(PropertyInfo(Variant::INT, "camera"), "set_camera", "get_camera"); // GLTFCameraIndex ADD_PROPERTY(PropertyInfo(Variant::INT, "skin"), "set_skin", "get_skin"); // GLTFSkinIndex ADD_PROPERTY(PropertyInfo(Variant::INT, "skeleton"), "set_skeleton", "get_skeleton"); // GLTFSkeletonIndex ADD_PROPERTY(PropertyInfo(Variant::BOOL, "joint"), "set_joint", "get_joint"); // bool ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "translation"), "set_translation", "get_translation"); // Vector3 - ADD_PROPERTY(PropertyInfo(Variant::QUAT, "rotation"), "set_rotation", "get_rotation"); // Quat + ADD_PROPERTY(PropertyInfo(Variant::QUATERNION, "rotation"), "set_rotation", "get_rotation"); // Quaternion ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale"), "set_scale", "get_scale"); // Vector3 ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "children"), "set_children", "get_children"); // Vector<int> - ADD_PROPERTY(PropertyInfo(Variant::INT, "fake_joint_parent"), "set_fake_joint_parent", "get_fake_joint_parent"); // GLTFNodeIndex ADD_PROPERTY(PropertyInfo(Variant::INT, "light"), "set_light", "get_light"); // GLTFLightIndex } @@ -92,11 +89,11 @@ void GLTFNode::set_height(int p_height) { height = p_height; } -Transform GLTFNode::get_xform() { +Transform3D GLTFNode::get_xform() { return xform; } -void GLTFNode::set_xform(Transform p_xform) { +void GLTFNode::set_xform(Transform3D p_xform) { xform = p_xform; } @@ -148,11 +145,11 @@ void GLTFNode::set_translation(Vector3 p_translation) { translation = p_translation; } -Quat GLTFNode::get_rotation() { +Quaternion GLTFNode::get_rotation() { return rotation; } -void GLTFNode::set_rotation(Quat p_rotation) { +void GLTFNode::set_rotation(Quaternion p_rotation) { rotation = p_rotation; } @@ -172,14 +169,6 @@ void GLTFNode::set_children(Vector<int> p_children) { children = p_children; } -GLTFNodeIndex GLTFNode::get_fake_joint_parent() { - return fake_joint_parent; -} - -void GLTFNode::set_fake_joint_parent(GLTFNodeIndex p_fake_joint_parent) { - fake_joint_parent = p_fake_joint_parent; -} - GLTFLightIndex GLTFNode::get_light() { return light; } diff --git a/modules/gltf/gltf_node.h b/modules/gltf/gltf_node.h index ce8aff8944..378b6da8bf 100644 --- a/modules/gltf/gltf_node.h +++ b/modules/gltf/gltf_node.h @@ -43,17 +43,16 @@ private: // matrices need to be transformed to this GLTFNodeIndex parent = -1; int height = -1; - Transform xform; + Transform3D xform; GLTFMeshIndex mesh = -1; GLTFCameraIndex camera = -1; GLTFSkinIndex skin = -1; GLTFSkeletonIndex skeleton = -1; bool joint = false; Vector3 translation; - Quat rotation; + Quaternion rotation; Vector3 scale = Vector3(1, 1, 1); Vector<int> children; - GLTFNodeIndex fake_joint_parent = -1; GLTFLightIndex light = -1; protected: @@ -66,8 +65,8 @@ public: int get_height(); void set_height(int p_height); - Transform get_xform(); - void set_xform(Transform p_xform); + Transform3D get_xform(); + void set_xform(Transform3D p_xform); GLTFMeshIndex get_mesh(); void set_mesh(GLTFMeshIndex p_mesh); @@ -87,8 +86,8 @@ public: Vector3 get_translation(); void set_translation(Vector3 p_translation); - Quat get_rotation(); - void set_rotation(Quat p_rotation); + Quaternion get_rotation(); + void set_rotation(Quaternion p_rotation); Vector3 get_scale(); void set_scale(Vector3 p_scale); @@ -96,9 +95,6 @@ public: Vector<int> get_children(); void set_children(Vector<int> p_children); - GLTFNodeIndex get_fake_joint_parent(); - void set_fake_joint_parent(GLTFNodeIndex p_fake_joint_parent); - GLTFLightIndex get_light(); void set_light(GLTFLightIndex p_light); }; diff --git a/modules/gltf/gltf_skin.cpp b/modules/gltf/gltf_skin.cpp index 5a61e5778c..5cf17135ac 100644 --- a/modules/gltf/gltf_skin.cpp +++ b/modules/gltf/gltf_skin.cpp @@ -54,7 +54,7 @@ void GLTFSkin::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "skin_root"), "set_skin_root", "get_skin_root"); // GLTFNodeIndex ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "joints_original"), "set_joints_original", "get_joints_original"); // Vector<GLTFNodeIndex> - ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "inverse_binds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL), "set_inverse_binds", "get_inverse_binds"); // Vector<Transform> + ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "inverse_binds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL), "set_inverse_binds", "get_inverse_binds"); // Vector<Transform3D> ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "joints"), "set_joints", "get_joints"); // Vector<GLTFNodeIndex> ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "non_joints"), "set_non_joints", "get_non_joints"); // Vector<GLTFNodeIndex> ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "roots"), "set_roots", "get_roots"); // Vector<GLTFNodeIndex> diff --git a/modules/gltf/gltf_skin.h b/modules/gltf/gltf_skin.h index 7cc09d85bc..e32e2d397c 100644 --- a/modules/gltf/gltf_skin.h +++ b/modules/gltf/gltf_skin.h @@ -43,7 +43,7 @@ private: GLTFNodeIndex skin_root = -1; Vector<GLTFNodeIndex> joints_original; - Vector<Transform> inverse_binds; + Vector<Transform3D> inverse_binds; // Note: joints + non_joints should form a complete subtree, or subtrees // with a common parent diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h index ba6bf8a533..d8209523c5 100644 --- a/modules/gltf/gltf_state.h +++ b/modules/gltf/gltf_state.h @@ -31,9 +31,6 @@ #ifndef GLTF_STATE_H #define GLTF_STATE_H -#include "core/io/resource.h" -#include "core/templates/vector.h" -#include "editor_scene_importer_gltf.h" #include "gltf_accessor.h" #include "gltf_animation.h" #include "gltf_buffer_view.h" @@ -45,6 +42,9 @@ #include "gltf_skeleton.h" #include "gltf_skin.h" #include "gltf_texture.h" + +#include "core/io/resource.h" +#include "core/templates/vector.h" #include "scene/animation/animation_player.h" #include "scene/resources/texture.h" diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp index dc995c9249..85921490d2 100644 --- a/modules/gltf/register_types.cpp +++ b/modules/gltf/register_types.cpp @@ -51,7 +51,7 @@ #ifdef TOOLS_ENABLED static void _editor_init() { Ref<EditorSceneImporterGLTF> import_gltf; - import_gltf.instance(); + import_gltf.instantiate(); ResourceImporterScene::get_singleton()->add_importer(import_gltf); } #endif @@ -62,25 +62,25 @@ void register_gltf_types() { #ifdef TOOLS_ENABLED ClassDB::APIType prev_api = ClassDB::get_current_api(); ClassDB::set_current_api(ClassDB::API_EDITOR); - ClassDB::register_class<EditorSceneImporterGLTF>(); - ClassDB::register_class<GLTFMesh>(); + GDREGISTER_CLASS(EditorSceneImporterGLTF); + GDREGISTER_CLASS(GLTFMesh); EditorPlugins::add_by_type<SceneExporterGLTFPlugin>(); ClassDB::set_current_api(prev_api); EditorNode::add_init_callback(_editor_init); #endif - ClassDB::register_class<GLTFSpecGloss>(); - ClassDB::register_class<GLTFNode>(); - ClassDB::register_class<GLTFAnimation>(); - ClassDB::register_class<GLTFBufferView>(); - ClassDB::register_class<GLTFAccessor>(); - ClassDB::register_class<GLTFTexture>(); - ClassDB::register_class<GLTFSkeleton>(); - ClassDB::register_class<GLTFSkin>(); - ClassDB::register_class<GLTFCamera>(); - ClassDB::register_class<GLTFLight>(); - ClassDB::register_class<GLTFState>(); - ClassDB::register_class<GLTFDocument>(); - ClassDB::register_class<PackedSceneGLTF>(); + GDREGISTER_CLASS(GLTFSpecGloss); + GDREGISTER_CLASS(GLTFNode); + GDREGISTER_CLASS(GLTFAnimation); + GDREGISTER_CLASS(GLTFBufferView); + GDREGISTER_CLASS(GLTFAccessor); + GDREGISTER_CLASS(GLTFTexture); + GDREGISTER_CLASS(GLTFSkeleton); + GDREGISTER_CLASS(GLTFSkin); + GDREGISTER_CLASS(GLTFCamera); + GDREGISTER_CLASS(GLTFLight); + GDREGISTER_CLASS(GLTFState); + GDREGISTER_CLASS(GLTFDocument); + GDREGISTER_CLASS(PackedSceneGLTF); #endif } diff --git a/modules/gridmap/config.py b/modules/gridmap/config.py index a6319fe1ea..720401b92d 100644 --- a/modules/gridmap/config.py +++ b/modules/gridmap/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return True + return not env["disable_3d"] def configure(env): diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml index 9b6fa138e5..8ea7384658 100644 --- a/modules/gridmap/doc_classes/GridMap.xml +++ b/modules/gridmap/doc_classes/GridMap.xml @@ -17,119 +17,93 @@ </tutorials> <methods> <method name="clear"> - <return type="void"> - </return> + <return type="void" /> <description> Clear all cells. </description> </method> <method name="clear_baked_meshes"> - <return type="void"> - </return> + <return type="void" /> <description> </description> </method> <method name="get_bake_mesh_instance"> - <return type="RID"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="RID" /> + <argument index="0" name="idx" type="int" /> <description> </description> </method> <method name="get_bake_meshes"> - <return type="Array"> - </return> + <return type="Array" /> <description> - Returns an array of [ArrayMesh]es and [Transform] references of all bake meshes that exist within the current GridMap. + Returns an array of [ArrayMesh]es and [Transform3D] references of all bake meshes that exist within the current GridMap. </description> </method> <method name="get_cell_item" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="position" type="Vector3i"> - </argument> + <return type="int" /> + <argument index="0" name="position" type="Vector3i" /> <description> The [MeshLibrary] item index located at the given grid coordinates. If the cell is empty, [constant INVALID_CELL_ITEM] will be returned. </description> </method> <method name="get_cell_item_orientation" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="position" type="Vector3i"> - </argument> + <return type="int" /> + <argument index="0" name="position" type="Vector3i" /> <description> The orientation of the cell at the given grid coordinates. [code]-1[/code] is returned if the cell is empty. </description> </method> <method name="get_collision_layer_bit" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="bit" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="bit" type="int" /> <description> Returns an individual bit on the [member collision_layer]. </description> </method> <method name="get_collision_mask_bit" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="bit" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="bit" type="int" /> <description> Returns an individual bit on the [member collision_mask]. </description> </method> <method name="get_meshes"> - <return type="Array"> - </return> + <return type="Array" /> <description> - Returns an array of [Transform] and [Mesh] references corresponding to the non-empty cells in the grid. The transforms are specified in world space. + Returns an array of [Transform3D] and [Mesh] references corresponding to the non-empty cells in the grid. The transforms are specified in world space. </description> </method> <method name="get_used_cells" qualifiers="const"> - <return type="Array"> - </return> + <return type="Array" /> <description> Returns an array of [Vector3] with the non-empty cell coordinates in the grid map. </description> </method> <method name="make_baked_meshes"> - <return type="void"> - </return> - <argument index="0" name="gen_lightmap_uv" type="bool" default="false"> - </argument> - <argument index="1" name="lightmap_uv_texel_size" type="float" default="0.1"> - </argument> + <return type="void" /> + <argument index="0" name="gen_lightmap_uv" type="bool" default="false" /> + <argument index="1" name="lightmap_uv_texel_size" type="float" default="0.1" /> <description> </description> </method> <method name="map_to_world" qualifiers="const"> - <return type="Vector3"> - </return> - <argument index="0" name="map_position" type="Vector3i"> - </argument> + <return type="Vector3" /> + <argument index="0" name="map_position" type="Vector3i" /> <description> Returns the position of a grid cell in the GridMap's local coordinate space. </description> </method> <method name="resource_changed"> - <return type="void"> - </return> - <argument index="0" name="resource" type="Resource"> - </argument> + <return type="void" /> + <argument index="0" name="resource" type="Resource" /> <description> </description> </method> <method name="set_cell_item"> - <return type="void"> - </return> - <argument index="0" name="position" type="Vector3i"> - </argument> - <argument index="1" name="item" type="int"> - </argument> - <argument index="2" name="orientation" type="int" default="0"> - </argument> + <return type="void" /> + <argument index="0" name="position" type="Vector3i" /> + <argument index="1" name="item" type="int" /> + <argument index="2" name="orientation" type="int" default="0" /> <description> Sets the mesh index for the cell referenced by its grid coordinates. A negative item index such as [constant INVALID_CELL_ITEM] will clear the cell. @@ -137,46 +111,33 @@ </description> </method> <method name="set_clip"> - <return type="void"> - </return> - <argument index="0" name="enabled" type="bool"> - </argument> - <argument index="1" name="clipabove" type="bool" default="true"> - </argument> - <argument index="2" name="floor" type="int" default="0"> - </argument> - <argument index="3" name="axis" type="int" enum="Vector3.Axis" default="0"> - </argument> + <return type="void" /> + <argument index="0" name="enabled" type="bool" /> + <argument index="1" name="clipabove" type="bool" default="true" /> + <argument index="2" name="floor" type="int" default="0" /> + <argument index="3" name="axis" type="int" enum="Vector3.Axis" default="0" /> <description> </description> </method> <method name="set_collision_layer_bit"> - <return type="void"> - </return> - <argument index="0" name="bit" type="int"> - </argument> - <argument index="1" name="value" type="bool"> - </argument> + <return type="void" /> + <argument index="0" name="bit" type="int" /> + <argument index="1" name="value" type="bool" /> <description> Sets an individual bit on the [member collision_layer]. </description> </method> <method name="set_collision_mask_bit"> - <return type="void"> - </return> - <argument index="0" name="bit" type="int"> - </argument> - <argument index="1" name="value" type="bool"> - </argument> + <return type="void" /> + <argument index="0" name="bit" type="int" /> + <argument index="1" name="value" type="bool" /> <description> Sets an individual bit on the [member collision_mask]. </description> </method> <method name="world_to_map" qualifiers="const"> - <return type="Vector3i"> - </return> - <argument index="0" name="world_position" type="Vector3"> - </argument> + <return type="Vector3i" /> + <argument index="0" name="world_position" type="Vector3" /> <description> Returns the coordinates of the grid cell containing the given point. [code]pos[/code] should be in the GridMap's local coordinate space. @@ -203,7 +164,7 @@ The scale of the cell items. This does not affect the size of the grid cells themselves, only the items in them. This can be used to make cell items overlap their neighbors. </member> - <member name="cell_size" type="Vector3" setter="set_cell_size" getter="get_cell_size" default="Vector3( 2, 2, 2 )"> + <member name="cell_size" type="Vector3" setter="set_cell_size" getter="get_cell_size" default="Vector3(2, 2, 2)"> The dimensions of the grid's cells. This does not affect the size of the meshes. See [member cell_scale]. </member> @@ -223,8 +184,7 @@ </members> <signals> <signal name="cell_size_changed"> - <argument index="0" name="cell_size" type="Vector3"> - </argument> + <argument index="0" name="cell_size" type="Vector3" /> <description> Emitted when [member cell_size] changes. </description> diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index 4e4f88ed6a..fea513c820 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -152,6 +152,7 @@ uint32_t GridMap::get_collision_mask() const { } void GridMap::set_collision_mask_bit(int p_bit, bool p_value) { + ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision mask bit must be between 0 and 31 inclusive."); uint32_t mask = get_collision_mask(); if (p_value) { mask |= 1 << p_bit; @@ -162,20 +163,23 @@ void GridMap::set_collision_mask_bit(int p_bit, bool p_value) { } bool GridMap::get_collision_mask_bit(int p_bit) const { + ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision mask bit must be between 0 and 31 inclusive."); return get_collision_mask() & (1 << p_bit); } void GridMap::set_collision_layer_bit(int p_bit, bool p_value) { - uint32_t mask = get_collision_layer(); + ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision layer bit must be between 0 and 31 inclusive."); + uint32_t layer = get_collision_layer(); if (p_value) { - mask |= 1 << p_bit; + layer |= 1 << p_bit; } else { - mask &= ~(1 << p_bit); + layer &= ~(1 << p_bit); } - set_collision_layer(mask); + set_collision_layer(layer); } bool GridMap::get_collision_layer_bit(int p_bit) const { + ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision layer bit must be between 0 and 31 inclusive."); return get_collision_layer() & (1 << p_bit); } @@ -217,7 +221,7 @@ void GridMap::set_cell_size(const Vector3 &p_size) { ERR_FAIL_COND(p_size.x < 0.001 || p_size.y < 0.001 || p_size.z < 0.001); cell_size = p_size; _recreate_octant_data(); - emit_signal("cell_size_changed", cell_size); + emit_signal(SNAME("cell_size_changed"), cell_size); } Vector3 GridMap::get_cell_size() const { @@ -442,7 +446,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) { * and set said multimesh bounding box to one containing all cells which have this item */ - Map<int, List<Pair<Transform, IndexKey>>> multimesh_items; + Map<int, List<Pair<Transform3D, IndexKey>>> multimesh_items; for (Set<IndexKey>::Element *E = g.cells.front(); E; E = E->next()) { ERR_CONTINUE(!cell_map.has(E->get())); @@ -455,7 +459,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) { Vector3 cellpos = Vector3(E->get().x, E->get().y, E->get().z); Vector3 ofs = _get_offset(); - Transform xform; + Transform3D xform; xform.basis.set_orthogonal_index(c.rot); xform.set_origin(cellpos * cell_size + ofs); @@ -463,10 +467,10 @@ bool GridMap::_octant_update(const OctantKey &p_key) { if (baked_meshes.size() == 0) { if (mesh_library->get_item_mesh(c.item).is_valid()) { if (!multimesh_items.has(c.item)) { - multimesh_items[c.item] = List<Pair<Transform, IndexKey>>(); + multimesh_items[c.item] = List<Pair<Transform3D, IndexKey>>(); } - Pair<Transform, IndexKey> p; + Pair<Transform3D, IndexKey> p; p.first = xform; p.second = E->get(); multimesh_items[c.item].push_back(p); @@ -507,7 +511,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) { //update multimeshes, only if not baked if (baked_meshes.size() == 0) { - for (Map<int, List<Pair<Transform, IndexKey>>>::Element *E = multimesh_items.front(); E; E = E->next()) { + for (Map<int, List<Pair<Transform3D, IndexKey>>>::Element *E = multimesh_items.front(); E; E = E->next()) { Octant::MultimeshInstance mmi; RID mm = RS::get_singleton()->multimesh_create(); @@ -515,14 +519,14 @@ bool GridMap::_octant_update(const OctantKey &p_key) { RS::get_singleton()->multimesh_set_mesh(mm, mesh_library->get_item_mesh(E->key())->get_rid()); int idx = 0; - for (List<Pair<Transform, IndexKey>>::Element *F = E->get().front(); F; F = F->next()) { - RS::get_singleton()->multimesh_instance_set_transform(mm, idx, F->get().first); + for (const Pair<Transform3D, IndexKey> &F : E->get()) { + RS::get_singleton()->multimesh_instance_set_transform(mm, idx, F.first); #ifdef TOOLS_ENABLED Octant::MultimeshInstance::Item it; it.index = idx; - it.transform = F->get().first; - it.key = F->get().second; + it.transform = F.first; + it.key = F.second; mmi.items.push_back(it); #endif @@ -668,7 +672,7 @@ void GridMap::_notification(int p_what) { } break; case NOTIFICATION_TRANSFORM_CHANGED: { - Transform new_xform = get_global_transform(); + Transform3D new_xform = get_global_transform(); if (new_xform == last_transform) { break; } @@ -682,7 +686,6 @@ void GridMap::_notification(int p_what) { for (int i = 0; i < baked_meshes.size(); i++) { RS::get_singleton()->instance_set_transform(baked_meshes[i].instance, get_global_transform()); } - } break; case NOTIFICATION_EXIT_WORLD: { for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) { @@ -777,7 +780,7 @@ void GridMap::_update_octants_callback() { while (to_delete.front()) { octant_map.erase(to_delete.front()->get()); - to_delete.pop_back(); + to_delete.pop_front(); } _update_visibility(); @@ -930,7 +933,7 @@ Array GridMap::get_meshes() { Vector3 cellpos = Vector3(ik.x, ik.y, ik.z); - Transform xform; + Transform3D xform; xform.basis.set_orthogonal_index(E->get().rot); @@ -984,7 +987,7 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe Vector3 cellpos = Vector3(key.x, key.y, key.z); Vector3 ofs = _get_offset(); - Transform xform; + Transform3D xform; xform.basis.set_orthogonal_index(E->get().rot); xform.set_origin(cellpos * cell_size + ofs); @@ -1009,7 +1012,7 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe Ref<Material> surf_mat = mesh->surface_get_material(i); if (!mat_map.has(surf_mat)) { Ref<SurfaceTool> st; - st.instance(); + st.instantiate(); st->begin(Mesh::PRIMITIVE_TRIANGLES); st->set_material(surf_mat); mat_map[surf_mat] = st; @@ -1021,7 +1024,7 @@ void GridMap::make_baked_meshes(bool p_gen_lightmap_uv, float p_lightmap_uv_texe for (Map<OctantKey, Map<Ref<Material>, Ref<SurfaceTool>>>::Element *E = surface_map.front(); E; E = E->next()) { Ref<ArrayMesh> mesh; - mesh.instance(); + mesh.instantiate(); for (Map<Ref<Material>, Ref<SurfaceTool>>::Element *F = E->get().front(); F; F = F->next()) { F->get()->commit(mesh); } @@ -1053,7 +1056,7 @@ Array GridMap::get_bake_meshes() { Array arr; for (int i = 0; i < baked_meshes.size(); i++) { arr.push_back(baked_meshes[i].mesh); - arr.push_back(Transform()); + arr.push_back(Transform3D()); } return arr; diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h index 4c04d492f7..8cd82e1f4c 100644 --- a/modules/gridmap/grid_map.h +++ b/modules/gridmap/grid_map.h @@ -89,7 +89,7 @@ class GridMap : public Node3D { struct Octant { struct NavMesh { RID region; - Transform xform; + Transform3D xform; }; struct MultimeshInstance { @@ -97,7 +97,7 @@ class GridMap : public Node3D { RID multimesh; struct Item { int index = 0; - Transform transform; + Transform3D transform; IndexKey key; }; @@ -137,7 +137,7 @@ class GridMap : public Node3D { bool bake_navigation = false; uint32_t navigation_layers = 1; - Transform last_transform; + Transform3D last_transform; bool _in_tree = false; Vector3 cell_size = Vector3(2, 2, 2); diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp index 74ae45a46e..f101c43e89 100644 --- a/modules/gridmap/grid_map_editor_plugin.cpp +++ b/modules/gridmap/grid_map_editor_plugin.cpp @@ -62,12 +62,6 @@ void GridMapEditor::_menu_option(int p_option) { floor->set_value(floor->get_value() + 1); } break; - case MENU_OPTION_LOCK_VIEW: { - int index = options->get_popup()->get_item_index(MENU_OPTION_LOCK_VIEW); - lock_view = !options->get_popup()->is_item_checked(index); - - options->get_popup()->set_item_checked(index, lock_view); - } break; case MENU_OPTION_CLIP_DISABLED: case MENU_OPTION_CLIP_ABOVE: case MENU_OPTION_CLIP_BELOW: { @@ -255,7 +249,7 @@ void GridMapEditor::_menu_option(int p_option) { } void GridMapEditor::_update_cursor_transform() { - cursor_transform = Transform(); + cursor_transform = Transform3D(); cursor_transform.origin = cursor_origin; cursor_transform.basis.set_orthogonal_index(cursor_rot); cursor_transform.basis *= node->get_cell_scale(); @@ -268,7 +262,7 @@ void GridMapEditor::_update_cursor_transform() { } void GridMapEditor::_update_selection_transform() { - Transform xf_zero; + Transform3D xf_zero; xf_zero.basis.set_zero(); if (!selection.active) { @@ -279,7 +273,7 @@ void GridMapEditor::_update_selection_transform() { return; } - Transform xf; + Transform3D xf; xf.scale((Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size()); xf.origin = selection.begin * node->get_cell_size(); @@ -297,7 +291,7 @@ void GridMapEditor::_update_selection_transform() { scale *= node->get_cell_size(); position *= node->get_cell_size(); - Transform xf2; + Transform3D xf2; xf2.basis.scale(scale); xf2.origin = position; @@ -362,7 +356,7 @@ bool GridMapEditor::do_input_action(Camera3D *p_camera, const Point2 &p_point, b Camera3D *camera = p_camera; Vector3 from = camera->project_ray_origin(p_point); Vector3 normal = camera->project_ray_normal(p_point); - Transform local_xform = node->get_global_transform().affine_inverse(); + Transform3D local_xform = node->get_global_transform().affine_inverse(); Vector<Plane> planes = camera->get_frustum(); from = local_xform.xform(from); normal = local_xform.basis.xform(normal).normalized(); @@ -503,8 +497,8 @@ void GridMapEditor::_fill_selection() { } void GridMapEditor::_clear_clipboard_data() { - for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) { - RenderingServer::get_singleton()->free(E->get().instance); + for (const ClipboardItem &E : clipboard_items) { + RenderingServer::get_singleton()->free(E.instance); } clipboard_items.clear(); @@ -540,7 +534,7 @@ void GridMapEditor::_set_clipboard_data() { void GridMapEditor::_update_paste_indicator() { if (input_action != INPUT_PASTE) { - Transform xf; + Transform3D xf; xf.basis.set_zero(); RenderingServer::get_singleton()->instance_set_transform(paste_instance, xf); return; @@ -548,7 +542,7 @@ void GridMapEditor::_update_paste_indicator() { Vector3 center = 0.5 * Vector3(real_t(node->get_center_x()), real_t(node->get_center_y()), real_t(node->get_center_z())); Vector3 scale = (Vector3(1, 1, 1) + (paste_indicator.end - paste_indicator.begin)) * node->get_cell_size(); - Transform xf; + Transform3D xf; xf.scale(scale); xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size(); Basis rot; @@ -558,10 +552,8 @@ void GridMapEditor::_update_paste_indicator() { RenderingServer::get_singleton()->instance_set_transform(paste_instance, node->get_global_transform() * xf); - for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) { - ClipboardItem &item = E->get(); - - xf = Transform(); + for (const ClipboardItem &item : clipboard_items) { + xf = Transform3D(); xf.origin = (paste_indicator.begin + (paste_indicator.current - paste_indicator.click) + center) * node->get_cell_size(); xf.basis = rot * xf.basis; xf.translate(item.grid_offset * node->get_cell_size()); @@ -584,9 +576,7 @@ void GridMapEditor::_do_paste() { Vector3 ofs = paste_indicator.current - paste_indicator.click; undo_redo->create_action(TTR("GridMap Paste Selection")); - for (List<ClipboardItem>::Element *E = clipboard_items.front(); E; E = E->next()) { - ClipboardItem &item = E->get(); - + for (const ClipboardItem &item : clipboard_items) { Vector3 position = rot.xform(item.grid_offset) + paste_indicator.begin + ofs; Basis orm; @@ -615,13 +605,13 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid()) { - if (mb->get_button_index() == MOUSE_BUTTON_WHEEL_UP && (mb->get_command() || mb->get_shift())) { + if (mb->get_button_index() == MOUSE_BUTTON_WHEEL_UP && (mb->is_command_pressed() || mb->is_shift_pressed())) { if (mb->is_pressed()) { floor->set_value(floor->get_value() + mb->get_factor()); } return true; // Eaten. - } else if (mb->get_button_index() == MOUSE_BUTTON_WHEEL_DOWN && (mb->get_command() || mb->get_shift())) { + } else if (mb->get_button_index() == MOUSE_BUTTON_WHEEL_DOWN && (mb->is_command_pressed() || mb->is_shift_pressed())) { if (mb->is_pressed()) { floor->set_value(floor->get_value() - mb->get_factor()); } @@ -630,7 +620,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In if (mb->is_pressed()) { Node3DEditorViewport::NavigationScheme nav_scheme = (Node3DEditorViewport::NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int(); - if ((nav_scheme == Node3DEditorViewport::NAVIGATION_MAYA || nav_scheme == Node3DEditorViewport::NAVIGATION_MODO) && mb->get_alt()) { + 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() == MOUSE_BUTTON_LEFT) { bool can_edit = (node && node->get_mesh_library().is_valid()); @@ -638,10 +628,10 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In _do_paste(); input_action = INPUT_NONE; _update_paste_indicator(); - } else if (mb->get_shift() && can_edit) { + } else if (mb->is_shift_pressed() && can_edit) { input_action = INPUT_SELECT; last_selection = selection; - } else if (mb->get_command() && can_edit) { + } else if (mb->is_command_pressed() && can_edit) { input_action = INPUT_PICK; } else { input_action = INPUT_PAINT; @@ -669,8 +659,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In if ((mb->get_button_index() == MOUSE_BUTTON_RIGHT && input_action == INPUT_ERASE) || (mb->get_button_index() == MOUSE_BUTTON_LEFT && input_action == INPUT_PAINT)) { if (set_items.size()) { undo_redo->create_action(TTR("GridMap Paint")); - for (List<SetItem>::Element *E = set_items.front(); E; E = E->next()) { - const SetItem &si = E->get(); + for (const SetItem &si : set_items) { undo_redo->add_do_method(node, "set_cell_item", si.position, si.new_value, si.new_orientation); } for (List<SetItem>::Element *E = set_items.back(); E; E = E->prev()) { @@ -686,7 +675,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In } if (mb->get_button_index() == MOUSE_BUTTON_LEFT && input_action == INPUT_SELECT) { - undo_redo->create_action("GridMap Selection"); + undo_redo->create_action(TTR("GridMap Selection")); undo_redo->add_do_method(this, "_set_selection", selection.active, selection.begin, selection.end); undo_redo->add_undo_method(this, "_set_selection", last_selection.active, last_selection.begin, last_selection.end); undo_redo->commit_action(); @@ -732,7 +721,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In } } - if (k->get_shift() && selection.active && input_action != INPUT_PASTE) { + if (k->is_shift_pressed() && selection.active && input_action != INPUT_PASTE) { if (k->get_keycode() == options->get_popup()->get_item_accelerator(options->get_popup()->get_item_index(MENU_OPTION_PREV_LEVEL))) { selection.click[edit_axis]--; _validate_selection(); @@ -749,7 +738,7 @@ bool GridMapEditor::forward_spatial_input_event(Camera3D *p_camera, const Ref<In Ref<InputEventPanGesture> pan_gesture = p_event; if (pan_gesture.is_valid()) { - if (pan_gesture->get_alt() && (pan_gesture->get_command() || pan_gesture->get_shift())) { + if (pan_gesture->is_alt_pressed() && (pan_gesture->is_command_pressed() || pan_gesture->is_shift_pressed())) { const real_t delta = pan_gesture->get_delta().y * 0.5; accumulated_floor_delta += delta; int step = 0; @@ -810,7 +799,7 @@ void GridMapEditor::_mesh_library_palette_input(const Ref<InputEvent> &p_ie) { const Ref<InputEventMouseButton> mb = p_ie; // Zoom in/out using Ctrl + mouse wheel - if (mb.is_valid() && mb->is_pressed() && mb->get_command()) { + if (mb.is_valid() && mb->is_pressed() && mb->is_command_pressed()) { if (mb->is_pressed() && mb->get_button_index() == MOUSE_BUTTON_WHEEL_UP) { size_slider->set_value(size_slider->get_value() + 0.2); } @@ -875,8 +864,8 @@ void GridMapEditor::update_palette() { int item = 0; - for (List<_CGMEItemSort>::Element *E = il.front(); E; E = E->next()) { - int id = E->get().id; + for (_CGMEItemSort &E : il) { + int id = E.id; String name = mesh_library->get_item_name(id); Ref<Texture2D> preview = mesh_library->get_item_preview(id); @@ -1068,7 +1057,7 @@ void GridMapEditor::_notification(int p_what) { return; } - Transform xf = node->get_global_transform(); + Transform3D xf = node->get_global_transform(); if (xf != grid_xform) { for (int i = 0; i < 3; i++) { @@ -1080,25 +1069,21 @@ void GridMapEditor::_notification(int p_what) { if (cgmt.operator->() != last_mesh_library) { update_palette(); } - - if (lock_view) { - EditorNode *editor = Object::cast_to<EditorNode>(get_tree()->get_root()->get_child(0)); - - Plane p; - p.normal[edit_axis] = 1.0; - p.d = edit_floor[edit_axis] * node->get_cell_size()[edit_axis]; - p = node->get_transform().xform(p); // plane to snap - - Node3DEditorPlugin *sep = Object::cast_to<Node3DEditorPlugin>(editor->get_editor_plugin_screen()); - if (sep) { - sep->snap_cursor_to_plane(p); - } - } } break; case NOTIFICATION_THEME_CHANGED: { - options->set_icon(get_theme_icon("GridMap", "EditorIcons")); - search_box->set_right_icon(get_theme_icon("Search", "EditorIcons")); + options->set_icon(get_theme_icon(SNAME("GridMap"), SNAME("EditorIcons"))); + search_box->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons"))); + } break; + + case NOTIFICATION_APPLICATION_FOCUS_OUT: { + if (input_action == INPUT_PAINT) { + // Simulate mouse released event to stop drawing when editor focus exists. + Ref<InputEventMouseButton> release; + release.instantiate(); + release->set_button_index(MOUSE_BUTTON_LEFT); + forward_spatial_input_event(nullptr, release); + } } break; } } @@ -1187,8 +1172,6 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { spatial_editor_hb->hide(); options->set_text(TTR("Grid Map")); - options->get_popup()->add_check_item(TTR("Snap View"), MENU_OPTION_LOCK_VIEW); - options->get_popup()->add_separator(); options->get_popup()->add_item(TTR("Previous Floor"), MENU_OPTION_PREV_LEVEL, KEY_Q); options->get_popup()->add_item(TTR("Next Floor"), MENU_OPTION_NEXT_LEVEL, KEY_E); options->get_popup()->add_separator(); @@ -1251,7 +1234,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { mode_thumbnail->set_flat(true); mode_thumbnail->set_toggle_mode(true); mode_thumbnail->set_pressed(true); - mode_thumbnail->set_icon(p_editor->get_gui_base()->get_theme_icon("FileThumbnail", "EditorIcons")); + mode_thumbnail->set_icon(p_editor->get_gui_base()->get_theme_icon(SNAME("FileThumbnail"), SNAME("EditorIcons"))); hb->add_child(mode_thumbnail); mode_thumbnail->connect("pressed", callable_mp(this, &GridMapEditor::_set_display_mode), varray(DISPLAY_THUMBNAIL)); @@ -1259,7 +1242,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { mode_list->set_flat(true); mode_list->set_toggle_mode(true); mode_list->set_pressed(false); - mode_list->set_icon(p_editor->get_gui_base()->get_theme_icon("FileList", "EditorIcons")); + mode_list->set_icon(p_editor->get_gui_base()->get_theme_icon(SNAME("FileList"), SNAME("EditorIcons"))); hb->add_child(mode_list); mode_list->connect("pressed", callable_mp(this, &GridMapEditor::_set_display_mode), varray(DISPLAY_LIST)); @@ -1283,7 +1266,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { info_message->set_text(TTR("Give a MeshLibrary resource to this GridMap to use its meshes.")); info_message->set_valign(Label::VALIGN_CENTER); info_message->set_align(Label::ALIGN_CENTER); - info_message->set_autowrap(true); + info_message->set_autowrap_mode(Label::AUTOWRAP_WORD_SMART); info_message->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); info_message->set_anchors_and_offsets_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE); mesh_library_palette->add_child(info_message); @@ -1368,7 +1351,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { Array d; d.resize(RS::ARRAY_MAX); - inner_mat.instance(); + inner_mat.instantiate(); inner_mat->set_albedo(Color(0.7, 0.7, 1.0, 0.2)); inner_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); inner_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); @@ -1377,14 +1360,14 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { RenderingServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh, RS::PRIMITIVE_TRIANGLES, d); RenderingServer::get_singleton()->mesh_surface_set_material(selection_mesh, 0, inner_mat->get_rid()); - outer_mat.instance(); + outer_mat.instantiate(); outer_mat->set_albedo(Color(0.7, 0.7, 1.0, 0.8)); outer_mat->set_on_top_of_alpha(); outer_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); outer_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); - selection_floor_mat.instance(); + selection_floor_mat.instantiate(); selection_floor_mat->set_albedo(Color(0.80, 0.80, 1.0, 1)); selection_floor_mat->set_on_top_of_alpha(); selection_floor_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); @@ -1411,7 +1394,7 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) { _set_selection(false); - indicator_mat.instance(); + indicator_mat.instantiate(); indicator_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); indicator_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); indicator_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h index 6c7f0bedf6..4bc849e071 100644 --- a/modules/gridmap/grid_map_editor_plugin.h +++ b/modules/gridmap/grid_map_editor_plugin.h @@ -94,9 +94,8 @@ class GridMapEditor : public VBoxContainer { MeshLibrary *last_mesh_library; ClipMode clip_mode = CLIP_DISABLED; - bool lock_view = false; - Transform grid_xform; - Transform edit_grid_xform; + Transform3D grid_xform; + Transform3D edit_grid_xform; Vector3::Axis edit_axis; int edit_floor[3]; Vector3 grid_ofs; @@ -146,7 +145,7 @@ class GridMapEditor : public VBoxContainer { PasteIndicator paste_indicator; bool cursor_visible = false; - Transform cursor_transform; + Transform3D cursor_transform; Vector3 cursor_origin; diff --git a/modules/gridmap/icons/GridMap.svg b/modules/gridmap/icons/GridMap.svg index 7a36fd888c..e208257855 100644 --- a/modules/gridmap/icons/GridMap.svg +++ b/modules/gridmap/icons/GridMap.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1-6 3v8l6 3 6-3v-2l-2-1-4 2-2-1v-4l2-1v-2l2-1zm4 2-2 1v2l2 1 2-1v-2z" fill="#fc9c9c" fill-opacity=".99608"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m8 1-6 3v8l6 3 6-3v-2l-2-1-4 2-2-1v-4l2-1v-2l2-1zm4 2-2 1v2l2 1 2-1v-2z" fill="#fc7f7f" fill-opacity=".99608"/></svg> diff --git a/modules/gridmap/register_types.cpp b/modules/gridmap/register_types.cpp index 5680664213..85739d202e 100644 --- a/modules/gridmap/register_types.cpp +++ b/modules/gridmap/register_types.cpp @@ -37,7 +37,7 @@ void register_gridmap_types() { #ifndef _3D_DISABLED - ClassDB::register_class<GridMap>(); + GDREGISTER_CLASS(GridMap); #ifdef TOOLS_ENABLED EditorPlugins::add_by_type<GridMapEditorPlugin>(); #endif diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index 7daf6a3a57..b5e4753e8d 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -105,7 +105,7 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p Error ImageLoaderJPG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { Vector<uint8_t> src_image; - int src_image_len = f->get_len(); + uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); src_image.resize(src_image_len); @@ -127,7 +127,7 @@ void ImageLoaderJPG::get_recognized_extensions(List<String> *p_extensions) const static Ref<Image> _jpegd_mem_loader_func(const uint8_t *p_png, int p_size) { Ref<Image> img; - img.instance(); + img.instantiate(); Error err = jpeg_load_image_from_buffer(img.ptr(), p_png, p_size); ERR_FAIL_COND_V(err, Ref<Image>()); return img; diff --git a/modules/jsonrpc/jsonrpc.cpp b/modules/jsonrpc/jsonrpc.cpp index 306c0ff087..3d0759d83e 100644 --- a/modules/jsonrpc/jsonrpc.cpp +++ b/modules/jsonrpc/jsonrpc.cpp @@ -29,6 +29,7 @@ /*************************************************************************/ #include "jsonrpc.h" + #include "core/io/json.h" JSONRPC::JSONRPC() { @@ -156,19 +157,17 @@ String JSONRPC::process_string(const String &p_input) { } Variant ret; - Variant input; - String err_message; - int err_line; - if (OK != JSON::parse(p_input, input, err_message, err_line)) { - ret = make_response_error(JSONRPC::PARSE_ERROR, "Parse error"); + JSON json; + if (json.parse(p_input) == OK) { + ret = process_action(json.get_data(), true); } else { - ret = process_action(input, true); + ret = make_response_error(JSONRPC::PARSE_ERROR, "Parse error"); } if (ret.get_type() == Variant::NIL) { return ""; } - return JSON::print(ret); + return ret.to_json_string(); } void JSONRPC::set_scope(const String &p_scope, Object *p_obj) { diff --git a/modules/jsonrpc/register_types.cpp b/modules/jsonrpc/register_types.cpp index d6b565ba84..8fdf6fe1aa 100644 --- a/modules/jsonrpc/register_types.cpp +++ b/modules/jsonrpc/register_types.cpp @@ -33,7 +33,7 @@ #include "jsonrpc.h" void register_jsonrpc_types() { - ClassDB::register_class<JSONRPC>(); + GDREGISTER_CLASS(JSONRPC); } void unregister_jsonrpc_types() { diff --git a/modules/lightmapper_rd/lightmapper_rd.cpp b/modules/lightmapper_rd/lightmapper_rd.cpp index 61ebabdfb6..fe941e25e7 100644 --- a/modules/lightmapper_rd/lightmapper_rd.cpp +++ b/modules/lightmapper_rd/lightmapper_rd.cpp @@ -162,8 +162,8 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_ MeshInstance &mi = mesh_instances.write[m_i]; Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()); sizes.push_back(s); - atlas_size.width = MAX(atlas_size.width, s.width); - atlas_size.height = MAX(atlas_size.height, s.height); + atlas_size.width = MAX(atlas_size.width, s.width + 2); + atlas_size.height = MAX(atlas_size.height, s.height + 2); } int max = nearest_power_of_2_templated(atlas_size.width); @@ -186,10 +186,12 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_ //determine best texture array atlas size by bruteforce fitting while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) { - Vector<Vector2i> source_sizes = sizes; + Vector<Vector2i> source_sizes; Vector<int> source_indices; - source_indices.resize(source_sizes.size()); + source_sizes.resize(sizes.size()); + source_indices.resize(sizes.size()); for (int i = 0; i < source_indices.size(); i++) { + source_sizes.write[i] = sizes[i] + Vector2i(2, 2); // Add padding between lightmaps source_indices.write[i] = i; } Vector<Vector3i> atlas_offsets; @@ -207,7 +209,7 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_ if (ofs.z > 0) { //valid ofs.z = slices; - atlas_offsets.write[sidx] = ofs; + atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region } else { new_indices.push_back(sidx); new_sources.push_back(source_sizes[i]); @@ -246,13 +248,13 @@ Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_ for (int i = 0; i < atlas_slices; i++) { Ref<Image> albedo; - albedo.instance(); + albedo.instantiate(); albedo->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8); albedo->set_as_black(); albedo_images.write[i] = albedo; Ref<Image> emission; - emission.instance(); + emission.instantiate(); emission->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH); emission->set_as_black(); emission_images.write[i] = emission; @@ -272,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 &box_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &grid_texture_sdf, 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> &probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &box_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 @@ -432,10 +434,10 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i triangle_indices.resize(triangle_sort.size()); Vector<uint32_t> grid_indices; grid_indices.resize(grid_size * grid_size * grid_size * 2); - zeromem(grid_indices.ptrw(), grid_indices.size() * sizeof(uint32_t)); + memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t)); Vector<bool> solid; solid.resize(grid_size * grid_size * grid_size); - zeromem(solid.ptrw(), solid.size() * sizeof(bool)); + memset(solid.ptrw(), 0, solid.size() * sizeof(bool)); { uint32_t *tiw = triangle_indices.ptrw(); @@ -477,19 +479,11 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i } Ref<Image> img; - img.instance(); + img.instantiate(); img->create(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage); img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png"); } #endif - if (p_step_function) { - p_step_function(0.45, TTR("Generating Signed Distance Field"), p_bake_userdata, true); - } - - //generate SDF for raytracing - Vector<uint32_t> euclidean_pos = Geometry3D::generate_edf(solid, Vector3i(grid_size, grid_size, grid_size), false); - Vector<uint32_t> euclidean_neg = Geometry3D::generate_edf(solid, Vector3i(grid_size, grid_size, grid_size), true); - Vector<int8_t> sdf8 = Geometry3D::generate_sdf8(euclidean_pos, euclidean_neg); /*****************************/ /*** CREATE GPU STRUCTURES ***/ @@ -551,10 +545,6 @@ void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i tf.format = RD::DATA_FORMAT_R32G32_UINT; texdata.write[0] = grid_indices.to_byte_array(); grid_texture = rd->texture_create(tf, RD::TextureView(), texdata); - //sdf - tf.format = RD::DATA_FORMAT_R8_SNORM; - texdata.write[0] = sdf8.to_byte_array(); - grid_texture_sdf = rd->texture_create(tf, RD::TextureView(), texdata); } } @@ -735,7 +725,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d panorama_tex = p_environment_panorama; panorama_tex->convert(Image::FORMAT_RGBAF); } else { - panorama_tex.instance(); + panorama_tex.instantiate(); panorama_tex->create(8, 8, false, Image::FORMAT_RGBAF); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { @@ -755,8 +745,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata); #ifdef DEBUG_TEXTURES - panorama_tex->convert(Image::FORMAT_RGB8); - panorama_tex->save_png("res://0_panorama.png"); + panorama_tex->save_exr("res://0_panorama.exr", false); #endif } } @@ -770,7 +759,6 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RID lights_buffer; RID triangle_cell_indices_buffer; RID grid_texture; - RID grid_texture_sdf; RID seams_buffer; RID probe_positions_buffer; @@ -783,11 +771,10 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d rd->free(lights_buffer); \ rd->free(triangle_cell_indices_buffer); \ rd->free(grid_texture); \ - rd->free(grid_texture_sdf); \ rd->free(seams_buffer); \ rd->free(probe_positions_buffer); - _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, box_buffer, lights_buffer, triangle_cell_indices_buffer, probe_positions_buffer, grid_texture, grid_texture_sdf, seams_buffer, p_step_function, p_bake_userdata); + _create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, box_buffer, lights_buffer, triangle_cell_indices_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata); if (p_step_function) { p_step_function(0.47, TTR("Preparing shaders"), p_bake_userdata, true); @@ -795,7 +782,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d //shaders Ref<RDShaderFile> raster_shader; - raster_shader.instance(); + raster_shader.instantiate(); Error err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl); if (err != OK) { raster_shader->print_errors("raster_shader"); @@ -807,7 +794,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d } ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); - RID rasterize_shader = rd->shader_create_from_bytecode(raster_shader->get_bytecode()); + RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages()); ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen @@ -883,27 +870,20 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 9; - u.ids.push_back(grid_texture_sdf); - base_uniforms.push_back(u); - } - { - RD::Uniform u; - u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; - u.binding = 10; u.ids.push_back(albedo_array_tex); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; - u.binding = 11; + u.binding = 10; u.ids.push_back(emission_array_tex); base_uniforms.push_back(u); } { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_SAMPLER; - u.binding = 12; + u.binding = 11; u.ids.push_back(sampler); base_uniforms.push_back(u); } @@ -935,15 +915,13 @@ 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.instance(); + img.instantiate(); img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s); - img->convert(Image::FORMAT_RGBA8); - img->save_png("res://1_position_" + itos(i) + ".png"); + 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->convert(Image::FORMAT_RGBA8); - img->save_png("res://1_normal_" + itos(i) + ".png"); + img->save_exr("res://1_normal_" + itos(i) + ".exr", false); } #endif @@ -955,7 +933,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d /* Plot direct light */ Ref<RDShaderFile> compute_shader; - compute_shader.instance(); + compute_shader.instantiate(); err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, p_bake_sh ? "\n#define USE_SH_LIGHTMAPS\n" : ""); if (err != OK) { FREE_TEXTURES @@ -966,28 +944,28 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d } ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); - //unoccluder - RID compute_shader_unocclude = rd->shader_create_from_bytecode(compute_shader->get_bytecode("unocclude")); + // Unoccluder + RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude")); ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude); - //direct light - RID compute_shader_primary = rd->shader_create_from_bytecode(compute_shader->get_bytecode("primary")); + // Direct light + RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary")); ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary); - //indirect light - RID compute_shader_secondary = rd->shader_create_from_bytecode(compute_shader->get_bytecode("secondary")); + // Indirect light + RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary")); ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary); - //dilate - RID compute_shader_dilate = rd->shader_create_from_bytecode(compute_shader->get_bytecode("dilate")); + // Dilate + RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate")); ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate); - //dilate - RID compute_shader_light_probes = rd->shader_create_from_bytecode(compute_shader->get_bytecode("light_probes")); + // Light probes + RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes")); ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes); @@ -1151,10 +1129,9 @@ 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.instance(); + img.instantiate(); img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); - img->convert(Image::FORMAT_RGBA8); - img->save_png("res://2_light_primary_" + itos(i) + ".png"); + img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false); } #endif @@ -1212,7 +1189,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; u.binding = 6; - u.ids.push_back(light_environment_tex); //reuse unocclude tex + u.ids.push_back(light_environment_tex); uniforms.push_back(u); } } @@ -1298,7 +1275,15 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d } } } + + if (b == 0) { + // This disables the environment for subsequent bounces + push_constant.environment_xform[3] = -99.0f; + } } + + // Restore the correct environment transform + push_constant.environment_xform[3] = 0.0f; } /* LIGHPROBES */ @@ -1394,12 +1379,12 @@ 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.instance(); + img.instantiate(); img->create(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.instance(); + img2.instantiate(); img2->create(2, 2, false, Image::FORMAT_RGBAF, s); img2->convert(Image::FORMAT_RGB8); img->blit_rect(img2, Rect2(0, 0, 2, 2), Point2((j % 3) * 2, (j / 3) * 2)); @@ -1420,7 +1405,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.instance(); + img.instantiate(); img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); Ref<Image> denoised = denoiser->denoise_image(img); @@ -1447,10 +1432,9 @@ 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.instance(); + img.instantiate(); img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); - img->convert(Image::FORMAT_RGBA8); - img->save_png("res://4_light_secondary_" + itos(i) + ".png"); + img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false); } #endif @@ -1500,7 +1484,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.instance(); + img.instantiate(); img->create(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"); @@ -1510,7 +1494,7 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d /* BLEND SEAMS */ //shaders Ref<RDShaderFile> blendseams_shader; - blendseams_shader.instance(); + blendseams_shader.instantiate(); err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl); if (err != OK) { FREE_TEXTURES @@ -1522,11 +1506,11 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d } ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); - RID blendseams_line_raster_shader = rd->shader_create_from_bytecode(blendseams_shader->get_bytecode("lines")); + RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines")); ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); - RID blendseams_triangle_raster_shader = rd->shader_create_from_bytecode(blendseams_shader->get_bytecode("triangles")); + RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles")); ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); @@ -1582,6 +1566,11 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d clear_colors.push_back(Color(0, 0, 0, 1)); for (int i = 0; i < atlas_slices; i++) { int subslices = (p_bake_sh ? 4 : 1); + + if (slice_seam_count[i] == 0) { + continue; + } + for (int k = 0; k < subslices; k++) { RasterSeamsPushConstant seams_push_constant; seams_push_constant.slice = uint32_t(i * subslices + k); @@ -1652,10 +1641,9 @@ 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.instance(); + img.instantiate(); img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); - img->convert(Image::FORMAT_RGBA8); - img->save_png("res://5_blendseams" + itos(i) + ".png"); + img->save_exr("res://5_blendseams" + itos(i) + ".exr", false); } #endif if (p_step_function) { @@ -1665,7 +1653,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.instance(); + img.instantiate(); img->create(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s); img->convert(Image::FORMAT_RGBH); //remove alpha bake_textures.push_back(img); @@ -1674,15 +1662,15 @@ LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_d if (probe_positions.size() > 0) { probe_values.resize(probe_positions.size() * 9); Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer); - copymem(probe_values.ptrw(), probe_data.ptr(), probe_data.size()); + memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size()); rd->free(light_probe_buffer); #ifdef DEBUG_TEXTURES { Ref<Image> img2; - img2.instance(); + img2.instantiate(); img2->create(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data); - img2->save_png("res://6_lightprobes.png"); + img2->save_exr("res://6_lightprobes.exr", false); } #endif } @@ -1743,7 +1731,7 @@ Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const { ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>()); Vector<Color> ret; ret.resize(9); - copymem(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9); + memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9); return ret; } diff --git a/modules/lightmapper_rd/lightmapper_rd.h b/modules/lightmapper_rd/lightmapper_rd.h index f2a826a447..7ab7f34464 100644 --- a/modules/lightmapper_rd/lightmapper_rd.h +++ b/modules/lightmapper_rd/lightmapper_rd.h @@ -231,7 +231,7 @@ class LightmapperRD : public Lightmapper { Vector<Color> probe_values; BakeError _blit_meshes_into_atlas(int p_max_texture_size, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, BakeStepFunc p_step_function, void *p_bake_userdata); - void _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 &box_buffer, RID &lights_buffer, RID &triangle_cell_indices_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &grid_texture_sdf, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata); + void _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 &box_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 _raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform); public: diff --git a/modules/lightmapper_rd/lm_common_inc.glsl b/modules/lightmapper_rd/lm_common_inc.glsl index f8a0cd16de..1581639036 100644 --- a/modules/lightmapper_rd/lm_common_inc.glsl +++ b/modules/lightmapper_rd/lm_common_inc.glsl @@ -84,9 +84,8 @@ layout(set = 0, binding = 7, std430) restrict readonly buffer Probes { probe_positions; layout(set = 0, binding = 8) uniform utexture3D grid; -layout(set = 0, binding = 9) uniform texture3D grid_sdf; -layout(set = 0, binding = 10) uniform texture2DArray albedo_tex; -layout(set = 0, binding = 11) uniform texture2DArray emission_tex; +layout(set = 0, binding = 9) uniform texture2DArray albedo_tex; +layout(set = 0, binding = 10) uniform texture2DArray emission_tex; -layout(set = 0, binding = 12) uniform sampler linear_sampler; +layout(set = 0, binding = 11) uniform sampler linear_sampler; diff --git a/modules/lightmapper_rd/lm_compute.glsl b/modules/lightmapper_rd/lm_compute.glsl index 3dd96893fb..9ca40535f9 100644 --- a/modules/lightmapper_rd/lm_compute.glsl +++ b/modules/lightmapper_rd/lm_compute.glsl @@ -96,15 +96,22 @@ params; bool ray_hits_triangle(vec3 from, vec3 dir, float max_dist, vec3 p0, vec3 p1, vec3 p2, out float r_distance, out vec3 r_barycentric) { const vec3 e0 = p1 - p0; const vec3 e1 = p0 - p2; - vec3 triangleNormal = cross(e1, e0); + vec3 triangle_normal = cross(e1, e0); - const vec3 e2 = (1.0 / dot(triangleNormal, dir)) * (p0 - from); + float n_dot_dir = dot(triangle_normal, dir); + + if (abs(n_dot_dir) < 0.01) { + return false; + } + + const vec3 e2 = (p0 - from) / n_dot_dir; const vec3 i = cross(dir, e2); r_barycentric.y = dot(i, e1); r_barycentric.z = dot(i, e0); r_barycentric.x = 1.0 - (r_barycentric.z + r_barycentric.y); - r_distance = dot(triangleNormal, e2); + r_distance = dot(triangle_normal, e2); + return (r_distance > params.bias) && (r_distance < max_dist) && all(greaterThanEqual(r_barycentric, vec3(0.0))); } @@ -307,8 +314,6 @@ void main() { continue; } - d /= lights.data[i].range; - attenuation = get_omni_attenuation(d, 1.0 / lights.data[i].range, lights.data[i].attenuation); if (lights.data[i].type == LIGHT_TYPE_SPOT) { @@ -410,7 +415,7 @@ void main() { uint tidx; vec3 barycentric; - vec3 light; + vec3 light = vec3(0.0); if (trace_ray(position + ray_dir * params.bias, position + ray_dir * length(params.world_size), tidx, barycentric)) { //hit a triangle vec2 uv0 = vertices.data[triangles.data[tidx].indices.x].uv; @@ -419,8 +424,8 @@ void main() { vec3 uvw = vec3(barycentric.x * uv0 + barycentric.y * uv1 + barycentric.z * uv2, float(triangles.data[tidx].slice)); light = textureLod(sampler2DArray(source_light, linear_sampler), uvw, 0.0).rgb; - } else { - //did not hit a triangle, reach out for the sky + } else if (params.env_transform[0][3] == 0.0) { // Use env_transform[0][3] to indicate when we are computing the first bounce + // Did not hit a triangle, reach out for the sky vec3 sky_dir = normalize(mat3(params.env_transform) * ray_dir); vec2 st = vec2( diff --git a/modules/lightmapper_rd/register_types.cpp b/modules/lightmapper_rd/register_types.cpp index 191bb3d765..ae9c5fc390 100644 --- a/modules/lightmapper_rd/register_types.cpp +++ b/modules/lightmapper_rd/register_types.cpp @@ -54,7 +54,7 @@ void register_lightmapper_rd_types() { GLOBAL_DEF("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count", 2048); GLOBAL_DEF("rendering/lightmapping/bake_performance/max_rays_per_probe_pass", 64); #ifndef _3D_DISABLED - ClassDB::register_class<LightmapperRD>(); + GDREGISTER_CLASS(LightmapperRD); Lightmapper::create_gpu = create_lightmapper_rd; #endif } diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp index 73931b0365..2522f1bb11 100644 --- a/modules/mbedtls/crypto_mbedtls.cpp +++ b/modules/mbedtls/crypto_mbedtls.cpp @@ -30,7 +30,7 @@ #include "crypto_mbedtls.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "core/config/engine.h" #include "core/config/project_settings.h" @@ -58,7 +58,7 @@ Error CryptoKeyMbedTLS::load(String p_path, bool p_public_only) { FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'."); - int flen = f->get_len(); + uint64_t flen = f->get_length(); out.resize(flen + 1); f->get_buffer(out.ptrw(), flen); out.write[flen] = 0; // string terminator @@ -146,7 +146,7 @@ Error X509CertificateMbedTLS::load(String p_path) { FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open X509CertificateMbedTLS file '" + p_path + "'."); - int flen = f->get_len(); + uint64_t flen = f->get_length(); out.resize(flen + 1); f->get_buffer(out.ptrw(), flen); out.write[flen] = 0; // string terminator @@ -249,6 +249,13 @@ PackedByteArray HMACContextMbedTLS::finish() { return out; } +HMACContextMbedTLS::~HMACContextMbedTLS() { + if (ctx != nullptr) { + mbedtls_md_free((mbedtls_md_context_t *)ctx); + memfree((mbedtls_md_context_t *)ctx); + } +} + Crypto *CryptoMbedTLS::create() { return memnew(CryptoMbedTLS); } @@ -324,7 +331,7 @@ void CryptoMbedTLS::load_default_certificates(String p_path) { Ref<CryptoKey> CryptoMbedTLS::generate_rsa(int p_bytes) { Ref<CryptoKeyMbedTLS> out; - out.instance(); + out.instantiate(); int ret = mbedtls_pk_setup(&(out->pkey), mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)); ERR_FAIL_COND_V(ret != 0, nullptr); ret = mbedtls_rsa_gen_key(mbedtls_pk_rsa(out->pkey), mbedtls_ctr_drbg_random, &ctr_drbg, p_bytes, 65537); @@ -366,7 +373,7 @@ Ref<X509Certificate> CryptoMbedTLS::generate_self_signed_certificate(Ref<CryptoK buf[4095] = '\0'; // Make sure strlen can't fail. Ref<X509CertificateMbedTLS> out; - out.instance(); + out.instantiate(); out->load_from_memory(buf, strlen((char *)buf) + 1); // Use strlen to find correct output size. return out; } @@ -409,7 +416,7 @@ Vector<uint8_t> CryptoMbedTLS::sign(HashingContext::HashType p_hash_type, Vector int ret = mbedtls_pk_sign(&(key->pkey), type, p_hash.ptr(), size, buf, &sig_size, mbedtls_ctr_drbg_random, &ctr_drbg); ERR_FAIL_COND_V_MSG(ret, out, "Error while signing: " + itos(ret)); out.resize(sig_size); - copymem(out.ptrw(), buf, sig_size); + memcpy(out.ptrw(), buf, sig_size); return out; } @@ -432,7 +439,7 @@ Vector<uint8_t> CryptoMbedTLS::encrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_p int ret = mbedtls_pk_encrypt(&(key->pkey), p_plaintext.ptr(), p_plaintext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg); ERR_FAIL_COND_V_MSG(ret, out, "Error while encrypting: " + itos(ret)); out.resize(size); - copymem(out.ptrw(), buf, size); + memcpy(out.ptrw(), buf, size); return out; } @@ -446,6 +453,6 @@ Vector<uint8_t> CryptoMbedTLS::decrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_c int ret = mbedtls_pk_decrypt(&(key->pkey), p_ciphertext.ptr(), p_ciphertext.size(), buf, &size, sizeof(buf), mbedtls_ctr_drbg_random, &ctr_drbg); ERR_FAIL_COND_V_MSG(ret, out, "Error while decrypting: " + itos(ret)); out.resize(size); - copymem(out.ptrw(), buf, size); + memcpy(out.ptrw(), buf, size); return out; } diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h index 5ced4d136c..afa1ea7a64 100644 --- a/modules/mbedtls/crypto_mbedtls.h +++ b/modules/mbedtls/crypto_mbedtls.h @@ -119,6 +119,7 @@ public: virtual PackedByteArray finish(); HMACContextMbedTLS() {} + ~HMACContextMbedTLS(); }; class CryptoMbedTLS : public Crypto { diff --git a/modules/mbedtls/dtls_server_mbedtls.cpp b/modules/mbedtls/dtls_server_mbedtls.cpp index 5d895d8579..b1b6b3844b 100644 --- a/modules/mbedtls/dtls_server_mbedtls.cpp +++ b/modules/mbedtls/dtls_server_mbedtls.cpp @@ -45,7 +45,7 @@ void DTLSServerMbedTLS::stop() { Ref<PacketPeerDTLS> DTLSServerMbedTLS::take_connection(Ref<PacketPeerUDP> p_udp_peer) { Ref<PacketPeerMbedDTLS> out; - out.instance(); + out.instantiate(); ERR_FAIL_COND_V(!out.is_valid(), out); ERR_FAIL_COND_V(!p_udp_peer.is_valid(), out); @@ -68,7 +68,7 @@ void DTLSServerMbedTLS::finalize() { } DTLSServerMbedTLS::DTLSServerMbedTLS() { - _cookies.instance(); + _cookies.instantiate(); } DTLSServerMbedTLS::~DTLSServerMbedTLS() { diff --git a/modules/mbedtls/packet_peer_mbed_dtls.cpp b/modules/mbedtls/packet_peer_mbed_dtls.cpp index 8a6cdfb131..114bf49e9e 100644 --- a/modules/mbedtls/packet_peer_mbed_dtls.cpp +++ b/modules/mbedtls/packet_peer_mbed_dtls.cpp @@ -31,8 +31,8 @@ #include "packet_peer_mbed_dtls.h" #include "mbedtls/platform_util.h" +#include "core/io/file_access.h" #include "core/io/stream_peer_ssl.h" -#include "core/os/file_access.h" int PacketPeerMbedDTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) { if (buf == nullptr || len <= 0) { @@ -74,7 +74,7 @@ int PacketPeerMbedDTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { if (err != OK) { return MBEDTLS_ERR_SSL_INTERNAL_ERROR; } - copymem(buf, buffer, buffer_size); + memcpy(buf, buffer, buffer_size); return buffer_size; } @@ -87,10 +87,10 @@ void PacketPeerMbedDTLS::_cleanup() { int PacketPeerMbedDTLS::_set_cookie() { // Setup DTLS session cookie for this client uint8_t client_id[18]; - IP_Address addr = base->get_packet_address(); + IPAddress addr = base->get_packet_address(); uint16_t port = base->get_packet_port(); - copymem(client_id, addr.get_ipv6(), 16); - copymem(&client_id[16], (uint8_t *)&port, 2); + memcpy(client_id, addr.get_ipv6(), 16); + memcpy(&client_id[16], (uint8_t *)&port, 2); return mbedtls_ssl_set_client_transport_id(ssl_ctx->get_context(), client_id, 18); } @@ -245,7 +245,7 @@ int PacketPeerMbedDTLS::get_max_packet_size() const { } PacketPeerMbedDTLS::PacketPeerMbedDTLS() { - ssl_ctx.instance(); + ssl_ctx.instantiate(); } PacketPeerMbedDTLS::~PacketPeerMbedDTLS() { diff --git a/modules/mbedtls/ssl_context_mbedtls.h b/modules/mbedtls/ssl_context_mbedtls.h index 30632018a8..1b55a54a10 100644 --- a/modules/mbedtls/ssl_context_mbedtls.h +++ b/modules/mbedtls/ssl_context_mbedtls.h @@ -33,9 +33,9 @@ #include "crypto_mbedtls.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include <mbedtls/config.h> #include <mbedtls/ctr_drbg.h> @@ -46,7 +46,7 @@ class SSLContextMbedTLS; -class CookieContextMbedTLS : public Reference { +class CookieContextMbedTLS : public RefCounted { friend class SSLContextMbedTLS; protected: @@ -63,7 +63,7 @@ public: ~CookieContextMbedTLS(); }; -class SSLContextMbedTLS : public Reference { +class SSLContextMbedTLS : public RefCounted { protected: bool inited = false; diff --git a/modules/mbedtls/stream_peer_mbedtls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp index b39a6ecc2f..5727f5f82f 100644 --- a/modules/mbedtls/stream_peer_mbedtls.cpp +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -30,8 +30,8 @@ #include "stream_peer_mbedtls.h" +#include "core/io/file_access.h" #include "core/io/stream_peer_tcp.h" -#include "core/os/file_access.h" int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) { if (buf == nullptr || len <= 0) { @@ -242,7 +242,7 @@ void StreamPeerMbedTLS::poll() { return; } - // We could pass NULL as second parameter, but some behaviour sanitizers don't seem to like that. + // We could pass nullptr as second parameter, but some behaviour sanitizers don't seem to like that. // Passing a 1 byte buffer to workaround it. uint8_t byte; int ret = mbedtls_ssl_read(ssl_ctx->get_context(), &byte, 0); @@ -273,7 +273,7 @@ int StreamPeerMbedTLS::get_available_bytes() const { } StreamPeerMbedTLS::StreamPeerMbedTLS() { - ssl_ctx.instance(); + ssl_ctx.instantiate(); } StreamPeerMbedTLS::~StreamPeerMbedTLS() { diff --git a/modules/mbedtls/tests/test_crypto_mbedtls.cpp b/modules/mbedtls/tests/test_crypto_mbedtls.cpp index 4217497082..8762838883 100644 --- a/modules/mbedtls/tests/test_crypto_mbedtls.cpp +++ b/modules/mbedtls/tests/test_crypto_mbedtls.cpp @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "modules/mbedtls/tests/test_crypto_mbedtls.h" +#include "test_crypto_mbedtls.h" #include "modules/mbedtls/crypto_mbedtls.h" #include "tests/test_macros.h" diff --git a/modules/meshoptimizer/config.py b/modules/meshoptimizer/config.py index 82e4e43397..b7e69569b9 100644 --- a/modules/meshoptimizer/config.py +++ b/modules/meshoptimizer/config.py @@ -1,6 +1,6 @@ def can_build(env, platform): # Having this on release by default, it's small and a lot of users like to do procedural stuff - return True + return not env["disable_3d"] def configure(env): diff --git a/modules/meshoptimizer/register_types.cpp b/modules/meshoptimizer/register_types.cpp index a03310f518..77cc82a4e2 100644 --- a/modules/meshoptimizer/register_types.cpp +++ b/modules/meshoptimizer/register_types.cpp @@ -35,6 +35,7 @@ void register_meshoptimizer_types() { SurfaceTool::optimize_vertex_cache_func = meshopt_optimizeVertexCache; SurfaceTool::simplify_func = meshopt_simplify; + SurfaceTool::simplify_with_attrib_func = meshopt_simplifyWithAttributes; SurfaceTool::simplify_scale_func = meshopt_simplifyScale; SurfaceTool::simplify_sloppy_func = meshopt_simplifySloppy; } diff --git a/modules/minimp3/audio_stream_mp3.cpp b/modules/minimp3/audio_stream_mp3.cpp index aaa05a910c..2cc974322d 100644 --- a/modules/minimp3/audio_stream_mp3.cpp +++ b/modules/minimp3/audio_stream_mp3.cpp @@ -35,7 +35,7 @@ #include "audio_stream_mp3.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" void AudioStreamPlaybackMP3::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); @@ -126,7 +126,7 @@ Ref<AudioStreamPlayback> AudioStreamMP3::instance_playback() { "to it. AudioStreamMP3 should not be created from the " "inspector or with `.new()`. Instead, load an audio file."); - mp3s.instance(); + mp3s.instantiate(); mp3s->mp3_stream = Ref<AudioStreamMP3>(this); mp3s->mp3d = (mp3dec_ex_t *)memalloc(sizeof(mp3dec_ex_t)); @@ -172,7 +172,7 @@ void AudioStreamMP3::set_data(const Vector<uint8_t> &p_data) { clear_data(); data = memalloc(src_data_len); - copymem(data, src_datar, src_data_len); + memcpy(data, src_datar, src_data_len); data_len = src_data_len; } @@ -183,7 +183,7 @@ Vector<uint8_t> AudioStreamMP3::get_data() const { vdata.resize(data_len); { uint8_t *w = vdata.ptrw(); - copymem(w, data, data_len); + memcpy(w, data, data_len); } } diff --git a/modules/minimp3/doc_classes/AudioStreamMP3.xml b/modules/minimp3/doc_classes/AudioStreamMP3.xml index 92e777ca0f..5507329a18 100644 --- a/modules/minimp3/doc_classes/AudioStreamMP3.xml +++ b/modules/minimp3/doc_classes/AudioStreamMP3.xml @@ -11,7 +11,7 @@ <methods> </methods> <members> - <member name="data" type="PackedByteArray" setter="set_data" getter="get_data" default="PackedByteArray( )"> + <member name="data" type="PackedByteArray" setter="set_data" getter="get_data" default="PackedByteArray()"> Contains the audio data in bytes. </member> <member name="loop" type="bool" setter="set_loop" getter="has_loop" default="false"> diff --git a/modules/minimp3/register_types.cpp b/modules/minimp3/register_types.cpp index 4ab4c743d6..63f2589f42 100644 --- a/modules/minimp3/register_types.cpp +++ b/modules/minimp3/register_types.cpp @@ -41,11 +41,11 @@ void register_minimp3_types() { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { Ref<ResourceImporterMP3> mp3_import; - mp3_import.instance(); + mp3_import.instantiate(); ResourceFormatImporter::get_singleton()->add_importer(mp3_import); } #endif - ClassDB::register_class<AudioStreamMP3>(); + GDREGISTER_CLASS(AudioStreamMP3); } void unregister_minimp3_types() { diff --git a/modules/minimp3/resource_importer_mp3.cpp b/modules/minimp3/resource_importer_mp3.cpp index afd26fb79e..dc360c12ba 100644 --- a/modules/minimp3/resource_importer_mp3.cpp +++ b/modules/minimp3/resource_importer_mp3.cpp @@ -30,8 +30,8 @@ #include "resource_importer_mp3.h" +#include "core/io/file_access.h" #include "core/io/resource_saver.h" -#include "core/os/file_access.h" #include "scene/resources/texture.h" String ResourceImporterMP3::get_importer_name() const { @@ -79,7 +79,7 @@ Error ResourceImporterMP3::import(const String &p_source_file, const String &p_s ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); - size_t len = f->get_len(); + uint64_t len = f->get_length(); Vector<uint8_t> data; data.resize(len); @@ -90,7 +90,7 @@ Error ResourceImporterMP3::import(const String &p_source_file, const String &p_s memdelete(f); Ref<AudioStreamMP3> mp3_stream; - mp3_stream.instance(); + mp3_stream.instantiate(); mp3_stream->set_data(data); ERR_FAIL_COND_V(!mp3_stream->get_data().size(), ERR_FILE_CORRUPT); diff --git a/modules/mobile_vr/config.py b/modules/mobile_vr/config.py index ee401c1a2a..f6b64fb690 100644 --- a/modules/mobile_vr/config.py +++ b/modules/mobile_vr/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return True + return not env["disable_3d"] def configure(env): diff --git a/modules/mobile_vr/mobile_vr_interface.cpp b/modules/mobile_vr/mobile_vr_interface.cpp index 5140cfbbaf..590b95ab79 100644 --- a/modules/mobile_vr/mobile_vr_interface.cpp +++ b/modules/mobile_vr/mobile_vr_interface.cpp @@ -185,8 +185,8 @@ void MobileVRInterface::set_position_from_sensors() { // if you have a gyro + accelerometer that combo tends to be better than combining all three but without a gyro you need the magnetometer.. if (has_magneto && has_grav && !has_gyro) { // convert to quaternions, easier to smooth those out - Quat transform_quat(orientation); - Quat acc_mag_quat(combine_acc_mag(grav, magneto)); + Quaternion transform_quat(orientation); + Quaternion acc_mag_quat(combine_acc_mag(grav, magneto)); transform_quat = transform_quat.slerp(acc_mag_quat, 0.1); orientation = Basis(transform_quat); @@ -300,9 +300,9 @@ real_t MobileVRInterface::get_k2() const { return k2; }; -bool MobileVRInterface::is_stereo() { +uint32_t MobileVRInterface::get_view_count() { // needs stereo... - return true; + return 2; }; bool MobileVRInterface::is_initialized() const { @@ -361,10 +361,32 @@ Size2 MobileVRInterface::get_render_targetsize() { return target_size; }; -Transform MobileVRInterface::get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) { +Transform3D MobileVRInterface::get_camera_transform() { _THREAD_SAFE_METHOD_ - Transform transform_for_eye; + Transform3D transform_for_eye; + + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, transform_for_eye); + + if (initialized) { + float world_scale = xr_server->get_world_scale(); + + // just scale our origin point of our transform + Transform3D hmd_transform; + hmd_transform.basis = orientation; + hmd_transform.origin = Vector3(0.0, eye_height * world_scale, 0.0); + + transform_for_eye = (xr_server->get_reference_frame()) * hmd_transform; + } + + return transform_for_eye; +}; + +Transform3D MobileVRInterface::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) { + _THREAD_SAFE_METHOD_ + + Transform3D transform_for_eye; XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL_V(xr_server, transform_for_eye); @@ -374,16 +396,16 @@ Transform MobileVRInterface::get_transform_for_eye(XRInterface::Eyes p_eye, cons // we don't need to check for the existence of our HMD, doesn't affect our values... // note * 0.01 to convert cm to m and * 0.5 as we're moving half in each direction... - if (p_eye == XRInterface::EYE_LEFT) { + if (p_view == 0) { transform_for_eye.origin.x = -(intraocular_dist * 0.01 * 0.5 * world_scale); - } else if (p_eye == XRInterface::EYE_RIGHT) { + } else if (p_view == 1) { transform_for_eye.origin.x = intraocular_dist * 0.01 * 0.5 * world_scale; } else { - // for mono we don't reposition, we want our center position. + // should not have any other values.. }; // just scale our origin point of our transform - Transform hmd_transform; + Transform3D hmd_transform; hmd_transform.basis = orientation; hmd_transform.origin = Vector3(0.0, eye_height * world_scale, 0.0); @@ -396,21 +418,13 @@ Transform MobileVRInterface::get_transform_for_eye(XRInterface::Eyes p_eye, cons return transform_for_eye; }; -CameraMatrix MobileVRInterface::get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) { +CameraMatrix MobileVRInterface::get_projection_for_view(uint32_t p_view, real_t p_aspect, real_t p_z_near, real_t p_z_far) { _THREAD_SAFE_METHOD_ CameraMatrix eye; - if (p_eye == XRInterface::EYE_MONO) { - ///@TODO for now hardcode some of this, what is really needed here is that this needs to be in sync with the real camera's properties - // which probably means implementing a specific class for iOS and Android. For now this is purely here as an example. - // Note also that if you use a normal viewport with AR/VR turned off you can still use the tracker output of this interface - // to position a stock standard Godot camera and have control over this. - // This will make more sense when we implement ARkit on iOS (probably a separate interface). - eye.set_perspective(60.0, p_aspect, p_z_near, p_z_far, false); - } else { - eye.set_for_hmd(p_eye == XRInterface::EYE_LEFT ? 1 : 2, p_aspect, intraocular_dist, display_width, display_to_lens, oversample, p_z_near, p_z_far); - }; + aspect = p_aspect; + eye.set_for_hmd(p_view + 1, p_aspect, intraocular_dist, display_width, display_to_lens, oversample, p_z_near, p_z_far); return eye; }; @@ -440,6 +454,45 @@ void MobileVRInterface::commit_for_eye(XRInterface::Eyes p_eye, RID p_render_tar eye_center.y = 0.0; } +Vector<BlitToScreen> MobileVRInterface::commit_views(RID p_render_target, const Rect2 &p_screen_rect) { + _THREAD_SAFE_METHOD_ + + Vector<BlitToScreen> blit_to_screen; + + // We must have a valid render target + ERR_FAIL_COND_V(!p_render_target.is_valid(), blit_to_screen); + + // Because we are rendering to our device we must use our main viewport! + ERR_FAIL_COND_V(p_screen_rect == Rect2(), blit_to_screen); + + // and add our blits + BlitToScreen blit; + blit.render_target = p_render_target; + blit.multi_view.use_layer = true; + blit.lens_distortion.apply = true; + blit.lens_distortion.k1 = k1; + blit.lens_distortion.k2 = k2; + blit.lens_distortion.upscale = oversample; + blit.lens_distortion.aspect_ratio = aspect; + + // left eye + blit.rect = p_screen_rect; + blit.rect.size.width *= 0.5; + blit.multi_view.layer = 0; + blit.lens_distortion.eye_center.x = ((-intraocular_dist / 2.0) + (display_width / 4.0)) / (display_width / 2.0); + blit_to_screen.push_back(blit); + + // right eye + blit.rect = p_screen_rect; + blit.rect.size.width *= 0.5; + blit.rect.position.x = blit.rect.size.width; + blit.multi_view.layer = 1; + blit.lens_distortion.eye_center.x = ((intraocular_dist / 2.0) - (display_width / 4.0)) / (display_width / 2.0); + blit_to_screen.push_back(blit); + + return blit_to_screen; +} + void MobileVRInterface::process() { _THREAD_SAFE_METHOD_ diff --git a/modules/mobile_vr/mobile_vr_interface.h b/modules/mobile_vr/mobile_vr_interface.h index d28c2196af..29ce0f92c8 100644 --- a/modules/mobile_vr/mobile_vr_interface.h +++ b/modules/mobile_vr/mobile_vr_interface.h @@ -63,9 +63,9 @@ private: real_t display_to_lens = 4.0; real_t oversample = 1.5; - //@TODO not yet used, these are needed in our distortion shader... real_t k1 = 0.215; real_t k2 = 0.215; + real_t aspect = 1.0; /* logic for processing our sensor data, this was originally in our positional tracker logic but I think @@ -138,16 +138,20 @@ public: virtual void uninitialize() override; virtual Size2 get_render_targetsize() override; - virtual bool is_stereo() override; - virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) override; - virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) override; - virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) 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 CameraMatrix get_projection_for_view(uint32_t p_view, real_t p_aspect, real_t p_z_near, real_t p_z_far) override; + virtual Vector<BlitToScreen> commit_views(RID p_render_target, const Rect2 &p_screen_rect) override; virtual void process() override; virtual void notification(int p_what) override {} MobileVRInterface(); ~MobileVRInterface(); + + // deprecated + virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override; }; #endif // !MOBILE_VR_INTERFACE_H diff --git a/modules/mobile_vr/register_types.cpp b/modules/mobile_vr/register_types.cpp index e7d33ba8a7..47d1fe482c 100644 --- a/modules/mobile_vr/register_types.cpp +++ b/modules/mobile_vr/register_types.cpp @@ -33,11 +33,11 @@ #include "mobile_vr_interface.h" void register_mobile_vr_types() { - ClassDB::register_class<MobileVRInterface>(); + GDREGISTER_CLASS(MobileVRInterface); if (XRServer::get_singleton()) { Ref<MobileVRInterface> mobile_vr; - mobile_vr.instance(); + mobile_vr.instantiate(); XRServer::get_singleton()->add_interface(mobile_vr); } } diff --git a/modules/mono/.editorconfig b/modules/mono/.editorconfig new file mode 100644 index 0000000000..c9dcd7724e --- /dev/null +++ b/modules/mono/.editorconfig @@ -0,0 +1,14 @@ +[*.sln] +indent_style = tab + +[*.{csproj,props,targets,nuspec,resx}] +indent_style = space +indent_size = 2 + +[*.cs] +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true +max_line_length = 120 +csharp_indent_case_contents_when_block = false diff --git a/modules/mono/build_scripts/mono_configure.py b/modules/mono/build_scripts/mono_configure.py index 309abfbff7..8e441e7e07 100644 --- a/modules/mono/build_scripts/mono_configure.py +++ b/modules/mono/build_scripts/mono_configure.py @@ -101,12 +101,6 @@ def configure(env, env_mono): mono_lib_names = ["mono-2.0-sgen", "monosgen-2.0"] - is_travis = os.environ.get("TRAVIS") == "true" - - if is_travis: - # Travis CI may have a Mono version lower than 5.12 - env_mono.Append(CPPDEFINES=["NO_PENDING_EXCEPTIONS"]) - if is_android and not env["android_arch"] in android_arch_dirs: raise RuntimeError("This module does not support the specified 'android_arch': " + env["android_arch"]) diff --git a/modules/mono/class_db_api_json.cpp b/modules/mono/class_db_api_json.cpp index 553c6eca53..0da06131af 100644 --- a/modules/mono/class_db_api_json.cpp +++ b/modules/mono/class_db_api_json.cpp @@ -33,8 +33,8 @@ #ifdef DEBUG_METHODS_ENABLED #include "core/config/project_settings.h" +#include "core/io/file_access.h" #include "core/io/json.h" -#include "core/os/file_access.h" #include "core/version.h" void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { @@ -50,8 +50,8 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { //must be alphabetically sorted for hash to compute names.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *E = names.front(); E; E = E->next()) { - ClassDB::ClassInfo *t = ClassDB::classes.getptr(E->get()); + for (const StringName &E : names) { + ClassDB::ClassInfo *t = ClassDB::classes.getptr(E); ERR_FAIL_COND(!t); if (t->api != p_api || !t->exposed) { continue; @@ -84,11 +84,11 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { Array methods; - for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + for (const StringName &F : snames) { Dictionary method_dict; methods.push_back(method_dict); - MethodBind *mb = t->method_map[F->get()]; + MethodBind *mb = t->method_map[F]; method_dict["name"] = mb->get_name(); method_dict["argument_count"] = mb->get_argument_count(); method_dict["return_type"] = mb->get_argument_type(-1); @@ -141,12 +141,12 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { Array constants; - for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + for (const StringName &F : snames) { Dictionary constant_dict; constants.push_back(constant_dict); - constant_dict["name"] = F->get(); - constant_dict["value"] = t->constant_map[F->get()]; + constant_dict["name"] = F; + constant_dict["value"] = t->constant_map[F]; } if (!constants.is_empty()) { @@ -168,12 +168,12 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { Array signals; - for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + for (const StringName &F : snames) { Dictionary signal_dict; signals.push_back(signal_dict); - MethodInfo &mi = t->signal_map[F->get()]; - signal_dict["name"] = F->get(); + MethodInfo &mi = t->signal_map[F]; + signal_dict["name"] = F; Array arguments; signal_dict["arguments"] = arguments; @@ -203,13 +203,13 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { Array properties; - for (List<StringName>::Element *F = snames.front(); F; F = F->next()) { + for (const StringName &F : snames) { Dictionary property_dict; properties.push_back(property_dict); - ClassDB::PropertySetGet *psg = t->property_setget.getptr(F->get()); + ClassDB::PropertySetGet *psg = t->property_setget.getptr(F); - property_dict["name"] = F->get(); + property_dict["name"] = F; property_dict["setter"] = psg->setter; property_dict["getter"] = psg->getter; } @@ -222,15 +222,15 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { Array property_list; //property list - for (List<PropertyInfo>::Element *F = t->property_list.front(); F; F = F->next()) { + for (const PropertyInfo &F : t->property_list) { Dictionary property_dict; property_list.push_back(property_dict); - property_dict["name"] = F->get().name; - property_dict["type"] = F->get().type; - property_dict["hint"] = F->get().hint; - property_dict["hint_string"] = F->get().hint_string; - property_dict["usage"] = F->get().usage; + property_dict["name"] = F.name; + property_dict["type"] = F.type; + property_dict["hint"] = F.hint; + property_dict["hint_string"] = F.hint_string; + property_dict["usage"] = F.usage; } if (!property_list.is_empty()) { @@ -240,7 +240,8 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { FileAccessRef f = FileAccess::open(p_output_file, FileAccess::WRITE); ERR_FAIL_COND_MSG(!f, "Cannot open file '" + p_output_file + "'."); - f->store_string(JSON::print(classes_dict, /*indent: */ "\t")); + JSON json; + f->store_string(json.stringify(classes_dict, "\t")); f->close(); print_line(String() + "ClassDB API JSON written to: " + ProjectSettings::get_singleton()->globalize_path(p_output_file)); diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 09f3ea1f50..520262c0eb 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -37,8 +37,7 @@ #include "core/config/project_settings.h" #include "core/debugger/engine_debugger.h" #include "core/debugger/script_debugger.h" -#include "core/io/json.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "core/os/mutex.h" #include "core/os/os.h" #include "core/os/thread.h" @@ -146,8 +145,8 @@ void CSharpLanguage::finalize() { finalizing = true; // Make sure all script binding gchandles are released before finalizing GDMono - for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { - CSharpScriptBinding &script_binding = E->value(); + for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) { + CSharpScriptBinding &script_binding = E.value; if (!script_binding.gchandle.is_released()) { script_binding.gchandle.release(); @@ -164,8 +163,8 @@ void CSharpLanguage::finalize() { script_bindings.clear(); #ifdef DEBUG_ENABLED - for (Map<ObjectID, int>::Element *E = unsafe_object_references.front(); E; E = E->next()) { - const ObjectID &id = E->key(); + for (const KeyValue<ObjectID, int> &E : unsafe_object_references) { + const ObjectID &id = E.key; Object *obj = ObjectDB::get_instance(id); if (obj) { @@ -304,6 +303,26 @@ void CSharpLanguage::get_reserved_words(List<String> *p_words) const { } } +bool CSharpLanguage::is_control_flow_keyword(String p_keyword) const { + return p_keyword == "break" || + p_keyword == "case" || + p_keyword == "catch" || + p_keyword == "continue" || + p_keyword == "default" || + p_keyword == "do" || + p_keyword == "else" || + p_keyword == "finally" || + p_keyword == "for" || + p_keyword == "foreach" || + p_keyword == "goto" || + p_keyword == "if" || + p_keyword == "return" || + p_keyword == "switch" || + p_keyword == "throw" || + p_keyword == "try" || + p_keyword == "while"; +} + void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const { p_delimiters->push_back("//"); // single-line comment p_delimiters->push_back("/* */"); // delimited comment @@ -348,7 +367,7 @@ Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const Strin "}\n"; // Replaces all spaces in p_class_name with underscores to prevent - // erronous C# Script templates from being generated when the object name + // invalid C# Script templates from being generated when the object name // has spaces in it. String class_name_no_spaces = p_class_name.replace(" ", "_"); String base_class_name = get_base_class_name(p_base_class_name, class_name_no_spaces); @@ -356,7 +375,7 @@ Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const Strin .replace("%CLASS%", class_name_no_spaces); Ref<CSharpScript> script; - script.instance(); + script.instantiate(); script->set_source_code(script_template); script->set_name(class_name_no_spaces); @@ -476,10 +495,10 @@ static String variant_type_to_managed_name(const String &p_var_type_name) { Variant::VECTOR3I, Variant::TRANSFORM2D, Variant::PLANE, - Variant::QUAT, + Variant::QUATERNION, Variant::AABB, Variant::BASIS, - Variant::TRANSFORM, + Variant::TRANSFORM3D, Variant::COLOR, Variant::STRING_NAME, Variant::NODE_PATH, @@ -843,20 +862,25 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { List<Ref<CSharpScript>> to_reload; // We need to keep reference instances alive during reloading - List<Ref<Reference>> ref_instances; + List<Ref<RefCounted>> rc_instances; - for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { - CSharpScriptBinding &script_binding = E->value(); - Reference *ref = Object::cast_to<Reference>(script_binding.owner); - if (ref) { - ref_instances.push_back(Ref<Reference>(ref)); + for (const KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) { + const CSharpScriptBinding &script_binding = E.value; + RefCounted *rc = Object::cast_to<RefCounted>(script_binding.owner); + if (rc) { + rc_instances.push_back(Ref<RefCounted>(rc)); } } // As scripts are going to be reloaded, must proceed without locking here - for (List<Ref<CSharpScript>>::Element *E = scripts.front(); E; E = E->next()) { - Ref<CSharpScript> &script = E->get(); + for (Ref<CSharpScript> &script : scripts) { + // If someone removes a script from a node, deletes the script, builds, adds a script to the + // same node, then builds again, the script might have no path and also no script_class. In + // that case, we can't (and don't need to) reload it. + if (script->get_path().is_empty() && !script->script_class) { + continue; + } to_reload.push_back(script); @@ -868,24 +892,23 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { // Script::instances are deleted during managed object disposal, which happens on domain finalize. // Only placeholders are kept. Therefore we need to keep a copy before that happens. - for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) { - Object *obj = F->get(); + for (Object *&obj : script->instances) { script->pending_reload_instances.insert(obj->get_instance_id()); - Reference *ref = Object::cast_to<Reference>(obj); - if (ref) { - ref_instances.push_back(Ref<Reference>(ref)); + RefCounted *rc = Object::cast_to<RefCounted>(obj); + if (rc) { + rc_instances.push_back(Ref<RefCounted>(rc)); } } #ifdef TOOLS_ENABLED - for (Set<PlaceHolderScriptInstance *>::Element *F = script->placeholders.front(); F; F = F->next()) { - Object *obj = F->get()->get_owner(); + for (PlaceHolderScriptInstance *&script_instance : script->placeholders) { + Object *obj = script_instance->get_owner(); script->pending_reload_instances.insert(obj->get_instance_id()); - Reference *ref = Object::cast_to<Reference>(obj); - if (ref) { - ref_instances.push_back(Ref<Reference>(ref)); + RefCounted *rc = Object::cast_to<RefCounted>(obj); + if (rc) { + rc_instances.push_back(Ref<RefCounted>(rc)); } } #endif @@ -893,9 +916,7 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { // Save state and remove script from instances Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state; - for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) { - Object *obj = F->get(); - + for (Object *&obj : script->instances) { ERR_CONTINUE(!obj->get_script_instance()); CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance()); @@ -917,9 +938,7 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { } // After the state of all instances is saved, clear scripts and script instances - for (List<Ref<CSharpScript>>::Element *E = scripts.front(); E; E = E->next()) { - Ref<CSharpScript> &script = E->get(); - + for (Ref<CSharpScript> &script : scripts) { while (script->instances.front()) { Object *obj = script->instances.front()->get(); obj->set_script(REF()); // Remove script and existing script instances (placeholder are not removed before domain reload) @@ -932,11 +951,9 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { if (gdmono->reload_scripts_domain() != OK) { // Failed to reload the scripts domain // Make sure to add the scripts back to their owners before returning - for (List<Ref<CSharpScript>>::Element *E = to_reload.front(); E; E = E->next()) { - Ref<CSharpScript> scr = E->get(); - - for (const Map<ObjectID, CSharpScript::StateBackup>::Element *F = scr->pending_reload_state.front(); F; F = F->next()) { - Object *obj = ObjectDB::get_instance(F->key()); + for (Ref<CSharpScript> &scr : to_reload) { + for (const KeyValue<ObjectID, CSharpScript::StateBackup> &F : scr->pending_reload_state) { + Object *obj = ObjectDB::get_instance(F.key); if (!obj) { continue; @@ -956,8 +973,8 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { #endif // Restore Variant properties state, it will be kept by the placeholder until the next script reloading - for (List<Pair<StringName, Variant>>::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) { - placeholder->property_set_fallback(G->get().first, G->get().second, nullptr); + for (const Pair<StringName, Variant> &G : scr->pending_reload_state[obj_id].properties) { + placeholder->property_set_fallback(G.first, G.second, nullptr); } scr->pending_reload_state.erase(obj_id); @@ -969,9 +986,7 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { List<Ref<CSharpScript>> to_reload_state; - for (List<Ref<CSharpScript>>::Element *E = to_reload.front(); E; E = E->next()) { - Ref<CSharpScript> script = E->get(); - + for (Ref<CSharpScript> &script : to_reload) { #ifdef TOOLS_ENABLED script->exports_invalidated = true; #endif @@ -1024,8 +1039,7 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { StringName native_name = NATIVE_GDMONOCLASS_NAME(script->native); { - for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) { - ObjectID obj_id = F->get(); + for (const ObjectID &obj_id : script->pending_reload_instances) { Object *obj = ObjectDB::get_instance(obj_id); if (!obj) { @@ -1076,11 +1090,8 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { to_reload_state.push_back(script); } - for (List<Ref<CSharpScript>>::Element *E = to_reload_state.front(); E; E = E->next()) { - Ref<CSharpScript> script = E->get(); - - for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) { - ObjectID obj_id = F->get(); + for (Ref<CSharpScript> &script : to_reload_state) { + for (const ObjectID &obj_id : script->pending_reload_instances) { Object *obj = ObjectDB::get_instance(obj_id); if (!obj) { @@ -1094,16 +1105,16 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id]; - for (List<Pair<StringName, Variant>>::Element *G = state_backup.properties.front(); G; G = G->next()) { - obj->get_script_instance()->set(G->get().first, G->get().second); + for (const Pair<StringName, Variant> &G : state_backup.properties) { + obj->get_script_instance()->set(G.first, G.second); } CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance()); if (csi) { - for (List<Pair<StringName, Array>>::Element *G = state_backup.event_signals.front(); G; G = G->next()) { - const StringName &name = G->get().first; - const Array &serialized_data = G->get().second; + for (const Pair<StringName, Array> &G : state_backup.event_signals) { + const StringName &name = G.first; + const Array &serialized_data = G.second; Map<StringName, CSharpScript::EventSignal>::Element *match = script->event_signals.find(name); @@ -1147,9 +1158,9 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { { MutexLock lock(ManagedCallable::instances_mutex); - for (Map<ManagedCallable *, Array>::Element *elem = ManagedCallable::instances_pending_reload.front(); elem; elem = elem->next()) { - ManagedCallable *managed_callable = elem->key(); - const Array &serialized_data = elem->value(); + for (const KeyValue<ManagedCallable *, Array> &elem : ManagedCallable::instances_pending_reload) { + ManagedCallable *managed_callable = elem.key; + const Array &serialized_data = elem.value; MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data); MonoDelegate *delegate = nullptr; @@ -1293,8 +1304,8 @@ bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) { } void CSharpLanguage::_on_scripts_domain_unloaded() { - for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { - CSharpScriptBinding &script_binding = E->value(); + for (KeyValue<Object *, CSharpScriptBinding> &E : script_bindings) { + CSharpScriptBinding &script_binding = E.value; script_binding.gchandle.release(); script_binding.inited = false; } @@ -1418,16 +1429,16 @@ bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_b r_script_binding.owner = p_object; // Tie managed to unmanaged - Reference *ref = Object::cast_to<Reference>(p_object); + RefCounted *rc = Object::cast_to<RefCounted>(p_object); - if (ref) { + if (rc) { // Unsafe refcount increment. The managed instance also counts as a reference. // This way if the unmanaged world has no references to our owner // but the managed instance is alive, the refcount will be 1 instead of 0. - // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr) + // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr) - ref->reference(); - CSharpLanguage::get_singleton()->post_unsafe_reference(ref); + rc->reference(); + CSharpLanguage::get_singleton()->post_unsafe_reference(rc); } return true; @@ -1491,10 +1502,11 @@ void CSharpLanguage::free_instance_binding_data(void *p_data) { } void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) { - Reference *ref_owner = Object::cast_to<Reference>(p_object); +#if 0 + RefCounted *rc_owner = Object::cast_to<RefCounted>(p_object); #ifdef DEBUG_ENABLED - CRASH_COND(!ref_owner); + CRASH_COND(!rc_owner); CRASH_COND(!p_object->has_script_instance_binding(get_language_index())); #endif @@ -1508,7 +1520,7 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) { return; } - if (ref_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 + if (rc_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 GD_MONO_SCOPE_THREAD_ATTACH; // The reference count was increased after the managed side was the only one referencing our owner. @@ -1525,13 +1537,15 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) { gchandle.release(); gchandle = strong_gchandle; } +#endif } bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) { - Reference *ref_owner = Object::cast_to<Reference>(p_object); +#if 0 + RefCounted *rc_owner = Object::cast_to<RefCounted>(p_object); #ifdef DEBUG_ENABLED - CRASH_COND(!ref_owner); + CRASH_COND(!rc_owner); CRASH_COND(!p_object->has_script_instance_binding(get_language_index())); #endif @@ -1541,7 +1555,7 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) { CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); MonoGCHandleData &gchandle = script_binding.gchandle; - int refcount = ref_owner->reference_get_count(); + int refcount = rc_owner->reference_get_count(); if (!script_binding.inited) { return refcount == 0; @@ -1567,18 +1581,20 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) { } return refcount == 0; +#endif + return false; } CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) { CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script))); - Reference *ref = Object::cast_to<Reference>(p_owner); + RefCounted *rc = Object::cast_to<RefCounted>(p_owner); - instance->base_ref = ref != nullptr; + instance->base_ref_counted = rc != nullptr; instance->owner = p_owner; instance->gchandle = p_gchandle; - if (instance->base_ref) { + if (instance->base_ref_counted) { instance->_reference_owner_unsafe(); } @@ -1714,12 +1730,12 @@ bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const { } void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant>> &r_state) { - List<PropertyInfo> pinfo; - get_property_list(&pinfo); + List<PropertyInfo> property_list; + get_property_list(&property_list); - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + for (const PropertyInfo &prop_info : property_list) { Pair<StringName, Variant> state_pair; - state_pair.first = E->get().name; + state_pair.first = prop_info.name; ManagedType managedType; @@ -1742,8 +1758,8 @@ void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName, MonoObject *owner_managed = get_mono_object(); ERR_FAIL_NULL(owner_managed); - for (const Map<StringName, CSharpScript::EventSignal>::Element *E = script->event_signals.front(); E; E = E->next()) { - const CSharpScript::EventSignal &event_signal = E->value(); + for (const KeyValue<StringName, CSharpScript::EventSignal> &E : script->event_signals) { + const CSharpScript::EventSignal &event_signal = E.value; MonoDelegate *delegate_field_value = (MonoDelegate *)event_signal.field->get_value(owner_managed); if (!delegate_field_value) { @@ -1770,8 +1786,8 @@ void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName, } void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const { - for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) { - p_properties->push_back(E->value()); + for (const KeyValue<StringName, PropertyInfo> &E : script->member_info) { + p_properties->push_back(E.value); } // Call _get_property_list @@ -1880,7 +1896,7 @@ Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, bool CSharpInstance::_reference_owner_unsafe() { #ifdef DEBUG_ENABLED - CRASH_COND(!base_ref); + CRASH_COND(!base_ref_counted); CRASH_COND(owner == nullptr); CRASH_COND(unsafe_referenced); // already referenced #endif @@ -1891,7 +1907,7 @@ bool CSharpInstance::_reference_owner_unsafe() { // See: _unreference_owner_unsafe() // May not me referenced yet, so we must use init_ref() instead of reference() - if (static_cast<Reference *>(owner)->init_ref()) { + if (static_cast<RefCounted *>(owner)->init_ref()) { CSharpLanguage::get_singleton()->post_unsafe_reference(owner); unsafe_referenced = true; } @@ -1901,7 +1917,7 @@ bool CSharpInstance::_reference_owner_unsafe() { bool CSharpInstance::_unreference_owner_unsafe() { #ifdef DEBUG_ENABLED - CRASH_COND(!base_ref); + CRASH_COND(!base_ref_counted); CRASH_COND(owner == nullptr); #endif @@ -1918,7 +1934,7 @@ bool CSharpInstance::_unreference_owner_unsafe() { // Destroying the owner here means self destructing, so we defer the owner destruction to the caller. CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner); - return static_cast<Reference *>(owner)->unreference(); + return static_cast<RefCounted *>(owner)->unreference(); } MonoObject *CSharpInstance::_internal_new_managed() { @@ -1950,7 +1966,7 @@ MonoObject *CSharpInstance::_internal_new_managed() { // Tie managed to unmanaged gchandle = MonoGCHandleData::new_strong_handle(mono_object); - if (base_ref) { + if (base_ref_counted) { _reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback) } @@ -1967,7 +1983,7 @@ void CSharpInstance::mono_object_disposed(MonoObject *p_obj) { disconnect_event_signals(); #ifdef DEBUG_ENABLED - CRASH_COND(base_ref); + CRASH_COND(base_ref_counted); CRASH_COND(gchandle.is_released()); #endif CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle); @@ -1975,7 +1991,7 @@ void CSharpInstance::mono_object_disposed(MonoObject *p_obj) { void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) { #ifdef DEBUG_ENABLED - CRASH_COND(!base_ref); + CRASH_COND(!base_ref_counted); CRASH_COND(gchandle.is_released()); #endif @@ -2010,8 +2026,8 @@ void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_f } void CSharpInstance::connect_event_signals() { - for (const Map<StringName, CSharpScript::EventSignal>::Element *E = script->event_signals.front(); E; E = E->next()) { - const CSharpScript::EventSignal &event_signal = E->value(); + for (const KeyValue<StringName, CSharpScript::EventSignal> &E : script->event_signals) { + const CSharpScript::EventSignal &event_signal = E.value; StringName signal_name = event_signal.field->get_name(); @@ -2025,8 +2041,7 @@ void CSharpInstance::connect_event_signals() { } void CSharpInstance::disconnect_event_signals() { - for (const List<Callable>::Element *E = connected_event_signals.front(); E; E = E->next()) { - const Callable &callable = E->get(); + for (const Callable &callable : connected_event_signals) { const EventSignalCallable *event_signal_callable = static_cast<const EventSignalCallable *>(callable.get_custom()); owner->disconnect(event_signal_callable->get_signal(), callable); } @@ -2036,13 +2051,13 @@ void CSharpInstance::disconnect_event_signals() { void CSharpInstance::refcount_incremented() { #ifdef DEBUG_ENABLED - CRASH_COND(!base_ref); + CRASH_COND(!base_ref_counted); CRASH_COND(owner == nullptr); #endif - Reference *ref_owner = Object::cast_to<Reference>(owner); + RefCounted *rc_owner = Object::cast_to<RefCounted>(owner); - if (ref_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 + if (rc_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 GD_MONO_SCOPE_THREAD_ATTACH; // The reference count was increased after the managed side was the only one referencing our owner. @@ -2058,13 +2073,13 @@ void CSharpInstance::refcount_incremented() { bool CSharpInstance::refcount_decremented() { #ifdef DEBUG_ENABLED - CRASH_COND(!base_ref); + CRASH_COND(!base_ref_counted); CRASH_COND(owner == nullptr); #endif - Reference *ref_owner = Object::cast_to<Reference>(owner); + RefCounted *rc_owner = Object::cast_to<RefCounted>(owner); - int refcount = ref_owner->reference_get_count(); + int refcount = rc_owner->reference_get_count(); if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 GD_MONO_SCOPE_THREAD_ATTACH; @@ -2085,46 +2100,10 @@ bool CSharpInstance::refcount_decremented() { return ref_dying; } -Vector<ScriptNetData> CSharpInstance::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> CSharpInstance::get_rpc_methods() const { return script->get_rpc_methods(); } -uint16_t CSharpInstance::get_rpc_method_id(const StringName &p_method) const { - return script->get_rpc_method_id(p_method); -} - -StringName CSharpInstance::get_rpc_method(const uint16_t p_rpc_method_id) const { - return script->get_rpc_method(p_rpc_method_id); -} - -MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const { - return script->get_rpc_mode_by_id(p_rpc_method_id); -} - -MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const { - return script->get_rpc_mode(p_method); -} - -Vector<ScriptNetData> CSharpInstance::get_rset_properties() const { - return script->get_rset_properties(); -} - -uint16_t CSharpInstance::get_rset_property_id(const StringName &p_variable) const { - return script->get_rset_property_id(p_variable); -} - -StringName CSharpInstance::get_rset_property(const uint16_t p_rset_member_id) const { - return script->get_rset_property(p_rset_member_id); -} - -MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode_by_id(const uint16_t p_rset_member_id) const { - return script->get_rset_mode_by_id(p_rset_member_id); -} - -MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const { - return script->get_rset_mode(p_variable); -} - void CSharpInstance::notification(int p_notification) { GD_MONO_SCOPE_THREAD_ATTACH; @@ -2135,12 +2114,12 @@ void CSharpInstance::notification(int p_notification) { predelete_notified = true; - if (base_ref) { - // It's not safe to proceed if the owner derives Reference and the refcount reached 0. + if (base_ref_counted) { + // It's not safe to proceed if the owner derives RefCounted and the refcount reached 0. // At this point, Dispose() was already called (manually or from the finalizer) so // that's not a problem. The refcount wouldn't have reached 0 otherwise, since the // managed side references it and Dispose() needs to be called to release it. - // However, this means C# Reference scripts can't receive NOTIFICATION_PREDELETE, but + // However, this means C# RefCounted scripts can't receive NOTIFICATION_PREDELETE, but // this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784 return; } @@ -2266,23 +2245,25 @@ CSharpInstance::~CSharpInstance() { } // If not being called from the owner's destructor, and we still hold a reference to the owner - if (base_ref && !ref_dying && owner && unsafe_referenced) { + if (base_ref_counted && !ref_dying && owner && unsafe_referenced) { // The owner's script or script instance is being replaced (or removed) // Transfer ownership to an "instance binding" - Reference *ref_owner = static_cast<Reference *>(owner); + RefCounted *rc_owner = static_cast<RefCounted *>(owner); // We will unreference the owner before referencing it again, so we need to keep it alive - Ref<Reference> scope_keep_owner_alive(ref_owner); + Ref<RefCounted> scope_keep_owner_alive(rc_owner); (void)scope_keep_owner_alive; // Unreference the owner here, before the new "instance binding" references it. // Otherwise, the unsafe reference debug checks will incorrectly detect a bug. bool die = _unreference_owner_unsafe(); CRASH_COND(die); // `owner_keep_alive` holds a reference, so it can't die - +#if 0 void *data = owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index()); + + CRASH_COND(data == nullptr); CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); @@ -2299,7 +2280,8 @@ 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(ref_owner->reference_get_count() <= 1); + CRASH_COND(rc_owner->reference_get_count() <= 1); +#endif #endif } @@ -2329,12 +2311,12 @@ void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List base_cache->_update_exports_values(values, propnames); } - for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) { - values[E->key()] = E->get(); + for (const KeyValue<StringName, Variant> &E : exported_members_defval_cache) { + values[E.key] = E.value; } - for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) { - propnames.push_back(E->get()); + for (const PropertyInfo &prop_info : exported_members_cache) { + propnames.push_back(prop_info); } } @@ -2386,7 +2368,7 @@ void CSharpScript::_update_member_info_no_exports() { } #endif -bool CSharpScript::_update_exports() { +bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_update) { #ifdef TOOLS_ENABLED bool is_editor = Engine::get_singleton()->is_editor_hint(); if (is_editor) { @@ -2527,7 +2509,7 @@ bool CSharpScript::_update_exports() { #ifdef TOOLS_ENABLED if (is_editor) { // Need to check this here, before disposal - bool base_ref = Object::cast_to<Reference>(tmp_native) != nullptr; + bool base_ref_counted = Object::cast_to<RefCounted>(tmp_native) != nullptr; // Dispose the temporary managed instance @@ -2542,7 +2524,7 @@ bool CSharpScript::_update_exports() { GDMonoUtils::free_gchandle(tmp_pinned_gchandle); tmp_object = nullptr; - if (tmp_native && !base_ref) { + if (tmp_native && !base_ref_counted) { Node *node = Object::cast_to<Node>(tmp_native); if (node && node->is_inside_tree()) { ERR_PRINT("Temporary instance was added to the scene tree."); @@ -2558,14 +2540,18 @@ bool CSharpScript::_update_exports() { if (is_editor) { placeholder_fallback_enabled = false; - if (placeholders.size()) { + if ((changed || p_instance_to_update) && placeholders.size()) { // Update placeholders if any Map<StringName, Variant> values; List<PropertyInfo> propnames; _update_exports_values(values, propnames); - for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { - E->get()->update(propnames, values); + if (changed) { + for (PlaceHolderScriptInstance *&script_instance : placeholders) { + script_instance->update(propnames, values); + } + } else { + p_instance_to_update->update(propnames, values); } } } @@ -3026,7 +3012,6 @@ void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) { p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native); p_script->rpc_functions.clear(); - p_script->rpc_variables.clear(); GDMonoClass *top = p_script->script_class; while (top && top != p_script->native) { @@ -3040,9 +3025,12 @@ void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) { if (!methods[i]->is_static()) { MultiplayerAPI::RPCMode mode = p_script->_member_get_rpc_mode(methods[i]); if (MultiplayerAPI::RPC_MODE_DISABLED != mode) { - ScriptNetData nd; + MultiplayerAPI::RPCConfig nd; nd.name = methods[i]->get_name(); - nd.mode = mode; + nd.rpc_mode = mode; + // TODO Transfer mode, channel + nd.transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE; + nd.channel = 0; if (-1 == p_script->rpc_functions.find(nd)) { p_script->rpc_functions.push_back(nd); } @@ -3051,51 +3039,16 @@ void CSharpScript::update_script_class_info(Ref<CSharpScript> p_script) { } } - { - Vector<GDMonoField *> fields = top->get_all_fields(); - for (int i = 0; i < fields.size(); i++) { - if (!fields[i]->is_static()) { - MultiplayerAPI::RPCMode mode = p_script->_member_get_rpc_mode(fields[i]); - if (MultiplayerAPI::RPC_MODE_DISABLED != mode) { - ScriptNetData nd; - nd.name = fields[i]->get_name(); - nd.mode = mode; - if (-1 == p_script->rpc_variables.find(nd)) { - p_script->rpc_variables.push_back(nd); - } - } - } - } - } - - { - Vector<GDMonoProperty *> properties = top->get_all_properties(); - for (int i = 0; i < properties.size(); i++) { - if (!properties[i]->is_static()) { - MultiplayerAPI::RPCMode mode = p_script->_member_get_rpc_mode(properties[i]); - if (MultiplayerAPI::RPC_MODE_DISABLED != mode) { - ScriptNetData nd; - nd.name = properties[i]->get_name(); - nd.mode = mode; - if (-1 == p_script->rpc_variables.find(nd)) { - p_script->rpc_variables.push_back(nd); - } - } - } - } - } - top = top->get_parent_class(); } // Sort so we are 100% that they are always the same. - p_script->rpc_functions.sort_custom<SortNetData>(); - p_script->rpc_variables.sort_custom<SortNetData>(); + p_script->rpc_functions.sort_custom<MultiplayerAPI::SortRPCConfig>(); p_script->load_script_signals(p_script->script_class, p_script->native); } -bool CSharpScript::can_instance() const { +bool CSharpScript::can_instantiate() const { #ifdef TOOLS_ENABLED bool extra_cond = tool || ScriptServer::is_scripting_enabled(); #else @@ -3126,7 +3079,7 @@ StringName CSharpScript::get_instance_base_type() const { } } -CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error) { +CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error) { GD_MONO_ASSERT_THREAD_ATTACHED; /* STEP 1, CREATE */ @@ -3142,12 +3095,12 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg ERR_FAIL_V_MSG(nullptr, "Constructor not found."); } - Ref<Reference> ref; - if (p_isref) { + Ref<RefCounted> ref; + if (p_is_ref_counted) { // Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance. - ref = Ref<Reference>(static_cast<Reference *>(p_owner)); + ref = Ref<RefCounted>(static_cast<RefCounted *>(p_owner)); } - +#if 0 // If the object had a script instance binding, dispose it before adding the CSharpInstance if (p_owner->has_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index())) { void *data = p_owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index()); @@ -3169,9 +3122,9 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg script_binding.inited = false; } } - +#endif CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(this))); - instance->base_ref = p_isref; + instance->base_ref_counted = p_is_ref_counted; instance->owner = p_owner; instance->owner->set_script_instance(instance); @@ -3196,7 +3149,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg // Tie managed to unmanaged instance->gchandle = MonoGCHandleData::new_strong_handle(mono_object); - if (instance->base_ref) { + if (instance->base_ref_counted) { instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback) } @@ -3228,10 +3181,10 @@ Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::Cal GD_MONO_SCOPE_THREAD_ATTACH; - Object *owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native)); + Object *owner = ClassDB::instantiate(NATIVE_GDMONOCLASS_NAME(native)); REF ref; - Reference *r = Object::cast_to<Reference>(owner); + RefCounted *r = Object::cast_to<RefCounted>(owner); if (r) { ref = REF(r); } @@ -3262,24 +3215,24 @@ 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 instanced in object of type: '" + p_this->get_class() + "'"); + "', 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 instanced in object of type: '" + p_this->get_class() + "'."); + "', so it can't be instantiated in object of type: '" + p_this->get_class() + "'."); } } GD_MONO_SCOPE_THREAD_ATTACH; Callable::CallError unchecked_error; - return _create_instance(nullptr, 0, p_this, Object::cast_to<Reference>(p_this) != nullptr, unchecked_error); + return _create_instance(nullptr, 0, p_this, Object::cast_to<RefCounted>(p_this) != nullptr, unchecked_error); } PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) { #ifdef TOOLS_ENABLED PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this)); placeholders.insert(si); - _update_exports(); + _update_exports(si); return si; #else return nullptr; @@ -3427,11 +3380,11 @@ bool CSharpScript::has_script_signal(const StringName &p_signal) const { } void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const { - for (const Map<StringName, Vector<SignalParameter>>::Element *E = _signals.front(); E; E = E->next()) { + for (const KeyValue<StringName, Vector<SignalParameter>> &E : _signals) { MethodInfo mi; - mi.name = E->key(); + mi.name = E.key; - const Vector<SignalParameter> ¶ms = E->value(); + const Vector<SignalParameter> ¶ms = E.value; for (int i = 0; i < params.size(); i++) { const SignalParameter ¶m = params[i]; @@ -3446,11 +3399,11 @@ void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const { r_signals->push_back(mi); } - for (const Map<StringName, EventSignal>::Element *E = event_signals.front(); E; E = E->next()) { + for (const KeyValue<StringName, EventSignal> &E : event_signals) { MethodInfo mi; - mi.name = E->key(); + mi.name = E.key; - const EventSignal &event_signal = E->value(); + const EventSignal &event_signal = E.value; const Vector<SignalParameter> ¶ms = event_signal.parameters; for (int i = 0; i < params.size(); i++) { const SignalParameter ¶m = params[i]; @@ -3490,8 +3443,8 @@ Ref<Script> CSharpScript::get_base_script() const { } void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const { - for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) { - p_list->push_back(E->value()); + for (const KeyValue<StringName, PropertyInfo> &E : member_info) { + p_list->push_back(E.value); } } @@ -3510,73 +3463,14 @@ MultiplayerAPI::RPCMode CSharpScript::_member_get_rpc_mode(IMonoClassMember *p_m if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute))) { return MultiplayerAPI::RPC_MODE_PUPPET; } - if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute))) { - return MultiplayerAPI::RPC_MODE_REMOTESYNC; - } - if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute))) { - return MultiplayerAPI::RPC_MODE_MASTERSYNC; - } - if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute))) { - return MultiplayerAPI::RPC_MODE_PUPPETSYNC; - } return MultiplayerAPI::RPC_MODE_DISABLED; } -Vector<ScriptNetData> CSharpScript::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> CSharpScript::get_rpc_methods() const { return rpc_functions; } -uint16_t CSharpScript::get_rpc_method_id(const StringName &p_method) const { - for (int i = 0; i < rpc_functions.size(); i++) { - if (rpc_functions[i].name == p_method) { - return i; - } - } - return UINT16_MAX; -} - -StringName CSharpScript::get_rpc_method(const uint16_t p_rpc_method_id) const { - ERR_FAIL_COND_V(p_rpc_method_id >= rpc_functions.size(), StringName()); - return rpc_functions[p_rpc_method_id].name; -} - -MultiplayerAPI::RPCMode CSharpScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const { - ERR_FAIL_COND_V(p_rpc_method_id >= rpc_functions.size(), MultiplayerAPI::RPC_MODE_DISABLED); - return rpc_functions[p_rpc_method_id].mode; -} - -MultiplayerAPI::RPCMode CSharpScript::get_rpc_mode(const StringName &p_method) const { - return get_rpc_mode_by_id(get_rpc_method_id(p_method)); -} - -Vector<ScriptNetData> CSharpScript::get_rset_properties() const { - return rpc_variables; -} - -uint16_t CSharpScript::get_rset_property_id(const StringName &p_variable) const { - for (int i = 0; i < rpc_variables.size(); i++) { - if (rpc_variables[i].name == p_variable) { - return i; - } - } - return UINT16_MAX; -} - -StringName CSharpScript::get_rset_property(const uint16_t p_rset_member_id) const { - ERR_FAIL_COND_V(p_rset_member_id >= rpc_variables.size(), StringName()); - return rpc_variables[p_rset_member_id].name; -} - -MultiplayerAPI::RPCMode CSharpScript::get_rset_mode_by_id(const uint16_t p_rset_member_id) const { - ERR_FAIL_COND_V(p_rset_member_id >= rpc_functions.size(), MultiplayerAPI::RPC_MODE_DISABLED); - return rpc_functions[p_rset_member_id].mode; -} - -MultiplayerAPI::RPCMode CSharpScript::get_rset_mode(const StringName &p_variable) const { - return get_rset_mode_by_id(get_rset_property_id(p_variable)); -} - Error CSharpScript::load_source_code(const String &p_path) { Error ferr = read_all_file_utf8(p_path, source); @@ -3633,8 +3527,8 @@ CSharpScript::~CSharpScript() { void CSharpScript::get_members(Set<StringName> *p_members) { #if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED) if (p_members) { - for (Set<StringName>::Element *E = exported_members_names.front(); E; E = E->next()) { - p_members->insert(E->get()); + for (const StringName &member_name : exported_members_names) { + p_members->insert(member_name); } } #endif diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index dd93a86d7a..da6b60aee2 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -136,8 +136,7 @@ private: Map<StringName, EventSignal> event_signals; bool signals_invalidated = true; - Vector<ScriptNetData> rpc_functions; - Vector<ScriptNetData> rpc_variables; + Vector<MultiplayerAPI::RPCConfig> rpc_functions; #ifdef TOOLS_ENABLED List<PropertyInfo> exported_members_cache; // members_cache @@ -164,14 +163,14 @@ private: void load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class); bool _get_signal(GDMonoClass *p_class, GDMonoMethod *p_delegate_invoke, Vector<SignalParameter> ¶ms); - bool _update_exports(); + bool _update_exports(PlaceHolderScriptInstance *p_instance_to_update = nullptr); bool _get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported); #ifdef TOOLS_ENABLED static int _try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string); #endif - CSharpInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error); + CSharpInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error); Variant _new(const Variant **p_args, int p_argcount, Callable::CallError &r_error); // Do not use unless you know what you are doing @@ -192,7 +191,7 @@ protected: void _get_property_list(List<PropertyInfo> *p_properties) const; public: - bool can_instance() const override; + bool can_instantiate() const override; StringName get_instance_base_type() const override; ScriptInstance *instance_create(Object *p_this) override; PlaceHolderScriptInstance *placeholder_instance_create(Object *p_this) override; @@ -235,17 +234,7 @@ public: int get_member_line(const StringName &p_member) const override; - Vector<ScriptNetData> get_rpc_methods() const override; - uint16_t get_rpc_method_id(const StringName &p_method) const override; - StringName get_rpc_method(const uint16_t p_rpc_method_id) const override; - MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override; - MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override; - - Vector<ScriptNetData> get_rset_properties() const override; - uint16_t get_rset_property_id(const StringName &p_variable) const override; - StringName get_rset_property(const uint16_t p_variable_id) const override; - MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const override; - MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override; + const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const override; #ifdef TOOLS_ENABLED bool is_placeholder_fallback_enabled() const override { return placeholder_fallback_enabled; } @@ -262,7 +251,7 @@ class CSharpInstance : public ScriptInstance { friend class CSharpLanguage; Object *owner = nullptr; - bool base_ref = false; + bool base_ref_counted = false; bool ref_dying = false; bool unsafe_referenced = false; bool predelete_notified = false; @@ -322,17 +311,7 @@ public: void refcount_incremented() override; bool refcount_decremented() override; - Vector<ScriptNetData> get_rpc_methods() const override; - uint16_t get_rpc_method_id(const StringName &p_method) const override; - StringName get_rpc_method(const uint16_t p_rpc_method_id) const override; - MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override; - MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override; - - Vector<ScriptNetData> get_rset_properties() const override; - uint16_t get_rset_property_id(const StringName &p_variable) const override; - StringName get_rset_property(const uint16_t p_variable_id) const override; - MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_variable_id) const override; - MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override; + const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const override; void notification(int p_notification) override; void _call_notification(int p_notification); @@ -470,14 +449,14 @@ public: /* EDITOR FUNCTIONS */ void get_reserved_words(List<String> *p_words) const override; + bool is_control_flow_keyword(String p_keyword) const override; void get_comment_delimiters(List<String> *p_delimiters) const override; void get_string_delimiters(List<String> *p_delimiters) const override; Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const override; bool is_using_templates() override; void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) override; - /* TODO */ bool validate(const String &p_script, int &r_line_error, int &r_col_error, - String &r_test_error, const String &p_path, List<String> *r_functions, - List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const override { + /* TODO */ bool validate(const String &p_script, const String &p_path, List<String> *r_functions, + List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const override { return true; } String validate_path(const String &p_path) const override; diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj index 224d7e5b5a..11d8e0f72b 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/Godot.SourceGenerators.csproj @@ -15,8 +15,9 @@ <PackageProjectUrl>$(RepositoryUrl)</PackageProjectUrl> <PackageLicenseExpression>MIT</PackageLicenseExpression> - <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <!-- Generates a package at build --> - <IncludeBuildOutput>false</IncludeBuildOutput> <!-- Do not include the generator as a lib dependency --> + <GeneratePackageOnBuild>true</GeneratePackageOnBuild> + <!-- Do not include the generator as a lib dependency --> + <IncludeBuildOutput>false</IncludeBuildOutput> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" /> diff --git a/modules/mono/editor/GodotTools/.gitignore b/modules/mono/editor/GodotTools/.gitignore index 48e2f914d8..a41d1c89b5 100644 --- a/modules/mono/editor/GodotTools/.gitignore +++ b/modules/mono/editor/GodotTools/.gitignore @@ -353,4 +353,3 @@ healthchecksdb # Backup folder for Package Reference Convert tool in Visual Studio 2017 MigrationBackup/ - diff --git a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs index 4db71500da..450c4bf0cb 100644 --- a/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs +++ b/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs @@ -113,8 +113,7 @@ namespace GodotTools.IdeMessaging.CLI } } - ExitMainLoop: - + ExitMainLoop: await forwarder.WriteLineToOutput("Event=Quit"); } diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs index cc0da44a13..284e94810a 100644 --- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/DotNetSolution.cs @@ -150,8 +150,8 @@ EndProject"; {"Tools|Any CPU", "ExportRelease|Any CPU"} }; - var regex = new Regex(string.Join("|",dict.Keys.Select(Regex.Escape))); - var result = regex.Replace(input,m => dict[m.Value]); + var regex = new Regex(string.Join("|", dict.Keys.Select(Regex.Escape))); + var result = regex.Replace(input, m => dict[m.Value]); if (result != input) { diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs index 51055dc9b9..27737c3da0 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildInfo.cs @@ -7,7 +7,7 @@ using Path = System.IO.Path; namespace GodotTools.Build { [Serializable] - public sealed class BuildInfo : Reference // TODO Remove Reference once we have proper serialization + public sealed class BuildInfo : RefCounted // TODO Remove RefCounted once we have proper serialization { public string Solution { get; } public string[] Targets { get; } diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs index 1a1639aac7..c380707587 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs @@ -11,7 +11,7 @@ namespace GodotTools.Build public class BuildOutputView : VBoxContainer, ISerializationListener { [Serializable] - private class BuildIssue : Reference // TODO Remove Reference once we have proper serialization + private class BuildIssue : RefCounted // TODO Remove RefCounted once we have proper serialization { public bool Warning { get; set; } public string File { get; set; } diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs index ed69c2b833..5f35d506de 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs @@ -11,6 +11,7 @@ namespace GodotTools.Build { public BuildOutputView BuildOutputView { get; private set; } + private MenuButton buildMenuBtn; private Button errorsBtn; private Button warningsBtn; private Button viewLogBtn; @@ -72,7 +73,7 @@ namespace GodotTools.Build GD.PushError("Failed to setup Godot NuGet Offline Packages: " + e.Message); } - if (!BuildManager.BuildProjectBlocking("Debug", targets: new[] {"Rebuild"})) + if (!BuildManager.BuildProjectBlocking("Debug", targets: new[] { "Rebuild" })) return; // Build failed // Notify running game for hot-reload @@ -91,7 +92,7 @@ namespace GodotTools.Build if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) return; // No solution to build - BuildManager.BuildProjectBlocking("Debug", targets: new[] {"Clean"}); + BuildManager.BuildProjectBlocking("Debug", targets: new[] { "Clean" }); } private void ViewLogToggled(bool pressed) => BuildOutputView.LogVisible = pressed; @@ -128,10 +129,10 @@ namespace GodotTools.Build RectMinSize = new Vector2(0, 228) * EditorScale; SizeFlagsVertical = (int)SizeFlags.ExpandFill; - var toolBarHBox = new HBoxContainer {SizeFlagsHorizontal = (int)SizeFlags.ExpandFill}; + var toolBarHBox = new HBoxContainer { SizeFlagsHorizontal = (int)SizeFlags.ExpandFill }; AddChild(toolBarHBox); - var buildMenuBtn = new MenuButton {Text = "Build", Icon = GetThemeIcon("Play", "EditorIcons")}; + buildMenuBtn = new MenuButton { Text = "Build", Icon = GetThemeIcon("Play", "EditorIcons") }; toolBarHBox.AddChild(buildMenuBtn); var buildMenu = buildMenuBtn.GetPopup(); @@ -177,5 +178,20 @@ namespace GodotTools.Build BuildOutputView = new BuildOutputView(); AddChild(BuildOutputView); } + + public override void _Notification(int what) + { + base._Notification(what); + + if (what == NotificationThemeChanged) + { + if (buildMenuBtn != null) + buildMenuBtn.Icon = GetThemeIcon("Play", "EditorIcons"); + if (errorsBtn != null) + errorsBtn.Icon = GetThemeIcon("StatusError", "EditorIcons"); + if (warningsBtn != null) + warningsBtn.Icon = GetThemeIcon("NodeWarning", "EditorIcons"); + } + } } } diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs index 5bb8d444c2..f69307104f 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Export/AotBuilder.cs @@ -577,27 +577,27 @@ MONO_AOT_MODE_LAST = 1000, { case OS.Platforms.Windows: case OS.Platforms.UWP: - { - string arch = bits == "64" ? "x86_64" : "i686"; - return $"windows-{arch}"; - } + { + string arch = bits == "64" ? "x86_64" : "i686"; + return $"windows-{arch}"; + } case OS.Platforms.MacOS: - { - Debug.Assert(bits == null || bits == "64"); - string arch = "x86_64"; - return $"{platform}-{arch}"; - } + { + Debug.Assert(bits == null || bits == "64"); + string arch = "x86_64"; + return $"{platform}-{arch}"; + } case OS.Platforms.LinuxBSD: case OS.Platforms.Server: - { - string arch = bits == "64" ? "x86_64" : "i686"; - return $"linux-{arch}"; - } + { + string arch = bits == "64" ? "x86_64" : "i686"; + return $"linux-{arch}"; + } case OS.Platforms.Haiku: - { - string arch = bits == "64" ? "x86_64" : "i686"; - return $"{platform}-{arch}"; - } + { + string arch = bits == "64" ? "x86_64" : "i686"; + return $"{platform}-{arch}"; + } default: throw new NotSupportedException($"Platform not supported: {platform}"); } diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs index 270be8b6bf..0b5aa72a81 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs @@ -76,9 +76,9 @@ namespace GodotTools.Export GlobalDef("mono/export/aot/use_interpreter", true); // --aot or --aot=opt1,opt2 (use 'mono --aot=help AuxAssembly.dll' to list AOT options) - GlobalDef("mono/export/aot/extra_aot_options", new string[] { }); + GlobalDef("mono/export/aot/extra_aot_options", Array.Empty<string>()); // --optimize/-O=opt1,opt2 (use 'mono --list-opt'' to list optimize options) - GlobalDef("mono/export/aot/extra_optimizer_options", new string[] { }); + GlobalDef("mono/export/aot/extra_optimizer_options", Array.Empty<string>()); GlobalDef("mono/export/aot/android_toolchain_path", ""); } @@ -188,7 +188,7 @@ namespace GodotTools.Export // However, at least in the case of 'WebAssembly.Net.Http' for some reason the BCL assemblies // reference a different version even though the assembly is the same, for some weird reason. - var wasmFrameworkAssemblies = new[] {"WebAssembly.Bindings", "WebAssembly.Net.WebSockets"}; + var wasmFrameworkAssemblies = new[] { "WebAssembly.Bindings", "WebAssembly.Net.WebSockets" }; foreach (string thisWasmFrameworkAssemblyName in wasmFrameworkAssemblies) { @@ -298,8 +298,8 @@ namespace GodotTools.Export LLVMOutputPath = "", FullAot = platform == OS.Platforms.iOS || (bool)(ProjectSettings.GetSetting("mono/export/aot/full_aot") ?? false), UseInterpreter = (bool)ProjectSettings.GetSetting("mono/export/aot/use_interpreter"), - ExtraAotOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_aot_options") ?? new string[] { }, - ExtraOptimizerOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_optimizer_options") ?? new string[] { }, + ExtraAotOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_aot_options") ?? Array.Empty<string>(), + ExtraOptimizerOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_optimizer_options") ?? Array.Empty<string>(), ToolchainPath = aotToolchainPath }; @@ -381,7 +381,7 @@ namespace GodotTools.Export private static bool PlatformHasTemplateDir(string platform) { // OSX export templates are contained in a zip, so we place our custom template inside it and let Godot do the rest. - return !new[] {OS.Platforms.MacOS, OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5}.Contains(platform); + return !new[] { OS.Platforms.MacOS, OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5 }.Contains(platform); } private static bool DeterminePlatformFromFeatures(IEnumerable<string> features, out string platform) @@ -430,7 +430,7 @@ namespace GodotTools.Export /// </summary> private static bool PlatformRequiresCustomBcl(string platform) { - if (new[] {OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5}.Contains(platform)) + if (new[] { OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5 }.Contains(platform)) return true; // The 'net_4_x' BCL is not compatible between Windows and the other platforms. diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs index 58561c5097..1faa6eeac0 100644 --- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs +++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs @@ -26,8 +26,6 @@ namespace GodotTools private PopupMenu menuPopup; private AcceptDialog errorDialog; - private AcceptDialog aboutDialog; - private CheckBox aboutDialogCheckBox; private Button bottomPanelBtn; private Button toolBarBuildButton; @@ -130,13 +128,6 @@ namespace GodotTools toolBarBuildButton.Show(); } - private void _ShowAboutDialog() - { - bool showOnStart = (bool)editorSettings.GetSetting("mono/editor/show_info_on_start"); - aboutDialogCheckBox.Pressed = showOnStart; - aboutDialog.PopupCentered(); - } - private void _MenuOptionPressed(int id) { switch ((MenuOptions)id) @@ -144,9 +135,6 @@ namespace GodotTools case MenuOptions.CreateSln: CreateProjectSolution(); break; - case MenuOptions.AboutCSharp: - _ShowAboutDialog(); - break; case MenuOptions.SetupGodotNugetFallbackFolder: { try @@ -183,21 +171,11 @@ namespace GodotTools base._Ready(); MSBuildPanel.BuildOutputView.BuildStateChanged += BuildStateChanged; - - bool showInfoDialog = (bool)editorSettings.GetSetting("mono/editor/show_info_on_start"); - if (showInfoDialog) - { - aboutDialog.Exclusive = true; - _ShowAboutDialog(); - // Once shown a first time, it can be seen again via the Mono menu - it doesn't have to be exclusive from that time on. - aboutDialog.Exclusive = false; - } } private enum MenuOptions { CreateSln, - AboutCSharp, SetupGodotNugetFallbackFolder, } @@ -371,7 +349,7 @@ namespace GodotTools return (ExternalEditorId)editorSettings.GetSetting("mono/editor/external_editor") != ExternalEditorId.None; } - public override bool Build() + public override bool _Build() { return BuildManager.EditorBuildCallback(); } @@ -413,9 +391,9 @@ namespace GodotTools bottomPanelBtn.Icon = MSBuildPanel.BuildOutputView.BuildStateIcon; } - public override void EnablePlugin() + public override void _EnablePlugin() { - base.EnablePlugin(); + base._EnablePlugin(); if (Instance != null) throw new InvalidOperationException(); @@ -439,57 +417,6 @@ namespace GodotTools AddToolSubmenuItem("C#", menuPopup); - // TODO: Remove or edit this info dialog once Mono support is no longer in alpha - { - menuPopup.AddItem("About C# support".TTR(), (int)MenuOptions.AboutCSharp); - menuPopup.AddItem("Setup Godot NuGet Offline Packages".TTR(), (int)MenuOptions.SetupGodotNugetFallbackFolder); - aboutDialog = new AcceptDialog(); - editorBaseControl.AddChild(aboutDialog); - aboutDialog.Title = "Important: C# support is not feature-complete"; - - // We don't use DialogText as the default AcceptDialog Label doesn't play well with the TextureRect and CheckBox - // we'll add. Instead we add containers and a new autowrapped Label inside. - - // Main VBoxContainer (icon + label on top, checkbox at bottom) - var aboutVBox = new VBoxContainer(); - aboutDialog.AddChild(aboutVBox); - - // HBoxContainer for icon + label - var aboutHBox = new HBoxContainer(); - aboutVBox.AddChild(aboutHBox); - - var aboutIcon = new TextureRect(); - aboutIcon.Texture = aboutIcon.GetThemeIcon("NodeWarning", "EditorIcons"); - aboutHBox.AddChild(aboutIcon); - - var aboutLabel = new Label(); - aboutHBox.AddChild(aboutLabel); - aboutLabel.RectMinSize = new Vector2(600, 150) * EditorScale; - aboutLabel.SizeFlagsVertical = (int)Control.SizeFlags.ExpandFill; - aboutLabel.Autowrap = true; - aboutLabel.Text = - "C# support in Godot Engine is in late alpha stage and, while already usable, " + - "it is not meant for use in production.\n\n" + - "Projects can be exported to Linux, macOS, Windows, Android, iOS and HTML5, but not yet to UWP. " + - "Bugs and usability issues will be addressed gradually over future releases, " + - "potentially including compatibility breaking changes as new features are implemented for a better overall C# experience.\n\n" + - "If you experience issues with this Mono build, please report them on Godot's issue tracker with details about your system, MSBuild version, IDE, etc.:\n\n" + - " https://github.com/godotengine/godot/issues\n\n" + - "Your critical feedback at this stage will play a great role in shaping the C# support in future releases, so thank you!"; - - EditorDef("mono/editor/show_info_on_start", true); - - // CheckBox in main container - aboutDialogCheckBox = new CheckBox {Text = "Show this warning when starting the editor"}; - aboutDialogCheckBox.Toggled += enabled => - { - bool showOnStart = (bool)editorSettings.GetSetting("mono/editor/show_info_on_start"); - if (showOnStart != enabled) - editorSettings.SetSetting("mono/editor/show_info_on_start", enabled); - }; - aboutVBox.AddChild(aboutDialogCheckBox); - } - toolBarBuildButton = new Button { Text = "Build", diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj index 3f14629b11..b9aa760f4d 100644 --- a/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj +++ b/modules/mono/editor/GodotTools/GodotTools/GodotTools.csproj @@ -3,7 +3,8 @@ <ProjectGuid>{27B00618-A6F2-4828-B922-05CAEB08C286}</ProjectGuid> <TargetFramework>net472</TargetFramework> <LangVersion>7.2</LangVersion> - <GodotApiConfiguration>Debug</GodotApiConfiguration> <!-- The Godot editor uses the Debug Godot API assemblies --> + <!-- The Godot editor uses the Debug Godot API assemblies --> + <GodotApiConfiguration>Debug</GodotApiConfiguration> <GodotSourceRootPath>$(SolutionDir)/../../../../</GodotSourceRootPath> <GodotOutputDataDir>$(GodotSourceRootPath)/bin/GodotSharp</GodotOutputDataDir> <GodotApiAssembliesDir>$(GodotOutputDataDir)/Api/$(GodotApiConfiguration)</GodotApiAssembliesDir> diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs index 94fc5da425..821532f759 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs @@ -47,7 +47,7 @@ namespace GodotTools.Ides.Rider GD.PushWarning(e.Message); } - return new RiderInfo[0]; + return Array.Empty<RiderInfo>(); } private static RiderInfo[] CollectAllRiderPathsLinux() @@ -249,7 +249,7 @@ namespace GodotTools.Ides.Rider bool isMac) { if (!Directory.Exists(toolboxRiderRootPath)) - return new string[0]; + return Array.Empty<string>(); var channelDirs = Directory.GetDirectories(toolboxRiderRootPath); var paths = channelDirs.SelectMany(channelDir => @@ -295,7 +295,7 @@ namespace GodotTools.Ides.Rider Logger.Warn($"Failed to get RiderPath from {channelDir}", e); } - return new string[0]; + return Array.Empty<string>(); }) .Where(c => !string.IsNullOrEmpty(c)) .ToArray(); @@ -306,7 +306,7 @@ namespace GodotTools.Ides.Rider { var folder = new DirectoryInfo(Path.Combine(buildDir, dirName)); if (!folder.Exists) - return new string[0]; + return Array.Empty<string>(); if (!isMac) return new[] { Path.Combine(folder.FullName, searchPattern) }.Where(File.Exists).ToArray(); diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs index ed25cdaa63..60dd565ef2 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathManager.cs @@ -57,7 +57,7 @@ namespace GodotTools.Ides.Rider public static bool IsExternalEditorSetToRider(EditorSettings editorSettings) { - return editorSettings.HasSetting(EditorPathSettingName) && IsRider((string) editorSettings.GetSetting(EditorPathSettingName)); + return editorSettings.HasSetting(EditorPathSettingName) && IsRider((string)editorSettings.GetSetting(EditorPathSettingName)); } public static bool IsRider(string path) diff --git a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs index e745966435..4624439665 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Utils/OS.cs @@ -74,10 +74,10 @@ namespace GodotTools.Utils } private static readonly IEnumerable<string> LinuxBSDPlatforms = - new[] {Names.Linux, Names.FreeBSD, Names.NetBSD, Names.BSD}; + new[] { Names.Linux, Names.FreeBSD, Names.NetBSD, Names.BSD }; private static readonly IEnumerable<string> UnixLikePlatforms = - new[] {Names.MacOS, Names.Server, Names.Haiku, Names.Android, Names.iOS} + new[] { Names.MacOS, Names.Server, Names.Haiku, Names.Android, Names.iOS } .Concat(LinuxBSDPlatforms).ToArray(); private static readonly Lazy<bool> _isWindows = new Lazy<bool>(() => IsOS(Names.Windows)); @@ -111,13 +111,22 @@ namespace GodotTools.Utils private static string PathWhichWindows([NotNull] string name) { - string[] windowsExts = Environment.GetEnvironmentVariable("PATHEXT")?.Split(PathSep) ?? new string[] { }; + string[] windowsExts = Environment.GetEnvironmentVariable("PATHEXT")?.Split(PathSep) ?? Array.Empty<string>(); string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep); + char[] invalidPathChars = Path.GetInvalidPathChars(); var searchDirs = new List<string>(); if (pathDirs != null) - searchDirs.AddRange(pathDirs); + { + foreach (var pathDir in pathDirs) + { + if (pathDir.IndexOfAny(invalidPathChars) != -1) + continue; + + searchDirs.Add(pathDir); + } + } string nameExt = Path.GetExtension(name); bool hasPathExt = !string.IsNullOrEmpty(nameExt) && windowsExts.Contains(nameExt, StringComparer.OrdinalIgnoreCase); @@ -128,20 +137,29 @@ namespace GodotTools.Utils return searchDirs.Select(dir => Path.Combine(dir, name)).FirstOrDefault(File.Exists); return (from dir in searchDirs - select Path.Combine(dir, name) + select Path.Combine(dir, name) into path - from ext in windowsExts - select path + ext).FirstOrDefault(File.Exists); + from ext in windowsExts + select path + ext).FirstOrDefault(File.Exists); } private static string PathWhichUnix([NotNull] string name) { string[] pathDirs = Environment.GetEnvironmentVariable("PATH")?.Split(PathSep); + char[] invalidPathChars = Path.GetInvalidPathChars(); var searchDirs = new List<string>(); if (pathDirs != null) - searchDirs.AddRange(pathDirs); + { + foreach (var pathDir in pathDirs) + { + if (pathDir.IndexOfAny(invalidPathChars) != -1) + continue; + + searchDirs.Add(pathDir); + } + } searchDirs.Add(System.IO.Directory.GetCurrentDirectory()); // last in the list @@ -196,7 +214,7 @@ namespace GodotTools.Utils startInfo.UseShellExecute = false; - using (var process = new Process {StartInfo = startInfo}) + using (var process = new Process { StartInfo = startInfo }) { process.Start(); process.WaitForExit(); diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index b48e5df9eb..632f7d61cc 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -35,8 +35,8 @@ #include "core/config/engine.h" #include "core/core_constants.h" #include "core/io/compression.h" -#include "core/os/dir_access.h" -#include "core/os/file_access.h" +#include "core/io/dir_access.h" +#include "core/io/file_access.h" #include "core/os/os.h" #include "core/string/ucaps.h" #include "main/main.h" @@ -416,8 +416,8 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf // Try to find as global enum constant const EnumInterface *target_ienum = nullptr; - for (const List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) { - target_ienum = &E->get(); + for (const EnumInterface &ienum : global_enums) { + target_ienum = &ienum; target_iconst = find_constant_by_name(target_name, target_ienum->constants); if (target_iconst) { break; @@ -455,8 +455,8 @@ String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterf // Try to find as enum constant in the current class const EnumInterface *target_ienum = nullptr; - for (const List<EnumInterface>::Element *E = target_itype->enums.front(); E; E = E->next()) { - target_ienum = &E->get(); + for (const EnumInterface &ienum : target_itype->enums) { + target_ienum = &ienum; target_iconst = find_constant_by_name(target_name, target_ienum->constants); if (target_iconst) { break; @@ -655,9 +655,7 @@ int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) { return 0; } - for (const List<ConstantInterface>::Element *E = p_ienum.constants.front()->next(); E; E = E->next()) { - const ConstantInterface &iconstant = E->get(); - + for (const ConstantInterface &iconstant : p_ienum.constants) { Vector<String> parts = iconstant.name.split("_", /* p_allow_empty: */ true); int i; @@ -682,12 +680,10 @@ int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) { void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumInterface &p_ienum, int p_prefix_length) { if (p_prefix_length > 0) { - for (List<ConstantInterface>::Element *E = p_ienum.constants.front(); E; E = E->next()) { + for (ConstantInterface &iconstant : p_ienum.constants) { int curr_prefix_length = p_prefix_length; - ConstantInterface &curr_const = E->get(); - - String constant_name = curr_const.name; + String constant_name = iconstant.name; Vector<String> parts = constant_name.split("_", /* p_allow_empty: */ true); @@ -713,15 +709,13 @@ void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumI constant_name += parts[i]; } - curr_const.proxy_name = snake_to_pascal_case(constant_name, true); + iconstant.proxy_name = snake_to_pascal_case(constant_name, true); } } } void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) { - for (const List<MethodInterface>::Element *E = p_itype.methods.front(); E; E = E->next()) { - const MethodInterface &imethod = E->get(); - + for (const MethodInterface &imethod : p_itype.methods) { if (imethod.is_virtual) { continue; } @@ -735,8 +729,8 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) { // Get arguments information int i = 0; - for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) { - const TypeInterface *arg_type = _get_type_or_placeholder(F->get().type); + for (const ArgumentInterface &iarg : imethod.arguments) { + const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type); im_sig += ", "; im_sig += arg_type->im_type_in; @@ -776,10 +770,10 @@ void BindingsGenerator::_generate_method_icalls(const TypeInterface &p_itype) { if (p_itype.api_type != ClassDB::API_EDITOR) { match->get().editor_only = false; } - method_icalls_map.insert(&E->get(), &match->get()); + method_icalls_map.insert(&imethod, &match->get()); } else { List<InternalCall>::Element *added = method_icalls.push_back(im_icall); - method_icalls_map.insert(&E->get(), &added->get()); + method_icalls_map.insert(&imethod, &added->get()); } } } @@ -859,9 +853,7 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) { p_output.append("namespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); p_output.append(INDENT1 "public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n" INDENT1 "{"); - for (const List<ConstantInterface>::Element *E = global_constants.front(); E; E = E->next()) { - const ConstantInterface &iconstant = E->get(); - + for (const ConstantInterface &iconstant : global_constants) { if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr); Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); @@ -894,9 +886,7 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) { // Enums - for (List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) { - const EnumInterface &ienum = E->get(); - + for (const EnumInterface &ienum : global_enums) { CRASH_COND(ienum.constants.is_empty()); String enum_proxy_name = ienum.cname.operator String(); @@ -921,9 +911,8 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) { p_output.append(enum_proxy_name); p_output.append("\n" INDENT1 OPEN_BLOCK); - for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) { - const ConstantInterface &iconstant = F->get(); - + const ConstantInterface &last = ienum.constants.back()->get(); + for (const ConstantInterface &iconstant : ienum.constants) { if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr); Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); @@ -945,7 +934,7 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) { p_output.append(iconstant.proxy_name); p_output.append(" = "); p_output.append(itos(iconstant.value)); - p_output.append(F != ienum.constants.back() ? ",\n" : "\n"); + p_output.append(&iconstant != &last ? ",\n" : "\n"); } p_output.append(INDENT1 CLOSE_BLOCK); @@ -1053,11 +1042,11 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) { cs_icalls_content.append(m_icall.im_sig + ");\n"); \ } - for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next()) { - ADD_INTERNAL_CALL(E->get()); + for (const InternalCall &internal_call : core_custom_icalls) { + ADD_INTERNAL_CALL(internal_call); } - for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) { - ADD_INTERNAL_CALL(E->get()); + for (const InternalCall &internal_call : method_icalls) { + ADD_INTERNAL_CALL(internal_call); } #undef ADD_INTERNAL_CALL @@ -1161,11 +1150,11 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) { cs_icalls_content.append(m_icall.im_sig + ");\n"); \ } - for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next()) { - ADD_INTERNAL_CALL(E->get()); + for (const InternalCall &internal_call : editor_custom_icalls) { + ADD_INTERNAL_CALL(internal_call); } - for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) { - ADD_INTERNAL_CALL(E->get()); + for (const InternalCall &internal_call : method_icalls) { + ADD_INTERNAL_CALL(internal_call); } #undef ADD_INTERNAL_CALL @@ -1260,7 +1249,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str CRASH_COND(itype.cname != name_cache.type_Object); CRASH_COND(!itype.is_instantiable); CRASH_COND(itype.api_type != ClassDB::API_CORE); - CRASH_COND(itype.is_reference); + CRASH_COND(itype.is_ref_counted); CRASH_COND(itype.is_singleton); } @@ -1327,9 +1316,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str // Add constants - for (const List<ConstantInterface>::Element *E = itype.constants.front(); E; E = E->next()) { - const ConstantInterface &iconstant = E->get(); - + for (const ConstantInterface &iconstant : itype.constants) { if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype); Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); @@ -1360,18 +1347,15 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str // Add enums - for (const List<EnumInterface>::Element *E = itype.enums.front(); E; E = E->next()) { - const EnumInterface &ienum = E->get(); - + for (const EnumInterface &ienum : itype.enums) { ERR_FAIL_COND_V(ienum.constants.is_empty(), ERR_BUG); output.append(MEMBER_BEGIN "public enum "); output.append(ienum.cname.operator String()); output.append(MEMBER_BEGIN OPEN_BLOCK); - for (const List<ConstantInterface>::Element *F = ienum.constants.front(); F; F = F->next()) { - const ConstantInterface &iconstant = F->get(); - + const ConstantInterface &last = ienum.constants.back()->get(); + for (const ConstantInterface &iconstant : ienum.constants) { if (iconstant.const_doc && iconstant.const_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype); Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); @@ -1393,7 +1377,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str output.append(iconstant.proxy_name); output.append(" = "); output.append(itos(iconstant.value)); - output.append(F != ienum.constants.back() ? ",\n" : "\n"); + output.append(&iconstant != &last ? ",\n" : "\n"); } output.append(INDENT2 CLOSE_BLOCK); @@ -1401,8 +1385,7 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str // Add properties - for (const List<PropertyInterface>::Element *E = itype.properties.front(); E; E = E->next()) { - const PropertyInterface &iprop = E->get(); + for (const PropertyInterface &iprop : itype.properties) { Error prop_err = _generate_cs_property(itype, iprop, output); ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err, "Failed to generate property '" + iprop.cname.operator String() + @@ -1463,15 +1446,13 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str } int method_bind_count = 0; - for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) { - const MethodInterface &imethod = E->get(); + for (const MethodInterface &imethod : itype.methods) { Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output); ERR_FAIL_COND_V_MSG(method_err != OK, method_err, "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'."); } - for (const List<SignalInterface>::Element *E = itype.signals_.front(); E; E = E->next()) { - const SignalInterface &isignal = E->get(); + for (const SignalInterface &isignal : itype.signals_) { Error method_err = _generate_cs_signal(itype, isignal, output); ERR_FAIL_COND_V_MSG(method_err != OK, method_err, "Failed to generate signal '" + isignal.name + "' for class '" + itype.name + "'."); @@ -1678,8 +1659,8 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf StringBuilder default_args_doc; // Retrieve information from the arguments - for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { - const ArgumentInterface &iarg = F->get(); + const ArgumentInterface &first = p_imethod.arguments.front()->get(); + for (const ArgumentInterface &iarg : p_imethod.arguments) { const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type); ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG, @@ -1699,7 +1680,7 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf // Add the current arguments to the signature // If the argument has a default value which is not a constant, we will make it Nullable { - if (F != p_imethod.arguments.front()) { + if (&iarg != &first) { arguments_sig += ", "; } @@ -1754,7 +1735,12 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf cs_in_statements += " : "; } - String def_arg = sformat(iarg.default_argument, arg_type->cs_type); + String cs_type = arg_type->cs_type; + if (cs_type.ends_with("[]")) { + cs_type = cs_type.substr(0, cs_type.length() - 2); + } + + String def_arg = sformat(iarg.default_argument, cs_type); cs_in_statements += def_arg; cs_in_statements += ";\n" INDENT3; @@ -1763,8 +1749,10 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf // Apparently the name attribute must not include the @ String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1, iarg.name.length()) : iarg.name; + // Escape < and > in the attribute default value + String param_def_arg = def_arg.replacen("<", "<").replacen(">", ">"); - default_args_doc.append(MEMBER_BEGIN "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is " + def_arg + "</param>"); + default_args_doc.append(MEMBER_BEGIN "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is " + param_def_arg + "</param>"); } else { icall_params += arg_type->cs_in.is_empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name); } @@ -1855,9 +1843,9 @@ Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterf p_output.append(p_imethod.name); p_output.append("\""); - for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { + for (const ArgumentInterface &iarg : p_imethod.arguments) { p_output.append(", "); - p_output.append(F->get().name); + p_output.append(iarg.name); } p_output.append(");\n" CLOSE_BLOCK_L2); @@ -1899,8 +1887,8 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf String arguments_sig; // Retrieve information from the arguments - for (const List<ArgumentInterface>::Element *F = p_isignal.arguments.front(); F; F = F->next()) { - const ArgumentInterface &iarg = F->get(); + const ArgumentInterface &first = p_isignal.arguments.front()->get(); + for (const ArgumentInterface &iarg : p_isignal.arguments) { const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type); ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG, @@ -1914,7 +1902,7 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf // Add the current arguments to the signature - if (F != p_isignal.arguments.front()) { + if (&iarg != &first) { arguments_sig += ", "; } @@ -2042,8 +2030,7 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); // Used only for derived types - for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) { - const MethodInterface &imethod = E->get(); + for (const MethodInterface &imethod : itype.methods) { Error method_err = _generate_glue_method(itype, imethod, output); ERR_FAIL_COND_V_MSG(method_err != OK, method_err, "Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'."); @@ -2114,20 +2101,20 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { } bool tools_sequence = false; - for (const List<InternalCall>::Element *E = core_custom_icalls.front(); E; E = E->next()) { + for (const InternalCall &internal_call : core_custom_icalls) { if (tools_sequence) { - if (!E->get().editor_only) { + if (!internal_call.editor_only) { tools_sequence = false; output.append("#endif\n"); } } else { - if (E->get().editor_only) { + if (internal_call.editor_only) { output.append("#ifdef TOOLS_ENABLED\n"); tools_sequence = true; } } - ADD_INTERNAL_CALL_REGISTRATION(E->get()); + ADD_INTERNAL_CALL_REGISTRATION(internal_call); } if (tools_sequence) { @@ -2136,24 +2123,24 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { } output.append("#ifdef TOOLS_ENABLED\n"); - for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next()) - ADD_INTERNAL_CALL_REGISTRATION(E->get()); + for (const InternalCall &internal_call : editor_custom_icalls) + ADD_INTERNAL_CALL_REGISTRATION(internal_call); output.append("#endif // TOOLS_ENABLED\n"); - for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) { + for (const InternalCall &internal_call : method_icalls) { if (tools_sequence) { - if (!E->get().editor_only) { + if (!internal_call.editor_only) { tools_sequence = false; output.append("#endif\n"); } } else { - if (E->get().editor_only) { + if (internal_call.editor_only) { output.append("#ifdef TOOLS_ENABLED\n"); tools_sequence = true; } } - ADD_INTERNAL_CALL_REGISTRATION(E->get()); + ADD_INTERNAL_CALL_REGISTRATION(internal_call); } if (tools_sequence) { @@ -2209,8 +2196,7 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte // Get arguments information int i = 0; - for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { - const ArgumentInterface &iarg = F->get(); + for (const ArgumentInterface &iarg : p_imethod.arguments) { const TypeInterface *arg_type = _get_type_or_placeholder(iarg.type); String c_param_name = "arg" + itos(i + 1); @@ -2284,8 +2270,8 @@ Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInte } if (return_type->is_object_type) { - ptrcall_return_type = return_type->is_reference ? "Ref<Reference>" : return_type->c_type; - initialization = return_type->is_reference ? "" : " = nullptr"; + ptrcall_return_type = return_type->is_ref_counted ? "Ref<RefCounted>" : return_type->c_type; + initialization = return_type->is_ref_counted ? "" : " = nullptr"; } else { ptrcall_return_type = return_type->c_type; } @@ -2520,10 +2506,10 @@ bool BindingsGenerator::_arg_default_value_is_assignable_to_type(const Variant & p_arg_type.name == name_cache.type_NodePath; case Variant::NODE_PATH: return p_arg_type.name == name_cache.type_NodePath; - case Variant::TRANSFORM: case Variant::TRANSFORM2D: + case Variant::TRANSFORM3D: case Variant::BASIS: - case Variant::QUAT: + case Variant::QUATERNION: case Variant::PLANE: case Variant::AABB: case Variant::COLOR: @@ -2600,12 +2586,12 @@ bool BindingsGenerator::_populate_object_type_interfaces() { itype.base_name = ClassDB::get_parent_class(type_cname); itype.is_singleton = Engine::get_singleton()->has_singleton(itype.proxy_name); itype.is_instantiable = class_info->creation_func && !itype.is_singleton; - itype.is_reference = ClassDB::is_parent_class(type_cname, name_cache.type_Reference); - itype.memory_own = itype.is_reference; + itype.is_ref_counted = ClassDB::is_parent_class(type_cname, name_cache.type_RefCounted); + itype.memory_own = itype.is_ref_counted; itype.c_out = "\treturn "; itype.c_out += C_METHOD_UNMANAGED_GET_MANAGED; - itype.c_out += itype.is_reference ? "(%1.ptr());\n" : "(%1);\n"; + itype.c_out += itype.is_ref_counted ? "(%1.ptr());\n" : "(%1);\n"; itype.cs_in = itype.is_singleton ? BINDINGS_PTR_FIELD : "Object." CS_SMETHOD_GETINSTANCE "(%0)"; @@ -2623,9 +2609,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() { Map<StringName, StringName> accessor_methods; - for (const List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) { - const PropertyInfo &property = E->get(); - + for (const PropertyInfo &property : property_list) { if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY) { continue; } @@ -2684,9 +2668,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() { ClassDB::get_method_list(type_cname, &method_list, true); method_list.sort(); - for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) { - const MethodInfo &method_info = E->get(); - + for (const MethodInfo &method_info : method_list) { int argc = method_info.arguments.size(); if (method_info.name.is_empty()) { @@ -2741,7 +2723,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() { imethod.return_type.cname = return_info.class_name; bool bad_reference_hint = !imethod.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE && - ClassDB::is_parent_class(return_info.class_name, name_cache.type_Reference); + ClassDB::is_parent_class(return_info.class_name, name_cache.type_RefCounted); ERR_FAIL_COND_V_MSG(bad_reference_hint, false, String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." + " Are you returning a reference type by pointer? Method: '" + itype.name + "." + imethod.name + "'."); @@ -2840,9 +2822,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() { // Classes starting with an underscore are ignored unless they're used as a property setter or getter if (!imethod.is_virtual && imethod.name[0] == '_') { - for (const List<PropertyInterface>::Element *F = itype.properties.front(); F; F = F->next()) { - const PropertyInterface &iprop = F->get(); - + for (const PropertyInterface &iprop : itype.properties) { if (iprop.setter == imethod.name || iprop.getter == imethod.name) { imethod.is_internal = true; itype.methods.push_back(imethod); @@ -2952,8 +2932,7 @@ bool BindingsGenerator::_populate_object_type_interfaces() { } EnumInterface ienum(enum_proxy_cname); const List<StringName> &enum_constants = enum_map.get(*k); - for (const List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) { - const StringName &constant_cname = E->get(); + for (const StringName &constant_cname : enum_constants) { String constant_name = constant_cname.operator String(); int *value = class_info->constant_map.getptr(constant_cname); ERR_FAIL_NULL_V(value, false); @@ -2989,9 +2968,8 @@ bool BindingsGenerator::_populate_object_type_interfaces() { enum_types.insert(enum_itype.cname, enum_itype); } - for (const List<String>::Element *E = constants.front(); E; E = E->next()) { - const String &constant_name = E->get(); - int *value = class_info->constant_map.getptr(StringName(E->get())); + for (const String &constant_name : constants) { + int *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); @@ -3053,28 +3031,25 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar break; case Variant::PLANE: { Plane plane = p_val.operator Plane(); - r_iarg.default_argument = "new Plane(new Vector3(" + plane.normal.operator String() + "), " + rtos(plane.d) + ")"; + r_iarg.default_argument = "new Plane(new Vector3" + plane.normal.operator String() + ", " + rtos(plane.d) + ")"; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; case Variant::AABB: { AABB aabb = p_val.operator ::AABB(); - r_iarg.default_argument = "new AABB(new Vector3(" + aabb.position.operator String() + "), new Vector3(" + aabb.position.operator String() + "))"; + r_iarg.default_argument = "new AABB(new Vector3" + aabb.position.operator String() + ", new Vector3" + aabb.size.operator String() + ")"; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; case Variant::RECT2: { Rect2 rect = p_val.operator Rect2(); - r_iarg.default_argument = "new Rect2(new Vector2(" + rect.position.operator String() + "), new Vector2(" + rect.position.operator String() + "))"; + r_iarg.default_argument = "new Rect2(new Vector2" + rect.position.operator String() + ", new Vector2" + rect.size.operator String() + ")"; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; case Variant::RECT2I: { Rect2i rect = p_val.operator Rect2i(); - r_iarg.default_argument = "new Rect2i(new Vector2i(" + rect.position.operator String() + "), new Vector2i(" + rect.position.operator String() + "))"; + r_iarg.default_argument = "new Rect2i(new Vector2i" + rect.position.operator String() + ", new Vector2i" + rect.size.operator String() + ")"; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; case Variant::COLOR: - r_iarg.default_argument = "new %s(" + r_iarg.default_argument + ")"; - r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; - break; case Variant::VECTOR2: case Variant::VECTOR2I: case Variant::VECTOR3: @@ -3102,6 +3077,9 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar r_iarg.default_argument = "null"; break; case Variant::ARRAY: + r_iarg.default_argument = "new %s { }"; + r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF; + break; case Variant::PACKED_BYTE_ARRAY: case Variant::PACKED_INT32_ARRAY: case Variant::PACKED_INT64_ARRAY: @@ -3111,7 +3089,7 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar case Variant::PACKED_VECTOR2_ARRAY: case Variant::PACKED_VECTOR3_ARRAY: case Variant::PACKED_COLOR_ARRAY: - r_iarg.default_argument = "new %s {}"; + r_iarg.default_argument = "Array.Empty<%s>()"; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF; break; case Variant::TRANSFORM2D: { @@ -3123,13 +3101,13 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar } r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; - case Variant::TRANSFORM: { - Transform transform = p_val.operator Transform(); - if (transform == Transform()) { - r_iarg.default_argument = "Transform.Identity"; + case Variant::TRANSFORM3D: { + Transform3D transform = p_val.operator Transform3D(); + if (transform == Transform3D()) { + r_iarg.default_argument = "Transform3D.Identity"; } else { Basis basis = transform.basis; - r_iarg.default_argument = "new Transform(new Vector3" + basis.get_column(0).operator String() + ", new Vector3" + basis.get_column(1).operator String() + ", new Vector3" + basis.get_column(2).operator String() + ", new Vector3" + transform.origin.operator String() + ")"; + r_iarg.default_argument = "new Transform3D(new Vector3" + basis.get_column(0).operator String() + ", new Vector3" + basis.get_column(1).operator String() + ", new Vector3" + basis.get_column(2).operator String() + ", new Vector3" + transform.origin.operator String() + ")"; } r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; @@ -3142,12 +3120,12 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar } r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; - case Variant::QUAT: { - Quat quat = p_val.operator Quat(); - if (quat == Quat()) { - r_iarg.default_argument = "Quat.Identity"; + case Variant::QUATERNION: { + Quaternion quaternion = p_val.operator Quaternion(); + if (quaternion == Quaternion()) { + r_iarg.default_argument = "Quaternion.Identity"; } else { - r_iarg.default_argument = "new Quat" + quat.operator String(); + r_iarg.default_argument = "new Quaternion" + quaternion.operator String(); } r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; } break; @@ -3196,8 +3174,8 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { INSERT_STRUCT_TYPE(Vector3) INSERT_STRUCT_TYPE(Vector3i) INSERT_STRUCT_TYPE(Basis) - INSERT_STRUCT_TYPE(Quat) - INSERT_STRUCT_TYPE(Transform) + INSERT_STRUCT_TYPE(Quaternion) + INSERT_STRUCT_TYPE(Transform3D) INSERT_STRUCT_TYPE(AABB) INSERT_STRUCT_TYPE(Color) INSERT_STRUCT_TYPE(Plane) @@ -3542,9 +3520,7 @@ void BindingsGenerator::_populate_global_constants() { } } - for (List<EnumInterface>::Element *E = global_enums.front(); E; E = E->next()) { - EnumInterface &ienum = E->get(); - + for (EnumInterface &ienum : global_enums) { TypeInterface enum_itype; enum_itype.is_enum = true; enum_itype.name = ienum.cname.operator String(); @@ -3574,13 +3550,13 @@ void BindingsGenerator::_populate_global_constants() { hardcoded_enums.push_back("Vector2i.Axis"); hardcoded_enums.push_back("Vector3.Axis"); hardcoded_enums.push_back("Vector3i.Axis"); - for (List<StringName>::Element *E = hardcoded_enums.front(); E; E = E->next()) { + for (const StringName &enum_cname : hardcoded_enums) { // These enums are not generated and must be written manually (e.g.: Vector3.Axis) // Here, we assume core types do not begin with underscore TypeInterface enum_itype; enum_itype.is_enum = true; - enum_itype.name = E->get().operator String(); - enum_itype.cname = E->get(); + enum_itype.name = enum_cname.operator String(); + enum_itype.cname = enum_cname; enum_itype.proxy_name = enum_itype.name; TypeInterface::postsetup_enum_type(enum_itype); enum_types.insert(enum_itype.cname, enum_itype); diff --git a/modules/mono/editor/bindings_generator.h b/modules/mono/editor/bindings_generator.h index 876046176b..a649181b20 100644 --- a/modules/mono/editor/bindings_generator.h +++ b/modules/mono/editor/bindings_generator.h @@ -216,7 +216,7 @@ class BindingsGenerator { bool is_enum = false; bool is_object_type = false; bool is_singleton = false; - bool is_reference = false; + bool is_ref_counted = false; /** * Used only by Object-derived types. @@ -228,7 +228,7 @@ class BindingsGenerator { /** * Used only by Object-derived types. * Determines if the C# class owns the native handle and must free it somehow when disposed. - * e.g.: Reference types must notify when the C# instance is disposed, for proper refcounting. + * e.g.: RefCounted types must notify when the C# instance is disposed, for proper refcounting. */ bool memory_own = false; @@ -295,7 +295,7 @@ class BindingsGenerator { * VarArg (fictitious type to represent variable arguments): Array * float: double (because ptrcall only supports double) * int: int64_t (because ptrcall only supports int64_t and uint64_t) - * Reference types override this for the type of the return variable: Ref<Reference> + * RefCounted types override this for the type of the return variable: Ref<RefCounted> */ String c_type; @@ -357,9 +357,9 @@ class BindingsGenerator { List<SignalInterface> signals_; const MethodInterface *find_method_by_name(const StringName &p_cname) const { - for (const List<MethodInterface>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().cname == p_cname) { - return &E->get(); + for (const MethodInterface &E : methods) { + if (E.cname == p_cname) { + return &E; } } @@ -367,9 +367,9 @@ class BindingsGenerator { } const PropertyInterface *find_property_by_name(const StringName &p_cname) const { - for (const List<PropertyInterface>::Element *E = properties.front(); E; E = E->next()) { - if (E->get().cname == p_cname) { - return &E->get(); + for (const PropertyInterface &E : properties) { + if (E.cname == p_cname) { + return &E; } } @@ -377,9 +377,9 @@ class BindingsGenerator { } const PropertyInterface *find_property_by_proxy_name(const String &p_proxy_name) const { - for (const List<PropertyInterface>::Element *E = properties.front(); E; E = E->next()) { - if (E->get().proxy_name == p_proxy_name) { - return &E->get(); + for (const PropertyInterface &E : properties) { + if (E.proxy_name == p_proxy_name) { + return &E; } } @@ -387,9 +387,9 @@ class BindingsGenerator { } const MethodInterface *find_method_by_proxy_name(const String &p_proxy_name) const { - for (const List<MethodInterface>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().proxy_name == p_proxy_name) { - return &E->get(); + for (const MethodInterface &E : methods) { + if (E.proxy_name == p_proxy_name) { + return &E; } } @@ -534,7 +534,7 @@ class BindingsGenerator { StringName type_Variant = StaticCString::create("Variant"); StringName type_VarArg = StaticCString::create("VarArg"); StringName type_Object = StaticCString::create("Object"); - StringName type_Reference = StaticCString::create("Reference"); + StringName type_RefCounted = StaticCString::create("RefCounted"); StringName type_RID = StaticCString::create("RID"); StringName type_String = StaticCString::create("String"); StringName type_StringName = StaticCString::create("StringName"); @@ -613,9 +613,9 @@ class BindingsGenerator { } const ConstantInterface *find_constant_by_name(const String &p_name, const List<ConstantInterface> &p_constants) const { - for (const List<ConstantInterface>::Element *E = p_constants.front(); E; E = E->next()) { - if (E->get().name == p_name) { - return &E->get(); + for (const ConstantInterface &E : p_constants) { + if (E.name == p_name) { + return &E; } } @@ -623,7 +623,7 @@ class BindingsGenerator { } inline String get_unique_sig(const TypeInterface &p_type) { - if (p_type.is_reference) { + if (p_type.is_ref_counted) { return "Ref"; } else if (p_type.is_object_type) { return "Obj"; diff --git a/modules/mono/editor/code_completion.cpp b/modules/mono/editor/code_completion.cpp index bbfba83e6f..b7b36a92d8 100644 --- a/modules/mono/editor/code_completion.cpp +++ b/modules/mono/editor/code_completion.cpp @@ -109,9 +109,7 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr List<PropertyInfo> project_props; ProjectSettings::get_singleton()->get_property_list(&project_props); - for (List<PropertyInfo>::Element *E = project_props.front(); E; E = E->next()) { - const PropertyInfo &prop = E->get(); - + for (const PropertyInfo &prop : project_props) { if (!prop.name.begins_with("input/")) { continue; } @@ -125,8 +123,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr // AutoLoads Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list(); - for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) { - const ProjectSettings::AutoloadInfo &info = E->value(); + for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) { + const ProjectSettings::AutoloadInfo &info = E.value; suggestions.push_back(quoted("/root/" + String(info.name))); } } @@ -187,8 +185,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr ClassDB::get_signal_list(native, &signals, /* p_no_inheritance: */ false); } - for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) { - const String &signal = E->get().name; + for (const MethodInfo &E : signals) { + const String &signal = E.name; suggestions.push_back(quoted(signal)); } } break; @@ -199,8 +197,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr List<StringName> sn; Theme::get_default()->get_color_list(base->get_class(), &sn); - for (List<StringName>::Element *E = sn.front(); E; E = E->next()) { - suggestions.push_back(quoted(E->get())); + for (const StringName &E : sn) { + suggestions.push_back(quoted(E)); } } } break; @@ -211,8 +209,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr List<StringName> sn; Theme::get_default()->get_constant_list(base->get_class(), &sn); - for (List<StringName>::Element *E = sn.front(); E; E = E->next()) { - suggestions.push_back(quoted(E->get())); + for (const StringName &E : sn) { + suggestions.push_back(quoted(E)); } } } break; @@ -223,8 +221,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr List<StringName> sn; Theme::get_default()->get_font_list(base->get_class(), &sn); - for (List<StringName>::Element *E = sn.front(); E; E = E->next()) { - suggestions.push_back(quoted(E->get())); + for (const StringName &E : sn) { + suggestions.push_back(quoted(E)); } } } break; @@ -235,8 +233,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr List<StringName> sn; Theme::get_default()->get_font_size_list(base->get_class(), &sn); - for (List<StringName>::Element *E = sn.front(); E; E = E->next()) { - suggestions.push_back(quoted(E->get())); + for (const StringName &E : sn) { + suggestions.push_back(quoted(E)); } } } break; @@ -247,8 +245,8 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr List<StringName> sn; Theme::get_default()->get_stylebox_list(base->get_class(), &sn); - for (List<StringName>::Element *E = sn.front(); E; E = E->next()) { - suggestions.push_back(quoted(E->get())); + for (const StringName &E : sn) { + suggestions.push_back(quoted(E)); } } } break; diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp index 21efd58938..8164f459ca 100644 --- a/modules/mono/editor/editor_internal_calls.cpp +++ b/modules/mono/editor/editor_internal_calls.cpp @@ -241,7 +241,7 @@ MonoBoolean godot_icall_Internal_IsAssembliesReloadingNeeded() { void godot_icall_Internal_ReloadAssemblies(MonoBoolean p_soft_reload) { #ifdef GD_MONO_HOT_RELOAD - _GodotSharp::get_singleton()->call_deferred("_reload_assemblies", (bool)p_soft_reload); + _GodotSharp::get_singleton()->call_deferred(SNAME("_reload_assemblies"), (bool)p_soft_reload); #endif } diff --git a/modules/mono/editor/godotsharp_export.cpp b/modules/mono/editor/godotsharp_export.cpp index 4b858c0e82..54dbaebf38 100644 --- a/modules/mono/editor/godotsharp_export.cpp +++ b/modules/mono/editor/godotsharp_export.cpp @@ -91,7 +91,7 @@ Error get_assembly_dependencies(GDMonoAssembly *p_assembly, MonoAssemblyName *re mono_assembly_get_assemblyref(image, i, reusable_aname); - GDMonoAssembly *ref_assembly = NULL; + GDMonoAssembly *ref_assembly = nullptr; if (!GDMono::get_singleton()->load_assembly(ref_name, reusable_aname, &ref_assembly, /* refonly: */ true, p_search_dirs)) { ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Cannot load assembly (refonly): '" + ref_name + "'."); } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs index 3aecce50f5..1a3b81487f 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/AABB.cs @@ -1,16 +1,10 @@ -// file: core/math/aabb.h -// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451 -// file: core/math/aabb.cpp -// commit: bd282ff43f23fe845f29a3e25c8efc01bd65ffb0 -// file: core/variant_call.cpp -// commit: 5ad9be4c24e9d7dc5672fdc42cea896622fe5685 -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -676,20 +670,12 @@ namespace Godot public override string ToString() { - return String.Format("{0} - {1}", new object[] - { - _position.ToString(), - _size.ToString() - }); + return $"{_position}, {_size}"; } public string ToString(string format) { - return String.Format("{0} - {1}", new object[] - { - _position.ToString(format), - _size.ToString(format) - }); + return $"{_position.ToString(format)}, {_size.ToString(format)}"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs index ce613f7ef9..f52a767018 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Array.cs @@ -25,16 +25,30 @@ namespace Godot.Collections } } + /// <summary> + /// Wrapper around Godot's Array class, an array of Variant + /// typed elements allocated in the engine in C++. Useful when + /// interfacing with the engine. Otherwise prefer .NET collections + /// such as <see cref="System.Array"/> or <see cref="List{T}"/>. + /// </summary> public class Array : IList, IDisposable { ArraySafeHandle safeHandle; bool disposed = false; + /// <summary> + /// Constructs a new empty <see cref="Array"/>. + /// </summary> public Array() { safeHandle = new ArraySafeHandle(godot_icall_Array_Ctor()); } + /// <summary> + /// Constructs a new <see cref="Array"/> from the given collection's elements. + /// </summary> + /// <param name="collection">The collection of elements to construct from.</param> + /// <returns>A new Godot Array.</returns> public Array(IEnumerable collection) : this() { if (collection == null) @@ -44,6 +58,11 @@ namespace Godot.Collections Add(element); } + /// <summary> + /// Constructs a new <see cref="Array"/> from the given objects. + /// </summary> + /// <param name="array">The objects to put in the new array.</param> + /// <returns>A new Godot Array.</returns> public Array(params object[] array) : this() { if (array == null) @@ -71,21 +90,40 @@ namespace Godot.Collections return safeHandle.DangerousGetHandle(); } + /// <summary> + /// Duplicates this <see cref="Array"/>. + /// </summary> + /// <param name="deep">If true, performs a deep copy.</param> + /// <returns>A new Godot Array.</returns> public Array Duplicate(bool deep = false) { return new Array(godot_icall_Array_Duplicate(GetPtr(), deep)); } + /// <summary> + /// Resizes this <see cref="Array"/> to the given size. + /// </summary> + /// <param name="newSize">The new size of the array.</param> + /// <returns><see cref="Error.Ok"/> if successful, or an error code.</returns> public Error Resize(int newSize) { return godot_icall_Array_Resize(GetPtr(), newSize); } + /// <summary> + /// Shuffles the contents of this <see cref="Array"/> into a random order. + /// </summary> public void Shuffle() { godot_icall_Array_Shuffle(GetPtr()); } + /// <summary> + /// Concatenates these two <see cref="Array"/>s. + /// </summary> + /// <param name="left">The first array.</param> + /// <param name="right">The second array.</param> + /// <returns>A new Godot Array with the contents of both arrays.</returns> public static Array operator +(Array left, Array right) { return new Array(godot_icall_Array_Concatenate(left.GetPtr(), right.GetPtr())); @@ -93,6 +131,9 @@ namespace Godot.Collections // IDisposable + /// <summary> + /// Disposes of this <see cref="Array"/>. + /// </summary> public void Dispose() { if (disposed) @@ -109,38 +150,90 @@ namespace Godot.Collections // IList - public bool IsReadOnly => false; + bool IList.IsReadOnly => false; - public bool IsFixedSize => false; + bool IList.IsFixedSize => false; + /// <summary> + /// Returns the object at the given index. + /// </summary> + /// <value>The object at the given index.</value> public object this[int index] { get => godot_icall_Array_At(GetPtr(), index); set => godot_icall_Array_SetAt(GetPtr(), index, value); } + /// <summary> + /// Adds an object to the end of this <see cref="Array"/>. + /// This is the same as `append` or `push_back` in GDScript. + /// </summary> + /// <param name="value">The object to add.</param> + /// <returns>The new size after adding the object.</returns> public int Add(object value) => godot_icall_Array_Add(GetPtr(), value); + /// <summary> + /// Checks if this <see cref="Array"/> contains the given object. + /// </summary> + /// <param name="value">The item to look for.</param> + /// <returns>Whether or not this array contains the given object.</returns> public bool Contains(object value) => godot_icall_Array_Contains(GetPtr(), value); + /// <summary> + /// Erases all items from this <see cref="Array"/>. + /// </summary> public void Clear() => godot_icall_Array_Clear(GetPtr()); + /// <summary> + /// Searches this <see cref="Array"/> for an object + /// and returns its index or -1 if not found. + /// </summary> + /// <param name="value">The object to search for.</param> + /// <returns>The index of the object, or -1 if not found.</returns> public int IndexOf(object value) => godot_icall_Array_IndexOf(GetPtr(), value); + /// <summary> + /// Inserts a new object at a given position in the array. + /// The position must be a valid position of an existing item, + /// or the position at the end of the array. + /// Existing items will be moved to the right. + /// </summary> + /// <param name="index">The index to insert at.</param> + /// <param name="value">The object to insert.</param> public void Insert(int index, object value) => godot_icall_Array_Insert(GetPtr(), index, value); + /// <summary> + /// Removes the first occurrence of the specified value + /// from this <see cref="Array"/>. + /// </summary> + /// <param name="value">The value to remove.</param> public void Remove(object value) => godot_icall_Array_Remove(GetPtr(), value); + /// <summary> + /// Removes an element from this <see cref="Array"/> by index. + /// </summary> + /// <param name="index">The index of the element to remove.</param> public void RemoveAt(int index) => godot_icall_Array_RemoveAt(GetPtr(), index); // ICollection + /// <summary> + /// Returns the number of elements in this <see cref="Array"/>. + /// This is also known as the size or length of the array. + /// </summary> + /// <returns>The number of elements.</returns> public int Count => godot_icall_Array_Count(GetPtr()); - public object SyncRoot => this; + object ICollection.SyncRoot => this; - public bool IsSynchronized => false; + bool ICollection.IsSynchronized => false; + /// <summary> + /// Copies the elements of this <see cref="Array"/> to the given + /// untyped C# array, starting at the given index. + /// </summary> + /// <param name="array">The array to copy to.</param> + /// <param name="index">The index to start at.</param> public void CopyTo(System.Array array, int index) { if (array == null) @@ -155,6 +248,10 @@ namespace Godot.Collections // IEnumerable + /// <summary> + /// Gets an enumerator for this <see cref="Array"/>. + /// </summary> + /// <returns>An enumerator.</returns> public IEnumerator GetEnumerator() { int count = Count; @@ -165,6 +262,10 @@ namespace Godot.Collections } } + /// <summary> + /// Converts this <see cref="Array"/> to a string. + /// </summary> + /// <returns>A string representation of this array.</returns> public override string ToString() { return godot_icall_Array_ToString(GetPtr()); @@ -234,6 +335,13 @@ namespace Godot.Collections internal extern static string godot_icall_Array_ToString(IntPtr ptr); } + /// <summary> + /// Typed wrapper around Godot's Array class, an array of Variant + /// typed elements allocated in the engine in C++. Useful when + /// interfacing with the engine. Otherwise prefer .NET collections + /// such as arrays or <see cref="List{T}"/>. + /// </summary> + /// <typeparam name="T">The type of the array.</typeparam> public class Array<T> : IList<T>, ICollection<T>, IEnumerable<T> { Array objectArray; @@ -246,11 +354,19 @@ namespace Godot.Collections Array.godot_icall_Array_Generic_GetElementTypeInfo(typeof(T), out elemTypeEncoding, out elemTypeClass); } + /// <summary> + /// Constructs a new empty <see cref="Array{T}"/>. + /// </summary> public Array() { objectArray = new Array(); } + /// <summary> + /// Constructs a new <see cref="Array{T}"/> from the given collection's elements. + /// </summary> + /// <param name="collection">The collection of elements to construct from.</param> + /// <returns>A new Godot Array.</returns> public Array(IEnumerable<T> collection) { if (collection == null) @@ -259,6 +375,11 @@ namespace Godot.Collections objectArray = new Array(collection); } + /// <summary> + /// Constructs a new <see cref="Array{T}"/> from the given items. + /// </summary> + /// <param name="array">The items to put in the new array.</param> + /// <returns>A new Godot Array.</returns> public Array(params T[] array) : this() { if (array == null) @@ -268,6 +389,10 @@ namespace Godot.Collections objectArray = new Array(array); } + /// <summary> + /// Constructs a typed <see cref="Array{T}"/> from an untyped <see cref="Array"/>. + /// </summary> + /// <param name="array">The untyped array to construct from.</param> public Array(Array array) { objectArray = array; @@ -288,26 +413,49 @@ namespace Godot.Collections return objectArray.GetPtr(); } + /// <summary> + /// Converts this typed <see cref="Array{T}"/> to an untyped <see cref="Array"/>. + /// </summary> + /// <param name="from">The typed array to convert.</param> public static explicit operator Array(Array<T> from) { return from.objectArray; } + /// <summary> + /// Duplicates this <see cref="Array{T}"/>. + /// </summary> + /// <param name="deep">If true, performs a deep copy.</param> + /// <returns>A new Godot Array.</returns> public Array<T> Duplicate(bool deep = false) { return new Array<T>(objectArray.Duplicate(deep)); } + /// <summary> + /// Resizes this <see cref="Array{T}"/> to the given size. + /// </summary> + /// <param name="newSize">The new size of the array.</param> + /// <returns><see cref="Error.Ok"/> if successful, or an error code.</returns> public Error Resize(int newSize) { return objectArray.Resize(newSize); } + /// <summary> + /// Shuffles the contents of this <see cref="Array{T}"/> into a random order. + /// </summary> public void Shuffle() { objectArray.Shuffle(); } + /// <summary> + /// Concatenates these two <see cref="Array{T}"/>s. + /// </summary> + /// <param name="left">The first array.</param> + /// <param name="right">The second array.</param> + /// <returns>A new Godot Array with the contents of both arrays.</returns> public static Array<T> operator +(Array<T> left, Array<T> right) { return new Array<T>(left.objectArray + right.objectArray); @@ -315,22 +463,44 @@ namespace Godot.Collections // IList<T> + /// <summary> + /// Returns the value at the given index. + /// </summary> + /// <value>The value at the given index.</value> public T this[int index] { get { return (T)Array.godot_icall_Array_At_Generic(GetPtr(), index, elemTypeEncoding, elemTypeClass); } set { objectArray[index] = value; } } + /// <summary> + /// Searches this <see cref="Array{T}"/> for an item + /// and returns its index or -1 if not found. + /// </summary> + /// <param name="item">The item to search for.</param> + /// <returns>The index of the item, or -1 if not found.</returns> public int IndexOf(T item) { return objectArray.IndexOf(item); } + /// <summary> + /// Inserts a new item at a given position in the <see cref="Array{T}"/>. + /// The position must be a valid position of an existing item, + /// or the position at the end of the array. + /// Existing items will be moved to the right. + /// </summary> + /// <param name="index">The index to insert at.</param> + /// <param name="item">The item to insert.</param> public void Insert(int index, T item) { objectArray.Insert(index, item); } + /// <summary> + /// Removes an element from this <see cref="Array{T}"/> by index. + /// </summary> + /// <param name="index">The index of the element to remove.</param> public void RemoveAt(int index) { objectArray.RemoveAt(index); @@ -338,31 +508,53 @@ namespace Godot.Collections // ICollection<T> + /// <summary> + /// Returns the number of elements in this <see cref="Array{T}"/>. + /// This is also known as the size or length of the array. + /// </summary> + /// <returns>The number of elements.</returns> public int Count { get { return objectArray.Count; } } - public bool IsReadOnly - { - get { return objectArray.IsReadOnly; } - } + bool ICollection<T>.IsReadOnly => false; + /// <summary> + /// Adds an item to the end of this <see cref="Array{T}"/>. + /// This is the same as `append` or `push_back` in GDScript. + /// </summary> + /// <param name="item">The item to add.</param> + /// <returns>The new size after adding the item.</returns> public void Add(T item) { objectArray.Add(item); } + /// <summary> + /// Erases all items from this <see cref="Array{T}"/>. + /// </summary> public void Clear() { objectArray.Clear(); } + /// <summary> + /// Checks if this <see cref="Array{T}"/> contains the given item. + /// </summary> + /// <param name="item">The item to look for.</param> + /// <returns>Whether or not this array contains the given item.</returns> public bool Contains(T item) { return objectArray.Contains(item); } + /// <summary> + /// Copies the elements of this <see cref="Array{T}"/> to the given + /// C# array, starting at the given index. + /// </summary> + /// <param name="array">The C# array to copy to.</param> + /// <param name="arrayIndex">The index to start at.</param> public void CopyTo(T[] array, int arrayIndex) { if (array == null) @@ -386,6 +578,12 @@ namespace Godot.Collections } } + /// <summary> + /// Removes the first occurrence of the specified value + /// from this <see cref="Array{T}"/>. + /// </summary> + /// <param name="item">The value to remove.</param> + /// <returns>A bool indicating success or failure.</returns> public bool Remove(T item) { return Array.godot_icall_Array_Remove(GetPtr(), item); @@ -393,6 +591,10 @@ namespace Godot.Collections // IEnumerable<T> + /// <summary> + /// Gets an enumerator for this <see cref="Array{T}"/>. + /// </summary> + /// <returns>An enumerator.</returns> public IEnumerator<T> GetEnumerator() { int count = objectArray.Count; @@ -408,6 +610,10 @@ namespace Godot.Collections return GetEnumerator(); } + /// <summary> + /// Converts this <see cref="Array{T}"/> to a string. + /// </summary> + /// <returns>A string representation of this array.</returns> public override string ToString() => objectArray.ToString(); } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/RPCAttributes.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/RPCAttributes.cs index 8fc430b6bc..6cec8773b2 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/RPCAttributes.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Attributes/RPCAttributes.cs @@ -2,21 +2,12 @@ using System; namespace Godot { - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + [AttributeUsage(AttributeTargets.Method)] public class RemoteAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + [AttributeUsage(AttributeTargets.Method)] public class MasterAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] + [AttributeUsage(AttributeTargets.Method)] public class PuppetAttribute : Attribute {} - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public class RemoteSyncAttribute : Attribute {} - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public class MasterSyncAttribute : Attribute {} - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] - public class PuppetSyncAttribute : Attribute {} } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs index 3f1120575f..968f853c2d 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Basis.cs @@ -1,10 +1,10 @@ -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -207,7 +207,7 @@ namespace Godot } } - public Quat RotationQuat() + public Quaternion GetRotationQuaternion() { Basis orthonormalizedBasis = Orthonormalized(); real_t det = orthonormalizedBasis.Determinant(); @@ -218,18 +218,18 @@ namespace Godot orthonormalizedBasis = orthonormalizedBasis.Scaled(-Vector3.One); } - return orthonormalizedBasis.Quat(); + return orthonormalizedBasis.Quaternion(); } - internal void SetQuatScale(Quat quat, Vector3 scale) + internal void SetQuaternionScale(Quaternion quaternion, Vector3 scale) { SetDiagonal(scale); - Rotate(quat); + Rotate(quaternion); } - private void Rotate(Quat quat) + private void Rotate(Quaternion quaternion) { - this *= new Basis(quat); + this *= new Basis(quaternion); } private void SetDiagonal(Vector3 diagonal) @@ -263,8 +263,8 @@ namespace Godot /// The returned vector contains the rotation angles in /// the format (X angle, Y angle, Z angle). /// - /// Consider using the <see cref="Basis.Quat()"/> method instead, which - /// returns a <see cref="Godot.Quat"/> quaternion instead of Euler angles. + /// Consider using the <see cref="Basis.Quaternion()"/> method instead, which + /// returns a <see cref="Godot.Quaternion"/> quaternion instead of Euler angles. /// </summary> /// <returns>A Vector3 representing the basis rotation in Euler angles.</returns> public Vector3 GetEuler() @@ -486,8 +486,8 @@ namespace Godot /// <returns>The resulting basis matrix of the interpolation.</returns> public Basis Slerp(Basis target, real_t weight) { - Quat from = new Quat(this); - Quat to = new Quat(target); + Quaternion from = new Quaternion(this); + Quaternion to = new Quaternion(target); Basis b = new Basis(from.Slerp(to, weight)); b.Row0 *= Mathf.Lerp(Row0.Length(), target.Row0.Length(), weight); @@ -588,8 +588,8 @@ namespace Godot /// 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="Godot.Quat"/> representing the basis's rotation.</returns> - public Quat Quat() + /// <returns>A <see cref="Godot.Quaternion"/> representing the basis's rotation.</returns> + public Quaternion Quaternion() { real_t trace = Row0[0] + Row1[1] + Row2[2]; @@ -597,7 +597,7 @@ namespace Godot { real_t s = Mathf.Sqrt(trace + 1.0f) * 2f; real_t inv_s = 1f / s; - return new Quat( + return new Quaternion( (Row2[1] - Row1[2]) * inv_s, (Row0[2] - Row2[0]) * inv_s, (Row1[0] - Row0[1]) * inv_s, @@ -609,7 +609,7 @@ namespace Godot { real_t s = Mathf.Sqrt(Row0[0] - Row1[1] - Row2[2] + 1.0f) * 2f; real_t inv_s = 1f / s; - return new Quat( + return new Quaternion( s * 0.25f, (Row0[1] + Row1[0]) * inv_s, (Row0[2] + Row2[0]) * inv_s, @@ -621,7 +621,7 @@ namespace Godot { real_t s = Mathf.Sqrt(-Row0[0] + Row1[1] - Row2[2] + 1.0f) * 2f; real_t inv_s = 1f / s; - return new Quat( + return new Quaternion( (Row0[1] + Row1[0]) * inv_s, s * 0.25f, (Row1[2] + Row2[1]) * inv_s, @@ -632,7 +632,7 @@ namespace Godot { real_t s = Mathf.Sqrt(-Row0[0] - Row1[1] + Row2[2] + 1.0f) * 2f; real_t inv_s = 1f / s; - return new Quat( + return new Quaternion( (Row0[2] + Row2[0]) * inv_s, (Row1[2] + Row2[1]) * inv_s, s * 0.25f, @@ -699,23 +699,23 @@ namespace Godot /// <summary> /// Constructs a pure rotation basis matrix from the given quaternion. /// </summary> - /// <param name="quat">The quaternion to create the basis from.</param> - public Basis(Quat quat) + /// <param name="quaternion">The quaternion to create the basis from.</param> + public Basis(Quaternion quaternion) { - real_t s = 2.0f / quat.LengthSquared; + real_t s = 2.0f / quaternion.LengthSquared; - real_t xs = quat.x * s; - real_t ys = quat.y * s; - real_t zs = quat.z * s; - real_t wx = quat.w * xs; - real_t wy = quat.w * ys; - real_t wz = quat.w * zs; - real_t xx = quat.x * xs; - real_t xy = quat.x * ys; - real_t xz = quat.x * zs; - real_t yy = quat.y * ys; - real_t yz = quat.y * zs; - real_t zz = quat.z * zs; + real_t xs = quaternion.x * s; + real_t ys = quaternion.y * s; + real_t zs = quaternion.z * s; + real_t wx = quaternion.w * xs; + real_t wy = quaternion.w * ys; + real_t wz = quaternion.w * zs; + real_t xx = quaternion.x * xs; + real_t xy = quaternion.x * ys; + real_t xz = quaternion.x * zs; + real_t yy = quaternion.y * ys; + real_t yz = quaternion.y * zs; + real_t zz = quaternion.z * zs; Row0 = new Vector3(1.0f - (yy + zz), xy - wz, xz + wy); Row1 = new Vector3(xy + wz, 1.0f - (xx + zz), yz - wx); @@ -727,8 +727,8 @@ namespace Godot /// (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(Quat)"/> constructor instead, which - /// uses a <see cref="Godot.Quat"/> quaternion instead of Euler angles. + /// Consider using the <see cref="Basis(Quaternion)"/> constructor instead, which + /// uses a <see cref="Godot.Quaternion"/> quaternion instead of Euler angles. /// </summary> /// <param name="eulerYXZ">The Euler angles to create the basis from.</param> public Basis(Vector3 eulerYXZ) @@ -863,22 +863,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1}, {2})", new object[] - { - Row0.ToString(), - Row1.ToString(), - Row2.ToString() - }); + return $"[X: {x}, Y: {y}, Z: {z}]"; } public string ToString(string format) { - return String.Format("({0}, {1}, {2})", new object[] - { - Row0.ToString(format), - Row1.ToString(format), - Row2.ToString(format) - }); + return $"[X: {x.ToString(format)}, Y: {y.ToString(format)}, Z: {z.ToString(format)}]"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs index 0c333d06ef..b9a98ba9c7 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Color.cs @@ -257,6 +257,27 @@ namespace Godot } /// <summary> + /// Returns a new color with all components clamped between the + /// components of `min` and `max` using + /// <see cref="Mathf.Clamp(float, float, float)"/>. + /// </summary> + /// <param name="min">The color with minimum allowed values.</param> + /// <param name="max">The color with maximum allowed values.</param> + /// <returns>The color with all components clamped.</returns> + public Color Clamp(Color? min = null, Color? max = null) + { + Color minimum = min ?? new Color(0, 0, 0, 0); + Color maximum = max ?? new Color(1, 1, 1, 1); + return new Color + ( + (float)Mathf.Clamp(r, minimum.r, maximum.r), + (float)Mathf.Clamp(g, minimum.g, maximum.g), + (float)Mathf.Clamp(b, minimum.b, maximum.b), + (float)Mathf.Clamp(a, minimum.a, maximum.a) + ); + } + + /// <summary> /// Returns a new color resulting from making this color darker /// by the specified ratio (on the range of 0 to 1). /// </summary> @@ -681,7 +702,7 @@ namespace Godot name = name.Replace("_", String.Empty); name = name.Replace("'", String.Empty); name = name.Replace(".", String.Empty); - name = name.ToLower(); + name = name.ToUpper(); if (!Colors.namedColors.ContainsKey(name)) { @@ -989,12 +1010,12 @@ namespace Godot public override string ToString() { - return String.Format("{0},{1},{2},{3}", r.ToString(), g.ToString(), b.ToString(), a.ToString()); + return $"({r}, {g}, {b}, {a})"; } public string ToString(string format) { - return String.Format("{0},{1},{2},{3}", r.ToString(format), g.ToString(format), b.ToString(format), a.ToString(format)); + return $"({r.ToString(format)}, {g.ToString(format)}, {b.ToString(format)}, {a.ToString(format)})"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs index d05a0414aa..d64c8b563e 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Colors.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; namespace Godot @@ -9,301 +8,301 @@ namespace Godot /// </summary> public static class Colors { - // Color names and values are derived from core/color_names.inc + // Color names and values are derived from core/math/color_names.inc internal static readonly Dictionary<string, Color> namedColors = new Dictionary<string, Color> { - {"aliceblue", new Color(0.94f, 0.97f, 1.00f)}, - {"antiquewhite", new Color(0.98f, 0.92f, 0.84f)}, - {"aqua", new Color(0.00f, 1.00f, 1.00f)}, - {"aquamarine", new Color(0.50f, 1.00f, 0.83f)}, - {"azure", new Color(0.94f, 1.00f, 1.00f)}, - {"beige", new Color(0.96f, 0.96f, 0.86f)}, - {"bisque", new Color(1.00f, 0.89f, 0.77f)}, - {"black", new Color(0.00f, 0.00f, 0.00f)}, - {"blanchedalmond", new Color(1.00f, 0.92f, 0.80f)}, - {"blue", new Color(0.00f, 0.00f, 1.00f)}, - {"blueviolet", new Color(0.54f, 0.17f, 0.89f)}, - {"brown", new Color(0.65f, 0.16f, 0.16f)}, - {"burlywood", new Color(0.87f, 0.72f, 0.53f)}, - {"cadetblue", new Color(0.37f, 0.62f, 0.63f)}, - {"chartreuse", new Color(0.50f, 1.00f, 0.00f)}, - {"chocolate", new Color(0.82f, 0.41f, 0.12f)}, - {"coral", new Color(1.00f, 0.50f, 0.31f)}, - {"cornflower", new Color(0.39f, 0.58f, 0.93f)}, - {"cornsilk", new Color(1.00f, 0.97f, 0.86f)}, - {"crimson", new Color(0.86f, 0.08f, 0.24f)}, - {"cyan", new Color(0.00f, 1.00f, 1.00f)}, - {"darkblue", new Color(0.00f, 0.00f, 0.55f)}, - {"darkcyan", new Color(0.00f, 0.55f, 0.55f)}, - {"darkgoldenrod", new Color(0.72f, 0.53f, 0.04f)}, - {"darkgray", new Color(0.66f, 0.66f, 0.66f)}, - {"darkgreen", new Color(0.00f, 0.39f, 0.00f)}, - {"darkkhaki", new Color(0.74f, 0.72f, 0.42f)}, - {"darkmagenta", new Color(0.55f, 0.00f, 0.55f)}, - {"darkolivegreen", new Color(0.33f, 0.42f, 0.18f)}, - {"darkorange", new Color(1.00f, 0.55f, 0.00f)}, - {"darkorchid", new Color(0.60f, 0.20f, 0.80f)}, - {"darkred", new Color(0.55f, 0.00f, 0.00f)}, - {"darksalmon", new Color(0.91f, 0.59f, 0.48f)}, - {"darkseagreen", new Color(0.56f, 0.74f, 0.56f)}, - {"darkslateblue", new Color(0.28f, 0.24f, 0.55f)}, - {"darkslategray", new Color(0.18f, 0.31f, 0.31f)}, - {"darkturquoise", new Color(0.00f, 0.81f, 0.82f)}, - {"darkviolet", new Color(0.58f, 0.00f, 0.83f)}, - {"deeppink", new Color(1.00f, 0.08f, 0.58f)}, - {"deepskyblue", new Color(0.00f, 0.75f, 1.00f)}, - {"dimgray", new Color(0.41f, 0.41f, 0.41f)}, - {"dodgerblue", new Color(0.12f, 0.56f, 1.00f)}, - {"firebrick", new Color(0.70f, 0.13f, 0.13f)}, - {"floralwhite", new Color(1.00f, 0.98f, 0.94f)}, - {"forestgreen", new Color(0.13f, 0.55f, 0.13f)}, - {"fuchsia", new Color(1.00f, 0.00f, 1.00f)}, - {"gainsboro", new Color(0.86f, 0.86f, 0.86f)}, - {"ghostwhite", new Color(0.97f, 0.97f, 1.00f)}, - {"gold", new Color(1.00f, 0.84f, 0.00f)}, - {"goldenrod", new Color(0.85f, 0.65f, 0.13f)}, - {"gray", new Color(0.75f, 0.75f, 0.75f)}, - {"green", new Color(0.00f, 1.00f, 0.00f)}, - {"greenyellow", new Color(0.68f, 1.00f, 0.18f)}, - {"honeydew", new Color(0.94f, 1.00f, 0.94f)}, - {"hotpink", new Color(1.00f, 0.41f, 0.71f)}, - {"indianred", new Color(0.80f, 0.36f, 0.36f)}, - {"indigo", new Color(0.29f, 0.00f, 0.51f)}, - {"ivory", new Color(1.00f, 1.00f, 0.94f)}, - {"khaki", new Color(0.94f, 0.90f, 0.55f)}, - {"lavender", new Color(0.90f, 0.90f, 0.98f)}, - {"lavenderblush", new Color(1.00f, 0.94f, 0.96f)}, - {"lawngreen", new Color(0.49f, 0.99f, 0.00f)}, - {"lemonchiffon", new Color(1.00f, 0.98f, 0.80f)}, - {"lightblue", new Color(0.68f, 0.85f, 0.90f)}, - {"lightcoral", new Color(0.94f, 0.50f, 0.50f)}, - {"lightcyan", new Color(0.88f, 1.00f, 1.00f)}, - {"lightgoldenrod", new Color(0.98f, 0.98f, 0.82f)}, - {"lightgray", new Color(0.83f, 0.83f, 0.83f)}, - {"lightgreen", new Color(0.56f, 0.93f, 0.56f)}, - {"lightpink", new Color(1.00f, 0.71f, 0.76f)}, - {"lightsalmon", new Color(1.00f, 0.63f, 0.48f)}, - {"lightseagreen", new Color(0.13f, 0.70f, 0.67f)}, - {"lightskyblue", new Color(0.53f, 0.81f, 0.98f)}, - {"lightslategray", new Color(0.47f, 0.53f, 0.60f)}, - {"lightsteelblue", new Color(0.69f, 0.77f, 0.87f)}, - {"lightyellow", new Color(1.00f, 1.00f, 0.88f)}, - {"lime", new Color(0.00f, 1.00f, 0.00f)}, - {"limegreen", new Color(0.20f, 0.80f, 0.20f)}, - {"linen", new Color(0.98f, 0.94f, 0.90f)}, - {"magenta", new Color(1.00f, 0.00f, 1.00f)}, - {"maroon", new Color(0.69f, 0.19f, 0.38f)}, - {"mediumaquamarine", new Color(0.40f, 0.80f, 0.67f)}, - {"mediumblue", new Color(0.00f, 0.00f, 0.80f)}, - {"mediumorchid", new Color(0.73f, 0.33f, 0.83f)}, - {"mediumpurple", new Color(0.58f, 0.44f, 0.86f)}, - {"mediumseagreen", new Color(0.24f, 0.70f, 0.44f)}, - {"mediumslateblue", new Color(0.48f, 0.41f, 0.93f)}, - {"mediumspringgreen", new Color(0.00f, 0.98f, 0.60f)}, - {"mediumturquoise", new Color(0.28f, 0.82f, 0.80f)}, - {"mediumvioletred", new Color(0.78f, 0.08f, 0.52f)}, - {"midnightblue", new Color(0.10f, 0.10f, 0.44f)}, - {"mintcream", new Color(0.96f, 1.00f, 0.98f)}, - {"mistyrose", new Color(1.00f, 0.89f, 0.88f)}, - {"moccasin", new Color(1.00f, 0.89f, 0.71f)}, - {"navajowhite", new Color(1.00f, 0.87f, 0.68f)}, - {"navyblue", new Color(0.00f, 0.00f, 0.50f)}, - {"oldlace", new Color(0.99f, 0.96f, 0.90f)}, - {"olive", new Color(0.50f, 0.50f, 0.00f)}, - {"olivedrab", new Color(0.42f, 0.56f, 0.14f)}, - {"orange", new Color(1.00f, 0.65f, 0.00f)}, - {"orangered", new Color(1.00f, 0.27f, 0.00f)}, - {"orchid", new Color(0.85f, 0.44f, 0.84f)}, - {"palegoldenrod", new Color(0.93f, 0.91f, 0.67f)}, - {"palegreen", new Color(0.60f, 0.98f, 0.60f)}, - {"paleturquoise", new Color(0.69f, 0.93f, 0.93f)}, - {"palevioletred", new Color(0.86f, 0.44f, 0.58f)}, - {"papayawhip", new Color(1.00f, 0.94f, 0.84f)}, - {"peachpuff", new Color(1.00f, 0.85f, 0.73f)}, - {"peru", new Color(0.80f, 0.52f, 0.25f)}, - {"pink", new Color(1.00f, 0.75f, 0.80f)}, - {"plum", new Color(0.87f, 0.63f, 0.87f)}, - {"powderblue", new Color(0.69f, 0.88f, 0.90f)}, - {"purple", new Color(0.63f, 0.13f, 0.94f)}, - {"rebeccapurple", new Color(0.40f, 0.20f, 0.60f)}, - {"red", new Color(1.00f, 0.00f, 0.00f)}, - {"rosybrown", new Color(0.74f, 0.56f, 0.56f)}, - {"royalblue", new Color(0.25f, 0.41f, 0.88f)}, - {"saddlebrown", new Color(0.55f, 0.27f, 0.07f)}, - {"salmon", new Color(0.98f, 0.50f, 0.45f)}, - {"sandybrown", new Color(0.96f, 0.64f, 0.38f)}, - {"seagreen", new Color(0.18f, 0.55f, 0.34f)}, - {"seashell", new Color(1.00f, 0.96f, 0.93f)}, - {"sienna", new Color(0.63f, 0.32f, 0.18f)}, - {"silver", new Color(0.75f, 0.75f, 0.75f)}, - {"skyblue", new Color(0.53f, 0.81f, 0.92f)}, - {"slateblue", new Color(0.42f, 0.35f, 0.80f)}, - {"slategray", new Color(0.44f, 0.50f, 0.56f)}, - {"snow", new Color(1.00f, 0.98f, 0.98f)}, - {"springgreen", new Color(0.00f, 1.00f, 0.50f)}, - {"steelblue", new Color(0.27f, 0.51f, 0.71f)}, - {"tan", new Color(0.82f, 0.71f, 0.55f)}, - {"teal", new Color(0.00f, 0.50f, 0.50f)}, - {"thistle", new Color(0.85f, 0.75f, 0.85f)}, - {"tomato", new Color(1.00f, 0.39f, 0.28f)}, - {"transparent", new Color(1.00f, 1.00f, 1.00f, 0.00f)}, - {"turquoise", new Color(0.25f, 0.88f, 0.82f)}, - {"violet", new Color(0.93f, 0.51f, 0.93f)}, - {"webgreen", new Color(0.00f, 0.50f, 0.00f)}, - {"webgray", new Color(0.50f, 0.50f, 0.50f)}, - {"webmaroon", new Color(0.50f, 0.00f, 0.00f)}, - {"webpurple", new Color(0.50f, 0.00f, 0.50f)}, - {"wheat", new Color(0.96f, 0.87f, 0.70f)}, - {"white", new Color(1.00f, 1.00f, 1.00f)}, - {"whitesmoke", new Color(0.96f, 0.96f, 0.96f)}, - {"yellow", new Color(1.00f, 1.00f, 0.00f)}, - {"yellowgreen", new Color(0.60f, 0.80f, 0.20f)}, + {"ALICEBLUE", new Color(0.94f, 0.97f, 1.00f)}, + {"ANTIQUEWHITE", new Color(0.98f, 0.92f, 0.84f)}, + {"AQUA", new Color(0.00f, 1.00f, 1.00f)}, + {"AQUAMARINE", new Color(0.50f, 1.00f, 0.83f)}, + {"AZURE", new Color(0.94f, 1.00f, 1.00f)}, + {"BEIGE", new Color(0.96f, 0.96f, 0.86f)}, + {"BISQUE", new Color(1.00f, 0.89f, 0.77f)}, + {"BLACK", new Color(0.00f, 0.00f, 0.00f)}, + {"BLANCHEDALMOND", new Color(1.00f, 0.92f, 0.80f)}, + {"BLUE", new Color(0.00f, 0.00f, 1.00f)}, + {"BLUEVIOLET", new Color(0.54f, 0.17f, 0.89f)}, + {"BROWN", new Color(0.65f, 0.16f, 0.16f)}, + {"BURLYWOOD", new Color(0.87f, 0.72f, 0.53f)}, + {"CADETBLUE", new Color(0.37f, 0.62f, 0.63f)}, + {"CHARTREUSE", new Color(0.50f, 1.00f, 0.00f)}, + {"CHOCOLATE", new Color(0.82f, 0.41f, 0.12f)}, + {"CORAL", new Color(1.00f, 0.50f, 0.31f)}, + {"CORNFLOWERBLUE", new Color(0.39f, 0.58f, 0.93f)}, + {"CORNSILK", new Color(1.00f, 0.97f, 0.86f)}, + {"CRIMSON", new Color(0.86f, 0.08f, 0.24f)}, + {"CYAN", new Color(0.00f, 1.00f, 1.00f)}, + {"DARKBLUE", new Color(0.00f, 0.00f, 0.55f)}, + {"DARKCYAN", new Color(0.00f, 0.55f, 0.55f)}, + {"DARKGOLDENROD", new Color(0.72f, 0.53f, 0.04f)}, + {"DARKGRAY", new Color(0.66f, 0.66f, 0.66f)}, + {"DARKGREEN", new Color(0.00f, 0.39f, 0.00f)}, + {"DARKKHAKI", new Color(0.74f, 0.72f, 0.42f)}, + {"DARKMAGENTA", new Color(0.55f, 0.00f, 0.55f)}, + {"DARKOLIVEGREEN", new Color(0.33f, 0.42f, 0.18f)}, + {"DARKORANGE", new Color(1.00f, 0.55f, 0.00f)}, + {"DARKORCHID", new Color(0.60f, 0.20f, 0.80f)}, + {"DARKRED", new Color(0.55f, 0.00f, 0.00f)}, + {"DARKSALMON", new Color(0.91f, 0.59f, 0.48f)}, + {"DARKSEAGREEN", new Color(0.56f, 0.74f, 0.56f)}, + {"DARKSLATEBLUE", new Color(0.28f, 0.24f, 0.55f)}, + {"DARKSLATEGRAY", new Color(0.18f, 0.31f, 0.31f)}, + {"DARKTURQUOISE", new Color(0.00f, 0.81f, 0.82f)}, + {"DARKVIOLET", new Color(0.58f, 0.00f, 0.83f)}, + {"DEEPPINK", new Color(1.00f, 0.08f, 0.58f)}, + {"DEEPSKYBLUE", new Color(0.00f, 0.75f, 1.00f)}, + {"DIMGRAY", new Color(0.41f, 0.41f, 0.41f)}, + {"DODGERBLUE", new Color(0.12f, 0.56f, 1.00f)}, + {"FIREBRICK", new Color(0.70f, 0.13f, 0.13f)}, + {"FLORALWHITE", new Color(1.00f, 0.98f, 0.94f)}, + {"FORESTGREEN", new Color(0.13f, 0.55f, 0.13f)}, + {"FUCHSIA", new Color(1.00f, 0.00f, 1.00f)}, + {"GAINSBORO", new Color(0.86f, 0.86f, 0.86f)}, + {"GHOSTWHITE", new Color(0.97f, 0.97f, 1.00f)}, + {"GOLD", new Color(1.00f, 0.84f, 0.00f)}, + {"GOLDENROD", new Color(0.85f, 0.65f, 0.13f)}, + {"GRAY", new Color(0.75f, 0.75f, 0.75f)}, + {"GREEN", new Color(0.00f, 1.00f, 0.00f)}, + {"GREENYELLOW", new Color(0.68f, 1.00f, 0.18f)}, + {"HONEYDEW", new Color(0.94f, 1.00f, 0.94f)}, + {"HOTPINK", new Color(1.00f, 0.41f, 0.71f)}, + {"INDIANRED", new Color(0.80f, 0.36f, 0.36f)}, + {"INDIGO", new Color(0.29f, 0.00f, 0.51f)}, + {"IVORY", new Color(1.00f, 1.00f, 0.94f)}, + {"KHAKI", new Color(0.94f, 0.90f, 0.55f)}, + {"LAVENDER", new Color(0.90f, 0.90f, 0.98f)}, + {"LAVENDERBLUSH", new Color(1.00f, 0.94f, 0.96f)}, + {"LAWNGREEN", new Color(0.49f, 0.99f, 0.00f)}, + {"LEMONCHIFFON", new Color(1.00f, 0.98f, 0.80f)}, + {"LIGHTBLUE", new Color(0.68f, 0.85f, 0.90f)}, + {"LIGHTCORAL", new Color(0.94f, 0.50f, 0.50f)}, + {"LIGHTCYAN", new Color(0.88f, 1.00f, 1.00f)}, + {"LIGHTGOLDENROD", new Color(0.98f, 0.98f, 0.82f)}, + {"LIGHTGRAY", new Color(0.83f, 0.83f, 0.83f)}, + {"LIGHTGREEN", new Color(0.56f, 0.93f, 0.56f)}, + {"LIGHTPINK", new Color(1.00f, 0.71f, 0.76f)}, + {"LIGHTSALMON", new Color(1.00f, 0.63f, 0.48f)}, + {"LIGHTSEAGREEN", new Color(0.13f, 0.70f, 0.67f)}, + {"LIGHTSKYBLUE", new Color(0.53f, 0.81f, 0.98f)}, + {"LIGHTSLATEGRAY", new Color(0.47f, 0.53f, 0.60f)}, + {"LIGHTSTEELBLUE", new Color(0.69f, 0.77f, 0.87f)}, + {"LIGHTYELLOW", new Color(1.00f, 1.00f, 0.88f)}, + {"LIME", new Color(0.00f, 1.00f, 0.00f)}, + {"LIMEGREEN", new Color(0.20f, 0.80f, 0.20f)}, + {"LINEN", new Color(0.98f, 0.94f, 0.90f)}, + {"MAGENTA", new Color(1.00f, 0.00f, 1.00f)}, + {"MAROON", new Color(0.69f, 0.19f, 0.38f)}, + {"MEDIUMAQUAMARINE", new Color(0.40f, 0.80f, 0.67f)}, + {"MEDIUMBLUE", new Color(0.00f, 0.00f, 0.80f)}, + {"MEDIUMORCHID", new Color(0.73f, 0.33f, 0.83f)}, + {"MEDIUMPURPLE", new Color(0.58f, 0.44f, 0.86f)}, + {"MEDIUMSEAGREEN", new Color(0.24f, 0.70f, 0.44f)}, + {"MEDIUMSLATEBLUE", new Color(0.48f, 0.41f, 0.93f)}, + {"MEDIUMSPRINGGREEN", new Color(0.00f, 0.98f, 0.60f)}, + {"MEDIUMTURQUOISE", new Color(0.28f, 0.82f, 0.80f)}, + {"MEDIUMVIOLETRED", new Color(0.78f, 0.08f, 0.52f)}, + {"MIDNIGHTBLUE", new Color(0.10f, 0.10f, 0.44f)}, + {"MINTCREAM", new Color(0.96f, 1.00f, 0.98f)}, + {"MISTYROSE", new Color(1.00f, 0.89f, 0.88f)}, + {"MOCCASIN", new Color(1.00f, 0.89f, 0.71f)}, + {"NAVAJOWHITE", new Color(1.00f, 0.87f, 0.68f)}, + {"NAVYBLUE", new Color(0.00f, 0.00f, 0.50f)}, + {"OLDLACE", new Color(0.99f, 0.96f, 0.90f)}, + {"OLIVE", new Color(0.50f, 0.50f, 0.00f)}, + {"OLIVEDRAB", new Color(0.42f, 0.56f, 0.14f)}, + {"ORANGE", new Color(1.00f, 0.65f, 0.00f)}, + {"ORANGERED", new Color(1.00f, 0.27f, 0.00f)}, + {"ORCHID", new Color(0.85f, 0.44f, 0.84f)}, + {"PALEGOLDENROD", new Color(0.93f, 0.91f, 0.67f)}, + {"PALEGREEN", new Color(0.60f, 0.98f, 0.60f)}, + {"PALETURQUOISE", new Color(0.69f, 0.93f, 0.93f)}, + {"PALEVIOLETRED", new Color(0.86f, 0.44f, 0.58f)}, + {"PAPAYAWHIP", new Color(1.00f, 0.94f, 0.84f)}, + {"PEACHPUFF", new Color(1.00f, 0.85f, 0.73f)}, + {"PERU", new Color(0.80f, 0.52f, 0.25f)}, + {"PINK", new Color(1.00f, 0.75f, 0.80f)}, + {"PLUM", new Color(0.87f, 0.63f, 0.87f)}, + {"POWDERBLUE", new Color(0.69f, 0.88f, 0.90f)}, + {"PURPLE", new Color(0.63f, 0.13f, 0.94f)}, + {"REBECCAPURPLE", new Color(0.40f, 0.20f, 0.60f)}, + {"RED", new Color(1.00f, 0.00f, 0.00f)}, + {"ROSYBROWN", new Color(0.74f, 0.56f, 0.56f)}, + {"ROYALBLUE", new Color(0.25f, 0.41f, 0.88f)}, + {"SADDLEBROWN", new Color(0.55f, 0.27f, 0.07f)}, + {"SALMON", new Color(0.98f, 0.50f, 0.45f)}, + {"SANDYBROWN", new Color(0.96f, 0.64f, 0.38f)}, + {"SEAGREEN", new Color(0.18f, 0.55f, 0.34f)}, + {"SEASHELL", new Color(1.00f, 0.96f, 0.93f)}, + {"SIENNA", new Color(0.63f, 0.32f, 0.18f)}, + {"SILVER", new Color(0.75f, 0.75f, 0.75f)}, + {"SKYBLUE", new Color(0.53f, 0.81f, 0.92f)}, + {"SLATEBLUE", new Color(0.42f, 0.35f, 0.80f)}, + {"SLATEGRAY", new Color(0.44f, 0.50f, 0.56f)}, + {"SNOW", new Color(1.00f, 0.98f, 0.98f)}, + {"SPRINGGREEN", new Color(0.00f, 1.00f, 0.50f)}, + {"STEELBLUE", new Color(0.27f, 0.51f, 0.71f)}, + {"TAN", new Color(0.82f, 0.71f, 0.55f)}, + {"TEAL", new Color(0.00f, 0.50f, 0.50f)}, + {"THISTLE", new Color(0.85f, 0.75f, 0.85f)}, + {"TOMATO", new Color(1.00f, 0.39f, 0.28f)}, + {"TRANSPARENT", new Color(1.00f, 1.00f, 1.00f, 0.00f)}, + {"TURQUOISE", new Color(0.25f, 0.88f, 0.82f)}, + {"VIOLET", new Color(0.93f, 0.51f, 0.93f)}, + {"WEBGRAY", new Color(0.50f, 0.50f, 0.50f)}, + {"WEBGREEN", new Color(0.00f, 0.50f, 0.00f)}, + {"WEBMAROON", new Color(0.50f, 0.00f, 0.00f)}, + {"WEBPURPLE", new Color(0.50f, 0.00f, 0.50f)}, + {"WHEAT", new Color(0.96f, 0.87f, 0.70f)}, + {"WHITE", new Color(1.00f, 1.00f, 1.00f)}, + {"WHITESMOKE", new Color(0.96f, 0.96f, 0.96f)}, + {"YELLOW", new Color(1.00f, 1.00f, 0.00f)}, + {"YELLOWGREEN", new Color(0.60f, 0.80f, 0.20f)}, }; - public static Color AliceBlue { get { return namedColors["aliceblue"]; } } - public static Color AntiqueWhite { get { return namedColors["antiquewhite"]; } } - public static Color Aqua { get { return namedColors["aqua"]; } } - public static Color Aquamarine { get { return namedColors["aquamarine"]; } } - public static Color Azure { get { return namedColors["azure"]; } } - public static Color Beige { get { return namedColors["beige"]; } } - public static Color Bisque { get { return namedColors["bisque"]; } } - public static Color Black { get { return namedColors["black"]; } } - public static Color BlanchedAlmond { get { return namedColors["blanchedalmond"]; } } - public static Color Blue { get { return namedColors["blue"]; } } - public static Color BlueViolet { get { return namedColors["blueviolet"]; } } - public static Color Brown { get { return namedColors["brown"]; } } - public static Color BurlyWood { get { return namedColors["burlywood"]; } } - public static Color CadetBlue { get { return namedColors["cadetblue"]; } } - public static Color Chartreuse { get { return namedColors["chartreuse"]; } } - public static Color Chocolate { get { return namedColors["chocolate"]; } } - public static Color Coral { get { return namedColors["coral"]; } } - public static Color Cornflower { get { return namedColors["cornflower"]; } } - public static Color Cornsilk { get { return namedColors["cornsilk"]; } } - public static Color Crimson { get { return namedColors["crimson"]; } } - public static Color Cyan { get { return namedColors["cyan"]; } } - public static Color DarkBlue { get { return namedColors["darkblue"]; } } - public static Color DarkCyan { get { return namedColors["darkcyan"]; } } - public static Color DarkGoldenrod { get { return namedColors["darkgoldenrod"]; } } - public static Color DarkGray { get { return namedColors["darkgray"]; } } - public static Color DarkGreen { get { return namedColors["darkgreen"]; } } - public static Color DarkKhaki { get { return namedColors["darkkhaki"]; } } - public static Color DarkMagenta { get { return namedColors["darkmagenta"]; } } - public static Color DarkOliveGreen { get { return namedColors["darkolivegreen"]; } } - public static Color DarkOrange { get { return namedColors["darkorange"]; } } - public static Color DarkOrchid { get { return namedColors["darkorchid"]; } } - public static Color DarkRed { get { return namedColors["darkred"]; } } - public static Color DarkSalmon { get { return namedColors["darksalmon"]; } } - public static Color DarkSeaGreen { get { return namedColors["darkseagreen"]; } } - public static Color DarkSlateBlue { get { return namedColors["darkslateblue"]; } } - public static Color DarkSlateGray { get { return namedColors["darkslategray"]; } } - public static Color DarkTurquoise { get { return namedColors["darkturquoise"]; } } - public static Color DarkViolet { get { return namedColors["darkviolet"]; } } - public static Color DeepPink { get { return namedColors["deeppink"]; } } - public static Color DeepSkyBlue { get { return namedColors["deepskyblue"]; } } - public static Color DimGray { get { return namedColors["dimgray"]; } } - public static Color DodgerBlue { get { return namedColors["dodgerblue"]; } } - public static Color Firebrick { get { return namedColors["firebrick"]; } } - public static Color FloralWhite { get { return namedColors["floralwhite"]; } } - public static Color ForestGreen { get { return namedColors["forestgreen"]; } } - public static Color Fuchsia { get { return namedColors["fuchsia"]; } } - public static Color Gainsboro { get { return namedColors["gainsboro"]; } } - public static Color GhostWhite { get { return namedColors["ghostwhite"]; } } - public static Color Gold { get { return namedColors["gold"]; } } - public static Color Goldenrod { get { return namedColors["goldenrod"]; } } - public static Color Gray { get { return namedColors["gray"]; } } - public static Color Green { get { return namedColors["green"]; } } - public static Color GreenYellow { get { return namedColors["greenyellow"]; } } - public static Color Honeydew { get { return namedColors["honeydew"]; } } - public static Color HotPink { get { return namedColors["hotpink"]; } } - public static Color IndianRed { get { return namedColors["indianred"]; } } - public static Color Indigo { get { return namedColors["indigo"]; } } - public static Color Ivory { get { return namedColors["ivory"]; } } - public static Color Khaki { get { return namedColors["khaki"]; } } - public static Color Lavender { get { return namedColors["lavender"]; } } - public static Color LavenderBlush { get { return namedColors["lavenderblush"]; } } - public static Color LawnGreen { get { return namedColors["lawngreen"]; } } - public static Color LemonChiffon { get { return namedColors["lemonchiffon"]; } } - public static Color LightBlue { get { return namedColors["lightblue"]; } } - public static Color LightCoral { get { return namedColors["lightcoral"]; } } - public static Color LightCyan { get { return namedColors["lightcyan"]; } } - public static Color LightGoldenrod { get { return namedColors["lightgoldenrod"]; } } - public static Color LightGray { get { return namedColors["lightgray"]; } } - public static Color LightGreen { get { return namedColors["lightgreen"]; } } - public static Color LightPink { get { return namedColors["lightpink"]; } } - public static Color LightSalmon { get { return namedColors["lightsalmon"]; } } - public static Color LightSeaGreen { get { return namedColors["lightseagreen"]; } } - public static Color LightSkyBlue { get { return namedColors["lightskyblue"]; } } - public static Color LightSlateGray { get { return namedColors["lightslategray"]; } } - public static Color LightSteelBlue { get { return namedColors["lightsteelblue"]; } } - public static Color LightYellow { get { return namedColors["lightyellow"]; } } - public static Color Lime { get { return namedColors["lime"]; } } - public static Color Limegreen { get { return namedColors["limegreen"]; } } - public static Color Linen { get { return namedColors["linen"]; } } - public static Color Magenta { get { return namedColors["magenta"]; } } - public static Color Maroon { get { return namedColors["maroon"]; } } - public static Color MediumAquamarine { get { return namedColors["mediumaquamarine"]; } } - public static Color MediumBlue { get { return namedColors["mediumblue"]; } } - public static Color MediumOrchid { get { return namedColors["mediumorchid"]; } } - public static Color MediumPurple { get { return namedColors["mediumpurple"]; } } - public static Color MediumSeaGreen { get { return namedColors["mediumseagreen"]; } } - public static Color MediumSlateBlue { get { return namedColors["mediumslateblue"]; } } - public static Color MediumSpringGreen { get { return namedColors["mediumspringgreen"]; } } - public static Color MediumTurquoise { get { return namedColors["mediumturquoise"]; } } - public static Color MediumVioletRed { get { return namedColors["mediumvioletred"]; } } - public static Color MidnightBlue { get { return namedColors["midnightblue"]; } } - public static Color MintCream { get { return namedColors["mintcream"]; } } - public static Color MistyRose { get { return namedColors["mistyrose"]; } } - public static Color Moccasin { get { return namedColors["moccasin"]; } } - public static Color NavajoWhite { get { return namedColors["navajowhite"]; } } - public static Color NavyBlue { get { return namedColors["navyblue"]; } } - public static Color OldLace { get { return namedColors["oldlace"]; } } - public static Color Olive { get { return namedColors["olive"]; } } - public static Color OliveDrab { get { return namedColors["olivedrab"]; } } - public static Color Orange { get { return namedColors["orange"]; } } - public static Color OrangeRed { get { return namedColors["orangered"]; } } - public static Color Orchid { get { return namedColors["orchid"]; } } - public static Color PaleGoldenrod { get { return namedColors["palegoldenrod"]; } } - public static Color PaleGreen { get { return namedColors["palegreen"]; } } - public static Color PaleTurquoise { get { return namedColors["paleturquoise"]; } } - public static Color PaleVioletRed { get { return namedColors["palevioletred"]; } } - public static Color PapayaWhip { get { return namedColors["papayawhip"]; } } - public static Color PeachPuff { get { return namedColors["peachpuff"]; } } - public static Color Peru { get { return namedColors["peru"]; } } - public static Color Pink { get { return namedColors["pink"]; } } - public static Color Plum { get { return namedColors["plum"]; } } - public static Color PowderBlue { get { return namedColors["powderblue"]; } } - public static Color Purple { get { return namedColors["purple"]; } } - public static Color RebeccaPurple { get { return namedColors["rebeccapurple"]; } } - public static Color Red { get { return namedColors["red"]; } } - public static Color RosyBrown { get { return namedColors["rosybrown"]; } } - public static Color RoyalBlue { get { return namedColors["royalblue"]; } } - public static Color SaddleBrown { get { return namedColors["saddlebrown"]; } } - public static Color Salmon { get { return namedColors["salmon"]; } } - public static Color SandyBrown { get { return namedColors["sandybrown"]; } } - public static Color SeaGreen { get { return namedColors["seagreen"]; } } - public static Color SeaShell { get { return namedColors["seashell"]; } } - public static Color Sienna { get { return namedColors["sienna"]; } } - public static Color Silver { get { return namedColors["silver"]; } } - public static Color SkyBlue { get { return namedColors["skyblue"]; } } - public static Color SlateBlue { get { return namedColors["slateblue"]; } } - public static Color SlateGray { get { return namedColors["slategray"]; } } - public static Color Snow { get { return namedColors["snow"]; } } - public static Color SpringGreen { get { return namedColors["springgreen"]; } } - public static Color SteelBlue { get { return namedColors["steelblue"]; } } - public static Color Tan { get { return namedColors["tan"]; } } - public static Color Teal { get { return namedColors["teal"]; } } - public static Color Thistle { get { return namedColors["thistle"]; } } - public static Color Tomato { get { return namedColors["tomato"]; } } - public static Color Transparent { get { return namedColors["transparent"]; } } - public static Color Turquoise { get { return namedColors["turquoise"]; } } - public static Color Violet { get { return namedColors["violet"]; } } - public static Color WebGreen { get { return namedColors["webgreen"]; } } - public static Color WebGray { get { return namedColors["webgray"]; } } - public static Color WebMaroon { get { return namedColors["webmaroon"]; } } - public static Color WebPurple { get { return namedColors["webpurple"]; } } - public static Color Wheat { get { return namedColors["wheat"]; } } - public static Color White { get { return namedColors["white"]; } } - public static Color WhiteSmoke { get { return namedColors["whitesmoke"]; } } - public static Color Yellow { get { return namedColors["yellow"]; } } - public static Color YellowGreen { get { return namedColors["yellowgreen"]; } } + public static Color AliceBlue { get { return namedColors["ALICEBLUE"]; } } + public static Color AntiqueWhite { get { return namedColors["ANTIQUEWHITE"]; } } + public static Color Aqua { get { return namedColors["AQUA"]; } } + public static Color Aquamarine { get { return namedColors["AQUAMARINE"]; } } + public static Color Azure { get { return namedColors["AZURE"]; } } + public static Color Beige { get { return namedColors["BEIGE"]; } } + public static Color Bisque { get { return namedColors["BISQUE"]; } } + public static Color Black { get { return namedColors["BLACK"]; } } + public static Color BlanchedAlmond { get { return namedColors["BLANCHEDALMOND"]; } } + public static Color Blue { get { return namedColors["BLUE"]; } } + public static Color BlueViolet { get { return namedColors["BLUEVIOLET"]; } } + public static Color Brown { get { return namedColors["BROWN"]; } } + public static Color Burlywood { get { return namedColors["BURLYWOOD"]; } } + public static Color CadetBlue { get { return namedColors["CADETBLUE"]; } } + public static Color Chartreuse { get { return namedColors["CHARTREUSE"]; } } + public static Color Chocolate { get { return namedColors["CHOCOLATE"]; } } + public static Color Coral { get { return namedColors["CORAL"]; } } + public static Color CornflowerBlue { get { return namedColors["CORNFLOWERBLUE"]; } } + public static Color Cornsilk { get { return namedColors["CORNSILK"]; } } + public static Color Crimson { get { return namedColors["CRIMSON"]; } } + public static Color Cyan { get { return namedColors["CYAN"]; } } + public static Color DarkBlue { get { return namedColors["DARKBLUE"]; } } + public static Color DarkCyan { get { return namedColors["DARKCYAN"]; } } + public static Color DarkGoldenrod { get { return namedColors["DARKGOLDENROD"]; } } + public static Color DarkGray { get { return namedColors["DARKGRAY"]; } } + public static Color DarkGreen { get { return namedColors["DARKGREEN"]; } } + public static Color DarkKhaki { get { return namedColors["DARKKHAKI"]; } } + public static Color DarkMagenta { get { return namedColors["DARKMAGENTA"]; } } + public static Color DarkOliveGreen { get { return namedColors["DARKOLIVEGREEN"]; } } + public static Color DarkOrange { get { return namedColors["DARKORANGE"]; } } + public static Color DarkOrchid { get { return namedColors["DARKORCHID"]; } } + public static Color DarkRed { get { return namedColors["DARKRED"]; } } + public static Color DarkSalmon { get { return namedColors["DARKSALMON"]; } } + public static Color DarkSeaGreen { get { return namedColors["DARKSEAGREEN"]; } } + public static Color DarkSlateBlue { get { return namedColors["DARKSLATEBLUE"]; } } + public static Color DarkSlateGray { get { return namedColors["DARKSLATEGRAY"]; } } + public static Color DarkTurquoise { get { return namedColors["DARKTURQUOISE"]; } } + public static Color DarkViolet { get { return namedColors["DARKVIOLET"]; } } + public static Color DeepPink { get { return namedColors["DEEPPINK"]; } } + public static Color DeepSkyBlue { get { return namedColors["DEEPSKYBLUE"]; } } + public static Color DimGray { get { return namedColors["DIMGRAY"]; } } + public static Color DodgerBlue { get { return namedColors["DODGERBLUE"]; } } + public static Color Firebrick { get { return namedColors["FIREBRICK"]; } } + public static Color FloralWhite { get { return namedColors["FLORALWHITE"]; } } + public static Color ForestGreen { get { return namedColors["FORESTGREEN"]; } } + public static Color Fuchsia { get { return namedColors["FUCHSIA"]; } } + public static Color Gainsboro { get { return namedColors["GAINSBORO"]; } } + public static Color GhostWhite { get { return namedColors["GHOSTWHITE"]; } } + public static Color Gold { get { return namedColors["GOLD"]; } } + public static Color Goldenrod { get { return namedColors["GOLDENROD"]; } } + public static Color Gray { get { return namedColors["GRAY"]; } } + public static Color Green { get { return namedColors["GREEN"]; } } + public static Color GreenYellow { get { return namedColors["GREENYELLOW"]; } } + public static Color Honeydew { get { return namedColors["HONEYDEW"]; } } + public static Color HotPink { get { return namedColors["HOTPINK"]; } } + public static Color IndianRed { get { return namedColors["INDIANRED"]; } } + public static Color Indigo { get { return namedColors["INDIGO"]; } } + public static Color Ivory { get { return namedColors["IVORY"]; } } + public static Color Khaki { get { return namedColors["KHAKI"]; } } + public static Color Lavender { get { return namedColors["LAVENDER"]; } } + public static Color LavenderBlush { get { return namedColors["LAVENDERBLUSH"]; } } + public static Color LawnGreen { get { return namedColors["LAWNGREEN"]; } } + public static Color LemonChiffon { get { return namedColors["LEMONCHIFFON"]; } } + public static Color LightBlue { get { return namedColors["LIGHTBLUE"]; } } + public static Color LightCoral { get { return namedColors["LIGHTCORAL"]; } } + public static Color LightCyan { get { return namedColors["LIGHTCYAN"]; } } + public static Color LightGoldenrod { get { return namedColors["LIGHTGOLDENROD"]; } } + public static Color LightGray { get { return namedColors["LIGHTGRAY"]; } } + public static Color LightGreen { get { return namedColors["LIGHTGREEN"]; } } + public static Color LightPink { get { return namedColors["LIGHTPINK"]; } } + public static Color LightSalmon { get { return namedColors["LIGHTSALMON"]; } } + public static Color LightSeaGreen { get { return namedColors["LIGHTSEAGREEN"]; } } + public static Color LightSkyBlue { get { return namedColors["LIGHTSKYBLUE"]; } } + public static Color LightSlateGray { get { return namedColors["LIGHTSLATEGRAY"]; } } + public static Color LightSteelBlue { get { return namedColors["LIGHTSTEELBLUE"]; } } + public static Color LightYellow { get { return namedColors["LIGHTYELLOW"]; } } + public static Color Lime { get { return namedColors["LIME"]; } } + public static Color LimeGreen { get { return namedColors["LIMEGREEN"]; } } + public static Color Linen { get { return namedColors["LINEN"]; } } + public static Color Magenta { get { return namedColors["MAGENTA"]; } } + public static Color Maroon { get { return namedColors["MAROON"]; } } + public static Color MediumAquamarine { get { return namedColors["MEDIUMAQUAMARINE"]; } } + public static Color MediumBlue { get { return namedColors["MEDIUMBLUE"]; } } + public static Color MediumOrchid { get { return namedColors["MEDIUMORCHID"]; } } + public static Color MediumPurple { get { return namedColors["MEDIUMPURPLE"]; } } + public static Color MediumSeaGreen { get { return namedColors["MEDIUMSEAGREEN"]; } } + public static Color MediumSlateBlue { get { return namedColors["MEDIUMSLATEBLUE"]; } } + public static Color MediumSpringGreen { get { return namedColors["MEDIUMSPRINGGREEN"]; } } + public static Color MediumTurquoise { get { return namedColors["MEDIUMTURQUOISE"]; } } + public static Color MediumVioletRed { get { return namedColors["MEDIUMVIOLETRED"]; } } + public static Color MidnightBlue { get { return namedColors["MIDNIGHTBLUE"]; } } + public static Color MintCream { get { return namedColors["MINTCREAM"]; } } + public static Color MistyRose { get { return namedColors["MISTYROSE"]; } } + public static Color Moccasin { get { return namedColors["MOCCASIN"]; } } + public static Color NavajoWhite { get { return namedColors["NAVAJOWHITE"]; } } + public static Color NavyBlue { get { return namedColors["NAVYBLUE"]; } } + public static Color OldLace { get { return namedColors["OLDLACE"]; } } + public static Color Olive { get { return namedColors["OLIVE"]; } } + public static Color OliveDrab { get { return namedColors["OLIVEDRAB"]; } } + public static Color Orange { get { return namedColors["ORANGE"]; } } + public static Color OrangeRed { get { return namedColors["ORANGERED"]; } } + public static Color Orchid { get { return namedColors["ORCHID"]; } } + public static Color PaleGoldenrod { get { return namedColors["PALEGOLDENROD"]; } } + public static Color PaleGreen { get { return namedColors["PALEGREEN"]; } } + public static Color PaleTurquoise { get { return namedColors["PALETURQUOISE"]; } } + public static Color PaleVioletRed { get { return namedColors["PALEVIOLETRED"]; } } + public static Color PapayaWhip { get { return namedColors["PAPAYAWHIP"]; } } + public static Color PeachPuff { get { return namedColors["PEACHPUFF"]; } } + public static Color Peru { get { return namedColors["PERU"]; } } + public static Color Pink { get { return namedColors["PINK"]; } } + public static Color Plum { get { return namedColors["PLUM"]; } } + public static Color PowderBlue { get { return namedColors["POWDERBLUE"]; } } + public static Color Purple { get { return namedColors["PURPLE"]; } } + public static Color RebeccaPurple { get { return namedColors["REBECCAPURPLE"]; } } + public static Color Red { get { return namedColors["RED"]; } } + public static Color RosyBrown { get { return namedColors["ROSYBROWN"]; } } + public static Color RoyalBlue { get { return namedColors["ROYALBLUE"]; } } + public static Color SaddleBrown { get { return namedColors["SADDLEBROWN"]; } } + public static Color Salmon { get { return namedColors["SALMON"]; } } + public static Color SandyBrown { get { return namedColors["SANDYBROWN"]; } } + public static Color SeaGreen { get { return namedColors["SEAGREEN"]; } } + public static Color Seashell { get { return namedColors["SEASHELL"]; } } + public static Color Sienna { get { return namedColors["SIENNA"]; } } + public static Color Silver { get { return namedColors["SILVER"]; } } + public static Color SkyBlue { get { return namedColors["SKYBLUE"]; } } + public static Color SlateBlue { get { return namedColors["SLATEBLUE"]; } } + public static Color SlateGray { get { return namedColors["SLATEGRAY"]; } } + public static Color Snow { get { return namedColors["SNOW"]; } } + public static Color SpringGreen { get { return namedColors["SPRINGGREEN"]; } } + public static Color SteelBlue { get { return namedColors["STEELBLUE"]; } } + public static Color Tan { get { return namedColors["TAN"]; } } + public static Color Teal { get { return namedColors["TEAL"]; } } + public static Color Thistle { get { return namedColors["THISTLE"]; } } + public static Color Tomato { get { return namedColors["TOMATO"]; } } + public static Color Transparent { get { return namedColors["TRANSPARENT"]; } } + public static Color Turquoise { get { return namedColors["TURQUOISE"]; } } + public static Color Violet { get { return namedColors["VIOLET"]; } } + public static Color WebGray { get { return namedColors["WEBGRAY"]; } } + public static Color WebGreen { get { return namedColors["WEBGREEN"]; } } + public static Color WebMaroon { get { return namedColors["WEBMAROON"]; } } + public static Color WebPurple { get { return namedColors["WEBPURPLE"]; } } + public static Color Wheat { get { return namedColors["WHEAT"]; } } + public static Color White { get { return namedColors["WHITE"]; } } + public static Color WhiteSmoke { get { return namedColors["WHITESMOKE"]; } } + public static Color Yellow { get { return namedColors["YELLOW"]; } } + public static Color YellowGreen { get { return namedColors["YELLOWGREEN"]; } } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs index 785e87a043..1dca9e6ea7 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/DelegateUtils.cs @@ -61,7 +61,7 @@ namespace Godot using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { - writer.Write((ulong) TargetKind.Static); + writer.Write((ulong)TargetKind.Static); SerializeType(writer, @delegate.GetType()); @@ -77,8 +77,8 @@ namespace Godot using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { - writer.Write((ulong) TargetKind.GodotObject); - writer.Write((ulong) godotObject.GetInstanceId()); + writer.Write((ulong)TargetKind.GodotObject); + writer.Write((ulong)godotObject.GetInstanceId()); SerializeType(writer, @delegate.GetType()); @@ -100,7 +100,7 @@ namespace Godot using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) { - writer.Write((ulong) TargetKind.CompilerGenerated); + writer.Write((ulong)TargetKind.CompilerGenerated); SerializeType(writer, targetType); SerializeType(writer, @delegate.GetType()); @@ -149,14 +149,14 @@ namespace Godot int flags = 0; if (methodInfo.IsPublic) - flags |= (int) BindingFlags.Public; + flags |= (int)BindingFlags.Public; else - flags |= (int) BindingFlags.NonPublic; + flags |= (int)BindingFlags.NonPublic; if (methodInfo.IsStatic) - flags |= (int) BindingFlags.Static; + flags |= (int)BindingFlags.Static; else - flags |= (int) BindingFlags.Instance; + flags |= (int)BindingFlags.Instance; writer.Write(flags); @@ -238,7 +238,7 @@ namespace Godot } else { - if (TryDeserializeSingleDelegate((byte[]) elem, out Delegate oneDelegate)) + if (TryDeserializeSingleDelegate((byte[])elem, out Delegate oneDelegate)) delegates.Add(oneDelegate); } } @@ -257,7 +257,7 @@ namespace Godot using (var stream = new MemoryStream(buffer, writable: false)) using (var reader = new BinaryReader(stream)) { - var targetKind = (TargetKind) reader.ReadUInt64(); + var targetKind = (TargetKind)reader.ReadUInt64(); switch (targetKind) { @@ -353,11 +353,11 @@ namespace Godot parameterTypes[i] = parameterType; } - methodInfo = declaringType.GetMethod(methodName, (BindingFlags) flags, null, parameterTypes, null); + methodInfo = declaringType.GetMethod(methodName, (BindingFlags)flags, null, parameterTypes, null); return methodInfo != null && methodInfo.ReturnType == returnType; } - methodInfo = declaringType.GetMethod(methodName, (BindingFlags) flags); + methodInfo = declaringType.GetMethod(methodName, (BindingFlags)flags); return methodInfo != null && methodInfo.ReturnType == returnType; } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs index 213fc181c1..61a34bfc87 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Dictionary.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Diagnostics.CodeAnalysis; namespace Godot.Collections { @@ -25,6 +26,11 @@ namespace Godot.Collections } } + /// <summary> + /// Wrapper around Godot's Dictionary class, a dictionary of Variant + /// typed elements allocated in the engine in C++. Useful when + /// interfacing with the engine. + /// </summary> public class Dictionary : IDictionary, IDisposable @@ -32,11 +38,19 @@ namespace Godot.Collections DictionarySafeHandle safeHandle; bool disposed = false; + /// <summary> + /// Constructs a new empty <see cref="Dictionary"/>. + /// </summary> public Dictionary() { safeHandle = new DictionarySafeHandle(godot_icall_Dictionary_Ctor()); } + /// <summary> + /// Constructs a new <see cref="Dictionary"/> from the given dictionary's elements. + /// </summary> + /// <param name="dictionary">The dictionary to construct from.</param> + /// <returns>A new Godot Dictionary.</returns> public Dictionary(IDictionary dictionary) : this() { if (dictionary == null) @@ -64,6 +78,9 @@ namespace Godot.Collections return safeHandle.DangerousGetHandle(); } + /// <summary> + /// Disposes of this <see cref="Dictionary"/>. + /// </summary> public void Dispose() { if (disposed) @@ -78,6 +95,11 @@ namespace Godot.Collections disposed = true; } + /// <summary> + /// Duplicates this <see cref="Dictionary"/>. + /// </summary> + /// <param name="deep">If <see langword="true"/>, performs a deep copy.</param> + /// <returns>A new Godot Dictionary.</returns> public Dictionary Duplicate(bool deep = false) { return new Dictionary(godot_icall_Dictionary_Duplicate(GetPtr(), deep)); @@ -85,6 +107,9 @@ namespace Godot.Collections // IDictionary + /// <summary> + /// Gets the collection of keys in this <see cref="Dictionary"/>. + /// </summary> public ICollection Keys { get @@ -94,6 +119,9 @@ namespace Godot.Collections } } + /// <summary> + /// Gets the collection of elements in this <see cref="Dictionary"/>. + /// </summary> public ICollection Values { get @@ -103,47 +131,88 @@ namespace Godot.Collections } } - public bool IsFixedSize => false; + private (Array keys, Array values, int count) GetKeyValuePairs() + { + int count = godot_icall_Dictionary_KeyValuePairs(GetPtr(), out IntPtr keysHandle, out IntPtr valuesHandle); + Array keys = new Array(new ArraySafeHandle(keysHandle)); + Array values = new Array(new ArraySafeHandle(valuesHandle)); + return (keys, values, count); + } + + bool IDictionary.IsFixedSize => false; - public bool IsReadOnly => false; + bool IDictionary.IsReadOnly => false; + /// <summary> + /// Returns the object at the given <paramref name="key"/>. + /// </summary> + /// <value>The object at the given <paramref name="key"/>.</value> public object this[object key] { get => godot_icall_Dictionary_GetValue(GetPtr(), key); set => godot_icall_Dictionary_SetValue(GetPtr(), key, value); } + /// <summary> + /// Adds an object <paramref name="value"/> at key <paramref name="key"/> + /// to this <see cref="Dictionary"/>. + /// </summary> + /// <param name="key">The key at which to add the object.</param> + /// <param name="value">The object to add.</param> public void Add(object key, object value) => godot_icall_Dictionary_Add(GetPtr(), key, value); + /// <summary> + /// Erases all items from this <see cref="Dictionary"/>. + /// </summary> public void Clear() => godot_icall_Dictionary_Clear(GetPtr()); + /// <summary> + /// Checks if this <see cref="Dictionary"/> contains the given key. + /// </summary> + /// <param name="key">The key to look for.</param> + /// <returns>Whether or not this dictionary contains the given key.</returns> public bool Contains(object key) => godot_icall_Dictionary_ContainsKey(GetPtr(), key); + /// <summary> + /// Gets an enumerator for this <see cref="Dictionary"/>. + /// </summary> + /// <returns>An enumerator.</returns> public IDictionaryEnumerator GetEnumerator() => new DictionaryEnumerator(this); + /// <summary> + /// Removes an element from this <see cref="Dictionary"/> by key. + /// </summary> + /// <param name="key">The key of the element to remove.</param> public void Remove(object key) => godot_icall_Dictionary_RemoveKey(GetPtr(), key); // ICollection - public object SyncRoot => this; + object ICollection.SyncRoot => this; - public bool IsSynchronized => false; + bool ICollection.IsSynchronized => false; + /// <summary> + /// Returns the number of elements in this <see cref="Dictionary"/>. + /// This is also known as the size or length of the dictionary. + /// </summary> + /// <returns>The number of elements.</returns> public int Count => godot_icall_Dictionary_Count(GetPtr()); + /// <summary> + /// Copies the elements of this <see cref="Dictionary"/> to the given + /// untyped C# array, starting at the given index. + /// </summary> + /// <param name="array">The array to copy to.</param> + /// <param name="index">The index to start at.</param> public void CopyTo(System.Array array, int index) { - // TODO Can be done with single internal call - if (array == null) throw new ArgumentNullException(nameof(array), "Value cannot be null."); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), "Number was less than the array's lower bound in the first dimension."); - Array keys = (Array)Keys; - Array values = (Array)Values; - int count = Count; + var (keys, values, count) = GetKeyValuePairs(); if (array.Length < (index + count)) throw new ArgumentException("Destination array was not long enough. Check destIndex and length, and the array's lower bounds."); @@ -161,24 +230,39 @@ namespace Godot.Collections private class DictionaryEnumerator : IDictionaryEnumerator { - Array keys; - Array values; - int count; - int index = -1; + private readonly Dictionary dictionary; + private readonly int count; + private int index = -1; + private bool dirty = true; + + private DictionaryEntry entry; public DictionaryEnumerator(Dictionary dictionary) { - // TODO 3 internal calls, can reduce to 1 - keys = (Array)dictionary.Keys; - values = (Array)dictionary.Values; + this.dictionary = dictionary; count = dictionary.Count; } public object Current => Entry; - public DictionaryEntry Entry => - // TODO 2 internal calls, can reduce to 1 - new DictionaryEntry(keys[index], values[index]); + public DictionaryEntry Entry + { + get + { + if (dirty) + { + UpdateEntry(); + } + return entry; + } + } + + private void UpdateEntry() + { + dirty = false; + godot_icall_Dictionary_KeyValuePairAt(dictionary.GetPtr(), index, out object key, out object value); + entry = new DictionaryEntry(key, value); + } public object Key => Entry.Key; @@ -187,15 +271,21 @@ namespace Godot.Collections public bool MoveNext() { index++; + dirty = true; return index < count; } public void Reset() { index = -1; + dirty = true; } } + /// <summary> + /// Converts this <see cref="Dictionary"/> to a string. + /// </summary> + /// <returns>A string representation of this dictionary.</returns> public override string ToString() { return godot_icall_Dictionary_ToString(GetPtr()); @@ -226,6 +316,12 @@ namespace Godot.Collections internal extern static int godot_icall_Dictionary_Count(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static int godot_icall_Dictionary_KeyValuePairs(IntPtr ptr, out IntPtr keys, out IntPtr values); + + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern static void godot_icall_Dictionary_KeyValuePairAt(IntPtr ptr, int index, out object key, out object value); + + [MethodImpl(MethodImplOptions.InternalCall)] internal extern static void godot_icall_Dictionary_Add(IntPtr ptr, object key, object value); [MethodImpl(MethodImplOptions.InternalCall)] @@ -259,10 +355,18 @@ namespace Godot.Collections internal extern static string godot_icall_Dictionary_ToString(IntPtr ptr); } + /// <summary> + /// Typed wrapper around Godot's Dictionary class, a dictionary of Variant + /// typed elements allocated in the engine in C++. Useful when + /// interfacing with the engine. Otherwise prefer .NET collections + /// such as <see cref="System.Collections.Generic.Dictionary{TKey, TValue}"/>. + /// </summary> + /// <typeparam name="TKey">The type of the dictionary's keys.</typeparam> + /// <typeparam name="TValue">The type of the dictionary's values.</typeparam> public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue> { - Dictionary objectDict; + private readonly Dictionary objectDict; internal static int valTypeEncoding; internal static IntPtr valTypeClass; @@ -272,11 +376,19 @@ namespace Godot.Collections Dictionary.godot_icall_Dictionary_Generic_GetValueTypeInfo(typeof(TValue), out valTypeEncoding, out valTypeClass); } + /// <summary> + /// Constructs a new empty <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> public Dictionary() { objectDict = new Dictionary(); } + /// <summary> + /// Constructs a new <see cref="Dictionary{TKey, TValue}"/> from the given dictionary's elements. + /// </summary> + /// <param name="dictionary">The dictionary to construct from.</param> + /// <returns>A new Godot Dictionary.</returns> public Dictionary(IDictionary<TKey, TValue> dictionary) { objectDict = new Dictionary(); @@ -294,6 +406,11 @@ namespace Godot.Collections } } + /// <summary> + /// Constructs a new <see cref="Dictionary{TKey, TValue}"/> from the given dictionary's elements. + /// </summary> + /// <param name="dictionary">The dictionary to construct from.</param> + /// <returns>A new Godot Dictionary.</returns> public Dictionary(Dictionary dictionary) { objectDict = dictionary; @@ -309,6 +426,10 @@ namespace Godot.Collections objectDict = new Dictionary(handle); } + /// <summary> + /// Converts this typed <see cref="Dictionary{TKey, TValue}"/> to an untyped <see cref="Dictionary"/>. + /// </summary> + /// <param name="from">The typed dictionary to convert.</param> public static explicit operator Dictionary(Dictionary<TKey, TValue> from) { return from.objectDict; @@ -319,6 +440,11 @@ namespace Godot.Collections return objectDict.GetPtr(); } + /// <summary> + /// Duplicates this <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> + /// <param name="deep">If <see langword="true"/>, performs a deep copy.</param> + /// <returns>A new Godot Dictionary.</returns> public Dictionary<TKey, TValue> Duplicate(bool deep = false) { return new Dictionary<TKey, TValue>(objectDict.Duplicate(deep)); @@ -326,12 +452,19 @@ namespace Godot.Collections // IDictionary<TKey, TValue> + /// <summary> + /// Returns the value at the given <paramref name="key"/>. + /// </summary> + /// <value>The value at the given <paramref name="key"/>.</value> public TValue this[TKey key] { get { return (TValue)Dictionary.godot_icall_Dictionary_GetValue_Generic(objectDict.GetPtr(), key, valTypeEncoding, valTypeClass); } set { objectDict[key] = value; } } + /// <summary> + /// Gets the collection of keys in this <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> public ICollection<TKey> Keys { get @@ -341,6 +474,9 @@ namespace Godot.Collections } } + /// <summary> + /// Gets the collection of elements in this <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> public ICollection<TValue> Values { get @@ -350,56 +486,93 @@ namespace Godot.Collections } } + private KeyValuePair<TKey, TValue> GetKeyValuePair(int index) + { + Dictionary.godot_icall_Dictionary_KeyValuePairAt(GetPtr(), index, out object key, out object value); + return new KeyValuePair<TKey, TValue>((TKey)key, (TValue)value); + } + + /// <summary> + /// Adds an object <paramref name="value"/> at key <paramref name="key"/> + /// to this <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> + /// <param name="key">The key at which to add the object.</param> + /// <param name="value">The object to add.</param> public void Add(TKey key, TValue value) { objectDict.Add(key, value); } + /// <summary> + /// Checks if this <see cref="Dictionary{TKey, TValue}"/> contains the given key. + /// </summary> + /// <param name="key">The key to look for.</param> + /// <returns>Whether or not this dictionary contains the given key.</returns> public bool ContainsKey(TKey key) { return objectDict.Contains(key); } + /// <summary> + /// Removes an element from this <see cref="Dictionary{TKey, TValue}"/> by key. + /// </summary> + /// <param name="key">The key of the element to remove.</param> public bool Remove(TKey key) { return Dictionary.godot_icall_Dictionary_RemoveKey(GetPtr(), key); } - public bool TryGetValue(TKey key, out TValue value) + /// <summary> + /// Gets the object at the given <paramref name="key"/>. + /// </summary> + /// <param name="key">The key of the element to get.</param> + /// <param name="value">The value at the given <paramref name="key"/>.</param> + /// <returns>If an object was found for the given <paramref name="key"/>.</returns> + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { - object retValue; - bool found = Dictionary.godot_icall_Dictionary_TryGetValue_Generic(GetPtr(), key, out retValue, valTypeEncoding, valTypeClass); - value = found ? (TValue)retValue : default(TValue); + bool found = Dictionary.godot_icall_Dictionary_TryGetValue_Generic(GetPtr(), key, out object retValue, valTypeEncoding, valTypeClass); + value = found ? (TValue)retValue : default; return found; } // ICollection<KeyValuePair<TKey, TValue>> + /// <summary> + /// Returns the number of elements in this <see cref="Dictionary{TKey, TValue}"/>. + /// This is also known as the size or length of the dictionary. + /// </summary> + /// <returns>The number of elements.</returns> public int Count { get { return objectDict.Count; } } - public bool IsReadOnly - { - get { return objectDict.IsReadOnly; } - } + bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false; - public void Add(KeyValuePair<TKey, TValue> item) + void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { objectDict.Add(item.Key, item.Value); } + /// <summary> + /// Erases all the items from this <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> public void Clear() { objectDict.Clear(); } - public bool Contains(KeyValuePair<TKey, TValue> item) + bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return objectDict.Contains(new KeyValuePair<object, object>(item.Key, item.Value)); } + /// <summary> + /// Copies the elements of this <see cref="Dictionary{TKey, TValue}"/> to the given + /// untyped C# array, starting at the given index. + /// </summary> + /// <param name="array">The array to copy to.</param> + /// <param name="arrayIndex">The index to start at.</param> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (array == null) @@ -408,9 +581,6 @@ namespace Godot.Collections if (arrayIndex < 0) throw new ArgumentOutOfRangeException(nameof(arrayIndex), "Number was less than the array's lower bound in the first dimension."); - // TODO 3 internal calls, can reduce to 1 - Array<TKey> keys = (Array<TKey>)Keys; - Array<TValue> values = (Array<TValue>)Values; int count = Count; if (array.Length < (arrayIndex + count)) @@ -418,13 +588,12 @@ namespace Godot.Collections for (int i = 0; i < count; i++) { - // TODO 2 internal calls, can reduce to 1 - array[arrayIndex] = new KeyValuePair<TKey, TValue>(keys[i], values[i]); + array[arrayIndex] = GetKeyValuePair(i); arrayIndex++; } } - public bool Remove(KeyValuePair<TKey, TValue> item) + bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { return Dictionary.godot_icall_Dictionary_Remove(GetPtr(), item.Key, item.Value); ; @@ -432,17 +601,15 @@ namespace Godot.Collections // IEnumerable<KeyValuePair<TKey, TValue>> + /// <summary> + /// Gets an enumerator for this <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> + /// <returns>An enumerator.</returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { - // TODO 3 internal calls, can reduce to 1 - Array<TKey> keys = (Array<TKey>)Keys; - Array<TValue> values = (Array<TValue>)Values; - int count = Count; - - for (int i = 0; i < count; i++) + for (int i = 0; i < Count; i++) { - // TODO 2 internal calls, can reduce to 1 - yield return new KeyValuePair<TKey, TValue>(keys[i], values[i]); + yield return GetKeyValuePair(i); } } @@ -451,6 +618,10 @@ namespace Godot.Collections return GetEnumerator(); } + /// <summary> + /// Converts this <see cref="Dictionary{TKey, TValue}"/> to a string. + /// </summary> + /// <returns>A string representation of this dictionary.</returns> public override string ToString() => objectDict.ToString(); } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs index c4c911b863..0c21bcaa3f 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/DynamicObject.cs @@ -1,4 +1,3 @@ - using System; using System.Collections.Generic; using System.Dynamic; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/PackedSceneExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/PackedSceneExtensions.cs index 763f470504..214bbf5179 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/PackedSceneExtensions.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/PackedSceneExtensions.cs @@ -8,9 +8,9 @@ namespace Godot /// `Node.NotificationInstanced` notification on the root node. /// </summary> /// <typeparam name="T">The type to cast to. Should be a descendant of Node.</typeparam> - public T Instance<T>(PackedScene.GenEditState editState = (PackedScene.GenEditState)0) where T : class + public T Instantiate<T>(PackedScene.GenEditState editState = (PackedScene.GenEditState)0) where T : class { - return (T)(object)Instance(editState); + return (T)(object)Instantiate(editState); } /// <summary> @@ -19,9 +19,9 @@ namespace Godot /// `Node.NotificationInstanced` notification on the root node. /// </summary> /// <typeparam name="T">The type to cast to. Should be a descendant of Node.</typeparam> - public T InstanceOrNull<T>(PackedScene.GenEditState editState = (PackedScene.GenEditState)0) where T : class + public T InstantiateOrNull<T>(PackedScene.GenEditState editState = (PackedScene.GenEditState)0) where T : class { - return Instance(editState) as T; + return Instantiate(editState) as T; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs index 6699c5992c..71d0593916 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GD.cs @@ -1,12 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; - #endif +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; // TODO: Add comments describing what this class does. It is not obvious. @@ -26,17 +25,17 @@ namespace Godot public static real_t Db2Linear(real_t db) { - return (real_t) Math.Exp(db * 0.11512925464970228420089957273422); + return (real_t)Math.Exp(db * 0.11512925464970228420089957273422); } - public static real_t DecTime(real_t value, real_t amount, real_t step) + private static object[] GetPrintParams(object[] parameters) { - real_t sgn = Mathf.Sign(value); - real_t val = Mathf.Abs(value); - val -= amount * step; - if (val < 0) - val = 0; - return val * sgn; + if (parameters == null) + { + return new[] { "null" }; + } + + return Array.ConvertAll(parameters, x => x?.ToString() ?? "null"); } public static int Hash(object var) @@ -51,7 +50,7 @@ namespace Godot public static real_t Linear2Db(real_t linear) { - return (real_t) (Math.Log(linear) * 8.6858896380650365530225783783321); + return (real_t)(Math.Log(linear) * 8.6858896380650365530225783783321); } public static Resource Load(string path) @@ -76,7 +75,7 @@ namespace Godot public static void Print(params object[] what) { - godot_icall_GD_print(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); + godot_icall_GD_print(GetPrintParams(what)); } public static void PrintStack() @@ -86,22 +85,22 @@ namespace Godot public static void PrintErr(params object[] what) { - godot_icall_GD_printerr(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); + godot_icall_GD_printerr(GetPrintParams(what)); } public static void PrintRaw(params object[] what) { - godot_icall_GD_printraw(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); + godot_icall_GD_printraw(GetPrintParams(what)); } public static void PrintS(params object[] what) { - godot_icall_GD_prints(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); + godot_icall_GD_prints(GetPrintParams(what)); } public static void PrintT(params object[] what) { - godot_icall_GD_printt(Array.ConvertAll(what ?? new object[]{"null"}, x => x != null ? x.ToString() : "null")); + godot_icall_GD_printt(GetPrintParams(what)); } public static float Randf() @@ -129,9 +128,9 @@ namespace Godot return godot_icall_GD_randi_range(from, to); } - public static uint RandSeed(ulong seed, out ulong newSeed) + public static uint RandFromSeed(ref ulong seed) { - return godot_icall_GD_rand_seed(seed, out newSeed); + return godot_icall_GD_rand_seed(seed, out seed); } public static IEnumerable<int> Range(int end) diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs index f1a00ae0fa..a566b53659 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotTraceListener.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics; namespace Godot diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs index 702a6c76ba..729529d093 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/GodotUnhandledExceptionEvent.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Godot { diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs index c59d083080..f508211f68 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/MarshalUtils.cs @@ -1,12 +1,8 @@ using System; -using System.Collections; using System.Collections.Generic; namespace Godot { - using Array = Godot.Collections.Array; - using Dictionary = Godot.Collections.Dictionary; - static class MarshalUtils { /// <summary> diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs index c3f372d415..213f84ad73 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Mathf.cs @@ -1,9 +1,9 @@ -using System; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; namespace Godot { @@ -14,13 +14,15 @@ namespace Godot /// <summary> /// The circle constant, the circumference of the unit circle in radians. /// </summary> - public const real_t Tau = (real_t) 6.2831853071795864769252867666M; // 6.2831855f and 6.28318530717959 + // 6.2831855f and 6.28318530717959 + public const real_t Tau = (real_t)6.2831853071795864769252867666M; /// <summary> /// Constant that represents how many times the diameter of a circle /// fits around its perimeter. This is equivalent to `Mathf.Tau / 2`. /// </summary> - public const real_t Pi = (real_t) 3.1415926535897932384626433833M; // 3.1415927f and 3.14159265358979 + // 3.1415927f and 3.14159265358979 + public const real_t Pi = (real_t)3.1415926535897932384626433833M; /// <summary> /// Positive infinity. For negative infinity, use `-Mathf.Inf`. @@ -34,8 +36,10 @@ namespace Godot /// </summary> public const real_t NaN = real_t.NaN; - private const real_t Deg2RadConst = (real_t) 0.0174532925199432957692369077M; // 0.0174532924f and 0.0174532925199433 - private const real_t Rad2DegConst = (real_t) 57.295779513082320876798154814M; // 57.29578f and 57.2957795130823 + // 0.0174532924f and 0.0174532925199433 + private const real_t Deg2RadConst = (real_t)0.0174532925199432957692369077M; + // 57.29578f and 57.2957795130823 + private const real_t Rad2DegConst = (real_t)57.295779513082320876798154814M; /// <summary> /// Returns the absolute value of `s` (i.e. positive value). @@ -515,7 +519,8 @@ namespace Godot /// <returns>One of three possible values: `1`, `-1`, or `0`.</returns> public static int Sign(int s) { - if (s == 0) return 0; + if (s == 0) + return 0; return s < 0 ? -1 : 1; } @@ -526,7 +531,8 @@ namespace Godot /// <returns>One of three possible values: `1`, `-1`, or `0`.</returns> public static int Sign(real_t s) { - if (s == 0) return 0; + if (s == 0) + return 0; return s < 0 ? -1 : 1; } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs index c2f4701b5f..0888e33090 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/MathfEx.cs @@ -1,10 +1,9 @@ -using System; - #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; namespace Godot { @@ -15,12 +14,12 @@ namespace Godot /// <summary> /// The natural number `e`. /// </summary> - public const real_t E = (real_t) 2.7182818284590452353602874714M; // 2.7182817f and 2.718281828459045 + public const real_t E = (real_t)2.7182818284590452353602874714M; // 2.7182817f and 2.718281828459045 /// <summary> /// The square root of 2. /// </summary> - public const real_t Sqrt2 = (real_t) 1.4142135623730950488016887242M; // 1.4142136f and 1.414213562373095 + public const real_t Sqrt2 = (real_t)1.4142135623730950488016887242M; // 1.4142136f and 1.414213562373095 /// <summary> /// A very small number used for float comparison with error tolerance. diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs index 48582d5ad8..d486d79557 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Object.base.cs @@ -66,7 +66,7 @@ namespace Godot if (memoryOwn) { memoryOwn = false; - godot_icall_Reference_Disposed(this, ptr, !disposing); + godot_icall_RefCounted_Disposed(this, ptr, !disposing); } else { @@ -129,7 +129,7 @@ namespace Godot internal static extern void godot_icall_Object_Disposed(Object obj, IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void godot_icall_Reference_Disposed(Object obj, IntPtr ptr, bool isFinalizer); + internal static extern void godot_icall_RefCounted_Disposed(Object obj, IntPtr ptr, bool isFinalizer); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void godot_icall_Object_ConnectEventSignals(IntPtr obj); diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs index 2f8b5f297c..6972102730 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Plane.cs @@ -1,10 +1,10 @@ -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -177,7 +177,7 @@ namespace Godot return null; } - return from + dir * -dist; + return from - (dir * dist); } /// <summary> @@ -206,7 +206,7 @@ namespace Godot return null; } - return begin + segment * -dist; + return begin - (segment * dist); } /// <summary> @@ -355,20 +355,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1})", new object[] - { - _normal.ToString(), - D.ToString() - }); + return $"{_normal}, {D}"; } public string ToString(string format) { - return String.Format("({0}, {1})", new object[] - { - _normal.ToString(format), - D.ToString(format) - }); + return $"{_normal.ToString(format)}, {D.ToString(format)}"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quat.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs index bd3bcb0c58..0fed55cc30 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Quat.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Quaternion.cs @@ -1,10 +1,10 @@ -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -15,7 +15,7 @@ namespace Godot /// It is similar to Basis, which implements matrix representation of /// rotations, and can be parametrized using both an axis-angle pair /// or Euler angles. Basis stores rotation, scale, and shearing, - /// while Quat only stores rotation. + /// while Quaternion only stores rotation. /// /// Due to its compactness and the way it is stored in memory, certain /// operations (obtaining axis-angle and performing SLERP, in particular) @@ -23,7 +23,7 @@ namespace Godot /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] - public struct Quat : IEquatable<Quat> + public struct Quaternion : IEquatable<Quaternion> { /// <summary> /// X component of the quaternion (imaginary `i` axis part). @@ -114,6 +114,23 @@ namespace Godot } /// <summary> + /// Returns the angle between this quaternion and `to`. + /// This is the magnitude of the angle you would need to rotate + /// by to get from one to the other. + /// + /// Note: This method has an abnormally high amount + /// of floating-point error, so methods such as + /// <see cref="Mathf.IsZeroApprox"/> will not work reliably. + /// </summary> + /// <param name="to">The other quaternion.</param> + /// <returns>The angle between the quaternions.</returns> + public real_t AngleTo(Quaternion to) + { + real_t dot = Dot(to); + return Mathf.Acos(Mathf.Clamp(dot * dot * 2 - 1, -1, 1)); + } + + /// <summary> /// Performs a cubic spherical interpolation between quaternions `preA`, /// this vector, `b`, and `postB`, by the given amount `t`. /// </summary> @@ -122,11 +139,11 @@ namespace Godot /// <param name="postB">A quaternion after `b`.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The interpolated quaternion.</returns> - public Quat CubicSlerp(Quat b, Quat preA, Quat postB, real_t weight) + public Quaternion CubicSlerp(Quaternion b, Quaternion preA, Quaternion postB, real_t weight) { real_t t2 = (1.0f - weight) * weight * 2f; - Quat sp = Slerp(b, weight); - Quat sq = preA.Slerpni(postB, weight); + Quaternion sp = Slerp(b, weight); + Quaternion sq = preA.Slerpni(postB, weight); return sp.Slerpni(sq, t2); } @@ -135,7 +152,7 @@ namespace Godot /// </summary> /// <param name="b">The other quaternion.</param> /// <returns>The dot product.</returns> - public real_t Dot(Quat b) + public real_t Dot(Quaternion b) { return x * b.x + y * b.y + z * b.z + w * b.w; } @@ -152,7 +169,7 @@ namespace Godot #if DEBUG if (!IsNormalized()) { - throw new InvalidOperationException("Quat is not normalized"); + throw new InvalidOperationException("Quaternion is not normalized"); } #endif var basis = new Basis(this); @@ -163,15 +180,15 @@ namespace Godot /// Returns the inverse of the quaternion. /// </summary> /// <returns>The inverse quaternion.</returns> - public Quat Inverse() + public Quaternion Inverse() { #if DEBUG if (!IsNormalized()) { - throw new InvalidOperationException("Quat is not normalized"); + throw new InvalidOperationException("Quaternion is not normalized"); } #endif - return new Quat(-x, -y, -z, w); + return new Quaternion(-x, -y, -z, w); } /// <summary> @@ -187,7 +204,7 @@ namespace Godot /// Returns a copy of the quaternion, normalized to unit length. /// </summary> /// <returns>The normalized quaternion.</returns> - public Quat Normalized() + public Quaternion Normalized() { return this / Length; } @@ -201,12 +218,12 @@ namespace Godot /// <param name="to">The destination quaternion for interpolation. Must be normalized.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting quaternion of the interpolation.</returns> - public Quat Slerp(Quat to, real_t weight) + public Quaternion Slerp(Quaternion to, real_t weight) { #if DEBUG if (!IsNormalized()) { - throw new InvalidOperationException("Quat is not normalized"); + throw new InvalidOperationException("Quaternion is not normalized"); } if (!to.IsNormalized()) { @@ -217,7 +234,7 @@ namespace Godot // Calculate cosine. real_t cosom = x * to.x + y * to.y + z * to.z + w * to.w; - var to1 = new Quat(); + var to1 = new Quaternion(); // Adjust signs if necessary. if (cosom < 0.0) @@ -255,7 +272,7 @@ namespace Godot } // Calculate final values. - return new Quat + return new Quaternion ( scale0 * x + scale1 * to1.x, scale0 * y + scale1 * to1.y, @@ -272,7 +289,7 @@ namespace Godot /// <param name="to">The destination quaternion for interpolation. Must be normalized.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The resulting quaternion of the interpolation.</returns> - public Quat Slerpni(Quat to, real_t weight) + public Quaternion Slerpni(Quaternion to, real_t weight) { real_t dot = Dot(to); @@ -286,7 +303,7 @@ namespace Godot real_t newFactor = Mathf.Sin(weight * theta) * sinT; real_t invFactor = Mathf.Sin((1.0f - weight) * theta) * sinT; - return new Quat + return new Quaternion ( invFactor * x + newFactor * to.x, invFactor * y + newFactor * to.y, @@ -305,7 +322,7 @@ namespace Godot #if DEBUG if (!IsNormalized()) { - throw new InvalidOperationException("Quat is not normalized"); + throw new InvalidOperationException("Quaternion is not normalized"); } #endif var u = new Vector3(x, y, z); @@ -314,15 +331,15 @@ namespace Godot } // Constants - private static readonly Quat _identity = new Quat(0, 0, 0, 1); + private static readonly Quaternion _identity = new Quaternion(0, 0, 0, 1); /// <summary> /// The identity quaternion, representing no rotation. /// Equivalent to an identity <see cref="Basis"/> matrix. If a vector is transformed by /// an identity quaternion, it will not change. /// </summary> - /// <value>Equivalent to `new Quat(0, 0, 0, 1)`.</value> - public static Quat Identity { get { return _identity; } } + /// <value>Equivalent to `new Quaternion(0, 0, 0, 1)`.</value> + public static Quaternion Identity { get { return _identity; } } /// <summary> /// Constructs a quaternion defined by the given values. @@ -331,7 +348,7 @@ namespace Godot /// <param name="y">Y component of the quaternion (imaginary `j` axis part).</param> /// <param name="z">Z component of the quaternion (imaginary `k` axis part).</param> /// <param name="w">W component of the quaternion (real part).</param> - public Quat(real_t x, real_t y, real_t z, real_t w) + public Quaternion(real_t x, real_t y, real_t z, real_t w) { this.x = x; this.y = y; @@ -343,7 +360,7 @@ namespace Godot /// Constructs a quaternion from the given quaternion. /// </summary> /// <param name="q">The existing quaternion.</param> - public Quat(Quat q) + public Quaternion(Quaternion q) { this = q; } @@ -352,9 +369,9 @@ namespace Godot /// Constructs a quaternion from the given <see cref="Basis"/>. /// </summary> /// <param name="basis">The basis to construct from.</param> - public Quat(Basis basis) + public Quaternion(Basis basis) { - this = basis.Quat(); + this = basis.Quaternion(); } /// <summary> @@ -364,7 +381,7 @@ namespace Godot /// given in the vector format as (X angle, Y angle, Z angle). /// </summary> /// <param name="eulerYXZ"></param> - public Quat(Vector3 eulerYXZ) + public Quaternion(Vector3 eulerYXZ) { real_t half_a1 = eulerYXZ.y * 0.5f; real_t half_a2 = eulerYXZ.x * 0.5f; @@ -393,7 +410,7 @@ namespace Godot /// </summary> /// <param name="axis">The axis to rotate around. Must be normalized.</param> /// <param name="angle">The angle to rotate, in radians.</param> - public Quat(Vector3 axis, real_t angle) + public Quaternion(Vector3 axis, real_t angle) { #if DEBUG if (!axis.IsNormalized()) @@ -424,9 +441,9 @@ namespace Godot } } - public static Quat operator *(Quat left, Quat right) + public static Quaternion operator *(Quaternion left, Quaternion right) { - return new Quat + return new Quaternion ( left.w * right.x + left.x * right.w + left.y * right.z - left.z * right.y, left.w * right.y + left.y * right.w + left.z * right.x - left.x * right.z, @@ -435,24 +452,24 @@ namespace Godot ); } - public static Quat operator +(Quat left, Quat right) + public static Quaternion operator +(Quaternion left, Quaternion right) { - return new Quat(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); + return new Quaternion(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); } - public static Quat operator -(Quat left, Quat right) + public static Quaternion operator -(Quaternion left, Quaternion right) { - return new Quat(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); + return new Quaternion(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); } - public static Quat operator -(Quat left) + public static Quaternion operator -(Quaternion left) { - return new Quat(-left.x, -left.y, -left.z, -left.w); + return new Quaternion(-left.x, -left.y, -left.z, -left.w); } - public static Quat operator *(Quat left, Vector3 right) + public static Quaternion operator *(Quaternion left, Vector3 right) { - return new Quat + return new Quaternion ( left.w * right.x + left.y * right.z - left.z * right.y, left.w * right.y + left.z * right.x - left.x * right.z, @@ -461,9 +478,9 @@ namespace Godot ); } - public static Quat operator *(Vector3 left, Quat right) + public static Quaternion operator *(Vector3 left, Quaternion right) { - return new Quat + return new Quaternion ( right.w * left.x + right.y * left.z - right.z * left.y, right.w * left.y + right.z * left.x - right.x * left.z, @@ -472,42 +489,42 @@ namespace Godot ); } - public static Quat operator *(Quat left, real_t right) + public static Quaternion operator *(Quaternion left, real_t right) { - return new Quat(left.x * right, left.y * right, left.z * right, left.w * right); + return new Quaternion(left.x * right, left.y * right, left.z * right, left.w * right); } - public static Quat operator *(real_t left, Quat right) + public static Quaternion operator *(real_t left, Quaternion right) { - return new Quat(right.x * left, right.y * left, right.z * left, right.w * left); + return new Quaternion(right.x * left, right.y * left, right.z * left, right.w * left); } - public static Quat operator /(Quat left, real_t right) + public static Quaternion operator /(Quaternion left, real_t right) { return left * (1.0f / right); } - public static bool operator ==(Quat left, Quat right) + public static bool operator ==(Quaternion left, Quaternion right) { return left.Equals(right); } - public static bool operator !=(Quat left, Quat right) + public static bool operator !=(Quaternion left, Quaternion right) { return !left.Equals(right); } public override bool Equals(object obj) { - if (obj is Quat) + if (obj is Quaternion) { - return Equals((Quat)obj); + return Equals((Quaternion)obj); } return false; } - public bool Equals(Quat other) + public bool Equals(Quaternion other) { return x == other.x && y == other.y && z == other.z && w == other.w; } @@ -518,7 +535,7 @@ namespace Godot /// </summary> /// <param name="other">The other quaternion to compare.</param> /// <returns>Whether or not the quaternions are approximately equal.</returns> - public bool IsEqualApprox(Quat other) + public bool IsEqualApprox(Quaternion other) { return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y) && Mathf.IsEqualApprox(z, other.z) && Mathf.IsEqualApprox(w, other.w); } @@ -530,12 +547,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1}, {2}, {3})", x.ToString(), y.ToString(), z.ToString(), w.ToString()); + return $"({x}, {y}, {z}, {w})"; } public string ToString(string format) { - return String.Format("({0}, {1}, {2}, {3})", x.ToString(format), y.ToString(format), z.ToString(format), w.ToString(format)); + return $"({x.ToString(format)}, {y.ToString(format)}, {z.ToString(format)}, {w.ToString(format)})"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs index 868c3536fe..dec69c7f94 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2.cs @@ -1,10 +1,10 @@ -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -405,20 +405,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1})", new object[] - { - _position.ToString(), - _size.ToString() - }); + return $"{_position}, {_size}"; } public string ToString(string format) { - return String.Format("({0}, {1})", new object[] - { - _position.ToString(format), - _size.ToString(format) - }); + return $"{_position.ToString(format)}, {_size.ToString(format)}"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs index c27af74866..7fb6614d2c 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs @@ -383,20 +383,12 @@ namespace Godot public override string ToString() { - return String.Format("{0}, {1}", new object[] - { - _position.ToString(), - _size.ToString() - }); + return $"{_position}, {_size}"; } public string ToString(string format) { - return String.Format("{0}, {1}", new object[] - { - _position.ToString(format), - _size.ToString(format) - }); + return $"{_position.ToString(format)}, {_size.ToString(format)}"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs index 98efa89ef0..d9665cbf2b 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs @@ -61,9 +61,9 @@ namespace Godot return string.Empty; } - // <summary> - // If the string is a path to a file, return the path to the file without the extension. - // </summary> + /// <summary> + /// If the string is a path to a file, return the path to the file without the extension. + /// </summary> public static string BaseName(this string instance) { int index = instance.LastIndexOf('.'); @@ -74,17 +74,17 @@ namespace Godot return instance; } - // <summary> - // Return true if the strings begins with the given string. - // </summary> + /// <summary> + /// Return <see langword="true"/> if the strings begins with the given string. + /// </summary> public static bool BeginsWith(this string instance, string text) { return instance.StartsWith(text); } - // <summary> - // Return the bigrams (pairs of consecutive letters) of this string. - // </summary> + /// <summary> + /// Return the bigrams (pairs of consecutive letters) of this string. + /// </summary> public static string[] Bigrams(this string instance) { var b = new string[instance.Length - 1]; @@ -124,12 +124,12 @@ namespace Godot instance = instance.Substring(2); } - return sign * Convert.ToInt32(instance, 2);; + return sign * Convert.ToInt32(instance, 2); } - // <summary> - // Return the amount of substrings in string. - // </summary> + /// <summary> + /// Return the amount of substrings in string. + /// </summary> public static int Count(this string instance, string what, bool caseSensitive = true, int from = 0, int to = 0) { if (what.Length == 0) @@ -187,9 +187,9 @@ namespace Godot return c; } - // <summary> - // Return a copy of the string with special characters escaped using the C language standard. - // </summary> + /// <summary> + /// Return a copy of the string with special characters escaped using the C language standard. + /// </summary> public static string CEscape(this string instance) { var sb = new StringBuilder(string.Copy(instance)); @@ -209,9 +209,10 @@ namespace Godot return sb.ToString(); } - // <summary> - // Return a copy of the string with escaped characters replaced by their meanings according to the C language standard. - // </summary> + /// <summary> + /// Return a copy of the string with escaped characters replaced by their meanings + /// according to the C language standard. + /// </summary> public static string CUnescape(this string instance) { var sb = new StringBuilder(string.Copy(instance)); @@ -231,9 +232,12 @@ namespace Godot return sb.ToString(); } - // <summary> - // Change the case of some letters. Replace underscores with spaces, convert all letters to lowercase then capitalize first and every letter following the space character. For [code]capitalize camelCase mixed_with_underscores[/code] it will return [code]Capitalize Camelcase Mixed With Underscores[/code]. - // </summary> + /// <summary> + /// Change the case of some letters. Replace underscores with spaces, convert all letters + /// to lowercase then capitalize first and every letter following the space character. + /// For <c>capitalize camelCase mixed_with_underscores</c> it will return + /// <c>Capitalize Camelcase Mixed With Underscores</c>. + /// </summary> public static string Capitalize(this string instance) { string aux = instance.Replace("_", " ").ToLower(); @@ -254,17 +258,17 @@ namespace Godot return cap; } - // <summary> - // Perform a case-sensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater. - // </summary> + /// <summary> + /// Perform a case-sensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater. + /// </summary> public static int CasecmpTo(this string instance, string to) { return instance.CompareTo(to, caseSensitive: true); } - // <summary> - // Perform a comparison to another string, return -1 if less, 0 if equal and +1 if greater. - // </summary> + /// <summary> + /// Perform a comparison to another string, return -1 if less, 0 if equal and +1 if greater. + /// </summary> public static int CompareTo(this string instance, string to, bool caseSensitive = true) { if (string.IsNullOrEmpty(instance)) @@ -316,25 +320,25 @@ namespace Godot } } - // <summary> - // Return true if the strings ends with the given string. - // </summary> + /// <summary> + /// Return <see langword="true"/> if the strings ends with the given string. + /// </summary> public static bool EndsWith(this string instance, string text) { return instance.EndsWith(text); } - // <summary> - // Erase [code]chars[/code] characters from the string starting from [code]pos[/code]. - // </summary> + /// <summary> + /// Erase <paramref name="chars"/> characters from the string starting from <paramref name="pos"/>. + /// </summary> public static void Erase(this StringBuilder instance, int pos, int chars) { instance.Remove(pos, chars); } - // <summary> - // If the string is a path to a file, return the extension. - // </summary> + /// <summary> + /// If the string is a path to a file, return the extension. + /// </summary> public static string Extension(this string instance) { int pos = instance.FindLast("."); @@ -345,14 +349,18 @@ namespace Godot return instance.Substring(pos + 1); } - /// <summary>Find the first occurrence of a substring. Optionally, the search starting position can be passed.</summary> + /// <summary> + /// Find the first occurrence of a substring. Optionally, the search starting position can be passed. + /// </summary> /// <returns>The starting position of the substring, or -1 if not found.</returns> public static int Find(this string instance, string what, int from = 0, bool caseSensitive = true) { return instance.IndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); } - /// <summary>Find the first occurrence of a char. Optionally, the search starting position can be passed.</summary> + /// <summary> + /// Find the first occurrence of a char. Optionally, the search starting position can be passed. + /// </summary> /// <returns>The first instance of the char, or -1 if not found.</returns> public static int Find(this string instance, char what, int from = 0, bool caseSensitive = true) { @@ -375,16 +383,19 @@ namespace Godot return instance.LastIndexOf(what, from, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); } - /// <summary>Find the first occurrence of a substring but search as case-insensitive. Optionally, the search starting position can be passed.</summary> + /// <summary> + /// Find the first occurrence of a substring but search as case-insensitive. + /// Optionally, the search starting position can be passed. + /// </summary> /// <returns>The starting position of the substring, or -1 if not found.</returns> public static int FindN(this string instance, string what, int from = 0) { return instance.IndexOf(what, from, StringComparison.OrdinalIgnoreCase); } - // <summary> - // If the string is a path to a file, return the base directory. - // </summary> + /// <summary> + /// If the string is a path to a file, return the base directory. + /// </summary> public static string GetBaseDir(this string instance) { int basepos = instance.Find("://"); @@ -419,9 +430,9 @@ namespace Godot return @base + rs.Substr(0, sep); } - // <summary> - // If the string is a path to a file, return the file and ignore the base directory. - // </summary> + /// <summary> + /// If the string is a path to a file, return the file and ignore the base directory. + /// </summary> public static string GetFile(this string instance) { int sep = Mathf.Max(instance.FindLast("/"), instance.FindLast("\\")); @@ -461,14 +472,14 @@ namespace Godot return Encoding.UTF8.GetString(bytes); } - // <summary> - // Hash the string and return a 32 bits unsigned integer. - // </summary> + /// <summary> + /// Hash the string and return a 32 bits unsigned integer. + /// </summary> public static uint Hash(this string instance) { uint hash = 5381; - foreach(uint c in instance) + foreach (uint c in instance) { hash = (hash << 5) + hash + c; // hash * 33 + c } @@ -553,17 +564,17 @@ namespace Godot return sign * int.Parse(instance, NumberStyles.HexNumber); } - // <summary> - // Insert a substring at a given position. - // </summary> + /// <summary> + /// Insert a substring at a given position. + /// </summary> public static string Insert(this string instance, int pos, string what) { return instance.Insert(pos, what); } - // <summary> - // If the string is a path to a file or directory, return true if the path is absolute. - // </summary> + /// <summary> + /// If the string is a path to a file or directory, return <see langword="true"/> if the path is absolute. + /// </summary> public static bool IsAbsPath(this string instance) { if (string.IsNullOrEmpty(instance)) @@ -574,17 +585,17 @@ namespace Godot return instance[0] == '/' || instance[0] == '\\'; } - // <summary> - // If the string is a path to a file or directory, return true if the path is relative. - // </summary> + /// <summary> + /// If the string is a path to a file or directory, return <see langword="true"/> if the path is relative. + /// </summary> public static bool IsRelPath(this string instance) { return !IsAbsPath(instance); } - // <summary> - // Check whether this string is a subsequence of the given string. - // </summary> + /// <summary> + /// Check whether this string is a subsequence of the given string. + /// </summary> public static bool IsSubsequenceOf(this string instance, string text, bool caseSensitive = true) { int len = instance.Length; @@ -625,34 +636,36 @@ namespace Godot return false; } - // <summary> - // Check whether this string is a subsequence of the given string, ignoring case differences. - // </summary> + /// <summary> + /// Check whether this string is a subsequence of the given string, ignoring case differences. + /// </summary> public static bool IsSubsequenceOfI(this string instance, string text) { return instance.IsSubsequenceOf(text, caseSensitive: false); } - // <summary> - // Check whether the string contains a valid float. - // </summary> + /// <summary> + /// Check whether the string contains a valid <see langword="float"/>. + /// </summary> public static bool IsValidFloat(this string instance) { float f; return float.TryParse(instance, out f); } - // <summary> - // Check whether the string contains a valid color in HTML notation. - // </summary> + /// <summary> + /// Check whether the string contains a valid color in HTML notation. + /// </summary> public static bool IsValidHtmlColor(this string instance) { return Color.HtmlIsValid(instance); } - // <summary> - // Check whether the string is a valid identifier. As is common in programming languages, a valid identifier may contain only letters, digits and underscores (_) and the first character may not be a digit. - // </summary> + /// <summary> + /// Check whether the string is a valid identifier. As is common in + /// programming languages, a valid identifier may contain only letters, + /// digits and underscores (_) and the first character may not be a digit. + /// </summary> public static bool IsValidIdentifier(this string instance) { int len = instance.Length; @@ -680,18 +693,18 @@ namespace Godot return true; } - // <summary> - // Check whether the string contains a valid integer. - // </summary> + /// <summary> + /// Check whether the string contains a valid integer. + /// </summary> public static bool IsValidInteger(this string instance) { int f; return int.TryParse(instance, out f); } - // <summary> - // Check whether the string contains a valid IP address. - // </summary> + /// <summary> + /// Check whether the string contains a valid IP address. + /// </summary> public static bool IsValidIPAddress(this string instance) { // TODO: Support IPv6 addresses @@ -714,9 +727,9 @@ namespace Godot return true; } - // <summary> - // Return a copy of the string with special characters escaped using the JSON standard. - // </summary> + /// <summary> + /// Return a copy of the string with special characters escaped using the JSON standard. + /// </summary> public static string JSONEscape(this string instance) { var sb = new StringBuilder(string.Copy(instance)); @@ -733,9 +746,9 @@ namespace Godot return sb.ToString(); } - // <summary> - // Return an amount of characters from the left of the string. - // </summary> + /// <summary> + /// Return an amount of characters from the left of the string. + /// </summary> public static string Left(this string instance, int pos) { if (pos <= 0) @@ -783,7 +796,8 @@ namespace Godot } /// <summary> - /// Do a simple expression match, where '*' matches zero or more arbitrary characters and '?' matches any single character except '.'. + /// Do a simple expression match, where '*' matches zero or more + /// arbitrary characters and '?' matches any single character except '.'. /// </summary> private static bool ExprMatch(this string instance, string expr, bool caseSensitive) { @@ -798,13 +812,17 @@ namespace Godot case '?': return instance.Length > 0 && instance[0] != '.' && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive); default: - if (instance.Length == 0) return false; - return (caseSensitive ? instance[0] == expr[0] : char.ToUpper(instance[0]) == char.ToUpper(expr[0])) && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive); + if (instance.Length == 0) + return false; + if (caseSensitive) + return instance[0] == expr[0]; + return (char.ToUpper(instance[0]) == char.ToUpper(expr[0])) && ExprMatch(instance.Substring(1), expr.Substring(1), caseSensitive); } } /// <summary> - /// Do a simple case sensitive expression match, using ? and * wildcards (see [method expr_match]). + /// Do a simple case sensitive expression match, using ? and * wildcards + /// (see <see cref="ExprMatch(string, string, bool)"/>). /// </summary> public static bool Match(this string instance, string expr, bool caseSensitive = true) { @@ -815,7 +833,8 @@ namespace Godot } /// <summary> - /// Do a simple case insensitive expression match, using ? and * wildcards (see [method expr_match]). + /// Do a simple case insensitive expression match, using ? and * wildcards + /// (see <see cref="ExprMatch(string, string, bool)"/>). /// </summary> public static bool MatchN(this string instance, string expr) { @@ -825,9 +844,9 @@ namespace Godot return instance.ExprMatch(expr, caseSensitive: false); } - // <summary> - // Return the MD5 hash of the string as an array of bytes. - // </summary> + /// <summary> + /// Return the MD5 hash of the string as an array of bytes. + /// </summary> public static byte[] MD5Buffer(this string instance) { return godot_icall_String_md5_buffer(instance); @@ -836,9 +855,9 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static byte[] godot_icall_String_md5_buffer(string str); - // <summary> - // Return the MD5 hash of the string as a string. - // </summary> + /// <summary> + /// Return the MD5 hash of the string as a string. + /// </summary> public static string MD5Text(this string instance) { return godot_icall_String_md5_text(instance); @@ -847,25 +866,25 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_String_md5_text(string str); - // <summary> - // Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater. - // </summary> + /// <summary> + /// Perform a case-insensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater. + /// </summary> public static int NocasecmpTo(this string instance, string to) { return instance.CompareTo(to, caseSensitive: false); } - // <summary> - // Return the character code at position [code]at[/code]. - // </summary> + /// <summary> + /// Return the character code at position <paramref name="at"/>. + /// </summary> public static int OrdAt(this string instance, int at) { return instance[at]; } - // <summary> - // Format a number to have an exact number of [code]digits[/code] after the decimal point. - // </summary> + /// <summary> + /// Format a number to have an exact number of <paramref name="digits"/> after the decimal point. + /// </summary> public static string PadDecimals(this string instance, int digits) { int c = instance.Find("."); @@ -899,9 +918,9 @@ namespace Godot return instance; } - // <summary> - // Format a number to have an exact number of [code]digits[/code] before the decimal point. - // </summary> + /// <summary> + /// Format a number to have an exact number of <paramref name="digits"/> before the decimal point. + /// </summary> public static string PadZeros(this string instance, int digits) { string s = instance; @@ -932,9 +951,10 @@ namespace Godot return s; } - // <summary> - // If the string is a path, this concatenates [code]file[/code] at the end of the string as a subpath. E.g. [code]"this/is".plus_file("path") == "this/is/path"[/code]. - // </summary> + /// <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>. + /// </summary> public static string PlusFile(this string instance, string file) { if (instance.Length > 0 && instance[instance.Length - 1] == '/') @@ -942,25 +962,25 @@ namespace Godot return instance + "/" + file; } - // <summary> - // Replace occurrences of a substring for different ones inside the string. - // </summary> + /// <summary> + /// Replace occurrences of a substring for different ones inside the string. + /// </summary> public static string Replace(this string instance, string what, string forwhat) { return instance.Replace(what, forwhat); } - // <summary> - // Replace occurrences of a substring for different ones inside the string, but search case-insensitive. - // </summary> + /// <summary> + /// Replace occurrences of a substring for different ones inside the string, but search case-insensitive. + /// </summary> public static string ReplaceN(this string instance, string what, string forwhat) { return Regex.Replace(instance, what, forwhat, RegexOptions.IgnoreCase); } - // <summary> - // Perform a search for a substring, but start from the end of the string instead of the beginning. - // </summary> + /// <summary> + /// Perform a search for a substring, but start from the end of the string instead of the beginning. + /// </summary> public static int RFind(this string instance, string what, int from = -1) { return godot_icall_String_rfind(instance, what, from); @@ -969,9 +989,10 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_String_rfind(string str, string what, int from); - // <summary> - // Perform a search for a substring, but start from the end of the string instead of the beginning. Also search case-insensitive. - // </summary> + /// <summary> + /// Perform a search for a substring, but start from the end of the string instead of the beginning. + /// Also search case-insensitive. + /// </summary> public static int RFindN(this string instance, string what, int from = -1) { return godot_icall_String_rfindn(instance, what, from); @@ -980,9 +1001,9 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static int godot_icall_String_rfindn(string str, string what, int from); - // <summary> - // Return the right side of the string from a given position. - // </summary> + /// <summary> + /// Return the right side of the string from a given position. + /// </summary> public static string Right(this string instance, int pos) { if (pos >= instance.Length) @@ -1029,9 +1050,9 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static byte[] godot_icall_String_sha256_buffer(string str); - // <summary> - // Return the SHA-256 hash of the string as a string. - // </summary> + /// <summary> + /// Return the SHA-256 hash of the string as a string. + /// </summary> public static string SHA256Text(this string instance) { return godot_icall_String_sha256_text(instance); @@ -1040,9 +1061,10 @@ namespace Godot [MethodImpl(MethodImplOptions.InternalCall)] internal extern static string godot_icall_String_sha256_text(string str); - // <summary> - // Return the similarity index of the text compared to this string. 1 means totally similar and 0 means totally dissimilar. - // </summary> + /// <summary> + /// Return the similarity index of the text compared to this string. + /// 1 means totally similar and 0 means totally dissimilar. + /// </summary> public static float Similarity(this string instance, string text) { if (instance == text) @@ -1080,17 +1102,19 @@ namespace Godot return 2.0f * inter / sum; } - // <summary> - // Split the string by a divisor string, return an array of the substrings. Example "One,Two,Three" will return ["One","Two","Three"] if split by ",". - // </summary> + /// <summary> + /// Split the string by a divisor string, return an array of the substrings. + /// Example "One,Two,Three" will return ["One","Two","Three"] if split by ",". + /// </summary> public static string[] Split(this string instance, string divisor, bool allowEmpty = true) { - return instance.Split(new[] { divisor }, StringSplitOptions.RemoveEmptyEntries); + return instance.Split(new[] { divisor }, allowEmpty ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries); } - // <summary> - // Split the string in floats by using a divisor string, return an array of the substrings. Example "1,2.5,3" will return [1,2.5,3] if split by ",". - // </summary> + /// <summary> + /// Split the string in floats by using a divisor string, return an array of the substrings. + /// Example "1,2.5,3" will return [1,2.5,3] if split by ",". + /// </summary> public static float[] SplitFloats(this string instance, string divisor, bool allowEmpty = true) { var ret = new List<float>(); @@ -1122,9 +1146,10 @@ namespace Godot (char)30, (char)31, (char)32 }; - // <summary> - // Return a copy of the string stripped of any non-printable character at the beginning and the end. The optional arguments are used to toggle stripping on the left and right edges respectively. - // </summary> + /// <summary> + /// Return a copy of the string stripped of any non-printable character at the beginning and the end. + /// The optional arguments are used to toggle stripping on the left and right edges respectively. + /// </summary> public static string StripEdges(this string instance, bool left = true, bool right = true) { if (left) @@ -1137,58 +1162,62 @@ namespace Godot return instance.TrimEnd(_nonPrintable); } - // <summary> - // Return part of the string from the position [code]from[/code], with length [code]len[/code]. - // </summary> + /// <summary> + /// Return part of the string from the position <paramref name="from"/>, with length <paramref name="len"/>. + /// </summary> public static string Substr(this string instance, int from, int len) { int max = instance.Length - from; return instance.Substring(from, len > max ? max : len); } - // <summary> - // Convert the String (which is a character array) to PackedByteArray (which is an array of bytes). The conversion is speeded up in comparison to to_utf8() with the assumption that all the characters the String contains are only ASCII characters. - // </summary> + /// <summary> + /// Convert the String (which is a character array) to PackedByteArray (which is an array of bytes). + /// The conversion is speeded up in comparison to <see cref="ToUTF8(string)"/> with the assumption + /// that all the characters the String contains are only ASCII characters. + /// </summary> public static byte[] ToAscii(this string instance) { return Encoding.ASCII.GetBytes(instance); } - // <summary> - // Convert a string, containing a decimal number, into a [code]float[/code]. - // </summary> + /// <summary> + /// Convert a string, containing a decimal number, into a <see langword="float" />. + /// </summary> public static float ToFloat(this string instance) { return float.Parse(instance); } - // <summary> - // Convert a string, containing an integer number, into an [code]int[/code]. - // </summary> + /// <summary> + /// Convert a string, containing an integer number, into an <see langword="int" />. + /// </summary> public static int ToInt(this string instance) { return int.Parse(instance); } - // <summary> - // Return the string converted to lowercase. - // </summary> + /// <summary> + /// Return the string converted to lowercase. + /// </summary> public static string ToLower(this string instance) { return instance.ToLower(); } - // <summary> - // Return the string converted to uppercase. - // </summary> + /// <summary> + /// Return the string converted to uppercase. + /// </summary> public static string ToUpper(this string instance) { return instance.ToUpper(); } - // <summary> - // Convert the String (which is an array of characters) to PackedByteArray (which is an array of bytes). The conversion is a bit slower than to_ascii(), but supports all UTF-8 characters. Therefore, you should prefer this function over to_ascii(). - // </summary> + /// <summary> + /// Convert the String (which is an array of characters) to PackedByteArray (which is an array of bytes). + /// The conversion is a bit slower than <see cref="ToAscii(string)"/>, but supports all UTF-8 characters. + /// Therefore, you should prefer this function over <see cref="ToAscii(string)"/>. + /// </summary> public static byte[] ToUTF8(this string instance) { return Encoding.UTF8.GetBytes(instance); @@ -1221,17 +1250,18 @@ namespace Godot return Uri.EscapeDataString(instance); } - // <summary> - // Return a copy of the string with special characters escaped using the XML standard. - // </summary> + /// <summary> + /// Return a copy of the string with special characters escaped using the XML standard. + /// </summary> public static string XMLEscape(this string instance) { return SecurityElement.Escape(instance); } - // <summary> - // Return a copy of the string with escaped characters replaced by their meanings according to the XML standard. - // </summary> + /// <summary> + /// Return a copy of the string with escaped characters replaced by their meanings + /// according to the XML standard. + /// </summary> public static string XMLUnescape(this string instance) { return SecurityElement.FromString(instance).Text; diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs index bc0f81b2a7..62a6fe6959 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform2D.cs @@ -1,10 +1,10 @@ -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -492,22 +492,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1}, {2})", new object[] - { - x.ToString(), - y.ToString(), - origin.ToString() - }); + return $"[X: {x}, Y: {y}, O: {origin}]"; } public string ToString(string format) { - return String.Format("({0}, {1}, {2})", new object[] - { - x.ToString(format), - y.ToString(format), - origin.ToString(format) - }); + return $"[X: {x.ToString(format)}, Y: {y.ToString(format)}, O: {origin.ToString(format)}]"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs index ac47f6029f..afc6a65a45 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Transform3D.cs @@ -1,10 +1,10 @@ -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -19,7 +19,7 @@ namespace Godot /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] - public struct Transform : IEquatable<Transform> + public struct Transform3D : IEquatable<Transform3D> { /// <summary> /// The <see cref="Basis"/> of this transform. Contains the X, Y, and Z basis @@ -107,10 +107,10 @@ namespace Godot /// the transformation is composed of rotation, scaling, and translation. /// </summary> /// <returns>The inverse transformation matrix.</returns> - public Transform AffineInverse() + public Transform3D AffineInverse() { Basis basisInv = basis.Inverse(); - return new Transform(basisInv, basisInv.Xform(-origin)); + return new Transform3D(basisInv, basisInv.Xform(-origin)); } /// <summary> @@ -119,20 +119,20 @@ namespace Godot /// <param name="transform">The other transform.</param> /// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param> /// <returns>The interpolated transform.</returns> - public Transform InterpolateWith(Transform transform, real_t weight) + public Transform3D InterpolateWith(Transform3D transform, real_t weight) { /* not sure if very "efficient" but good enough? */ Vector3 sourceScale = basis.Scale; - Quat sourceRotation = basis.RotationQuat(); + Quaternion sourceRotation = basis.GetRotationQuaternion(); Vector3 sourceLocation = origin; Vector3 destinationScale = transform.basis.Scale; - Quat destinationRotation = transform.basis.RotationQuat(); + Quaternion destinationRotation = transform.basis.GetRotationQuaternion(); Vector3 destinationLocation = transform.origin; - var interpolated = new Transform(); - interpolated.basis.SetQuatScale(sourceRotation.Slerp(destinationRotation, weight).Normalized(), sourceScale.Lerp(destinationScale, weight)); + var interpolated = new Transform3D(); + interpolated.basis.SetQuaternionScale(sourceRotation.Slerp(destinationRotation, weight).Normalized(), sourceScale.Lerp(destinationScale, weight)); interpolated.origin = sourceLocation.Lerp(destinationLocation, weight); return interpolated; @@ -144,10 +144,10 @@ namespace Godot /// (no scaling, use <see cref="AffineInverse"/> for transforms with scaling). /// </summary> /// <returns>The inverse matrix.</returns> - public Transform Inverse() + public Transform3D Inverse() { Basis basisTr = basis.Transposed(); - return new Transform(basisTr, basisTr.Xform(-origin)); + return new Transform3D(basisTr, basisTr.Xform(-origin)); } /// <summary> @@ -163,7 +163,7 @@ namespace Godot /// <param name="target">The object to look at.</param> /// <param name="up">The relative up direction</param> /// <returns>The resulting transform.</returns> - public Transform LookingAt(Vector3 target, Vector3 up) + public Transform3D LookingAt(Vector3 target, Vector3 up) { var t = this; t.SetLookAt(origin, target, up); @@ -175,9 +175,9 @@ namespace Godot /// and normalized axis vectors (scale of 1 or -1). /// </summary> /// <returns>The orthonormalized transform.</returns> - public Transform Orthonormalized() + public Transform3D Orthonormalized() { - return new Transform(basis.Orthonormalized(), origin); + return new Transform3D(basis.Orthonormalized(), origin); } /// <summary> @@ -187,9 +187,9 @@ namespace Godot /// <param name="axis">The axis to rotate around. Must be normalized.</param> /// <param name="phi">The angle to rotate, in radians.</param> /// <returns>The rotated transformation matrix.</returns> - public Transform Rotated(Vector3 axis, real_t phi) + public Transform3D Rotated(Vector3 axis, real_t phi) { - return new Transform(new Basis(axis, phi), new Vector3()) * this; + return new Transform3D(new Basis(axis, phi), new Vector3()) * this; } /// <summary> @@ -197,9 +197,9 @@ namespace Godot /// </summary> /// <param name="scale">The scale to introduce.</param> /// <returns>The scaled transformation matrix.</returns> - public Transform Scaled(Vector3 scale) + public Transform3D Scaled(Vector3 scale) { - return new Transform(basis.Scaled(scale), origin * scale); + return new Transform3D(basis.Scaled(scale), origin * scale); } private void SetLookAt(Vector3 eye, Vector3 target, Vector3 up) @@ -234,9 +234,9 @@ namespace Godot /// </summary> /// <param name="offset">The offset to translate by.</param> /// <returns>The translated matrix.</returns> - public Transform Translated(Vector3 offset) + public Transform3D Translated(Vector3 offset) { - return new Transform(basis, new Vector3 + return new Transform3D(basis, new Vector3 ( origin[0] += basis.Row0.Dot(offset), origin[1] += basis.Row1.Dot(offset), @@ -280,10 +280,10 @@ namespace Godot } // Constants - private static readonly Transform _identity = new Transform(Basis.Identity, Vector3.Zero); - private static readonly Transform _flipX = new Transform(new Basis(-1, 0, 0, 0, 1, 0, 0, 0, 1), Vector3.Zero); - private static readonly Transform _flipY = new Transform(new Basis(1, 0, 0, 0, -1, 0, 0, 0, 1), Vector3.Zero); - private static readonly Transform _flipZ = new Transform(new Basis(1, 0, 0, 0, 1, 0, 0, 0, -1), Vector3.Zero); + private static readonly Transform3D _identity = new Transform3D(Basis.Identity, Vector3.Zero); + private static readonly Transform3D _flipX = new Transform3D(new Basis(-1, 0, 0, 0, 1, 0, 0, 0, 1), Vector3.Zero); + private static readonly Transform3D _flipY = new Transform3D(new Basis(1, 0, 0, 0, -1, 0, 0, 0, 1), Vector3.Zero); + private static readonly Transform3D _flipZ = new Transform3D(new Basis(1, 0, 0, 0, 1, 0, 0, 0, -1), Vector3.Zero); /// <summary> /// The identity transform, with no translation, rotation, or scaling applied. @@ -291,22 +291,22 @@ namespace Godot /// Do not use `new Transform()` with no arguments in C#, because it sets all values to zero. /// </summary> /// <value>Equivalent to `new Transform(Vector3.Right, Vector3.Up, Vector3.Back, Vector3.Zero)`.</value> - public static Transform Identity { get { return _identity; } } + public static Transform3D Identity { get { return _identity; } } /// <summary> /// The transform that will flip something along the X axis. /// </summary> /// <value>Equivalent to `new Transform(Vector3.Left, Vector3.Up, Vector3.Back, Vector3.Zero)`.</value> - public static Transform FlipX { get { return _flipX; } } + public static Transform3D FlipX { get { return _flipX; } } /// <summary> /// The transform that will flip something along the Y axis. /// </summary> /// <value>Equivalent to `new Transform(Vector3.Right, Vector3.Down, Vector3.Back, Vector3.Zero)`.</value> - public static Transform FlipY { get { return _flipY; } } + public static Transform3D FlipY { get { return _flipY; } } /// <summary> /// The transform that will flip something along the Z axis. /// </summary> /// <value>Equivalent to `new Transform(Vector3.Right, Vector3.Up, Vector3.Forward, Vector3.Zero)`.</value> - public static Transform FlipZ { get { return _flipZ; } } + public static Transform3D FlipZ { get { return _flipZ; } } /// <summary> /// Constructs a transformation matrix from 4 vectors (matrix columns). @@ -315,7 +315,7 @@ namespace Godot /// <param name="column1">The Y vector, or column index 1.</param> /// <param name="column2">The Z vector, or column index 2.</param> /// <param name="origin">The origin vector, or column index 3.</param> - public Transform(Vector3 column0, Vector3 column1, Vector3 column2, Vector3 origin) + public Transform3D(Vector3 column0, Vector3 column1, Vector3 column2, Vector3 origin) { basis = new Basis(column0, column1, column2); this.origin = origin; @@ -324,11 +324,11 @@ namespace Godot /// <summary> /// Constructs a transformation matrix from the given quaternion and origin vector. /// </summary> - /// <param name="quat">The <see cref="Godot.Quat"/> to create the basis from.</param> + /// <param name="quaternion">The <see cref="Godot.Quaternion"/> to create the basis from.</param> /// <param name="origin">The origin vector, or column index 3.</param> - public Transform(Quat quat, Vector3 origin) + public Transform3D(Quaternion quaternion, Vector3 origin) { - basis = new Basis(quat); + basis = new Basis(quaternion); this.origin = origin; } @@ -337,40 +337,40 @@ namespace Godot /// </summary> /// <param name="basis">The <see cref="Godot.Basis"/> to create the basis from.</param> /// <param name="origin">The origin vector, or column index 3.</param> - public Transform(Basis basis, Vector3 origin) + public Transform3D(Basis basis, Vector3 origin) { this.basis = basis; this.origin = origin; } - public static Transform operator *(Transform left, Transform right) + public static Transform3D operator *(Transform3D left, Transform3D right) { left.origin = left.Xform(right.origin); left.basis *= right.basis; return left; } - public static bool operator ==(Transform left, Transform right) + public static bool operator ==(Transform3D left, Transform3D right) { return left.Equals(right); } - public static bool operator !=(Transform left, Transform right) + public static bool operator !=(Transform3D left, Transform3D right) { return !left.Equals(right); } public override bool Equals(object obj) { - if (obj is Transform) + if (obj is Transform3D) { - return Equals((Transform)obj); + return Equals((Transform3D)obj); } return false; } - public bool Equals(Transform other) + public bool Equals(Transform3D other) { return basis.Equals(other.basis) && origin.Equals(other.origin); } @@ -381,7 +381,7 @@ namespace Godot /// </summary> /// <param name="other">The other transform to compare.</param> /// <returns>Whether or not the matrices are approximately equal.</returns> - public bool IsEqualApprox(Transform other) + public bool IsEqualApprox(Transform3D other) { return basis.IsEqualApprox(other.basis) && origin.IsEqualApprox(other.origin); } @@ -393,20 +393,12 @@ namespace Godot public override string ToString() { - return String.Format("{0} - {1}", new object[] - { - basis.ToString(), - origin.ToString() - }); + return $"[X: {basis.x}, Y: {basis.y}, Z: {basis.z}, O: {origin}]"; } public string ToString(string format) { - return String.Format("{0} - {1}", new object[] - { - basis.ToString(format), - origin.ToString(format) - }); + return $"[X: {basis.x.ToString(format)}, Y: {basis.y.ToString(format)}, Z: {basis.z.ToString(format)}, O: {origin.ToString(format)}]"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs index 6279ea1ace..8bb5e90a68 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs @@ -1,16 +1,10 @@ -// file: core/math/math_2d.h -// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451 -// file: core/math/math_2d.cpp -// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451 -// file: core/variant_call.cpp -// commit: 5ad9be4c24e9d7dc5672fdc42cea896622fe5685 -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -160,22 +154,20 @@ namespace Godot } /// <summary> - /// Returns the vector with a maximum length by limiting its length to `length`. + /// Returns a new vector with all components clamped between the + /// components of `min` and `max` using + /// <see cref="Mathf.Clamp(real_t, real_t, real_t)"/>. /// </summary> - /// <param name="length">The length to limit to.</param> - /// <returns>The vector with its length limited.</returns> - public Vector2 Clamped(real_t length) + /// <param name="min">The vector with minimum allowed values.</param> + /// <param name="max">The vector with maximum allowed values.</param> + /// <returns>The vector with all components clamped.</returns> + public Vector2 Clamp(Vector2 min, Vector2 max) { - var v = this; - real_t l = Length(); - - if (l > 0 && length < l) - { - v /= l; - v *= length; - } - - return v; + return new Vector2 + ( + Mathf.Clamp(x, min.x, max.x), + Mathf.Clamp(y, min.y, max.y) + ); } /// <summary> @@ -335,6 +327,25 @@ namespace Godot } /// <summary> + /// Returns the vector with a maximum length by limiting its length to `length`. + /// </summary> + /// <param name="length">The length to limit to.</param> + /// <returns>The vector with its length limited.</returns> + public Vector2 LimitLength(real_t length = 1.0f) + { + Vector2 v = this; + real_t l = Length(); + + if (l > 0 && length < l) + { + v /= l; + v *= length; + } + + return v; + } + + /// <summary> /// Returns the axis of the vector's largest value. See <see cref="Axis"/>. /// If both components are equal, this method returns <see cref="Axis.X"/>. /// </summary> @@ -425,7 +436,7 @@ namespace Godot #if DEBUG if (!normal.IsNormalized()) { - throw new ArgumentException("Argument is not normalized", nameof(normal)); + throw new ArgumentException("Argument is not normalized", nameof(normal)); } #endif return 2 * Dot(normal) * normal - this; @@ -519,7 +530,7 @@ namespace Godot /// compared to the original, with the same length. /// </summary> /// <returns>The perpendicular vector.</returns> - public Vector2 Perpendicular() + public Vector2 Orthogonal() { return new Vector2(y, -x); } @@ -740,20 +751,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1})", new object[] - { - x.ToString(), - y.ToString() - }); + return $"({x}, {y})"; } public string ToString(string format) { - return String.Format("({0}, {1})", new object[] - { - x.ToString(format), - y.ToString(format) - }); + return $"({x.ToString(format)}, {y.ToString(format)})"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs index 8dd9ab2f0d..959f262f52 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs @@ -1,11 +1,10 @@ -using System; -using System.Runtime.InteropServices; - #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -120,6 +119,23 @@ namespace Godot } /// <summary> + /// Returns a new vector with all components clamped between the + /// components of `min` and `max` using + /// <see cref="Mathf.Clamp(int, int, int)"/>. + /// </summary> + /// <param name="min">The vector with minimum allowed values.</param> + /// <param name="max">The vector with maximum allowed values.</param> + /// <returns>The vector with all components clamped.</returns> + public Vector2i Clamp(Vector2i min, Vector2i max) + { + return new Vector2i + ( + Mathf.Clamp(x, min.x, max.x), + Mathf.Clamp(y, min.y, max.y) + ); + } + + /// <summary> /// Returns the cross product of this vector and `b`. /// </summary> /// <param name="b">The other vector.</param> @@ -248,13 +264,13 @@ namespace Godot } /// <summary> - /// Returns a vector rotated 90 degrees counter-clockwise + /// Returns a perpendicular vector rotated 90 degrees counter-clockwise /// compared to the original, with the same length. /// </summary> /// <returns>The perpendicular vector.</returns> - public Vector2 Perpendicular() + public Vector2i Orthogonal() { - return new Vector2(y, -x); + return new Vector2i(y, -x); } // Constants @@ -492,20 +508,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1})", new object[] - { - this.x.ToString(), - this.y.ToString() - }); + return $"({x}, {y})"; } public string ToString(string format) { - return String.Format("({0}, {1})", new object[] - { - this.x.ToString(format), - this.y.ToString(format) - }); + return $"({x.ToString(format)}, {y.ToString(format)})"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs index 3b895bbbf6..bdf64159e9 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs @@ -1,16 +1,10 @@ -// file: core/math/vector3.h -// commit: bd282ff43f23fe845f29a3e25c8efc01bd65ffb0 -// file: core/math/vector3.cpp -// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451 -// file: core/variant_call.cpp -// commit: 5ad9be4c24e9d7dc5672fdc42cea896622fe5685 -using System; -using System.Runtime.InteropServices; #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -140,6 +134,24 @@ namespace Godot } /// <summary> + /// Returns a new vector with all components clamped between the + /// components of `min` and `max` using + /// <see cref="Mathf.Clamp(real_t, real_t, real_t)"/>. + /// </summary> + /// <param name="min">The vector with minimum allowed values.</param> + /// <param name="max">The vector with maximum allowed values.</param> + /// <returns>The vector with all components clamped.</returns> + public Vector3 Clamp(Vector3 min, Vector3 max) + { + return new Vector3 + ( + Mathf.Clamp(x, min.x, max.x), + Mathf.Clamp(y, min.y, max.y), + Mathf.Clamp(z, min.z, max.z) + ); + } + + /// <summary> /// Returns the cross product of this vector and `b`. /// </summary> /// <param name="b">The other vector.</param> @@ -313,6 +325,25 @@ namespace Godot } /// <summary> + /// Returns the vector with a maximum length by limiting its length to `length`. + /// </summary> + /// <param name="length">The length to limit to.</param> + /// <returns>The vector with its length limited.</returns> + public Vector3 LimitLength(real_t length = 1.0f) + { + Vector3 v = this; + real_t l = Length(); + + if (l > 0 && length < l) + { + v /= l; + v *= length; + } + + return v; + } + + /// <summary> /// Returns the axis of the vector's largest value. See <see cref="Axis"/>. /// If all components are equal, this method returns <see cref="Axis.X"/>. /// </summary> @@ -419,7 +450,7 @@ namespace Godot #if DEBUG if (!normal.IsNormalized()) { - throw new ArgumentException("Argument is not normalized", nameof(normal)); + throw new ArgumentException("Argument is not normalized", nameof(normal)); } #endif return 2.0f * Dot(normal) * normal - this; @@ -437,7 +468,7 @@ namespace Godot #if DEBUG if (!axis.IsNormalized()) { - throw new ArgumentException("Argument is not normalized", nameof(axis)); + throw new ArgumentException("Argument is not normalized", nameof(axis)); } #endif return new Basis(axis, phi).Xform(this); @@ -814,22 +845,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1}, {2})", new object[] - { - x.ToString(), - y.ToString(), - z.ToString() - }); + return $"({x}, {y}, {z})"; } public string ToString(string format) { - return String.Format("({0}, {1}, {2})", new object[] - { - x.ToString(format), - y.ToString(format), - z.ToString(format) - }); + return $"({x.ToString(format)}, {y.ToString(format)}, {z.ToString(format)})"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs index bf25ba9cb3..c96a7cf1b0 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs @@ -1,11 +1,10 @@ -using System; -using System.Runtime.InteropServices; - #if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif +using System; +using System.Runtime.InteropServices; namespace Godot { @@ -89,6 +88,24 @@ namespace Godot } /// <summary> + /// Returns a new vector with all components clamped between the + /// components of `min` and `max` using + /// <see cref="Mathf.Clamp(int, int, int)"/>. + /// </summary> + /// <param name="min">The vector with minimum allowed values.</param> + /// <param name="max">The vector with maximum allowed values.</param> + /// <returns>The vector with all components clamped.</returns> + public Vector3i Clamp(Vector3i min, Vector3i max) + { + return new Vector3i + ( + Mathf.Clamp(x, min.x, max.x), + Mathf.Clamp(y, min.y, max.y), + Mathf.Clamp(z, min.z, max.z) + ); + } + + /// <summary> /// Returns the squared distance between this vector and `b`. /// This method runs faster than <see cref="DistanceTo"/>, so prefer it if /// you need to compare vectors or need the squared distance for some formula. @@ -494,22 +511,12 @@ namespace Godot public override string ToString() { - return String.Format("({0}, {1}, {2})", new object[] - { - this.x.ToString(), - this.y.ToString(), - this.z.ToString() - }); + return $"({x}, {y}, {z})"; } public string ToString(string format) { - return String.Format("({0}, {1}, {2})", new object[] - { - this.x.ToString(format), - this.y.ToString(format), - this.z.ToString(format) - }); + return $"({x.ToString(format)}, {y.ToString(format)}, {z.ToString(format)})"; } } } diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj index 54aaaf1f92..1fcfe74c86 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj +++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj @@ -50,7 +50,7 @@ <Compile Include="Core\NodePath.cs" /> <Compile Include="Core\Object.base.cs" /> <Compile Include="Core\Plane.cs" /> - <Compile Include="Core\Quat.cs" /> + <Compile Include="Core\Quaternion.cs" /> <Compile Include="Core\Rect2.cs" /> <Compile Include="Core\Rect2i.cs" /> <Compile Include="Core\RID.cs" /> @@ -58,8 +58,8 @@ <Compile Include="Core\SignalAwaiter.cs" /> <Compile Include="Core\StringExtensions.cs" /> <Compile Include="Core\StringName.cs" /> - <Compile Include="Core\Transform.cs" /> <Compile Include="Core\Transform2D.cs" /> + <Compile Include="Core\Transform3D.cs" /> <Compile Include="Core\UnhandledExceptionArgs.cs" /> <Compile Include="Core\Vector2.cs" /> <Compile Include="Core\Vector2i.cs" /> diff --git a/modules/mono/glue/base_object_glue.cpp b/modules/mono/glue/base_object_glue.cpp index 34a96eba17..a99dff8432 100644 --- a/modules/mono/glue/base_object_glue.cpp +++ b/modules/mono/glue/base_object_glue.cpp @@ -31,7 +31,7 @@ #ifdef MONO_GLUE_ENABLED #include "core/object/class_db.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/string/string_name.h" #include "../csharp_script.h" @@ -64,7 +64,7 @@ void godot_icall_Object_Disposed(MonoObject *p_obj, Object *p_ptr) { return; } } - +#if 0 void *data = p_ptr->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index()); if (data) { @@ -76,19 +76,20 @@ void godot_icall_Object_Disposed(MonoObject *p_obj, Object *p_ptr) { } } } +#endif } -void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolean p_is_finalizer) { +void godot_icall_RefCounted_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolean p_is_finalizer) { #ifdef DEBUG_ENABLED CRASH_COND(p_ptr == nullptr); - // This is only called with Reference derived classes - CRASH_COND(!Object::cast_to<Reference>(p_ptr)); + // This is only called with RefCounted derived classes + CRASH_COND(!Object::cast_to<RefCounted>(p_ptr)); #endif +#if 0 + RefCounted *rc = static_cast<RefCounted *>(p_ptr); - Reference *ref = static_cast<Reference *>(p_ptr); - - if (ref->get_script_instance()) { - CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(ref->get_script_instance()); + if (rc->get_script_instance()) { + CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(rc->get_script_instance()); if (cs_instance) { if (!cs_instance->is_destructing_script_instance()) { bool delete_owner; @@ -97,9 +98,9 @@ void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolea cs_instance->mono_object_disposed_baseref(p_obj, p_is_finalizer, delete_owner, remove_script_instance); if (delete_owner) { - memdelete(ref); + memdelete(rc); } else if (remove_script_instance) { - ref->set_script_instance(nullptr); + rc->set_script_instance(nullptr); } } return; @@ -108,11 +109,11 @@ void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolea // Unsafe refcount decrement. The managed instance also counts as a reference. // See: CSharpLanguage::alloc_instance_binding_data(Object *p_object) - CSharpLanguage::get_singleton()->pre_unsafe_unreference(ref); - if (ref->unreference()) { - memdelete(ref); + CSharpLanguage::get_singleton()->pre_unsafe_unreference(rc); + if (rc->unreference()) { + memdelete(rc); } else { - void *data = ref->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index()); + void *data = rc->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index()); if (data) { CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); @@ -124,6 +125,7 @@ void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolea } } } +#endif } void godot_icall_Object_ConnectEventSignals(Object *p_ptr) { @@ -145,18 +147,18 @@ MonoObject *godot_icall_Object_weakref(Object *p_ptr) { } Ref<WeakRef> wref; - Reference *ref = Object::cast_to<Reference>(p_ptr); + RefCounted *rc = Object::cast_to<RefCounted>(p_ptr); - if (ref) { - REF r = ref; + if (rc) { + REF r = rc; if (!r.is_valid()) { return nullptr; } - wref.instance(); + wref.instantiate(); wref->set_ref(r); } else { - wref.instance(); + wref.instantiate(); wref->set_obj(p_ptr); } @@ -175,8 +177,8 @@ MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr) { MonoArray *result = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), property_list.size()); int i = 0; - for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) { - MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get().name); + for (const PropertyInfo &E : property_list) { + MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E.name); mono_array_setref(result, i, boxed); i++; } @@ -242,7 +244,7 @@ MonoString *godot_icall_Object_ToString(Object *p_ptr) { void godot_register_object_icalls() { GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_Ctor", godot_icall_Object_Ctor); GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_Disposed", godot_icall_Object_Disposed); - GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Reference_Disposed", godot_icall_Reference_Disposed); + GDMonoUtils::add_internal_call("Godot.Object::godot_icall_RefCounted_Disposed", godot_icall_RefCounted_Disposed); GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ConnectEventSignals", godot_icall_Object_ConnectEventSignals); GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ClassDB_get_method", godot_icall_Object_ClassDB_get_method); GDMonoUtils::add_internal_call("Godot.Object::godot_icall_Object_ToString", godot_icall_Object_ToString); diff --git a/modules/mono/glue/collections_glue.cpp b/modules/mono/glue/collections_glue.cpp index 191f863350..86976de244 100644 --- a/modules/mono/glue/collections_glue.cpp +++ b/modules/mono/glue/collections_glue.cpp @@ -230,6 +230,19 @@ int32_t godot_icall_Dictionary_Count(Dictionary *ptr) { return ptr->size(); } +int32_t godot_icall_Dictionary_KeyValuePairs(Dictionary *ptr, Array **keys, Array **values) { + *keys = godot_icall_Dictionary_Keys(ptr); + *values = godot_icall_Dictionary_Values(ptr); + return godot_icall_Dictionary_Count(ptr); +} + +void godot_icall_Dictionary_KeyValuePairAt(Dictionary *ptr, int index, MonoObject **key, MonoObject **value) { + Array *keys = godot_icall_Dictionary_Keys(ptr); + Array *values = godot_icall_Dictionary_Values(ptr); + *key = GDMonoMarshal::variant_to_mono_object(keys->get(index)); + *value = GDMonoMarshal::variant_to_mono_object(values->get(index)); +} + void godot_icall_Dictionary_Add(Dictionary *ptr, MonoObject *key, MonoObject *value) { Variant varKey = GDMonoMarshal::mono_object_to_variant(key); Variant *ret = ptr->getptr(varKey); @@ -338,6 +351,8 @@ void godot_register_collections_icalls() { GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Keys", godot_icall_Dictionary_Keys); GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Values", godot_icall_Dictionary_Values); GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Count", godot_icall_Dictionary_Count); + GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_KeyValuePairs", godot_icall_Dictionary_KeyValuePairs); + GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_KeyValuePairAt", godot_icall_Dictionary_KeyValuePairAt); GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Add", godot_icall_Dictionary_Add); GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Clear", godot_icall_Dictionary_Clear); GDMonoUtils::add_internal_call("Godot.Collections.Dictionary::godot_icall_Dictionary_Contains", godot_icall_Dictionary_Contains); diff --git a/modules/mono/glue/glue_header.h b/modules/mono/glue/glue_header.h index 3db52d7c30..eed3bd2167 100644 --- a/modules/mono/glue/glue_header.h +++ b/modules/mono/glue/glue_header.h @@ -61,7 +61,7 @@ void godot_register_glue_header_icalls() { #include "core/config/engine.h" #include "core/object/class_db.h" #include "core/object/method_bind.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/string/node_path.h" #include "core/string/ustring.h" #include "core/typedefs.h" diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index 020a40575c..375ad413c4 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -31,7 +31,7 @@ #include "godotsharp_dirs.h" #include "core/config/project_settings.h" -#include "core/os/dir_access.h" +#include "core/io/dir_access.h" #include "core/os/os.h" #ifdef TOOLS_ENABLED @@ -63,8 +63,8 @@ String _get_expected_build_config() { String _get_mono_user_dir() { #ifdef TOOLS_ENABLED - if (EditorSettings::get_singleton()) { - return EditorSettings::get_singleton()->get_data_dir().plus_file("mono"); + if (EditorPaths::get_singleton()) { + return EditorPaths::get_singleton()->get_data_dir().plus_file("mono"); } else { String settings_path; diff --git a/modules/mono/mono_gc_handle.h b/modules/mono/mono_gc_handle.h index f435aab3dd..d0e51d159f 100644 --- a/modules/mono/mono_gc_handle.h +++ b/modules/mono/mono_gc_handle.h @@ -33,7 +33,7 @@ #include <mono/jit/jit.h> -#include "core/object/reference.h" +#include "core/object/ref_counted.h" namespace gdmono { @@ -79,8 +79,8 @@ struct MonoGCHandleData { static MonoGCHandleData new_weak_handle(MonoObject *p_object); }; -class MonoGCHandleRef : public Reference { - GDCLASS(MonoGCHandleRef, Reference); +class MonoGCHandleRef : public RefCounted { + GDCLASS(MonoGCHandleRef, RefCounted); MonoGCHandleData data; diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index c523d381f6..299344bb93 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -39,8 +39,8 @@ #include "core/config/project_settings.h" #include "core/debugger/engine_debugger.h" -#include "core/os/dir_access.h" -#include "core/os/file_access.h" +#include "core/io/dir_access.h" +#include "core/io/file_access.h" #include "core/os/os.h" #include "core/os/thread.h" @@ -100,8 +100,8 @@ void gd_mono_setup_runtime_main_args() { main_args.write[0] = execpath.ptrw(); int i = 1; - for (List<String>::Element *E = cmdline_args.front(); E; E = E->next()) { - CharString &stored = cmdline_args_utf8.push_back(E->get().utf8())->get(); + for (const String &E : cmdline_args) { + CharString &stored = cmdline_args_utf8.push_back(E.utf8())->get(); main_args.write[i] = stored.ptrw(); i++; } @@ -691,7 +691,7 @@ static bool try_get_cached_api_hash_for(const String &p_api_assemblies_dir, bool } Ref<ConfigFile> cfg; - cfg.instance(); + cfg.instantiate(); Error cfg_err = cfg->load(cached_api_hash_path); ERR_FAIL_COND_V(cfg_err != OK, false); @@ -717,7 +717,7 @@ static void create_cached_api_hash_for(const String &p_api_assemblies_dir) { String cached_api_hash_path = p_api_assemblies_dir.plus_file("api_hash_cache.cfg"); Ref<ConfigFile> cfg; - cfg.instance(); + cfg.instantiate(); cfg->set_value("core", "modified_time", FileAccess::get_modified_time(core_api_assembly_path)); cfg->set_value("editor", "modified_time", FileAccess::get_modified_time(editor_api_assembly_path)); diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp index a1556bace5..67f38bf127 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.cpp +++ b/modules/mono/mono_gd/gd_mono_assembly.cpp @@ -34,8 +34,8 @@ #include <mono/metadata/tokentype.h> #include "core/config/project_settings.h" +#include "core/io/file_access.h" #include "core/io/file_access_pack.h" -#include "core/os/file_access.h" #include "core/os/os.h" #include "core/templates/list.h" @@ -330,8 +330,8 @@ no_pdb: void GDMonoAssembly::unload() { ERR_FAIL_NULL(image); // Should not be called if already unloaded - for (Map<MonoClass *, GDMonoClass *>::Element *E = cached_raw.front(); E; E = E->next()) { - memdelete(E->value()); + for (const KeyValue<MonoClass *, GDMonoClass *> &E : cached_raw) { + memdelete(E.value); } cached_classes.clear(); diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp index d66cc29b9a..0b36796d98 100644 --- a/modules/mono/mono_gd/gd_mono_cache.cpp +++ b/modules/mono/mono_gd/gd_mono_cache.cpp @@ -109,8 +109,8 @@ void CachedData::clear_godot_api_cache() { class_Vector3 = nullptr; class_Vector3i = nullptr; class_Basis = nullptr; - class_Quat = nullptr; - class_Transform = nullptr; + class_Quaternion = nullptr; + class_Transform3D = nullptr; class_AABB = nullptr; class_Color = nullptr; class_Plane = nullptr; @@ -143,9 +143,6 @@ void CachedData::clear_godot_api_cache() { class_RemoteAttribute = nullptr; class_MasterAttribute = nullptr; class_PuppetAttribute = nullptr; - class_RemoteSyncAttribute = nullptr; - class_MasterSyncAttribute = nullptr; - class_PuppetSyncAttribute = nullptr; class_GodotMethodAttribute = nullptr; field_GodotMethodAttribute_methodName = nullptr; class_ScriptPathAttribute = nullptr; @@ -238,8 +235,8 @@ void update_godot_api_cache() { CACHE_CLASS_AND_CHECK(Vector3, GODOT_API_CLASS(Vector3)); CACHE_CLASS_AND_CHECK(Vector3i, GODOT_API_CLASS(Vector3i)); CACHE_CLASS_AND_CHECK(Basis, GODOT_API_CLASS(Basis)); - CACHE_CLASS_AND_CHECK(Quat, GODOT_API_CLASS(Quat)); - CACHE_CLASS_AND_CHECK(Transform, GODOT_API_CLASS(Transform)); + CACHE_CLASS_AND_CHECK(Quaternion, GODOT_API_CLASS(Quaternion)); + CACHE_CLASS_AND_CHECK(Transform3D, GODOT_API_CLASS(Transform3D)); CACHE_CLASS_AND_CHECK(AABB, GODOT_API_CLASS(AABB)); CACHE_CLASS_AND_CHECK(Color, GODOT_API_CLASS(Color)); CACHE_CLASS_AND_CHECK(Plane, GODOT_API_CLASS(Plane)); @@ -272,9 +269,6 @@ void update_godot_api_cache() { CACHE_CLASS_AND_CHECK(RemoteAttribute, GODOT_API_CLASS(RemoteAttribute)); CACHE_CLASS_AND_CHECK(MasterAttribute, GODOT_API_CLASS(MasterAttribute)); CACHE_CLASS_AND_CHECK(PuppetAttribute, GODOT_API_CLASS(PuppetAttribute)); - CACHE_CLASS_AND_CHECK(RemoteSyncAttribute, GODOT_API_CLASS(RemoteSyncAttribute)); - CACHE_CLASS_AND_CHECK(MasterSyncAttribute, GODOT_API_CLASS(MasterSyncAttribute)); - CACHE_CLASS_AND_CHECK(PuppetSyncAttribute, GODOT_API_CLASS(PuppetSyncAttribute)); CACHE_CLASS_AND_CHECK(GodotMethodAttribute, GODOT_API_CLASS(GodotMethodAttribute)); CACHE_FIELD_AND_CHECK(GodotMethodAttribute, methodName, CACHED_CLASS(GodotMethodAttribute)->get_field("methodName")); CACHE_CLASS_AND_CHECK(ScriptPathAttribute, GODOT_API_CLASS(ScriptPathAttribute)); diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index 51370da452..6d49da0af3 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -80,8 +80,8 @@ struct CachedData { GDMonoClass *class_Vector3; GDMonoClass *class_Vector3i; GDMonoClass *class_Basis; - GDMonoClass *class_Quat; - GDMonoClass *class_Transform; + GDMonoClass *class_Quaternion; + GDMonoClass *class_Transform3D; GDMonoClass *class_AABB; GDMonoClass *class_Color; GDMonoClass *class_Plane; @@ -114,9 +114,6 @@ struct CachedData { GDMonoClass *class_RemoteAttribute; GDMonoClass *class_MasterAttribute; GDMonoClass *class_PuppetAttribute; - GDMonoClass *class_RemoteSyncAttribute; - GDMonoClass *class_MasterSyncAttribute; - GDMonoClass *class_PuppetSyncAttribute; GDMonoClass *class_GodotMethodAttribute; GDMonoField *field_GodotMethodAttribute_methodName; GDMonoClass *class_ScriptPathAttribute; diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp index f9fddd931b..27b4ac7fa7 100644 --- a/modules/mono/mono_gd/gd_mono_class.cpp +++ b/modules/mono/mono_gd/gd_mono_class.cpp @@ -522,12 +522,12 @@ GDMonoClass::~GDMonoClass() { mono_custom_attrs_free(attributes); } - for (Map<StringName, GDMonoField *>::Element *E = fields.front(); E; E = E->next()) { - memdelete(E->value()); + for (const KeyValue<StringName, GDMonoField *> &E : fields) { + memdelete(E.value); } - for (Map<StringName, GDMonoProperty *>::Element *E = properties.front(); E; E = E->next()) { - memdelete(E->value()); + for (const KeyValue<StringName, GDMonoProperty *> &E : properties) { + memdelete(E.value); } { diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp index 1d4d52dfce..111eaa0bbf 100644 --- a/modules/mono/mono_gd/gd_mono_field.cpp +++ b/modules/mono/mono_gd/gd_mono_field.cpp @@ -146,14 +146,14 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ break; } - if (tclass == CACHED_CLASS(Quat)) { - GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_value.operator ::Quat()); + if (tclass == CACHED_CLASS(Quaternion)) { + GDMonoMarshal::M_Quaternion from = MARSHALLED_OUT(Quaternion, p_value.operator ::Quaternion()); mono_field_set_value(p_object, mono_field, &from); break; } - if (tclass == CACHED_CLASS(Transform)) { - GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_value.operator ::Transform()); + if (tclass == CACHED_CLASS(Transform3D)) { + GDMonoMarshal::M_Transform3D from = MARSHALLED_OUT(Transform3D, p_value.operator ::Transform3D()); mono_field_set_value(p_object, mono_field, &from); break; } @@ -336,8 +336,8 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_value.operator ::Plane()); mono_field_set_value(p_object, mono_field, &from); } break; - case Variant::QUAT: { - GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_value.operator ::Quat()); + case Variant::QUATERNION: { + GDMonoMarshal::M_Quaternion from = MARSHALLED_OUT(Quaternion, p_value.operator ::Quaternion()); mono_field_set_value(p_object, mono_field, &from); } break; case Variant::AABB: { @@ -348,8 +348,8 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_value.operator ::Basis()); mono_field_set_value(p_object, mono_field, &from); } break; - case Variant::TRANSFORM: { - GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_value.operator ::Transform()); + case Variant::TRANSFORM3D: { + GDMonoMarshal::M_Transform3D from = MARSHALLED_OUT(Transform3D, p_value.operator ::Transform3D()); mono_field_set_value(p_object, mono_field, &from); } break; case Variant::COLOR: { diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp index fa93c6533a..d6545d50ec 100644 --- a/modules/mono/mono_gd/gd_mono_internals.cpp +++ b/modules/mono/mono_gd/gd_mono_internals.cpp @@ -45,13 +45,13 @@ namespace GDMonoInternals { void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { // This method should not fail - +#if 0 CRASH_COND(!unmanaged); // All mono objects created from the managed world (e.g.: 'new Player()') // need to have a CSharpScript in order for their methods to be callable from the unmanaged side - Reference *ref = Object::cast_to<Reference>(unmanaged); + RefCounted *rc = Object::cast_to<RefCounted>(unmanaged); GDMonoClass *klass = GDMonoUtils::get_object_class(managed); @@ -73,18 +73,18 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { script_binding.inited = true; script_binding.type_name = NATIVE_GDMONOCLASS_NAME(klass); script_binding.wrapper_class = klass; - script_binding.gchandle = ref ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); + script_binding.gchandle = rc ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); script_binding.owner = unmanaged; - if (ref) { + if (rc) { // Unsafe refcount increment. The managed instance also counts as a reference. // This way if the unmanaged world has no references to our owner // but the managed instance is alive, the refcount will be 1 instead of 0. - // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr) + // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr) // May not me referenced yet, so we must use init_ref() instead of reference() - if (ref->init_ref()) { - CSharpLanguage::get_singleton()->post_unsafe_reference(ref); + if (rc->init_ref()) { + CSharpLanguage::get_singleton()->post_unsafe_reference(rc); } } @@ -99,7 +99,7 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { return; } - MonoGCHandleData gchandle = ref ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); + MonoGCHandleData gchandle = rc ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); Ref<CSharpScript> script = CSharpScript::create_for_managed_type(klass, native); @@ -108,6 +108,7 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { CSharpInstance *csharp_instance = CSharpInstance::create_for_managed_type(unmanaged, script.ptr(), gchandle); unmanaged->set_script_and_instance(script, csharp_instance); +#endif } void unhandled_exception(MonoException *p_exc) { diff --git a/modules/mono/mono_gd/gd_mono_log.cpp b/modules/mono/mono_gd/gd_mono_log.cpp index dafd36c36b..179bbfb40c 100644 --- a/modules/mono/mono_gd/gd_mono_log.cpp +++ b/modules/mono/mono_gd/gd_mono_log.cpp @@ -32,7 +32,7 @@ #include <stdlib.h> // abort -#include "core/os/dir_access.h" +#include "core/io/dir_access.h" #include "core/os/os.h" #include "../godotsharp_dirs.h" @@ -161,8 +161,8 @@ void GDMonoLog::initialize() { OS::Time time_now = OS::get_singleton()->get_time(); String log_file_name = str_format("%04d-%02d-%02d_%02d.%02d.%02d", - date_now.year, date_now.month, date_now.day, - time_now.hour, time_now.min, time_now.sec); + (int)date_now.year, (int)date_now.month, (int)date_now.day, + (int)time_now.hour, (int)time_now.minute, (int)time_now.second); log_file_name += str_format("_%d", OS::get_singleton()->get_process_id()); diff --git a/modules/mono/mono_gd/gd_mono_log.h b/modules/mono/mono_gd/gd_mono_log.h index f7a53156ab..9ddbd251ac 100644 --- a/modules/mono/mono_gd/gd_mono_log.h +++ b/modules/mono/mono_gd/gd_mono_log.h @@ -41,7 +41,7 @@ #endif #ifdef GD_MONO_LOG_ENABLED -#include "core/os/file_access.h" +#include "core/io/file_access.h" #endif class GDMonoLog { diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp index 359f6bba4d..9f2977bfa2 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.cpp +++ b/modules/mono/mono_gd/gd_mono_marshal.cpp @@ -104,12 +104,12 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_ return Variant::BASIS; } - if (vtclass == CACHED_CLASS(Quat)) { - return Variant::QUAT; + if (vtclass == CACHED_CLASS(Quaternion)) { + return Variant::QUATERNION; } - if (vtclass == CACHED_CLASS(Transform)) { - return Variant::TRANSFORM; + if (vtclass == CACHED_CLASS(Transform3D)) { + return Variant::TRANSFORM3D; } if (vtclass == CACHED_CLASS(AABB)) { @@ -508,9 +508,9 @@ MonoObject *variant_to_mono_object(const Variant &p_var) { GDMonoMarshal::M_Plane from = MARSHALLED_OUT(Plane, p_var.operator ::Plane()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Plane), &from); } - case Variant::QUAT: { - GDMonoMarshal::M_Quat from = MARSHALLED_OUT(Quat, p_var.operator ::Quat()); - return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Quat), &from); + case Variant::QUATERNION: { + GDMonoMarshal::M_Quaternion from = MARSHALLED_OUT(Quaternion, p_var.operator ::Quaternion()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Quaternion), &from); } case Variant::AABB: { GDMonoMarshal::M_AABB from = MARSHALLED_OUT(AABB, p_var.operator ::AABB()); @@ -520,9 +520,9 @@ MonoObject *variant_to_mono_object(const Variant &p_var) { GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_var.operator ::Basis()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Basis), &from); } - case Variant::TRANSFORM: { - GDMonoMarshal::M_Transform from = MARSHALLED_OUT(Transform, p_var.operator ::Transform()); - return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform), &from); + case Variant::TRANSFORM3D: { + GDMonoMarshal::M_Transform3D from = MARSHALLED_OUT(Transform3D, p_var.operator ::Transform3D()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform3D), &from); } case Variant::COLOR: { GDMonoMarshal::M_Color from = MARSHALLED_OUT(Color, p_var.operator ::Color()); @@ -619,8 +619,8 @@ size_t variant_get_managed_unboxed_size(const ManagedType &p_type) { RETURN_CHECK_FOR_STRUCT(Vector3); RETURN_CHECK_FOR_STRUCT(Vector3i); RETURN_CHECK_FOR_STRUCT(Basis); - RETURN_CHECK_FOR_STRUCT(Quat); - RETURN_CHECK_FOR_STRUCT(Transform); + RETURN_CHECK_FOR_STRUCT(Quaternion); + RETURN_CHECK_FOR_STRUCT(Transform3D); RETURN_CHECK_FOR_STRUCT(AABB); RETURN_CHECK_FOR_STRUCT(Color); RETURN_CHECK_FOR_STRUCT(Plane); @@ -724,8 +724,8 @@ void *variant_to_managed_unboxed(const Variant &p_var, const ManagedType &p_type RETURN_CHECK_FOR_STRUCT(Vector3); RETURN_CHECK_FOR_STRUCT(Vector3i); RETURN_CHECK_FOR_STRUCT(Basis); - RETURN_CHECK_FOR_STRUCT(Quat); - RETURN_CHECK_FOR_STRUCT(Transform); + RETURN_CHECK_FOR_STRUCT(Quaternion); + RETURN_CHECK_FOR_STRUCT(Transform3D); RETURN_CHECK_FOR_STRUCT(AABB); RETURN_CHECK_FOR_STRUCT(Color); RETURN_CHECK_FOR_STRUCT(Plane); @@ -880,8 +880,8 @@ MonoObject *variant_to_mono_object(const Variant &p_var, const ManagedType &p_ty RETURN_CHECK_FOR_STRUCT(Vector3); RETURN_CHECK_FOR_STRUCT(Vector3i); RETURN_CHECK_FOR_STRUCT(Basis); - RETURN_CHECK_FOR_STRUCT(Quat); - RETURN_CHECK_FOR_STRUCT(Transform); + RETURN_CHECK_FOR_STRUCT(Quaternion); + RETURN_CHECK_FOR_STRUCT(Transform3D); RETURN_CHECK_FOR_STRUCT(AABB); RETURN_CHECK_FOR_STRUCT(Color); RETURN_CHECK_FOR_STRUCT(Plane); @@ -1036,12 +1036,12 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type return MARSHALLED_IN(Basis, unbox_addr<GDMonoMarshal::M_Basis>(p_obj)); } - if (vtclass == CACHED_CLASS(Quat)) { - return MARSHALLED_IN(Quat, unbox_addr<GDMonoMarshal::M_Quat>(p_obj)); + if (vtclass == CACHED_CLASS(Quaternion)) { + return MARSHALLED_IN(Quaternion, unbox_addr<GDMonoMarshal::M_Quaternion>(p_obj)); } - if (vtclass == CACHED_CLASS(Transform)) { - return MARSHALLED_IN(Transform, unbox_addr<GDMonoMarshal::M_Transform>(p_obj)); + if (vtclass == CACHED_CLASS(Transform3D)) { + return MARSHALLED_IN(Transform3D, unbox_addr<GDMonoMarshal::M_Transform3D>(p_obj)); } if (vtclass == CACHED_CLASS(AABB)) { @@ -1136,8 +1136,8 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) { Object *ptr = unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(p_obj)); if (ptr != nullptr) { - Reference *ref = Object::cast_to<Reference>(ptr); - return ref ? Variant(Ref<Reference>(ref)) : Variant(ptr); + RefCounted *rc = Object::cast_to<RefCounted>(ptr); + return rc ? Variant(Ref<RefCounted>(rc)) : Variant(ptr); } return Variant(); } diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h index 668809ae5d..88afc7ebc5 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ b/modules/mono/mono_gd/gd_mono_marshal.h @@ -263,15 +263,15 @@ enum { MATCHES_Basis = (MATCHES_Vector3 && (sizeof(Basis) == (sizeof(Vector3) * 3))), // No field offset required, it stores an array - MATCHES_Quat = (MATCHES_real_t && (sizeof(Quat) == (sizeof(real_t) * 4)) && - offsetof(Quat, x) == (sizeof(real_t) * 0) && - offsetof(Quat, y) == (sizeof(real_t) * 1) && - offsetof(Quat, z) == (sizeof(real_t) * 2) && - offsetof(Quat, w) == (sizeof(real_t) * 3)), + MATCHES_Quaternion = (MATCHES_real_t && (sizeof(Quaternion) == (sizeof(real_t) * 4)) && + offsetof(Quaternion, x) == (sizeof(real_t) * 0) && + offsetof(Quaternion, y) == (sizeof(real_t) * 1) && + offsetof(Quaternion, z) == (sizeof(real_t) * 2) && + offsetof(Quaternion, w) == (sizeof(real_t) * 3)), - MATCHES_Transform = (MATCHES_Basis && MATCHES_Vector3 && (sizeof(Transform) == (sizeof(Basis) + sizeof(Vector3))) && - offsetof(Transform, basis) == 0 && - offsetof(Transform, origin) == sizeof(Basis)), + MATCHES_Transform3D = (MATCHES_Basis && MATCHES_Vector3 && (sizeof(Transform3D) == (sizeof(Basis) + sizeof(Vector3))) && + offsetof(Transform3D, basis) == 0 && + offsetof(Transform3D, origin) == sizeof(Basis)), MATCHES_AABB = (MATCHES_Vector3 && (sizeof(AABB) == (sizeof(Vector3) * 2)) && offsetof(AABB, position) == (sizeof(Vector3) * 0) && @@ -292,7 +292,7 @@ enum { #ifdef GD_MONO_FORCE_INTEROP_STRUCT_COPY /* clang-format off */ static_assert(MATCHES_Vector2 && MATCHES_Rect2 && MATCHES_Transform2D && MATCHES_Vector3 && - MATCHES_Basis && MATCHES_Quat && MATCHES_Transform && MATCHES_AABB && MATCHES_Color && + MATCHES_Basis && MATCHES_Quaternion && MATCHES_Transform3D && MATCHES_AABB && MATCHES_Color && MATCHES_Plane && MATCHES_Vector2i && MATCHES_Rect2i && MATCHES_Vector3i); /* clang-format on */ #endif @@ -420,29 +420,29 @@ struct M_Basis { } }; -struct M_Quat { +struct M_Quaternion { real_t x, y, z, w; - static _FORCE_INLINE_ Quat convert_to(const M_Quat &p_from) { - return Quat(p_from.x, p_from.y, p_from.z, p_from.w); + static _FORCE_INLINE_ Quaternion convert_to(const M_Quaternion &p_from) { + return Quaternion(p_from.x, p_from.y, p_from.z, p_from.w); } - static _FORCE_INLINE_ M_Quat convert_from(const Quat &p_from) { - M_Quat ret = { p_from.x, p_from.y, p_from.z, p_from.w }; + static _FORCE_INLINE_ M_Quaternion convert_from(const Quaternion &p_from) { + M_Quaternion ret = { p_from.x, p_from.y, p_from.z, p_from.w }; return ret; } }; -struct M_Transform { +struct M_Transform3D { M_Basis basis; M_Vector3 origin; - static _FORCE_INLINE_ Transform convert_to(const M_Transform &p_from) { - return Transform(M_Basis::convert_to(p_from.basis), M_Vector3::convert_to(p_from.origin)); + static _FORCE_INLINE_ Transform3D convert_to(const M_Transform3D &p_from) { + return Transform3D(M_Basis::convert_to(p_from.basis), M_Vector3::convert_to(p_from.origin)); } - static _FORCE_INLINE_ M_Transform convert_from(const Transform &p_from) { - M_Transform ret = { M_Basis::convert_from(p_from.basis), M_Vector3::convert_from(p_from.origin) }; + static _FORCE_INLINE_ M_Transform3D convert_from(const Transform3D &p_from) { + M_Transform3D ret = { M_Basis::convert_from(p_from.basis), M_Vector3::convert_from(p_from.origin) }; return ret; } }; @@ -533,8 +533,8 @@ DECL_TYPE_MARSHAL_TEMPLATES(Transform2D) DECL_TYPE_MARSHAL_TEMPLATES(Vector3) DECL_TYPE_MARSHAL_TEMPLATES(Vector3i) DECL_TYPE_MARSHAL_TEMPLATES(Basis) -DECL_TYPE_MARSHAL_TEMPLATES(Quat) -DECL_TYPE_MARSHAL_TEMPLATES(Transform) +DECL_TYPE_MARSHAL_TEMPLATES(Quaternion) +DECL_TYPE_MARSHAL_TEMPLATES(Transform3D) DECL_TYPE_MARSHAL_TEMPLATES(AABB) DECL_TYPE_MARSHAL_TEMPLATES(Color) DECL_TYPE_MARSHAL_TEMPLATES(Plane) diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp index 6e0a263c7f..080398c997 100644 --- a/modules/mono/mono_gd/gd_mono_utils.cpp +++ b/modules/mono/mono_gd/gd_mono_utils.cpp @@ -35,8 +35,8 @@ #include "core/debugger/engine_debugger.h" #include "core/debugger/script_debugger.h" -#include "core/object/reference.h" -#include "core/os/dir_access.h" +#include "core/io/dir_access.h" +#include "core/object/ref_counted.h" #include "core/os/mutex.h" #include "core/os/os.h" @@ -54,6 +54,7 @@ namespace GDMonoUtils { MonoObject *unmanaged_get_managed(Object *unmanaged) { +#if 0 if (!unmanaged) { return nullptr; } @@ -108,18 +109,20 @@ MonoObject *unmanaged_get_managed(Object *unmanaged) { gchandle = MonoGCHandleData::new_strong_handle(mono_object); // Tie managed to unmanaged - Reference *ref = Object::cast_to<Reference>(unmanaged); + RefCounted *rc = Object::cast_to<RefCounted>(unmanaged); - if (ref) { + if (rc) { // Unsafe refcount increment. The managed instance also counts as a reference. // This way if the unmanaged world has no references to our owner // but the managed instance is alive, the refcount will be 1 instead of 0. - // See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr) - ref->reference(); - CSharpLanguage::get_singleton()->post_unsafe_reference(ref); + // See: godot_icall_RefCounted_Dtor(MonoObject *p_obj, Object *p_ptr) + rc->reference(); + CSharpLanguage::get_singleton()->post_unsafe_reference(rc); } return mono_object; +#endif + return nullptr; } void set_main_thread(MonoThread *p_thread) { @@ -238,7 +241,7 @@ GDMonoClass *get_class_native_base(GDMonoClass *p_class) { MonoObject *create_managed_for_godot_object(GDMonoClass *p_class, const StringName &p_native, Object *p_object) { bool parent_is_object_class = ClassDB::is_parent_class(p_object->get_class_name(), p_native); ERR_FAIL_COND_V_MSG(!parent_is_object_class, nullptr, - "Type inherits from native type '" + p_native + "', so it can't be instanced in object of type: '" + p_object->get_class() + "'."); + "Type inherits from native type '" + p_native + "', so it can't be instantiated in object of type: '" + p_object->get_class() + "'."); MonoObject *mono_object = mono_object_new(mono_domain_get(), p_class->get_mono_ptr()); ERR_FAIL_NULL_V(mono_object, nullptr); diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h index 9e024418e1..773501e93d 100644 --- a/modules/mono/mono_gd/gd_mono_utils.h +++ b/modules/mono/mono_gd/gd_mono_utils.h @@ -41,7 +41,7 @@ #endif #include "core/object/class_db.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #define UNHANDLED_EXCEPTION(m_exc) \ if (unlikely(m_exc != nullptr)) { \ diff --git a/modules/mono/mono_gd/support/ios_support.mm b/modules/mono/mono_gd/support/ios_support.mm index cdee04edcf..23424fbaf9 100644 --- a/modules/mono/mono_gd/support/ios_support.mm +++ b/modules/mono/mono_gd/support/ios_support.mm @@ -57,9 +57,9 @@ void ios_mono_log_callback(const char *log_domain, const char *log_level, const } void initialize() { - mono_dllmap_insert(NULL, "System.Native", NULL, "__Internal", NULL); - mono_dllmap_insert(NULL, "System.IO.Compression.Native", NULL, "__Internal", NULL); - mono_dllmap_insert(NULL, "System.Security.Cryptography.Native.Apple", NULL, "__Internal", NULL); + mono_dllmap_insert(nullptr, "System.Native", nullptr, "__Internal", nullptr); + mono_dllmap_insert(nullptr, "System.IO.Compression.Native", nullptr, "__Internal", nullptr); + mono_dllmap_insert(nullptr, "System.Security.Cryptography.Native.Apple", nullptr, "__Internal", nullptr); #ifdef IOS_DEVICE // This function is defined in an auto-generated source file @@ -85,7 +85,7 @@ void cleanup() { GD_PINVOKE_EXPORT const char *xamarin_get_locale_country_code() { NSLocale *locale = [NSLocale currentLocale]; NSString *countryCode = [locale objectForKey:NSLocaleCountryCode]; - if (countryCode == NULL) { + if (countryCode == nullptr) { return strdup("US"); } return strdup([countryCode UTF8String]); diff --git a/modules/mono/register_types.cpp b/modules/mono/register_types.cpp index 80eb47bfd4..2ba89eac55 100644 --- a/modules/mono/register_types.cpp +++ b/modules/mono/register_types.cpp @@ -41,21 +41,21 @@ Ref<ResourceFormatSaverCSharpScript> resource_saver_cs; _GodotSharp *_godotsharp = nullptr; void register_mono_types() { - ClassDB::register_class<CSharpScript>(); + GDREGISTER_CLASS(CSharpScript); _godotsharp = memnew(_GodotSharp); - ClassDB::register_class<_GodotSharp>(); + GDREGISTER_CLASS(_GodotSharp); Engine::get_singleton()->add_singleton(Engine::Singleton("GodotSharp", _GodotSharp::get_singleton())); script_language_cs = memnew(CSharpLanguage); script_language_cs->set_language_index(ScriptServer::get_language_count()); ScriptServer::register_language(script_language_cs); - resource_loader_cs.instance(); + resource_loader_cs.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_cs); - resource_saver_cs.instance(); + resource_saver_cs.instantiate(); ResourceSaver::add_resource_format_saver(resource_saver_cs); } diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h index 4c77f8cfed..e12ea45b3f 100644 --- a/modules/mono/signal_awaiter_utils.h +++ b/modules/mono/signal_awaiter_utils.h @@ -31,7 +31,7 @@ #ifndef SIGNAL_AWAITER_UTILS_H #define SIGNAL_AWAITER_UTILS_H -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "csharp_script.h" #include "mono_gc_handle.h" diff --git a/modules/mono/utils/mono_reg_utils.cpp b/modules/mono/utils/mono_reg_utils.cpp index bb1265e959..6b616dd52d 100644 --- a/modules/mono/utils/mono_reg_utils.cpp +++ b/modules/mono/utils/mono_reg_utils.cpp @@ -29,7 +29,7 @@ /*************************************************************************/ #include "mono_reg_utils.h" -#include "core/os/dir_access.h" +#include "core/io/dir_access.h" #ifdef WINDOWS_ENABLED diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp index 93d44628ac..ec04d50704 100644 --- a/modules/mono/utils/path_utils.cpp +++ b/modules/mono/utils/path_utils.cpp @@ -31,8 +31,8 @@ #include "path_utils.h" #include "core/config/project_settings.h" -#include "core/os/dir_access.h" -#include "core/os/file_access.h" +#include "core/io/dir_access.h" +#include "core/io/file_access.h" #include "core/os/os.h" #ifdef WINDOWS_ENABLED @@ -80,7 +80,7 @@ String cwd() { } String abspath(const String &p_path) { - if (p_path.is_abs_path()) { + if (p_path.is_absolute_path()) { return p_path.simplify_path(); } else { return path::join(path::cwd(), p_path).simplify_path(); diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp index 43de77005e..053618ebe4 100644 --- a/modules/mono/utils/string_utils.cpp +++ b/modules/mono/utils/string_utils.cpp @@ -30,7 +30,7 @@ #include "string_utils.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include <stdio.h> #include <stdlib.h> @@ -170,10 +170,10 @@ Error read_all_file_utf8(const String &p_path, String &r_content) { FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'."); - int len = f->get_len(); + uint64_t len = f->get_length(); sourcef.resize(len + 1); uint8_t *w = sourcef.ptrw(); - int r = f->get_buffer(w, len); + uint64_t r = f->get_buffer(w, len); f->close(); memdelete(f); ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); diff --git a/modules/gdnavigation/SCsub b/modules/navigation/SCsub index 22b5509b32..22b5509b32 100644 --- a/modules/gdnavigation/SCsub +++ b/modules/navigation/SCsub diff --git a/modules/gdnavigation/config.py b/modules/navigation/config.py index d22f9454ed..d22f9454ed 100644 --- a/modules/gdnavigation/config.py +++ b/modules/navigation/config.py diff --git a/modules/gdnavigation/gd_navigation_server.cpp b/modules/navigation/godot_navigation_server.cpp index 88ef434e0f..fd965674d6 100644 --- a/modules/gdnavigation/gd_navigation_server.cpp +++ b/modules/navigation/godot_navigation_server.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* gd_navigation_server.cpp */ +/* godot_navigation_server.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "gd_navigation_server.h" +#include "godot_navigation_server.h" #include "core/os/mutex.h" @@ -44,96 +44,96 @@ /// an instance of that struct with the submitted parameters. /// Then, that struct is stored in an array; the `sync` function consume that array. -#define COMMAND_1(F_NAME, T_0, D_0) \ - struct MERGE(F_NAME, _command) : public SetCommand { \ - T_0 d_0; \ - MERGE(F_NAME, _command) \ - (T_0 p_d_0) : \ - d_0(p_d_0) {} \ - virtual void exec(GdNavigationServer *server) { \ - server->MERGE(_cmd_, F_NAME)(d_0); \ - } \ - }; \ - void GdNavigationServer::F_NAME(T_0 D_0) const { \ - auto cmd = memnew(MERGE(F_NAME, _command)( \ - D_0)); \ - add_command(cmd); \ - } \ - void GdNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0) - -#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \ - struct MERGE(F_NAME, _command) : public SetCommand { \ - T_0 d_0; \ - T_1 d_1; \ - MERGE(F_NAME, _command) \ - ( \ - T_0 p_d_0, \ - T_1 p_d_1) : \ - d_0(p_d_0), \ - d_1(p_d_1) {} \ - virtual void exec(GdNavigationServer *server) { \ - server->MERGE(_cmd_, F_NAME)(d_0, d_1); \ - } \ - }; \ - void GdNavigationServer::F_NAME(T_0 D_0, T_1 D_1) const { \ - auto cmd = memnew(MERGE(F_NAME, _command)( \ - D_0, \ - D_1)); \ - add_command(cmd); \ - } \ - void GdNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1) - -#define COMMAND_4(F_NAME, T_0, D_0, T_1, D_1, T_2, D_2, T_3, D_3) \ - struct MERGE(F_NAME, _command) : public SetCommand { \ - T_0 d_0; \ - T_1 d_1; \ - T_2 d_2; \ - T_3 d_3; \ - MERGE(F_NAME, _command) \ - ( \ - T_0 p_d_0, \ - T_1 p_d_1, \ - T_2 p_d_2, \ - T_3 p_d_3) : \ - d_0(p_d_0), \ - d_1(p_d_1), \ - d_2(p_d_2), \ - d_3(p_d_3) {} \ - virtual void exec(GdNavigationServer *server) { \ - server->MERGE(_cmd_, F_NAME)(d_0, d_1, d_2, d_3); \ - } \ - }; \ - void GdNavigationServer::F_NAME(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3) const { \ - auto cmd = memnew(MERGE(F_NAME, _command)( \ - D_0, \ - D_1, \ - D_2, \ - D_3)); \ - add_command(cmd); \ - } \ - void GdNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3) - -GdNavigationServer::GdNavigationServer() : +#define COMMAND_1(F_NAME, T_0, D_0) \ + struct MERGE(F_NAME, _command) : public SetCommand { \ + T_0 d_0; \ + MERGE(F_NAME, _command) \ + (T_0 p_d_0) : \ + d_0(p_d_0) {} \ + virtual void exec(GodotNavigationServer *server) { \ + server->MERGE(_cmd_, F_NAME)(d_0); \ + } \ + }; \ + void GodotNavigationServer::F_NAME(T_0 D_0) const { \ + auto cmd = memnew(MERGE(F_NAME, _command)( \ + D_0)); \ + add_command(cmd); \ + } \ + void GodotNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0) + +#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \ + struct MERGE(F_NAME, _command) : public SetCommand { \ + T_0 d_0; \ + T_1 d_1; \ + MERGE(F_NAME, _command) \ + ( \ + T_0 p_d_0, \ + T_1 p_d_1) : \ + d_0(p_d_0), \ + d_1(p_d_1) {} \ + virtual void exec(GodotNavigationServer *server) { \ + server->MERGE(_cmd_, F_NAME)(d_0, d_1); \ + } \ + }; \ + void GodotNavigationServer::F_NAME(T_0 D_0, T_1 D_1) const { \ + auto cmd = memnew(MERGE(F_NAME, _command)( \ + D_0, \ + D_1)); \ + add_command(cmd); \ + } \ + void GodotNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1) + +#define COMMAND_4(F_NAME, T_0, D_0, T_1, D_1, T_2, D_2, T_3, D_3) \ + struct MERGE(F_NAME, _command) : public SetCommand { \ + T_0 d_0; \ + T_1 d_1; \ + T_2 d_2; \ + T_3 d_3; \ + MERGE(F_NAME, _command) \ + ( \ + T_0 p_d_0, \ + T_1 p_d_1, \ + T_2 p_d_2, \ + T_3 p_d_3) : \ + d_0(p_d_0), \ + d_1(p_d_1), \ + d_2(p_d_2), \ + d_3(p_d_3) {} \ + virtual void exec(GodotNavigationServer *server) { \ + server->MERGE(_cmd_, F_NAME)(d_0, d_1, d_2, d_3); \ + } \ + }; \ + void GodotNavigationServer::F_NAME(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3) const { \ + auto cmd = memnew(MERGE(F_NAME, _command)( \ + D_0, \ + D_1, \ + D_2, \ + D_3)); \ + add_command(cmd); \ + } \ + void GodotNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3) + +GodotNavigationServer::GodotNavigationServer() : NavigationServer3D() { } -GdNavigationServer::~GdNavigationServer() { +GodotNavigationServer::~GodotNavigationServer() { flush_queries(); } -void GdNavigationServer::add_command(SetCommand *command) const { - GdNavigationServer *mut_this = const_cast<GdNavigationServer *>(this); +void GodotNavigationServer::add_command(SetCommand *command) const { + GodotNavigationServer *mut_this = const_cast<GodotNavigationServer *>(this); { MutexLock lock(commands_mutex); mut_this->commands.push_back(command); } } -RID GdNavigationServer::map_create() const { - GdNavigationServer *mut_this = const_cast<GdNavigationServer *>(this); +RID GodotNavigationServer::map_create() const { + GodotNavigationServer *mut_this = const_cast<GodotNavigationServer *>(this); MutexLock lock(mut_this->operations_mutex); - NavMap *space = memnew(NavMap); - RID rid = map_owner.make_rid(space); + RID rid = map_owner.make_rid(); + NavMap *space = map_owner.getornull(rid); space->set_self(rid); return rid; } @@ -155,7 +155,7 @@ COMMAND_2(map_set_active, RID, p_map, bool, p_active) { } } -bool GdNavigationServer::map_is_active(RID p_map) const { +bool GodotNavigationServer::map_is_active(RID p_map) const { NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, false); @@ -169,7 +169,7 @@ COMMAND_2(map_set_up, RID, p_map, Vector3, p_up) { map->set_up(p_up); } -Vector3 GdNavigationServer::map_get_up(RID p_map) const { +Vector3 GodotNavigationServer::map_get_up(RID p_map) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, Vector3()); @@ -183,7 +183,7 @@ COMMAND_2(map_set_cell_size, RID, p_map, real_t, p_cell_size) { map->set_cell_size(p_cell_size); } -real_t GdNavigationServer::map_get_cell_size(RID p_map) const { +real_t GodotNavigationServer::map_get_cell_size(RID p_map) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, 0); @@ -197,53 +197,53 @@ COMMAND_2(map_set_edge_connection_margin, RID, p_map, real_t, p_connection_margi map->set_edge_connection_margin(p_connection_margin); } -real_t GdNavigationServer::map_get_edge_connection_margin(RID p_map) const { +real_t GodotNavigationServer::map_get_edge_connection_margin(RID p_map) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, 0); return map->get_edge_connection_margin(); } -Vector<Vector3> GdNavigationServer::map_get_path(RID p_map, Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_layers) const { +Vector<Vector3> GodotNavigationServer::map_get_path(RID p_map, Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_layers) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, Vector<Vector3>()); return map->get_path(p_origin, p_destination, p_optimize, p_layers); } -Vector3 GdNavigationServer::map_get_closest_point_to_segment(RID p_map, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const { +Vector3 GodotNavigationServer::map_get_closest_point_to_segment(RID p_map, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, Vector3()); return map->get_closest_point_to_segment(p_from, p_to, p_use_collision); } -Vector3 GdNavigationServer::map_get_closest_point(RID p_map, const Vector3 &p_point) const { +Vector3 GodotNavigationServer::map_get_closest_point(RID p_map, const Vector3 &p_point) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, Vector3()); return map->get_closest_point(p_point); } -Vector3 GdNavigationServer::map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const { +Vector3 GodotNavigationServer::map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, Vector3()); return map->get_closest_point_normal(p_point); } -RID GdNavigationServer::map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const { +RID GodotNavigationServer::map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const { const NavMap *map = map_owner.getornull(p_map); ERR_FAIL_COND_V(map == nullptr, RID()); return map->get_closest_point_owner(p_point); } -RID GdNavigationServer::region_create() const { - GdNavigationServer *mut_this = const_cast<GdNavigationServer *>(this); +RID GodotNavigationServer::region_create() const { + GodotNavigationServer *mut_this = const_cast<GodotNavigationServer *>(this); MutexLock lock(mut_this->operations_mutex); - NavRegion *reg = memnew(NavRegion); - RID rid = region_owner.make_rid(reg); + RID rid = region_owner.make_rid(); + NavRegion *reg = region_owner.getornull(rid); reg->set_self(rid); return rid; } @@ -270,7 +270,7 @@ COMMAND_2(region_set_map, RID, p_region, RID, p_map) { } } -COMMAND_2(region_set_transform, RID, p_region, Transform, p_transform) { +COMMAND_2(region_set_transform, RID, p_region, Transform3D, p_transform) { NavRegion *region = region_owner.getornull(p_region); ERR_FAIL_COND(region == nullptr); @@ -284,7 +284,7 @@ COMMAND_2(region_set_layers, RID, p_region, uint32_t, p_layers) { region->set_layers(p_layers); } -uint32_t GdNavigationServer::region_get_layers(RID p_region) const { +uint32_t GodotNavigationServer::region_get_layers(RID p_region) const { NavRegion *region = region_owner.getornull(p_region); ERR_FAIL_COND_V(region == nullptr, 0); @@ -298,7 +298,7 @@ COMMAND_2(region_set_navmesh, RID, p_region, Ref<NavigationMesh>, p_nav_mesh) { region->set_mesh(p_nav_mesh); } -void GdNavigationServer::region_bake_navmesh(Ref<NavigationMesh> r_mesh, Node *p_node) const { +void GodotNavigationServer::region_bake_navmesh(Ref<NavigationMesh> r_mesh, Node *p_node) const { ERR_FAIL_COND(r_mesh.is_null()); ERR_FAIL_COND(p_node == nullptr); @@ -308,32 +308,32 @@ void GdNavigationServer::region_bake_navmesh(Ref<NavigationMesh> r_mesh, Node *p #endif } -int GdNavigationServer::region_get_connections_count(RID p_region) const { +int GodotNavigationServer::region_get_connections_count(RID p_region) const { NavRegion *region = region_owner.getornull(p_region); ERR_FAIL_COND_V(!region, 0); return region->get_connections_count(); } -Vector3 GdNavigationServer::region_get_connection_pathway_start(RID p_region, int p_connection_id) const { +Vector3 GodotNavigationServer::region_get_connection_pathway_start(RID p_region, int p_connection_id) const { NavRegion *region = region_owner.getornull(p_region); ERR_FAIL_COND_V(!region, Vector3()); return region->get_connection_pathway_start(p_connection_id); } -Vector3 GdNavigationServer::region_get_connection_pathway_end(RID p_region, int p_connection_id) const { +Vector3 GodotNavigationServer::region_get_connection_pathway_end(RID p_region, int p_connection_id) const { NavRegion *region = region_owner.getornull(p_region); ERR_FAIL_COND_V(!region, Vector3()); return region->get_connection_pathway_end(p_connection_id); } -RID GdNavigationServer::agent_create() const { - GdNavigationServer *mut_this = const_cast<GdNavigationServer *>(this); +RID GodotNavigationServer::agent_create() const { + GodotNavigationServer *mut_this = const_cast<GodotNavigationServer *>(this); MutexLock lock(mut_this->operations_mutex); - RvoAgent *agent = memnew(RvoAgent()); - RID rid = agent_owner.make_rid(agent); + RID rid = agent_owner.make_rid(); + RvoAgent *agent = agent_owner.getornull(rid); agent->set_self(rid); return rid; } @@ -428,7 +428,7 @@ COMMAND_2(agent_set_ignore_y, RID, p_agent, bool, p_ignore) { agent->get_agent()->ignore_y_ = p_ignore; } -bool GdNavigationServer::agent_is_map_changed(RID p_agent) const { +bool GodotNavigationServer::agent_is_map_changed(RID p_agent) const { RvoAgent *agent = agent_owner.getornull(p_agent); ERR_FAIL_COND_V(agent == nullptr, false); @@ -472,7 +472,6 @@ COMMAND_1(free, RID, p_object) { active_maps.remove(map_index); active_maps_update_id.remove(map_index); map_owner.free(p_object); - memdelete(map); } else if (region_owner.owns(p_object)) { NavRegion *region = region_owner.getornull(p_object); @@ -484,7 +483,6 @@ COMMAND_1(free, RID, p_object) { } region_owner.free(p_object); - memdelete(region); } else if (agent_owner.owns(p_object)) { RvoAgent *agent = agent_owner.getornull(p_object); @@ -496,20 +494,19 @@ COMMAND_1(free, RID, p_object) { } agent_owner.free(p_object); - memdelete(agent); } else { ERR_FAIL_COND("Invalid ID."); } } -void GdNavigationServer::set_active(bool p_active) const { - GdNavigationServer *mut_this = const_cast<GdNavigationServer *>(this); +void GodotNavigationServer::set_active(bool p_active) const { + GodotNavigationServer *mut_this = const_cast<GodotNavigationServer *>(this); MutexLock lock(mut_this->operations_mutex); mut_this->active = p_active; } -void GdNavigationServer::flush_queries() { +void GodotNavigationServer::flush_queries() { // In c++ we can't be sure that this is performed in the main thread // even with mutable functions. MutexLock lock(commands_mutex); @@ -521,7 +518,7 @@ void GdNavigationServer::flush_queries() { commands.clear(); } -void GdNavigationServer::process(real_t p_delta_time) { +void GodotNavigationServer::process(real_t p_delta_time) { flush_queries(); if (!active) { @@ -539,7 +536,7 @@ void GdNavigationServer::process(real_t p_delta_time) { // Emit a signal if a map changed. const uint32_t new_map_update_id = active_maps[i]->get_map_update_id(); if (new_map_update_id != active_maps_update_id[i]) { - emit_signal("map_changed", active_maps[i]->get_self()); + emit_signal(SNAME("map_changed"), active_maps[i]->get_self()); active_maps_update_id[i] = new_map_update_id; } } diff --git a/modules/gdnavigation/gd_navigation_server.h b/modules/navigation/godot_navigation_server.h index 2f51f6431e..65224493fd 100644 --- a/modules/gdnavigation/gd_navigation_server.h +++ b/modules/navigation/godot_navigation_server.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* gd_navigation_server.h */ +/* godot_navigation_server.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef GD_NAVIGATION_SERVER_H -#define GD_NAVIGATION_SERVER_H +#ifndef GODOT_NAVIGATION_SERVER_H +#define GODOT_NAVIGATION_SERVER_H #include "core/templates/local_vector.h" #include "core/templates/rid.h" @@ -61,31 +61,31 @@ virtual void F_NAME(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3 = D_3_DEF) const; \ void MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3) -class GdNavigationServer; +class GodotNavigationServer; struct SetCommand { virtual ~SetCommand() {} - virtual void exec(GdNavigationServer *server) = 0; + virtual void exec(GodotNavigationServer *server) = 0; }; -class GdNavigationServer : public NavigationServer3D { +class GodotNavigationServer : public NavigationServer3D { Mutex commands_mutex; /// Mutex used to make any operation threadsafe. Mutex operations_mutex; std::vector<SetCommand *> commands; - mutable RID_PtrOwner<NavMap> map_owner; - mutable RID_PtrOwner<NavRegion> region_owner; - mutable RID_PtrOwner<RvoAgent> agent_owner; + mutable RID_Owner<NavMap> map_owner; + mutable RID_Owner<NavRegion> region_owner; + mutable RID_Owner<RvoAgent> agent_owner; bool active = true; LocalVector<NavMap *> active_maps; LocalVector<uint32_t> active_maps_update_id; public: - GdNavigationServer(); - virtual ~GdNavigationServer(); + GodotNavigationServer(); + virtual ~GodotNavigationServer(); void add_command(SetCommand *command) const; @@ -113,7 +113,7 @@ public: COMMAND_2(region_set_map, RID, p_region, RID, p_map); COMMAND_2(region_set_layers, RID, p_region, uint32_t, p_layers); virtual uint32_t region_get_layers(RID p_region) const; - COMMAND_2(region_set_transform, RID, p_region, Transform, p_transform); + COMMAND_2(region_set_transform, RID, p_region, Transform3D, p_transform); COMMAND_2(region_set_navmesh, RID, p_region, Ref<NavigationMesh>, p_nav_mesh); virtual void region_bake_navmesh(Ref<NavigationMesh> r_mesh, Node *p_node) const; virtual int region_get_connections_count(RID p_region) const; @@ -146,4 +146,4 @@ public: #undef COMMAND_2 #undef COMMAND_4_DEF -#endif // GD_NAVIGATION_SERVER_H +#endif // GODOT_NAVIGATION_SERVER_H diff --git a/modules/gdnavigation/nav_map.cpp b/modules/navigation/nav_map.cpp index 2513c62b6a..3150ca0bc8 100644 --- a/modules/gdnavigation/nav_map.cpp +++ b/modules/navigation/nav_map.cpp @@ -112,7 +112,7 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p } } - // Check for trival cases + // Check for trivial cases if (!begin_poly || !end_poly) { return Vector<Vector3>(); } @@ -734,7 +734,7 @@ void NavMap::dispatch_callbacks() { void NavMap::clip_path(const std::vector<gd::NavigationPoly> &p_navigation_polys, Vector<Vector3> &path, const gd::NavigationPoly *from_poly, const Vector3 &p_to_point, const gd::NavigationPoly *p_to_poly) const { Vector3 from = path[path.size() - 1]; - if (from.distance_to(p_to_point) < CMP_EPSILON) { + if (from.is_equal_approx(p_to_point)) { return; } Plane cut_plane; @@ -752,10 +752,10 @@ void NavMap::clip_path(const std::vector<gd::NavigationPoly> &p_navigation_polys ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1); from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id]; - if (pathway_start.distance_to(pathway_end) > CMP_EPSILON) { + if (!pathway_start.is_equal_approx(pathway_end)) { Vector3 inters; if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) { - if (inters.distance_to(p_to_point) > CMP_EPSILON && inters.distance_to(path[path.size() - 1]) > CMP_EPSILON) { + if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(path[path.size() - 1])) { path.push_back(inters); } } diff --git a/modules/gdnavigation/nav_map.h b/modules/navigation/nav_map.h index 8e013a72eb..8e013a72eb 100644 --- a/modules/gdnavigation/nav_map.h +++ b/modules/navigation/nav_map.h diff --git a/modules/gdnavigation/nav_region.cpp b/modules/navigation/nav_region.cpp index c1690b2a4b..81b15a49f5 100644 --- a/modules/gdnavigation/nav_region.cpp +++ b/modules/navigation/nav_region.cpp @@ -52,7 +52,7 @@ uint32_t NavRegion::get_layers() const { return layers; } -void NavRegion::set_transform(Transform p_transform) { +void NavRegion::set_transform(Transform3D p_transform) { transform = p_transform; polygons_dirty = true; } diff --git a/modules/gdnavigation/nav_region.h b/modules/navigation/nav_region.h index 527b2500ac..f8b067e638 100644 --- a/modules/gdnavigation/nav_region.h +++ b/modules/navigation/nav_region.h @@ -46,7 +46,7 @@ class NavRegion; class NavRegion : public NavRid { NavMap *map = nullptr; - Transform transform; + Transform3D transform; Ref<NavigationMesh> mesh; uint32_t layers = 1; Vector<gd::Edge::Connection> connections; @@ -71,8 +71,8 @@ public: void set_layers(uint32_t p_layers); uint32_t get_layers() const; - void set_transform(Transform transform); - const Transform &get_transform() const { + void set_transform(Transform3D transform); + const Transform3D &get_transform() const { return transform; } diff --git a/modules/gdnavigation/nav_rid.h b/modules/navigation/nav_rid.h index a0a60a3643..a0a60a3643 100644 --- a/modules/gdnavigation/nav_rid.h +++ b/modules/navigation/nav_rid.h diff --git a/modules/gdnavigation/nav_utils.h b/modules/navigation/nav_utils.h index 35da391eea..35da391eea 100644 --- a/modules/gdnavigation/nav_utils.h +++ b/modules/navigation/nav_utils.h diff --git a/modules/gdnavigation/navigation_mesh_editor_plugin.cpp b/modules/navigation/navigation_mesh_editor_plugin.cpp index aa9248d2a1..587e56f593 100644 --- a/modules/gdnavigation/navigation_mesh_editor_plugin.cpp +++ b/modules/navigation/navigation_mesh_editor_plugin.cpp @@ -47,8 +47,8 @@ void NavigationMeshEditor::_node_removed(Node *p_node) { void NavigationMeshEditor::_notification(int p_option) { if (p_option == NOTIFICATION_ENTER_TREE) { - button_bake->set_icon(get_theme_icon("Bake", "EditorIcons")); - button_reset->set_icon(get_theme_icon("Reload", "EditorIcons")); + button_bake->set_icon(get_theme_icon(SNAME("Bake"), SNAME("EditorIcons"))); + button_reset->set_icon(get_theme_icon(SNAME("Reload"), SNAME("EditorIcons"))); } } @@ -65,7 +65,7 @@ void NavigationMeshEditor::_bake_pressed() { NavigationMeshGenerator::get_singleton()->clear(node->get_navigation_mesh()); NavigationMeshGenerator::get_singleton()->bake(node->get_navigation_mesh(), node); - node->update_gizmo(); + node->update_gizmos(); } void NavigationMeshEditor::_clear_pressed() { @@ -77,7 +77,7 @@ void NavigationMeshEditor::_clear_pressed() { bake_info->set_text(""); if (node) { - node->update_gizmo(); + node->update_gizmos(); } } diff --git a/modules/gdnavigation/navigation_mesh_editor_plugin.h b/modules/navigation/navigation_mesh_editor_plugin.h index c39269865b..c39269865b 100644 --- a/modules/gdnavigation/navigation_mesh_editor_plugin.h +++ b/modules/navigation/navigation_mesh_editor_plugin.h diff --git a/modules/gdnavigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp index a7d4e79148..74da939e6f 100644 --- a/modules/gdnavigation/navigation_mesh_generator.cpp +++ b/modules/navigation/navigation_mesh_generator.cpp @@ -32,7 +32,7 @@ #include "navigation_mesh_generator.h" -#include "core/math/quick_hull.h" +#include "core/math/convex_hull.h" #include "core/os/thread.h" #include "scene/3d/collision_shape_3d.h" #include "scene/3d/mesh_instance_3d.h" @@ -47,12 +47,12 @@ #include "scene/resources/sphere_shape_3d.h" #include "scene/resources/world_margin_shape_3d.h" -#include "modules/modules_enabled.gen.h" #ifdef TOOLS_ENABLED #include "editor/editor_node.h" #include "editor/editor_settings.h" #endif +#include "modules/modules_enabled.gen.h" #ifdef MODULE_CSG_ENABLED #include "modules/csg/csg_shape.h" #endif @@ -68,7 +68,7 @@ void NavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> & p_verticies.push_back(p_vec3.z); } -void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) { +void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform3D &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) { int current_vertex_count; for (int i = 0; i < p_mesh->get_surface_count(); i++) { @@ -123,7 +123,7 @@ void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform } } -void NavigationMeshGenerator::_add_faces(const PackedVector3Array &p_faces, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) { +void NavigationMeshGenerator::_add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices) { int face_count = p_faces.size() / 3; int current_vertex_count = p_verticies.size() / 3; @@ -138,7 +138,7 @@ void NavigationMeshGenerator::_add_faces(const PackedVector3Array &p_faces, cons } } -void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices, int p_generate_from, uint32_t p_collision_mask, bool p_recurse_children) { +void NavigationMeshGenerator::_parse_geometry(Transform3D p_accumulated_transform, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices, NavigationMesh::ParsedGeometryType p_generate_from, uint32_t p_collision_mask, bool p_recurse_children) { if (Object::cast_to<MeshInstance3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) { MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(p_node); Ref<Mesh> mesh = mesh_instance->get_mesh(); @@ -169,7 +169,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, if (Object::cast_to<CollisionShape3D>(child)) { CollisionShape3D *col_shape = Object::cast_to<CollisionShape3D>(child); - Transform transform = p_accumulated_transform * static_body->get_transform() * col_shape->get_transform(); + Transform3D transform = p_accumulated_transform * static_body->get_transform() * col_shape->get_transform(); Ref<Mesh> mesh; Ref<Shape3D> s = col_shape->get_shape(); @@ -177,7 +177,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, BoxShape3D *box = Object::cast_to<BoxShape3D>(*s); if (box) { Ref<BoxMesh> box_mesh; - box_mesh.instance(); + box_mesh.instantiate(); box_mesh->set_size(box->get_size()); mesh = box_mesh; } @@ -185,7 +185,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, CapsuleShape3D *capsule = Object::cast_to<CapsuleShape3D>(*s); if (capsule) { Ref<CapsuleMesh> capsule_mesh; - capsule_mesh.instance(); + capsule_mesh.instantiate(); capsule_mesh->set_radius(capsule->get_radius()); capsule_mesh->set_mid_height(capsule->get_height() / 2.0); mesh = capsule_mesh; @@ -194,7 +194,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, CylinderShape3D *cylinder = Object::cast_to<CylinderShape3D>(*s); if (cylinder) { Ref<CylinderMesh> cylinder_mesh; - cylinder_mesh.instance(); + cylinder_mesh.instantiate(); cylinder_mesh->set_height(cylinder->get_height()); cylinder_mesh->set_bottom_radius(cylinder->get_radius()); cylinder_mesh->set_top_radius(cylinder->get_radius()); @@ -204,7 +204,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, SphereShape3D *sphere = Object::cast_to<SphereShape3D>(*s); if (sphere) { Ref<SphereMesh> sphere_mesh; - sphere_mesh.instance(); + sphere_mesh.instantiate(); sphere_mesh->set_radius(sphere->get_radius()); sphere_mesh->set_height(sphere->get_radius() * 2.0); mesh = sphere_mesh; @@ -220,7 +220,7 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, Vector<Vector3> varr = Variant(convex_polygon->get_points()); Geometry3D::MeshData md; - Error err = QuickHull::build(varr, md); + Error err = ConvexHullComputer::convex_hull(varr, md); if (err == OK) { PackedVector3Array faces; @@ -251,11 +251,11 @@ void NavigationMeshGenerator::_parse_geometry(Transform p_accumulated_transform, if (Object::cast_to<GridMap>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) { GridMap *gridmap_instance = Object::cast_to<GridMap>(p_node); Array meshes = gridmap_instance->get_meshes(); - Transform xform = gridmap_instance->get_transform(); + Transform3D xform = gridmap_instance->get_transform(); for (int i = 0; i < meshes.size(); i += 2) { Ref<Mesh> mesh = meshes[i + 1]; if (mesh.is_valid()) { - _add_mesh(mesh, p_accumulated_transform * xform * meshes[i], p_verticies, p_indices); + _add_mesh(mesh, p_accumulated_transform * xform * (Transform3D)meshes[i], p_verticies, p_indices); } } } @@ -513,12 +513,12 @@ void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) p_node->get_tree()->get_nodes_in_group(p_nav_mesh->get_source_group_name(), &parse_nodes); } - Transform navmesh_xform = Object::cast_to<Node3D>(p_node)->get_transform().affine_inverse(); - for (const List<Node *>::Element *E = parse_nodes.front(); E; E = E->next()) { - int geometry_type = p_nav_mesh->get_parsed_geometry_type(); + Transform3D navmesh_xform = Object::cast_to<Node3D>(p_node)->get_transform().affine_inverse(); + for (Node *E : parse_nodes) { + NavigationMesh::ParsedGeometryType geometry_type = p_nav_mesh->get_parsed_geometry_type(); uint32_t collision_mask = p_nav_mesh->get_collision_mask(); bool recurse_children = p_nav_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT; - _parse_geometry(navmesh_xform, E->get(), vertices, indices, geometry_type, collision_mask, recurse_children); + _parse_geometry(navmesh_xform, E, vertices, indices, geometry_type, collision_mask, recurse_children); } if (vertices.size() > 0 && indices.size() > 0) { diff --git a/modules/gdnavigation/navigation_mesh_generator.h b/modules/navigation/navigation_mesh_generator.h index 88ccdb1c41..78f1329e3f 100644 --- a/modules/gdnavigation/navigation_mesh_generator.h +++ b/modules/navigation/navigation_mesh_generator.h @@ -50,9 +50,9 @@ protected: static void _bind_methods(); static void _add_vertex(const Vector3 &p_vec3, Vector<float> &p_verticies); - static void _add_mesh(const Ref<Mesh> &p_mesh, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices); - static void _add_faces(const PackedVector3Array &p_faces, const Transform &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices); - static void _parse_geometry(Transform p_accumulated_transform, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices, int p_generate_from, uint32_t p_collision_mask, bool p_recurse_children); + static void _add_mesh(const Ref<Mesh> &p_mesh, const Transform3D &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices); + static void _add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform, Vector<float> &p_verticies, Vector<int> &p_indices); + static void _parse_geometry(Transform3D p_accumulated_transform, Node *p_node, Vector<float> &p_verticies, Vector<int> &p_indices, NavigationMesh::ParsedGeometryType p_generate_from, uint32_t p_collision_mask, bool p_recurse_children); static void _convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh); static void _build_recast_navigation_mesh( diff --git a/modules/gdnavigation/register_types.cpp b/modules/navigation/register_types.cpp index 8443d3d242..97c01d42ab 100644 --- a/modules/gdnavigation/register_types.cpp +++ b/modules/navigation/register_types.cpp @@ -31,9 +31,10 @@ #include "register_types.h" #include "core/config/engine.h" -#include "gd_navigation_server.h" #include "servers/navigation_server_3d.h" +#include "godot_navigation_server.h" + #ifndef _3D_DISABLED #include "navigation_mesh_generator.h" #endif @@ -42,38 +43,29 @@ #include "navigation_mesh_editor_plugin.h" #endif -/** - @author AndreaCatania -*/ - #ifndef _3D_DISABLED NavigationMeshGenerator *_nav_mesh_generator = nullptr; #endif NavigationServer3D *new_server() { - return memnew(GdNavigationServer); + return memnew(GodotNavigationServer); } -void register_gdnavigation_types() { +void register_navigation_types() { NavigationServer3DManager::set_default_server(new_server); #ifndef _3D_DISABLED _nav_mesh_generator = memnew(NavigationMeshGenerator); - ClassDB::register_class<NavigationMeshGenerator>(); + GDREGISTER_CLASS(NavigationMeshGenerator); Engine::get_singleton()->add_singleton(Engine::Singleton("NavigationMeshGenerator", NavigationMeshGenerator::get_singleton())); #endif #ifdef TOOLS_ENABLED EditorPlugins::add_by_type<NavigationMeshEditorPlugin>(); - - ClassDB::APIType prev_api = ClassDB::get_current_api(); - ClassDB::set_current_api(ClassDB::API_EDITOR); - - ClassDB::set_current_api(prev_api); #endif } -void unregister_gdnavigation_types() { +void unregister_navigation_types() { #ifndef _3D_DISABLED if (_nav_mesh_generator) { memdelete(_nav_mesh_generator); diff --git a/modules/gdnavigation/register_types.h b/modules/navigation/register_types.h index c2bb08c649..4737c818eb 100644 --- a/modules/gdnavigation/register_types.h +++ b/modules/navigation/register_types.h @@ -28,14 +28,10 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -/** - @author AndreaCatania -*/ +#ifndef NAVIGATION_REGISTER_TYPES_H +#define NAVIGATION_REGISTER_TYPES_H -#ifndef GDNAVIGATION_REGISTER_TYPES_H -#define GDNAVIGATION_REGISTER_TYPES_H +void register_navigation_types(); +void unregister_navigation_types(); -void register_gdnavigation_types(); -void unregister_gdnavigation_types(); - -#endif // GDNAVIGATION_REGISTER_TYPES_H +#endif // NAVIGATION_REGISTER_TYPES_H diff --git a/modules/gdnavigation/rvo_agent.cpp b/modules/navigation/rvo_agent.cpp index 21e43d08c1..21e43d08c1 100644 --- a/modules/gdnavigation/rvo_agent.cpp +++ b/modules/navigation/rvo_agent.cpp diff --git a/modules/gdnavigation/rvo_agent.h b/modules/navigation/rvo_agent.h index 369cb1f9a3..369cb1f9a3 100644 --- a/modules/gdnavigation/rvo_agent.h +++ b/modules/navigation/rvo_agent.h diff --git a/modules/opensimplex/doc_classes/NoiseTexture.xml b/modules/opensimplex/doc_classes/NoiseTexture.xml index 38c5138482..2ae7f8cad9 100644 --- a/modules/opensimplex/doc_classes/NoiseTexture.xml +++ b/modules/opensimplex/doc_classes/NoiseTexture.xml @@ -31,6 +31,9 @@ <member name="noise" type="OpenSimplexNoise" setter="set_noise" getter="get_noise"> The [OpenSimplexNoise] instance used to generate the noise. </member> + <member name="noise_offset" type="Vector2" setter="set_noise_offset" getter="get_noise_offset" default="Vector2(0, 0)"> + An offset used to specify the noise space coordinate of the top left corner of the generated noise. This value is ignored if [member seamless] is enabled. + </member> <member name="seamless" type="bool" setter="set_seamless" getter="get_seamless" default="false"> Whether the texture can be tiled without visible seams or not. Seamless textures take longer to generate. [b]Note:[/b] Seamless noise has a lower contrast compared to non-seamless noise. This is due to the way noise uses higher dimensions for generating seamless noise. diff --git a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml index ad82f87213..c470f3e1ab 100644 --- a/modules/opensimplex/doc_classes/OpenSimplexNoise.xml +++ b/modules/opensimplex/doc_classes/OpenSimplexNoise.xml @@ -25,88 +25,66 @@ </tutorials> <methods> <method name="get_image" qualifiers="const"> - <return type="Image"> - </return> - <argument index="0" name="width" type="int"> - </argument> - <argument index="1" name="height" type="int"> - </argument> + <return type="Image" /> + <argument index="0" name="width" type="int" /> + <argument index="1" name="height" type="int" /> + <argument index="2" name="noise_offset" type="Vector2" default="Vector2(0, 0)" /> <description> - Generate a noise image in [constant Image.FORMAT_L8] format with the requested [code]width[/code] and [code]height[/code], based on the current noise parameters. + Generate a noise image in [constant Image.FORMAT_L8] format with the requested [code]width[/code] and [code]height[/code], based on the current noise parameters. If [code]noise_offset[/code] is specified, then the offset value is used as the coordinates of the top-left corner of the generated noise. </description> </method> <method name="get_noise_1d" qualifiers="const"> - <return type="float"> - </return> - <argument index="0" name="x" type="float"> - </argument> + <return type="float" /> + <argument index="0" name="x" type="float" /> <description> Returns the 1D noise value [code][-1,1][/code] at the given x-coordinate. [b]Note:[/b] This method actually returns the 2D noise value [code][-1,1][/code] with fixed y-coordinate value 0.0. </description> </method> <method name="get_noise_2d" qualifiers="const"> - <return type="float"> - </return> - <argument index="0" name="x" type="float"> - </argument> - <argument index="1" name="y" type="float"> - </argument> + <return type="float" /> + <argument index="0" name="x" type="float" /> + <argument index="1" name="y" type="float" /> <description> Returns the 2D noise value [code][-1,1][/code] at the given position. </description> </method> <method name="get_noise_2dv" qualifiers="const"> - <return type="float"> - </return> - <argument index="0" name="pos" type="Vector2"> - </argument> + <return type="float" /> + <argument index="0" name="pos" type="Vector2" /> <description> Returns the 2D noise value [code][-1,1][/code] at the given position. </description> </method> <method name="get_noise_3d" qualifiers="const"> - <return type="float"> - </return> - <argument index="0" name="x" type="float"> - </argument> - <argument index="1" name="y" type="float"> - </argument> - <argument index="2" name="z" type="float"> - </argument> + <return type="float" /> + <argument index="0" name="x" type="float" /> + <argument index="1" name="y" type="float" /> + <argument index="2" name="z" type="float" /> <description> Returns the 3D noise value [code][-1,1][/code] at the given position. </description> </method> <method name="get_noise_3dv" qualifiers="const"> - <return type="float"> - </return> - <argument index="0" name="pos" type="Vector3"> - </argument> + <return type="float" /> + <argument index="0" name="pos" type="Vector3" /> <description> Returns the 3D noise value [code][-1,1][/code] at the given position. </description> </method> <method name="get_noise_4d" qualifiers="const"> - <return type="float"> - </return> - <argument index="0" name="x" type="float"> - </argument> - <argument index="1" name="y" type="float"> - </argument> - <argument index="2" name="z" type="float"> - </argument> - <argument index="3" name="w" type="float"> - </argument> + <return type="float" /> + <argument index="0" name="x" type="float" /> + <argument index="1" name="y" type="float" /> + <argument index="2" name="z" type="float" /> + <argument index="3" name="w" type="float" /> <description> Returns the 4D noise value [code][-1,1][/code] at the given position. </description> </method> <method name="get_seamless_image" qualifiers="const"> - <return type="Image"> - </return> - <argument index="0" name="size" type="int"> - </argument> + <return type="Image" /> + <argument index="0" name="size" type="int" /> <description> Generate a tileable noise image in [constant Image.FORMAT_L8] format, based on the current noise parameters. Generated seamless images are always square ([code]size[/code] × [code]size[/code]). [b]Note:[/b] Seamless noise has a lower contrast compared to non-seamless noise. This is due to the way noise uses higher dimensions for generating seamless noise. diff --git a/modules/opensimplex/noise_texture.cpp b/modules/opensimplex/noise_texture.cpp index 7272d32fac..9db3f3d5fd 100644 --- a/modules/opensimplex/noise_texture.cpp +++ b/modules/opensimplex/noise_texture.cpp @@ -52,6 +52,9 @@ void NoiseTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_noise", "noise"), &NoiseTexture::set_noise); ClassDB::bind_method(D_METHOD("get_noise"), &NoiseTexture::get_noise); + ClassDB::bind_method(D_METHOD("set_noise_offset", "noise_offset"), &NoiseTexture::set_noise_offset); + ClassDB::bind_method(D_METHOD("get_noise_offset"), &NoiseTexture::get_noise_offset); + ClassDB::bind_method(D_METHOD("set_seamless", "seamless"), &NoiseTexture::set_seamless); ClassDB::bind_method(D_METHOD("get_seamless"), &NoiseTexture::get_seamless); @@ -71,6 +74,7 @@ void NoiseTexture::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::BOOL, "as_normal_map"), "set_as_normal_map", "is_normal_map"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bump_strength", PROPERTY_HINT_RANGE, "0,32,0.1,or_greater"), "set_bump_strength", "get_bump_strength"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "noise", PROPERTY_HINT_RESOURCE_TYPE, "OpenSimplexNoise"), "set_noise", "get_noise"); + ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "noise_offset"), "set_noise_offset", "get_noise_offset"); } void NoiseTexture::_validate_property(PropertyInfo &property) const { @@ -105,7 +109,7 @@ void NoiseTexture::_thread_done(const Ref<Image> &p_image) { void NoiseTexture::_thread_function(void *p_ud) { NoiseTexture *tex = (NoiseTexture *)p_ud; - tex->call_deferred("_thread_done", tex->_generate_texture()); + tex->call_deferred(SNAME("_thread_done"), tex->_generate_texture()); } void NoiseTexture::_queue_update() { @@ -114,7 +118,7 @@ void NoiseTexture::_queue_update() { } update_queued = true; - call_deferred("_update_texture"); + call_deferred(SNAME("_update_texture")); } Ref<Image> NoiseTexture::_generate_texture() { @@ -130,7 +134,7 @@ Ref<Image> NoiseTexture::_generate_texture() { if (seamless) { image = ref_noise->get_seamless_image(size.x); } else { - image = ref_noise->get_image(size.x, size.y); + image = ref_noise->get_image(size.x, size.y, noise_offset); } if (as_normal_map) { @@ -183,6 +187,7 @@ Ref<OpenSimplexNoise> NoiseTexture::get_noise() { } void NoiseTexture::set_width(int p_width) { + ERR_FAIL_COND(p_width <= 0); if (p_width == size.x) { return; } @@ -191,6 +196,7 @@ void NoiseTexture::set_width(int p_width) { } void NoiseTexture::set_height(int p_height) { + ERR_FAIL_COND(p_height <= 0); if (p_height == size.y) { return; } @@ -198,6 +204,14 @@ void NoiseTexture::set_height(int p_height) { _queue_update(); } +void NoiseTexture::set_noise_offset(Vector2 p_noise_offset) { + if (noise_offset == p_noise_offset) { + return; + } + noise_offset = p_noise_offset; + _queue_update(); +} + void NoiseTexture::set_seamless(bool p_seamless) { if (p_seamless == seamless) { return; @@ -245,6 +259,10 @@ int NoiseTexture::get_height() const { return size.y; } +Vector2 NoiseTexture::get_noise_offset() const { + return noise_offset; +} + RID NoiseTexture::get_rid() const { if (!texture.is_valid()) { texture = RS::get_singleton()->texture_2d_placeholder_create(); diff --git a/modules/opensimplex/noise_texture.h b/modules/opensimplex/noise_texture.h index 6983ae18fe..6237b6460d 100644 --- a/modules/opensimplex/noise_texture.h +++ b/modules/opensimplex/noise_texture.h @@ -34,7 +34,7 @@ #include "open_simplex_noise.h" #include "core/io/image.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "editor/editor_node.h" #include "editor/editor_plugin.h" #include "editor/property_editor.h" @@ -56,6 +56,7 @@ private: Ref<OpenSimplexNoise> noise; Vector2i size = Vector2i(512, 512); + Vector2 noise_offset; bool seamless = false; bool as_normal_map = false; float bump_strength = 8.0; @@ -79,6 +80,9 @@ public: void set_width(int p_width); void set_height(int p_height); + void set_noise_offset(Vector2 p_noise_offset); + Vector2 get_noise_offset() const; + void set_seamless(bool p_seamless); bool get_seamless(); diff --git a/modules/opensimplex/open_simplex_noise.cpp b/modules/opensimplex/open_simplex_noise.cpp index 3773946112..f0a8867284 100644 --- a/modules/opensimplex/open_simplex_noise.cpp +++ b/modules/opensimplex/open_simplex_noise.cpp @@ -96,7 +96,7 @@ void OpenSimplexNoise::set_lacunarity(float p_lacunarity) { emit_changed(); } -Ref<Image> OpenSimplexNoise::get_image(int p_width, int p_height) const { +Ref<Image> OpenSimplexNoise::get_image(int p_width, int p_height, const Vector2 &p_noise_offset) const { Vector<uint8_t> data; data.resize(p_width * p_height); @@ -104,7 +104,7 @@ Ref<Image> OpenSimplexNoise::get_image(int p_width, int p_height) const { for (int i = 0; i < p_height; i++) { for (int j = 0; j < p_width; j++) { - float v = get_noise_2d(j, i); + float v = get_noise_2d(float(j) + p_noise_offset.x, float(i) + p_noise_offset.y); v = v * 0.5 + 0.5; // Normalize [0..1] wd8[(i * p_width + j)] = uint8_t(CLAMP(v * 255.0, 0, 255)); } @@ -161,7 +161,7 @@ void OpenSimplexNoise::_bind_methods() { ClassDB::bind_method(D_METHOD("set_lacunarity", "lacunarity"), &OpenSimplexNoise::set_lacunarity); ClassDB::bind_method(D_METHOD("get_lacunarity"), &OpenSimplexNoise::get_lacunarity); - ClassDB::bind_method(D_METHOD("get_image", "width", "height"), &OpenSimplexNoise::get_image); + ClassDB::bind_method(D_METHOD("get_image", "width", "height", "noise_offset"), &OpenSimplexNoise::get_image, DEFVAL(Vector2())); ClassDB::bind_method(D_METHOD("get_seamless_image", "size"), &OpenSimplexNoise::get_seamless_image); ClassDB::bind_method(D_METHOD("get_noise_1d", "x"), &OpenSimplexNoise::get_noise_1d); diff --git a/modules/opensimplex/open_simplex_noise.h b/modules/opensimplex/open_simplex_noise.h index 847c157409..dcf922a8bf 100644 --- a/modules/opensimplex/open_simplex_noise.h +++ b/modules/opensimplex/open_simplex_noise.h @@ -32,7 +32,7 @@ #define OPEN_SIMPLEX_NOISE_H #include "core/io/image.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "scene/resources/texture.h" #include "thirdparty/misc/open-simplex-noise.h" @@ -75,7 +75,7 @@ public: void set_lacunarity(float p_lacunarity); float get_lacunarity() const { return lacunarity; } - Ref<Image> get_image(int p_width, int p_height) const; + Ref<Image> get_image(int p_width, int p_height, const Vector2 &p_noise_offset = Vector2()) const; Ref<Image> get_seamless_image(int p_size) const; float get_noise_1d(float x) const; diff --git a/modules/opensimplex/register_types.cpp b/modules/opensimplex/register_types.cpp index e9735a2cc8..d6f9f3436d 100644 --- a/modules/opensimplex/register_types.cpp +++ b/modules/opensimplex/register_types.cpp @@ -33,8 +33,8 @@ #include "open_simplex_noise.h" void register_opensimplex_types() { - ClassDB::register_class<OpenSimplexNoise>(); - ClassDB::register_class<NoiseTexture>(); + GDREGISTER_CLASS(OpenSimplexNoise); + GDREGISTER_CLASS(NoiseTexture); } void unregister_opensimplex_types() { diff --git a/modules/pvr/image_compress_pvrtc.cpp b/modules/pvr/image_compress_pvrtc.cpp index d2d8976694..980cac17d3 100644 --- a/modules/pvr/image_compress_pvrtc.cpp +++ b/modules/pvr/image_compress_pvrtc.cpp @@ -31,7 +31,7 @@ #include "image_compress_pvrtc.h" #include "core/io/image.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include <PvrTcEncoder.h> #include <RgbaBitmap.h> @@ -43,6 +43,10 @@ static void _compress_pvrtc1_4bpp(Image *p_img) { if (!img->is_size_po2() || img->get_width() != img->get_height()) { make_mipmaps = img->has_mipmaps(); img->resize_to_po2(true); + // Resizing can fail for some formats + if (!img->is_size_po2() || img->get_width() != img->get_height()) { + ERR_FAIL_MSG("Failed to resize the image for compression."); + } } img->convert(Image::FORMAT_RGBA8); if (!img->has_mipmaps() && make_mipmaps) { @@ -52,7 +56,7 @@ static void _compress_pvrtc1_4bpp(Image *p_img) { bool use_alpha = img->detect_alpha(); Ref<Image> new_img; - new_img.instance(); + new_img.instantiate(); new_img->create(img->get_width(), img->get_height(), img->has_mipmaps(), use_alpha ? Image::FORMAT_PVRTC1_4A : Image::FORMAT_PVRTC1_4); Vector<uint8_t> data = new_img->get_data(); @@ -65,7 +69,7 @@ static void _compress_pvrtc1_4bpp(Image *p_img) { img->get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h); Javelin::RgbaBitmap bm(w, h); void *dst = (void *)bm.GetData(); - copymem(dst, &r[ofs], size); + memcpy(dst, &r[ofs], size); Javelin::ColorRgba<unsigned char> *dp = bm.GetData(); for (int j = 0; j < size / 4; j++) { // Red and blue colors are swapped. diff --git a/modules/pvr/register_types.cpp b/modules/pvr/register_types.cpp index aeac564c93..ef72087d25 100644 --- a/modules/pvr/register_types.cpp +++ b/modules/pvr/register_types.cpp @@ -36,7 +36,7 @@ static Ref<ResourceFormatPVR> resource_loader_pvr; void register_pvr_types() { - resource_loader_pvr.instance(); + resource_loader_pvr.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_pvr); _register_pvrtc_compress_func(); diff --git a/modules/pvr/texture_loader_pvr.cpp b/modules/pvr/texture_loader_pvr.cpp index 83f032ca2b..cb12976090 100644 --- a/modules/pvr/texture_loader_pvr.cpp +++ b/modules/pvr/texture_loader_pvr.cpp @@ -30,7 +30,7 @@ #include "texture_loader_pvr.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" static void _pvrtc_decompress(Image *p_img); diff --git a/modules/raycast/SCsub b/modules/raycast/SCsub index 68e9df5263..6e7b3e7b8d 100644 --- a/modules/raycast/SCsub +++ b/modules/raycast/SCsub @@ -3,84 +3,95 @@ Import("env") Import("env_modules") -embree_src = [ - "common/sys/sysinfo.cpp", - "common/sys/alloc.cpp", - "common/sys/filename.cpp", - "common/sys/library.cpp", - "common/sys/thread.cpp", - "common/sys/string.cpp", - "common/sys/regression.cpp", - "common/sys/mutex.cpp", - "common/sys/condition.cpp", - "common/sys/barrier.cpp", - "common/math/constants.cpp", - "common/simd/sse.cpp", - "common/lexers/stringstream.cpp", - "common/lexers/tokenstream.cpp", - "common/tasking/taskschedulerinternal.cpp", - "common/algorithms/parallel_for.cpp", - "common/algorithms/parallel_reduce.cpp", - "common/algorithms/parallel_prefix_sum.cpp", - "common/algorithms/parallel_for_for.cpp", - "common/algorithms/parallel_for_for_prefix_sum.cpp", - "common/algorithms/parallel_partition.cpp", - "common/algorithms/parallel_sort.cpp", - "common/algorithms/parallel_set.cpp", - "common/algorithms/parallel_map.cpp", - "common/algorithms/parallel_filter.cpp", - "kernels/common/device.cpp", - "kernels/common/stat.cpp", - "kernels/common/acceln.cpp", - "kernels/common/accelset.cpp", - "kernels/common/state.cpp", - "kernels/common/rtcore.cpp", - "kernels/common/rtcore_builder.cpp", - "kernels/common/scene.cpp", - "kernels/common/alloc.cpp", - "kernels/common/geometry.cpp", - "kernels/common/scene_triangle_mesh.cpp", - "kernels/geometry/primitive4.cpp", - "kernels/builders/primrefgen.cpp", - "kernels/bvh/bvh.cpp", - "kernels/bvh/bvh_statistics.cpp", - "kernels/bvh/bvh4_factory.cpp", - "kernels/bvh/bvh8_factory.cpp", - "kernels/bvh/bvh_collider.cpp", - "kernels/bvh/bvh_rotate.cpp", - "kernels/bvh/bvh_refit.cpp", - "kernels/bvh/bvh_builder.cpp", - "kernels/bvh/bvh_builder_morton.cpp", - "kernels/bvh/bvh_builder_sah.cpp", - "kernels/bvh/bvh_builder_sah_spatial.cpp", - "kernels/bvh/bvh_builder_sah_mb.cpp", - "kernels/bvh/bvh_builder_twolevel.cpp", - "kernels/bvh/bvh_intersector1_bvh4.cpp", -] - -embree_dir = "#thirdparty/embree-aarch64/" - -env_embree = env_modules.Clone() -embree_sources = [embree_dir + file for file in embree_src] -env_embree.Prepend(CPPPATH=[embree_dir, embree_dir + "include"]) -env_embree.Append(CPPFLAGS=["-DEMBREE_TARGET_SSE2", "-DEMBREE_LOWEST_ISA", "-DTASKING_INTERNAL", "-DNDEBUG"]) - -if not env_embree.msvc: - env_embree.Append(CPPFLAGS=["-msse2", "-mxsave"]) +env_raycast = env_modules.Clone() + +# Thirdparty source files + +thirdparty_obj = [] + +if env["builtin_embree"]: + thirdparty_dir = "#thirdparty/embree/" + + embree_src = [ + "common/sys/sysinfo.cpp", + "common/sys/alloc.cpp", + "common/sys/filename.cpp", + "common/sys/library.cpp", + "common/sys/thread.cpp", + "common/sys/string.cpp", + "common/sys/regression.cpp", + "common/sys/mutex.cpp", + "common/sys/condition.cpp", + "common/sys/barrier.cpp", + "common/math/constants.cpp", + "common/simd/sse.cpp", + "common/lexers/stringstream.cpp", + "common/lexers/tokenstream.cpp", + "common/tasking/taskschedulerinternal.cpp", + "kernels/common/device.cpp", + "kernels/common/stat.cpp", + "kernels/common/acceln.cpp", + "kernels/common/accelset.cpp", + "kernels/common/state.cpp", + "kernels/common/rtcore.cpp", + "kernels/common/rtcore_builder.cpp", + "kernels/common/scene.cpp", + "kernels/common/alloc.cpp", + "kernels/common/geometry.cpp", + "kernels/common/scene_triangle_mesh.cpp", + "kernels/geometry/primitive4.cpp", + "kernels/builders/primrefgen.cpp", + "kernels/bvh/bvh.cpp", + "kernels/bvh/bvh_statistics.cpp", + "kernels/bvh/bvh4_factory.cpp", + "kernels/bvh/bvh8_factory.cpp", + "kernels/bvh/bvh_collider.cpp", + "kernels/bvh/bvh_rotate.cpp", + "kernels/bvh/bvh_refit.cpp", + "kernels/bvh/bvh_builder.cpp", + "kernels/bvh/bvh_builder_morton.cpp", + "kernels/bvh/bvh_builder_sah.cpp", + "kernels/bvh/bvh_builder_sah_spatial.cpp", + "kernels/bvh/bvh_builder_sah_mb.cpp", + "kernels/bvh/bvh_builder_twolevel.cpp", + "kernels/bvh/bvh_intersector1_bvh4.cpp", + ] + + 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"]) + + if not env.msvc: + if env["arch"] in ["x86", "x86_64"]: + env_raycast.Append(CPPFLAGS=["-msse2", "-mxsave"]) + + if env["platform"] == "windows": + env_raycast.Append(CPPFLAGS=["-mstackrealign"]) + if env["platform"] == "windows": - env_embree.Append(CPPFLAGS=["-mstackrealign"]) + if env.msvc: + env.Append(LINKFLAGS=["psapi.lib"]) + else: + env.Append(LIBS=["psapi"]) -if env["platform"] == "windows": - if env.msvc: - env.Append(LINKFLAGS=["psapi.lib"]) - env_embree.Append(CPPFLAGS=["-D__SSE2__", "-D__SSE__"]) - else: - env.Append(LIBS=["psapi"]) + env_thirdparty = env_raycast.Clone() + env_thirdparty.disable_warnings() + env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources) -env_embree.disable_warnings() -env_embree.add_source_files(env.modules_sources, embree_sources) + if not env["arch"] in ["x86", "x86_64"] or env.msvc: + # Embree needs those, it will automatically use SSE2NEON in ARM + env_thirdparty.Append(CPPDEFINES=["__SSE2__", "__SSE__"]) -env_raycast = env_modules.Clone() -env_raycast.Prepend(CPPPATH=[embree_dir, embree_dir + "include", embree_dir + "common"]) + env.modules_sources += thirdparty_obj + + +# Godot source files + +module_obj = [] + +env_raycast.add_source_files(module_obj, "*.cpp") +env.modules_sources += module_obj -env_raycast.add_source_files(env.modules_sources, "*.cpp") +# Needed to force rebuilding the module files when the thirdparty library is updated. +env.Depends(module_obj, thirdparty_obj) diff --git a/modules/raycast/config.py b/modules/raycast/config.py index 26493da41b..5de36c5322 100644 --- a/modules/raycast/config.py +++ b/modules/raycast/config.py @@ -1,10 +1,15 @@ def can_build(env, platform): + # Depends on Embree library, which only supports x86_64 and aarch64. + if platform == "android": - return env["android_arch"] in ["arm64v8", "x86", "x86_64"] + return env["android_arch"] in ["arm64v8", "x86_64"] if platform == "javascript": return False # No SIMD support yet + if env["bits"] == "32": + return False + return True diff --git a/modules/raycast/godot_update_embree.py b/modules/raycast/godot_update_embree.py index db4fa95c21..31a25a318f 100644 --- a/modules/raycast/godot_update_embree.py +++ b/modules/raycast/godot_update_embree.py @@ -11,6 +11,7 @@ include_dirs = [ "common/algorithms", "common/lexers", "common/simd", + "common/simd/arm", "include/embree3", "kernels/subdiv", "kernels/geometry", @@ -32,16 +33,6 @@ cpp_files = [ "common/lexers/stringstream.cpp", "common/lexers/tokenstream.cpp", "common/tasking/taskschedulerinternal.cpp", - "common/algorithms/parallel_for.cpp", - "common/algorithms/parallel_reduce.cpp", - "common/algorithms/parallel_prefix_sum.cpp", - "common/algorithms/parallel_for_for.cpp", - "common/algorithms/parallel_for_for_prefix_sum.cpp", - "common/algorithms/parallel_partition.cpp", - "common/algorithms/parallel_sort.cpp", - "common/algorithms/parallel_set.cpp", - "common/algorithms/parallel_map.cpp", - "common/algorithms/parallel_filter.cpp", "kernels/common/device.cpp", "kernels/common/stat.cpp", "kernels/common/acceln.cpp", @@ -74,11 +65,11 @@ cpp_files = [ os.chdir("../../thirdparty") -dir_name = "embree-aarch64" +dir_name = "embree" if os.path.exists(dir_name): shutil.rmtree(dir_name) -subprocess.run(["git", "clone", "https://github.com/lighttransport/embree-aarch64.git", "embree-tmp"]) +subprocess.run(["git", "clone", "https://github.com/embree/embree.git", "embree-tmp"]) os.chdir("embree-tmp") commit_hash = str(subprocess.check_output(["git", "rev-parse", "HEAD"], universal_newlines=True)).strip() @@ -197,7 +188,7 @@ with open("CMakeLists.txt", "r") as cmake_file: with open(os.path.join(dest_dir, "include/embree3/rtcore_config.h"), "w") as config_file: config_file.write( f""" -// Copyright 2009-2020 Intel Corporation +// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once diff --git a/modules/raycast/lightmap_raycaster.cpp b/modules/raycast/lightmap_raycaster.cpp index 9039622d3d..0583acc119 100644 --- a/modules/raycast/lightmap_raycaster.cpp +++ b/modules/raycast/lightmap_raycaster.cpp @@ -32,13 +32,9 @@ #include "lightmap_raycaster.h" -// From Embree. -#include <math/vec2.h> -#include <math/vec3.h> - +#ifdef __SSE2__ #include <pmmintrin.h> - -using namespace embree; +#endif LightmapRaycaster *LightmapRaycasterEmbree::create_embree_raycaster() { return memnew(LightmapRaycasterEmbree); @@ -127,25 +123,24 @@ void LightmapRaycasterEmbree::add_mesh(const Vector<Vector3> &p_vertices, const ERR_FAIL_COND(vertex_count % 3 != 0); ERR_FAIL_COND(vertex_count != p_uv2s.size()); + ERR_FAIL_COND(!p_normals.is_empty() && vertex_count != p_normals.size()); - Vec3fa *embree_vertices = (Vec3fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, sizeof(Vec3fa), vertex_count); - Vec2fa *embree_light_uvs = (Vec2fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, RTC_FORMAT_FLOAT2, sizeof(Vec2fa), vertex_count); - uint32_t *embree_triangles = (uint32_t *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, sizeof(uint32_t) * 3, vertex_count / 3); + Vector3 *embree_vertices = (Vector3 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, sizeof(Vector3), vertex_count); + memcpy(embree_vertices, p_vertices.ptr(), sizeof(Vector3) * vertex_count); - Vec3fa *embree_normals = nullptr; - if (!p_normals.is_empty()) { - embree_normals = (Vec3fa *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, RTC_FORMAT_FLOAT3, sizeof(Vec3fa), vertex_count); - } + Vector2 *embree_light_uvs = (Vector2 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 0, RTC_FORMAT_FLOAT2, sizeof(Vector2), vertex_count); + memcpy(embree_light_uvs, p_uv2s.ptr(), sizeof(Vector2) * vertex_count); + uint32_t *embree_triangles = (uint32_t *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT3, sizeof(uint32_t) * 3, vertex_count / 3); for (int i = 0; i < vertex_count; i++) { - embree_vertices[i] = Vec3fa(p_vertices[i].x, p_vertices[i].y, p_vertices[i].z); - embree_light_uvs[i] = Vec2fa(p_uv2s[i].x, p_uv2s[i].y); - if (embree_normals != nullptr) { - embree_normals[i] = Vec3fa(p_normals[i].x, p_normals[i].y, p_normals[i].z); - } embree_triangles[i] = i; } + if (!p_normals.is_empty()) { + Vector3 *embree_normals = (Vector3 *)rtcSetNewGeometryBuffer(embree_mesh, RTC_BUFFER_TYPE_VERTEX_ATTRIBUTE, 1, RTC_FORMAT_FLOAT3, sizeof(Vector3), vertex_count); + memcpy(embree_normals, p_normals.ptr(), sizeof(Vector3) * vertex_count); + } + rtcCommitGeometry(embree_mesh); rtcSetGeometryIntersectFilterFunction(embree_mesh, filter_function); rtcSetGeometryUserData(embree_mesh, this); @@ -178,8 +173,10 @@ void embree_error_handler(void *p_user_data, RTCError p_code, const char *p_str) } LightmapRaycasterEmbree::LightmapRaycasterEmbree() { +#ifdef __SSE2__ _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); +#endif embree_device = rtcNewDevice(nullptr); rtcSetDeviceErrorFunction(embree_device, &embree_error_handler, nullptr); @@ -187,8 +184,10 @@ LightmapRaycasterEmbree::LightmapRaycasterEmbree() { } LightmapRaycasterEmbree::~LightmapRaycasterEmbree() { +#ifdef __SSE2__ _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_OFF); +#endif if (embree_scene != nullptr) { rtcReleaseScene(embree_scene); diff --git a/modules/raycast/raycast_occlusion_cull.cpp b/modules/raycast/raycast_occlusion_cull.cpp index ea43255eef..88c0145ebc 100644 --- a/modules/raycast/raycast_occlusion_cull.cpp +++ b/modules/raycast/raycast_occlusion_cull.cpp @@ -64,7 +64,7 @@ void RaycastOcclusionCull::RaycastHZBuffer::resize(const Size2i &p_size) { camera_ray_masks.resize(ray_packets_count * TILE_SIZE * TILE_SIZE); } -void RaycastOcclusionCull::RaycastHZBuffer::update_camera_rays(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_work_pool) { +void RaycastOcclusionCull::RaycastHZBuffer::update_camera_rays(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_work_pool) { CameraRayThreadData td; td.camera_matrix = p_cam_projection; td.camera_transform = p_cam_transform; @@ -82,7 +82,7 @@ void RaycastOcclusionCull::RaycastHZBuffer::_camera_rays_threaded(uint32_t p_thr _generate_camera_rays(p_data->camera_transform, p_data->camera_matrix, p_data->camera_orthogonal, from, to); } -void RaycastOcclusionCull::RaycastHZBuffer::_generate_camera_rays(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, int p_from, int p_to) { +void RaycastOcclusionCull::RaycastHZBuffer::_generate_camera_rays(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, int p_from, int p_to) { Size2i buffer_size = sizes[0]; CameraMatrix inv_camera_matrix = p_cam_projection.inverse(); @@ -227,7 +227,7 @@ void RaycastOcclusionCull::remove_scenario(RID p_scenario) { scenario.removed = true; } -void RaycastOcclusionCull::scenario_set_instance(RID p_scenario, RID p_instance, RID p_occluder, const Transform &p_xform, bool p_enabled) { +void RaycastOcclusionCull::scenario_set_instance(RID p_scenario, RID p_instance, RID p_occluder, const Transform3D &p_xform, bool p_enabled) { ERR_FAIL_COND(!scenarios.has(p_scenario)); Scenario &scenario = scenarios[p_scenario]; @@ -334,7 +334,7 @@ void RaycastOcclusionCull::Scenario::_update_dirty_instance(int p_idx, RID *p_in } occ_inst->indices.resize(occ->indices.size()); - copymem(occ_inst->indices.ptr(), occ->indices.ptr(), occ->indices.size() * sizeof(int32_t)); + memcpy(occ_inst->indices.ptr(), occ->indices.ptr(), occ->indices.size() * sizeof(int32_t)); } void RaycastOcclusionCull::Scenario::_transform_vertices_thread(uint32_t p_thread, TransformThreadData *p_data) { @@ -345,7 +345,7 @@ void RaycastOcclusionCull::Scenario::_transform_vertices_thread(uint32_t p_threa _transform_vertices_range(p_data->read, p_data->write, p_data->xform, from, to); } -void RaycastOcclusionCull::Scenario::_transform_vertices_range(const Vector3 *p_read, Vector3 *p_write, const Transform &p_xform, int p_from, int p_to) { +void RaycastOcclusionCull::Scenario::_transform_vertices_range(const Vector3 *p_read, Vector3 *p_write, const Transform3D &p_xform, int p_from, int p_to) { for (int i = p_from; i < p_to; i++) { p_write[i] = p_xform.xform(p_read[i]); } @@ -491,7 +491,7 @@ void RaycastOcclusionCull::buffer_set_size(RID p_buffer, const Vector2i &p_size) buffers[p_buffer].resize(p_size); } -void RaycastOcclusionCull::buffer_update(RID p_buffer, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_pool) { +void RaycastOcclusionCull::buffer_update(RID p_buffer, const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_pool) { if (!buffers.has(p_buffer)) { return; } diff --git a/modules/raycast/raycast_occlusion_cull.h b/modules/raycast/raycast_occlusion_cull.h index acaceb9459..85710a790c 100644 --- a/modules/raycast/raycast_occlusion_cull.h +++ b/modules/raycast/raycast_occlusion_cull.h @@ -34,7 +34,7 @@ #include "core/io/image.h" #include "core/math/camera_matrix.h" #include "core/object/object.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/templates/local_vector.h" #include "core/templates/rid_owner.h" #include "scene/resources/mesh.h" @@ -52,14 +52,14 @@ public: struct CameraRayThreadData { CameraMatrix camera_matrix; - Transform camera_transform; + Transform3D camera_transform; bool camera_orthogonal; int thread_count; Size2i buffer_size; }; void _camera_rays_threaded(uint32_t p_thread, CameraRayThreadData *p_data); - void _generate_camera_rays(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, int p_from, int p_to); + void _generate_camera_rays(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, int p_from, int p_to); public: LocalVector<RayPacket> camera_rays; @@ -69,7 +69,7 @@ public: virtual void clear() override; virtual void resize(const Size2i &p_size) override; void sort_rays(); - void update_camera_rays(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_work_pool); + void update_camera_rays(const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_work_pool); }; private: @@ -99,7 +99,7 @@ private: RID occluder; LocalVector<uint32_t> indices; LocalVector<Vector3> xformed_vertices; - Transform xform; + Transform3D xform; bool enabled = true; bool removed = false; }; @@ -113,7 +113,7 @@ private: struct TransformThreadData { uint32_t thread_count; uint32_t vertex_count; - Transform xform; + Transform3D xform; const Vector3 *read; Vector3 *write; }; @@ -134,7 +134,7 @@ private: void _update_dirty_instance_thread(int p_idx, RID *p_instances); void _update_dirty_instance(int p_idx, RID *p_instances, ThreadWorkPool *p_thread_pool); void _transform_vertices_thread(uint32_t p_thread, TransformThreadData *p_data); - void _transform_vertices_range(const Vector3 *p_read, Vector3 *p_write, const Transform &p_xform, int p_from, int p_to); + void _transform_vertices_range(const Vector3 *p_read, Vector3 *p_write, const Transform3D &p_xform, int p_from, int p_to); static void _commit_scene(void *p_ud); bool update(ThreadWorkPool &p_thread_pool); @@ -164,7 +164,7 @@ public: virtual void add_scenario(RID p_scenario) override; virtual void remove_scenario(RID p_scenario) override; - virtual void scenario_set_instance(RID p_scenario, RID p_instance, RID p_occluder, const Transform &p_xform, bool p_enabled) override; + virtual void scenario_set_instance(RID p_scenario, RID p_instance, RID p_occluder, const Transform3D &p_xform, bool p_enabled) override; virtual void scenario_remove_instance(RID p_scenario, RID p_instance) override; virtual void add_buffer(RID p_buffer) override; @@ -172,7 +172,7 @@ public: virtual HZBuffer *buffer_get_ptr(RID p_buffer) override; virtual void buffer_set_scenario(RID p_buffer, RID p_scenario) override; virtual void buffer_set_size(RID p_buffer, const Vector2i &p_size) override; - virtual void buffer_update(RID p_buffer, const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_pool) override; + virtual void buffer_update(RID p_buffer, const Transform3D &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, ThreadWorkPool &p_thread_pool) override; virtual RID buffer_get_debug_texture(RID p_buffer) override; virtual void set_build_quality(RS::ViewportOcclusionCullingBuildQuality p_quality) override; diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml index b21f5d1e7a..9c84974ff6 100644 --- a/modules/regex/doc_classes/RegEx.xml +++ b/modules/regex/doc_classes/RegEx.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="RegEx" inherits="Reference" version="4.0"> +<class name="RegEx" inherits="RefCounted" version="4.0"> <brief_description> Class for searching text for patterns using regular expressions. </brief_description> @@ -50,88 +50,67 @@ </tutorials> <methods> <method name="clear"> - <return type="void"> - </return> + <return type="void" /> <description> This method resets the state of the object, as if it was freshly created. Namely, it unassigns the regular expression of this object. </description> </method> <method name="compile"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="pattern" type="String"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="pattern" type="String" /> <description> Compiles and assign the search pattern to use. Returns [constant OK] if the compilation is successful. If an error is encountered, details are printed to standard output and an error is returned. </description> </method> <method name="get_group_count" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Returns the number of capturing groups in compiled pattern. </description> </method> <method name="get_names" qualifiers="const"> - <return type="Array"> - </return> + <return type="Array" /> <description> Returns an array of names of named capturing groups in the compiled pattern. They are ordered by appearance. </description> </method> <method name="get_pattern" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the original search pattern that was compiled. </description> </method> <method name="is_valid" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns whether this object has a valid search pattern assigned. </description> </method> <method name="search" qualifiers="const"> - <return type="RegExMatch"> - </return> - <argument index="0" name="subject" type="String"> - </argument> - <argument index="1" name="offset" type="int" default="0"> - </argument> - <argument index="2" name="end" type="int" default="-1"> - </argument> + <return type="RegExMatch" /> + <argument index="0" name="subject" type="String" /> + <argument index="1" name="offset" type="int" default="0" /> + <argument 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. </description> </method> <method name="search_all" qualifiers="const"> - <return type="Array"> - </return> - <argument index="0" name="subject" type="String"> - </argument> - <argument index="1" name="offset" type="int" default="0"> - </argument> - <argument index="2" name="end" type="int" default="-1"> - </argument> + <return type="Array" /> + <argument index="0" name="subject" type="String" /> + <argument index="1" name="offset" type="int" default="0" /> + <argument 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. </description> </method> <method name="sub" qualifiers="const"> - <return type="String"> - </return> - <argument index="0" name="subject" type="String"> - </argument> - <argument index="1" name="replacement" type="String"> - </argument> - <argument index="2" name="all" type="bool" default="false"> - </argument> - <argument index="3" name="offset" type="int" default="0"> - </argument> - <argument index="4" name="end" type="int" default="-1"> - </argument> + <return type="String" /> + <argument index="0" name="subject" type="String" /> + <argument index="1" name="replacement" type="String" /> + <argument index="2" name="all" type="bool" default="false" /> + <argument index="3" name="offset" type="int" default="0" /> + <argument 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. </description> diff --git a/modules/regex/doc_classes/RegExMatch.xml b/modules/regex/doc_classes/RegExMatch.xml index a45de60aef..3cde2836cc 100644 --- a/modules/regex/doc_classes/RegExMatch.xml +++ b/modules/regex/doc_classes/RegExMatch.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="RegExMatch" inherits="Reference" version="4.0"> +<class name="RegExMatch" inherits="RefCounted" version="4.0"> <brief_description> Contains the results of a [RegEx] search. </brief_description> @@ -10,37 +10,30 @@ </tutorials> <methods> <method name="get_end" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="name" type="Variant" default="0"> - </argument> + <return type="int" /> + <argument index="0" name="name" type="Variant" default="0" /> <description> Returns the end position of the match within the source string. The end position of capturing groups can be retrieved by providing its group number as an integer or its string name (if it's a named group). The default value of 0 refers to the whole pattern. Returns -1 if the group did not match or doesn't exist. </description> </method> <method name="get_group_count" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Returns the number of capturing groups. </description> </method> <method name="get_start" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="name" type="Variant" default="0"> - </argument> + <return type="int" /> + <argument index="0" name="name" type="Variant" default="0" /> <description> Returns the starting position of the match within the source string. The starting position of capturing groups can be retrieved by providing its group number as an integer or its string name (if it's a named group). The default value of 0 refers to the whole pattern. Returns -1 if the group did not match or doesn't exist. </description> </method> <method name="get_string" qualifiers="const"> - <return type="String"> - </return> - <argument index="0" name="name" type="Variant" default="0"> - </argument> + <return type="String" /> + <argument index="0" name="name" type="Variant" default="0" /> <description> Returns the substring of the match from the source string. Capturing groups can be retrieved by providing its group number as an integer or its string name (if it's a named group). The default value of 0 refers to the whole pattern. Returns an empty string if the group did not match or doesn't exist. @@ -51,7 +44,7 @@ <member name="names" type="Dictionary" setter="" getter="get_names" default="{}"> A dictionary of named groups and its corresponding group number. Only groups that were matched are included. If multiple groups have the same name, that name would refer to the first matching one. </member> - <member name="strings" type="Array" setter="" getter="get_strings" default="[ ]"> + <member name="strings" type="Array" setter="" getter="get_strings" default="[]"> An [Array] of the match and its capturing groups. </member> <member name="subject" type="String" setter="" getter="get_subject" default=""""> diff --git a/modules/regex/regex.h b/modules/regex/regex.h index f5773042fb..68fe2bc6e0 100644 --- a/modules/regex/regex.h +++ b/modules/regex/regex.h @@ -31,15 +31,15 @@ #ifndef REGEX_H #define REGEX_H -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/string/ustring.h" #include "core/templates/map.h" #include "core/templates/vector.h" #include "core/variant/array.h" #include "core/variant/dictionary.h" -class RegExMatch : public Reference { - GDCLASS(RegExMatch, Reference); +class RegExMatch : public RefCounted { + GDCLASS(RegExMatch, RefCounted); struct Range { int start = 0; @@ -68,8 +68,8 @@ public: int get_end(const Variant &p_name) const; }; -class RegEx : public Reference { - GDCLASS(RegEx, Reference); +class RegEx : public RefCounted { + GDCLASS(RegEx, RefCounted); void *general_ctx; void *code = nullptr; diff --git a/modules/regex/register_types.cpp b/modules/regex/register_types.cpp index 82f3eaf707..03957f88cf 100644 --- a/modules/regex/register_types.cpp +++ b/modules/regex/register_types.cpp @@ -33,8 +33,8 @@ #include "regex.h" void register_regex_types() { - ClassDB::register_class<RegExMatch>(); - ClassDB::register_class<RegEx>(); + GDREGISTER_CLASS(RegExMatch); + GDREGISTER_CLASS(RegEx); } void unregister_regex_types() { diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp index 6732078efc..768b419348 100644 --- a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp @@ -30,7 +30,7 @@ #include "audio_stream_ogg_vorbis.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); @@ -129,7 +129,7 @@ Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { "to it. AudioStreamOGGVorbis should not be created from the " "inspector or with `.new()`. Instead, load an audio file."); - ovs.instance(); + ovs.instantiate(); ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer = (char *)memalloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size; @@ -204,7 +204,7 @@ void AudioStreamOGGVorbis::set_data(const Vector<uint8_t> &p_data) { clear_data(); data = memalloc(src_data_len); - copymem(data, src_datar, src_data_len); + memcpy(data, src_datar, src_data_len); data_len = src_data_len; break; @@ -221,7 +221,7 @@ Vector<uint8_t> AudioStreamOGGVorbis::get_data() const { vdata.resize(data_len); { uint8_t *w = vdata.ptrw(); - copymem(w, data, data_len); + memcpy(w, data, data_len); } } diff --git a/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml b/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml index 8a1bb62e24..94fdff5d43 100644 --- a/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml +++ b/modules/stb_vorbis/doc_classes/AudioStreamOGGVorbis.xml @@ -11,7 +11,7 @@ <methods> </methods> <members> - <member name="data" type="PackedByteArray" setter="set_data" getter="get_data" default="PackedByteArray( )"> + <member name="data" type="PackedByteArray" setter="set_data" getter="get_data" default="PackedByteArray()"> Contains the audio data in bytes. </member> <member name="loop" type="bool" setter="set_loop" getter="has_loop" default="false"> diff --git a/modules/stb_vorbis/register_types.cpp b/modules/stb_vorbis/register_types.cpp index 6f7eb53bc8..bdb1cf69cf 100644 --- a/modules/stb_vorbis/register_types.cpp +++ b/modules/stb_vorbis/register_types.cpp @@ -41,11 +41,11 @@ void register_stb_vorbis_types() { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { Ref<ResourceImporterOGGVorbis> ogg_import; - ogg_import.instance(); + ogg_import.instantiate(); ResourceFormatImporter::get_singleton()->add_importer(ogg_import); } #endif - ClassDB::register_class<AudioStreamOGGVorbis>(); + GDREGISTER_CLASS(AudioStreamOGGVorbis); } void unregister_stb_vorbis_types() { diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp index ec1c30783a..85de698efd 100644 --- a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp +++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp @@ -30,8 +30,8 @@ #include "resource_importer_ogg_vorbis.h" +#include "core/io/file_access.h" #include "core/io/resource_saver.h" -#include "core/os/file_access.h" #include "scene/resources/texture.h" String ResourceImporterOGGVorbis::get_importer_name() const { @@ -79,7 +79,7 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot open file '" + p_source_file + "'."); - size_t len = f->get_len(); + uint64_t len = f->get_length(); Vector<uint8_t> data; data.resize(len); @@ -90,7 +90,7 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin memdelete(f); Ref<AudioStreamOGGVorbis> ogg_stream; - ogg_stream.instance(); + ogg_stream.instantiate(); ogg_stream->set_data(data); ERR_FAIL_COND_V(!ogg_stream->get_data().size(), ERR_FILE_CORRUPT); diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp index 6ce3e4b4b3..4911346b96 100644 --- a/modules/svg/image_loader_svg.cpp +++ b/modules/svg/image_loader_svg.cpp @@ -140,7 +140,7 @@ Error ImageLoaderSVG::create_image_from_string(Ref<Image> p_image, const char *p } Error ImageLoaderSVG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { - uint32_t size = f->get_len(); + uint64_t size = f->get_length(); Vector<uint8_t> src_image; src_image.resize(size + 1); uint8_t *src_w = src_image.ptrw(); diff --git a/modules/text_server_adv/SCsub b/modules/text_server_adv/SCsub index a55b6dc283..d06c5c2f14 100644 --- a/modules/text_server_adv/SCsub +++ b/modules/text_server_adv/SCsub @@ -131,7 +131,7 @@ if env["builtin_harfbuzz"]: ] ) - if env["platform"] == "android" or env["platform"] == "linuxbsd" or env["platform"] == "server": + if env["platform"] == "android" or env["platform"] == "linuxbsd": env_harfbuzz.Append(CCFLAGS=["-DHAVE_PTHREAD"]) if env["platform"] == "javascript": diff --git a/modules/text_server_adv/dynamic_font_adv.cpp b/modules/text_server_adv/dynamic_font_adv.cpp index 326af7f0ee..62eedebb59 100644 --- a/modules/text_server_adv/dynamic_font_adv.cpp +++ b/modules/text_server_adv/dynamic_font_adv.cpp @@ -66,7 +66,7 @@ DynamicFontDataAdvanced::DataAtSize *DynamicFontDataAdvanced::get_data_for_size( ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'."); } - size_t len = f->get_len(); + uint64_t len = f->get_length(); font_mem_cache.resize(len); f->get_buffer(font_mem_cache.ptrw(), len); font_mem = font_mem_cache.ptr(); @@ -420,7 +420,7 @@ DynamicFontDataAdvanced::Character DynamicFontDataAdvanced::bitmap_to_character( Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata)); if (tex.texture.is_null()) { - tex.texture.instance(); + tex.texture.instantiate(); tex.texture->create_from_image(img); } else { tex.texture->update(img); //update diff --git a/modules/text_server_adv/dynamic_font_adv.h b/modules/text_server_adv/dynamic_font_adv.h index 1292966f0c..b3f97bb029 100644 --- a/modules/text_server_adv/dynamic_font_adv.h +++ b/modules/text_server_adv/dynamic_font_adv.h @@ -34,7 +34,6 @@ #include "font_adv.h" #include "modules/modules_enabled.gen.h" - #ifdef MODULE_FREETYPE_ENABLED #include <ft2build.h> diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp index 8b8b6b7cd3..9ecb0de5b8 100644 --- a/modules/text_server_adv/text_server_adv.cpp +++ b/modules/text_server_adv/text_server_adv.cpp @@ -129,6 +129,10 @@ _FORCE_INLINE_ bool is_linebreak(char32_t p_char) { return (p_char >= 0x000a && p_char <= 0x000d) || (p_char == 0x0085) || (p_char == 0x2028) || (p_char == 0x2029); } +_FORCE_INLINE_ bool is_underscore(char32_t p_char) { + return (p_char == 0x005F); +} + /*************************************************************************/ String TextServerAdvanced::interface_name = "ICU / HarfBuzz / Graphite"; @@ -181,7 +185,7 @@ bool TextServerAdvanced::load_support_data(const String &p_filename) { UErrorCode err = U_ZERO_ERROR; // ICU data found. - size_t len = f->get_len(); + uint64_t len = f->get_length(); icu_data = (uint8_t *)memalloc(len); f->get_buffer(icu_data, len); f->close(); @@ -923,14 +927,14 @@ void TextServerAdvanced::font_set_oversampling(float p_oversampling) { oversampling = p_oversampling; List<RID> fonts; font_owner.get_owned_list(&fonts); - for (List<RID>::Element *E = fonts.front(); E; E = E->next()) { - font_owner.getornull(E->get())->clear_cache(); + for (const RID &E : fonts) { + font_owner.getornull(E)->clear_cache(); } List<RID> text_bufs; shaped_owner.get_owned_list(&text_bufs); - for (List<RID>::Element *E = text_bufs.front(); E; E = E->next()) { - invalidate(shaped_owner.getornull(E->get())); + for (const RID &E : text_bufs) { + invalidate(shaped_owner.getornull(E)); } } } @@ -973,6 +977,7 @@ void TextServerAdvanced::invalidate(TextServerAdvanced::ShapedTextDataAdvanced * p_shaped->sort_valid = false; p_shaped->line_breaks_valid = false; p_shaped->justification_ops_valid = false; + p_shaped->text_trimmed = false; p_shaped->ascent = 0.f; p_shaped->descent = 0.f; p_shaped->width = 0.f; @@ -980,6 +985,7 @@ void TextServerAdvanced::invalidate(TextServerAdvanced::ShapedTextDataAdvanced * p_shaped->uthk = 0.f; p_shaped->glyphs.clear(); p_shaped->glyphs_logical.clear(); + p_shaped->overrun_trim_data = TrimData(); p_shaped->utf16 = Char16String(); if (p_shaped->script_iter != nullptr) { memdelete(p_shaped->script_iter); @@ -1157,7 +1163,7 @@ bool TextServerAdvanced::shaped_text_add_string(RID p_shaped, const String &p_te return true; } -bool TextServerAdvanced::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) { +bool TextServerAdvanced::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align, int p_length) { _THREAD_SAFE_METHOD_ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -1187,7 +1193,7 @@ bool TextServerAdvanced::shaped_text_add_object(RID p_shaped, Variant p_key, con return true; } -bool TextServerAdvanced::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) { +bool TextServerAdvanced::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align) { _THREAD_SAFE_METHOD_ ShapedTextData *sd = shaped_owner.getornull(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -1218,34 +1224,10 @@ bool TextServerAdvanced::shaped_text_resize_object(RID p_shaped, Variant p_key, if (sd->orientation == ORIENTATION_HORIZONTAL) { sd->objects[key].rect.position.x = sd->width; sd->width += sd->objects[key].rect.size.x; - switch (sd->objects[key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.y / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.y / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y); - } break; - } sd->glyphs.write[i].advance = sd->objects[key].rect.size.x; } else { sd->objects[key].rect.position.y = sd->width; sd->width += sd->objects[key].rect.size.y; - switch (sd->objects[key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.x / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.x / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x); - } break; - } sd->glyphs.write[i].advance = sd->objects[key].rect.size.y; } } else { @@ -1275,35 +1257,71 @@ bool TextServerAdvanced::shaped_text_resize_object(RID p_shaped, Variant p_key, } // Align embedded objects to baseline. + float full_ascent = sd->ascent; + float full_descent = sd->descent; for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { if ((E->get().pos >= sd->start) && (E->get().pos < sd->end)) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.y = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.y = -(E->get().rect.size.y / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.y = (-sd->ascent + sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.y = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.y = sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.y -= E->get().rect.size.y; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.y -= E->get().rect.size.y / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.y = sd->descent - E->get().rect.size.y; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.y); + full_descent = MAX(full_descent, E->get().rect.position.y + E->get().rect.size.y); } else { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.x = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.x = -(E->get().rect.size.x / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.x = (-sd->ascent + sd->descent) / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.x = sd->descent - E->get().rect.size.x; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.x = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.x = sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.x -= E->get().rect.size.x; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.x -= E->get().rect.size.x / 2; + } break; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.x); + full_descent = MAX(full_descent, E->get().rect.position.x + E->get().rect.size.x); } } } + sd->ascent = full_ascent; + sd->descent = full_descent; } return true; } @@ -1359,7 +1377,7 @@ RID TextServerAdvanced::shaped_text_substr(RID p_shaped, int p_start, int p_leng ERR_FAIL_COND_V_MSG((start < 0 || end - start > new_sd->utf16.length()), RID(), "Invalid BiDi override range."); - //Create temporary line bidi & shape + // Create temporary line bidi & shape. UBiDi *bidi_iter = ubidi_openSized(end - start, 0, &err); ERR_FAIL_COND_V_MSG(U_FAILURE(err), RID(), u_errorName(err)); ubidi_setLine(sd->bidi_iter[ov], start, end, bidi_iter, &err); @@ -1400,33 +1418,9 @@ RID TextServerAdvanced::shaped_text_substr(RID p_shaped, int p_start, int p_leng if (new_sd->orientation == ORIENTATION_HORIZONTAL) { new_sd->objects[key].rect.position.x = new_sd->width; new_sd->width += new_sd->objects[key].rect.size.x; - switch (new_sd->objects[key].inline_align) { - case VALIGN_TOP: { - new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y); - } break; - case VALIGN_CENTER: { - new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.y / 2)); - new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.y / 2)); - } break; - case VALIGN_BOTTOM: { - new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y); - } break; - } } else { new_sd->objects[key].rect.position.y = new_sd->width; new_sd->width += new_sd->objects[key].rect.size.y; - switch (new_sd->objects[key].inline_align) { - case VALIGN_TOP: { - new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x); - } break; - case VALIGN_CENTER: { - new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.x / 2)); - new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.x / 2)); - } break; - case VALIGN_BOTTOM: { - new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x); - } break; - } } } else { if (prev_rid != gl.font_rid) { @@ -1460,37 +1454,72 @@ RID TextServerAdvanced::shaped_text_substr(RID p_shaped, int p_start, int p_leng } // Align embedded objects to baseline. + float full_ascent = new_sd->ascent; + float full_descent = new_sd->descent; for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = new_sd->objects.front(); E; E = E->next()) { if ((E->get().pos >= new_sd->start) && (E->get().pos < new_sd->end)) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.y = -new_sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.y = -(E->get().rect.size.y / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.y = (-new_sd->ascent + new_sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.y = 0; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.y = new_sd->descent - E->get().rect.size.y; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.y = new_sd->descent; } break; } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.y -= E->get().rect.size.y; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.y -= E->get().rect.size.y / 2; + } break; + case INLINE_ALIGN_TOP_TO: { + //NOP + } break; + } + full_ascent = MAX(full_ascent, -E->get().rect.position.y); + full_descent = MAX(full_descent, E->get().rect.position.y + E->get().rect.size.y); } else { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.x = -new_sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.x = -(E->get().rect.size.x / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.x = (-new_sd->ascent + new_sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.x = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.x = new_sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.x -= E->get().rect.size.x; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.x -= E->get().rect.size.x / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.x = new_sd->descent - E->get().rect.size.x; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.x); + full_descent = MAX(full_descent, E->get().rect.position.x + E->get().rect.size.x); } } } + new_sd->ascent = full_ascent; + new_sd->descent = full_descent; } - new_sd->valid = true; return shaped_owner.make_rid(new_sd); @@ -1514,6 +1543,7 @@ float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, const_cast<TextServerAdvanced *>(this)->shaped_text_update_justification_ops(p_shaped); } + sd->fit_width_minimum_reached = false; int start_pos = 0; int end_pos = sd->glyphs.size() - 1; @@ -1542,14 +1572,26 @@ float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, } } + float justification_width; + if ((p_jst_flags & JUSTIFICATION_CONSTRAIN_ELLIPSIS) == JUSTIFICATION_CONSTRAIN_ELLIPSIS) { + if (sd->overrun_trim_data.trim_pos >= 0) { + start_pos = sd->overrun_trim_data.trim_pos; + justification_width = sd->width_trimmed; + } else { + return sd->width; + } + } else { + justification_width = sd->width; + } + if ((p_jst_flags & JUSTIFICATION_TRIM_EDGE_SPACES) == JUSTIFICATION_TRIM_EDGE_SPACES) { while ((start_pos < end_pos) && ((sd->glyphs[start_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[start_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) { - sd->width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat; + justification_width -= sd->glyphs[start_pos].advance * sd->glyphs[start_pos].repeat; sd->glyphs.write[start_pos].advance = 0; start_pos += sd->glyphs[start_pos].count; } while ((start_pos < end_pos) && ((sd->glyphs[end_pos].flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_HARD) == GRAPHEME_IS_BREAK_HARD || (sd->glyphs[end_pos].flags & GRAPHEME_IS_BREAK_SOFT) == GRAPHEME_IS_BREAK_SOFT)) { - sd->width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat; + justification_width -= sd->glyphs[end_pos].advance * sd->glyphs[end_pos].repeat; sd->glyphs.write[end_pos].advance = 0; end_pos -= sd->glyphs[end_pos].count; } @@ -1570,7 +1612,7 @@ float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, } if ((elongation_count > 0) && ((p_jst_flags & JUSTIFICATION_KASHIDA) == JUSTIFICATION_KASHIDA)) { - float delta_width_per_kashida = (p_width - sd->width) / elongation_count; + float delta_width_per_kashida = (p_width - justification_width) / elongation_count; for (int i = start_pos; i <= end_pos; i++) { Glyph &gl = sd->glyphs.write[i]; if (gl.count > 0) { @@ -1578,34 +1620,50 @@ float TextServerAdvanced::shaped_text_fit_to_width(RID p_shaped, float p_width, int count = delta_width_per_kashida / gl.advance; int prev_count = gl.repeat; if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) { - gl.repeat = count; - } else { - gl.repeat = count + 1; + gl.repeat = MAX(count, 0); } - sd->width += (gl.repeat - prev_count) * gl.advance; + justification_width += (gl.repeat - prev_count) * gl.advance; } } } } - + float adv_remain = 0; if ((space_count > 0) && ((p_jst_flags & JUSTIFICATION_WORD_BOUND) == JUSTIFICATION_WORD_BOUND)) { - float delta_width_per_space = (p_width - sd->width) / space_count; + float delta_width_per_space = (p_width - justification_width) / space_count; for (int i = start_pos; i <= end_pos; i++) { Glyph &gl = sd->glyphs.write[i]; if (gl.count > 0) { if ((gl.flags & GRAPHEME_IS_SPACE) == GRAPHEME_IS_SPACE) { float old_adv = gl.advance; + float new_advance; if ((gl.flags & GRAPHEME_IS_VIRTUAL) == GRAPHEME_IS_VIRTUAL) { - gl.advance = Math::round(MAX(gl.advance + delta_width_per_space, 0.f)); + new_advance = MAX(gl.advance + delta_width_per_space, 0.f); } else { - gl.advance = Math::round(MAX(gl.advance + delta_width_per_space, 0.05 * gl.font_size)); + new_advance = MAX(gl.advance + delta_width_per_space, 0.05 * gl.font_size); } - sd->width += (gl.advance - old_adv); + gl.advance = new_advance; + adv_remain += (new_advance - gl.advance); + if (adv_remain >= 1.0) { + gl.advance++; + adv_remain -= 1.0; + } else if (adv_remain <= -1.0) { + gl.advance = MAX(gl.advance - 1, 0); + adv_remain -= 1.0; + } + justification_width += (gl.advance - old_adv); } } } } + if (Math::floor(p_width) < Math::floor(justification_width)) { + sd->fit_width_minimum_reached = true; + } + + if ((p_jst_flags & JUSTIFICATION_CONSTRAIN_ELLIPSIS) != JUSTIFICATION_CONSTRAIN_ELLIPSIS) { + sd->width = justification_width; + } + return sd->width; } @@ -1658,6 +1716,138 @@ float TextServerAdvanced::shaped_text_tab_align(RID p_shaped, const Vector<float return 0.f; } +void TextServerAdvanced::shaped_text_overrun_trim_to_width(RID p_shaped_line, float p_width, uint8_t p_trim_flags) { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped_line); + ERR_FAIL_COND_MSG(!sd, "ShapedTextDataAdvanced invalid."); + if (!sd->valid) { + shaped_text_shape(p_shaped_line); + } + + sd->overrun_trim_data.ellipsis_glyph_buf.clear(); + + bool add_ellipsis = (p_trim_flags & OVERRUN_ADD_ELLIPSIS) == OVERRUN_ADD_ELLIPSIS; + bool cut_per_word = (p_trim_flags & OVERRUN_TRIM_WORD_ONLY) == OVERRUN_TRIM_WORD_ONLY; + bool enforce_ellipsis = (p_trim_flags & OVERRUN_ENFORCE_ELLIPSIS) == OVERRUN_ENFORCE_ELLIPSIS; + bool justification_aware = (p_trim_flags & OVERRUN_JUSTIFICATION_AWARE) == OVERRUN_JUSTIFICATION_AWARE; + + Glyph *sd_glyphs = sd->glyphs.ptrw(); + + if ((p_trim_flags & OVERRUN_TRIM) == OVERRUN_NO_TRIMMING || sd_glyphs == nullptr || p_width <= 0 || !(sd->width > p_width || enforce_ellipsis)) { + sd->overrun_trim_data.trim_pos = -1; + sd->overrun_trim_data.ellipsis_pos = -1; + return; + } + + if (justification_aware && !sd->fit_width_minimum_reached) { + return; + } + + int sd_size = sd->glyphs.size(); + RID last_gl_font_rid = sd_glyphs[sd_size - 1].font_rid; + int last_gl_font_size = sd_glyphs[sd_size - 1].font_size; + uint32_t dot_gl_idx = font_get_glyph_index(last_gl_font_rid, '.'); + Vector2 dot_adv = font_get_glyph_advance(last_gl_font_rid, dot_gl_idx, last_gl_font_size); + uint32_t whitespace_gl_idx = font_get_glyph_index(last_gl_font_rid, ' '); + Vector2 whitespace_adv = font_get_glyph_advance(last_gl_font_rid, whitespace_gl_idx, last_gl_font_size); + + int ellipsis_width = 0; + if (add_ellipsis) { + ellipsis_width = 3 * dot_adv.x + font_get_spacing_glyph(last_gl_font_rid) + (cut_per_word ? whitespace_adv.x : 0); + } + + int ell_min_characters = 6; + float width = sd->width; + + bool is_rtl = sd->direction == DIRECTION_RTL || (sd->direction == DIRECTION_AUTO && sd->para_direction == DIRECTION_RTL); + + int trim_pos = (is_rtl) ? sd_size : 0; + int ellipsis_pos = (enforce_ellipsis) ? 0 : -1; + + int last_valid_cut = 0; + bool found = false; + + int glyphs_from = (is_rtl) ? 0 : sd_size - 1; + 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_treshold = ((is_rtl) ? sd_size - 1 - i : i) >= ell_min_characters; + + if (width + (((above_min_char_treshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) { + if (cut_per_word && above_min_char_treshold) { + 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; + } + if (found) { + trim_pos = last_valid_cut; + + if (add_ellipsis && (above_min_char_treshold || enforce_ellipsis) && width - ellipsis_width <= p_width) { + ellipsis_pos = trim_pos; + } + break; + } + } + } + if (is_rtl) { + width -= sd_glyphs[i].advance * sd_glyphs[i].repeat; + } + } + + sd->overrun_trim_data.trim_pos = trim_pos; + sd->overrun_trim_data.ellipsis_pos = ellipsis_pos; + if (trim_pos == 0 && enforce_ellipsis && add_ellipsis) { + sd->overrun_trim_data.ellipsis_pos = 0; + } + + if ((trim_pos >= 0 && sd->width > p_width) || enforce_ellipsis) { + if (add_ellipsis && (ellipsis_pos > 0 || enforce_ellipsis)) { + // Insert an additional space when cutting word bound for aesthetics. + if (cut_per_word && (ellipsis_pos > 0)) { + TextServer::Glyph gl; + gl.count = 1; + gl.advance = whitespace_adv.x; + gl.index = whitespace_gl_idx; + gl.font_rid = last_gl_font_rid; + gl.font_size = last_gl_font_size; + gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL | (is_rtl ? GRAPHEME_IS_RTL : 0); + + sd->overrun_trim_data.ellipsis_glyph_buf.append(gl); + } + // Add ellipsis dots. + TextServer::Glyph gl; + gl.count = 1; + gl.repeat = 3; + gl.advance = dot_adv.x; + gl.index = dot_gl_idx; + gl.font_rid = last_gl_font_rid; + gl.font_size = last_gl_font_size; + gl.flags = GRAPHEME_IS_PUNCTUATION | GRAPHEME_IS_VIRTUAL | (is_rtl ? GRAPHEME_IS_RTL : 0); + + sd->overrun_trim_data.ellipsis_glyph_buf.append(gl); + } + + sd->text_trimmed = true; + sd->width_trimmed = width + ((ellipsis_pos != -1) ? ellipsis_width : 0); + } +} + +TextServer::TrimData TextServerAdvanced::shaped_text_get_trim_data(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V_MSG(!sd, TrimData(), "ShapedTextDataAdvanced invalid."); + return sd->overrun_trim_data; +} + bool TextServerAdvanced::shaped_text_update_breaks(RID p_shaped) { _THREAD_SAFE_METHOD_ ShapedTextDataAdvanced *sd = shaped_owner.getornull(p_shaped); @@ -1684,7 +1874,7 @@ bool TextServerAdvanced::shaped_text_update_breaks(RID p_shaped) { int r_end = sd->spans[i].end; UBreakIterator *bi = ubrk_open(UBRK_LINE, language.ascii().get_data(), data + _convert_pos_inv(sd, r_start), _convert_pos_inv(sd, r_end - r_start), &err); if (U_FAILURE(err)) { - //No data loaded - use fallback. + // No data loaded - use fallback. for (int j = r_start; j < r_end; j++) { char32_t c = sd->text[j - sd->start]; if (is_whitespace(c)) { @@ -1728,7 +1918,10 @@ bool TextServerAdvanced::shaped_text_update_breaks(RID p_shaped) { if (is_whitespace(c)) { sd_glyphs[i].flags |= GRAPHEME_IS_SPACE; } - if (u_ispunct(c)) { + if (is_underscore(c)) { + sd_glyphs[i].flags |= GRAPHEME_IS_UNDERSCORE; + } + if (u_ispunct(c) && c != 0x005F) { sd_glyphs[i].flags |= GRAPHEME_IS_PUNCTUATION; } if (breaks.has(sd->glyphs[i].start)) { @@ -1745,7 +1938,7 @@ bool TextServerAdvanced::shaped_text_update_breaks(RID p_shaped) { gl.font_rid = sd_glyphs[i].font_rid; gl.font_size = sd_glyphs[i].font_size; gl.flags = GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL; - sd->glyphs.insert(i + sd_glyphs[i].count, gl); // insert after + sd->glyphs.insert(i + sd_glyphs[i].count, gl); // Insert after. // Update write pointer and size. sd_size = sd->glyphs.size(); @@ -1865,7 +2058,7 @@ bool TextServerAdvanced::shaped_text_update_justification_ops(RID p_shaped) { UErrorCode err = U_ZERO_ERROR; UBreakIterator *bi = ubrk_open(UBRK_WORD, "", data, data_size, &err); if (U_FAILURE(err)) { - // No data - use fallback + // No data - use fallback. int limit = 0; for (int i = 0; i < sd->text.length(); i++) { if (is_whitespace(data[i])) { @@ -1938,7 +2131,7 @@ bool TextServerAdvanced::shaped_text_update_justification_ops(RID p_shaped) { gl.font_rid = sd->glyphs[i].font_rid; gl.font_size = sd->glyphs[i].font_size; gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_VIRTUAL; - sd->glyphs.insert(i + sd->glyphs[i].count, gl); // insert after + sd->glyphs.insert(i + sd->glyphs[i].count, gl); // Insert after. i += sd->glyphs[i].count; continue; } @@ -2004,7 +2197,7 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_star int fs = p_sd->spans[p_span].font_size; if (fd == nullptr) { - // Add fallback glyphs + // Add fallback glyphs. for (int i = p_start; i < p_end; i++) { if (p_sd->preserve_invalid || (p_sd->preserve_control && is_control(p_sd->text[i]))) { TextServer::Glyph gl; @@ -2147,7 +2340,7 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int32_t p_star w[last_cluster_index].flags |= GRAPHEME_IS_VALID; } - //Fallback. + // Fallback. int failed_subrun_start = p_end + 1; int failed_subrun_end = p_start; @@ -2311,33 +2504,9 @@ bool TextServerAdvanced::shaped_text_shape(RID p_shaped) { if (sd->orientation == ORIENTATION_HORIZONTAL) { sd->objects[span.embedded_key].rect.position.x = sd->width; sd->width += sd->objects[span.embedded_key].rect.size.x; - switch (sd->objects[span.embedded_key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y); - } break; - } } else { sd->objects[span.embedded_key].rect.position.y = sd->width; sd->width += sd->objects[span.embedded_key].rect.size.y; - switch (sd->objects[span.embedded_key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x); - } break; - } } Glyph gl; gl.start = span.start; @@ -2352,24 +2521,22 @@ bool TextServerAdvanced::shaped_text_shape(RID p_shaped) { sd->glyphs.push_back(gl); } else { Vector<RID> fonts; - // Push fonts with the language and script support first. - for (int l = 0; l < span.fonts.size(); l++) { - if ((font_is_language_supported(span.fonts[l], span.language)) && (font_is_script_supported(span.fonts[l], script))) { - fonts.push_back(sd->spans[k].fonts[l]); - } - } - // Push fonts with the script support. - for (int l = 0; l < sd->spans[k].fonts.size(); l++) { - if (!(font_is_language_supported(span.fonts[l], span.language)) && (font_is_script_supported(span.fonts[l], script))) { - fonts.push_back(sd->spans[k].fonts[l]); - } - } - // Push the rest valid fonts. - for (int l = 0; l < sd->spans[k].fonts.size(); l++) { - if (!(font_is_language_supported(span.fonts[l], span.language)) && !(font_is_script_supported(span.fonts[l], script))) { - fonts.push_back(sd->spans[k].fonts[l]); + Vector<RID> fonts_scr_only; + Vector<RID> 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)) { + fonts.push_back(sd->spans[k].fonts[l]); + } else { + fonts_scr_only.push_back(sd->spans[k].fonts[l]); + } + } else { + fonts_no_match.push_back(sd->spans[k].fonts[l]); } } + fonts.append_array(fonts_scr_only); + fonts.append_array(fonts_no_match); _shape_run(sd, MAX(sd->spans[k].start, script_run_start), MIN(sd->spans[k].end, script_run_end), sd->script_iter->script_ranges[j].script, bidi_run_direction, fonts, k, 0); } } @@ -2379,34 +2546,69 @@ bool TextServerAdvanced::shaped_text_shape(RID p_shaped) { } // Align embedded objects to baseline. + float full_ascent = sd->ascent; + float full_descent = sd->descent; for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.y = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.y = -(E->get().rect.size.y / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.y = (-sd->ascent + sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.y = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.y = sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.y -= E->get().rect.size.y; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.y -= E->get().rect.size.y / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.y = sd->descent - E->get().rect.size.y; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.y); + full_descent = MAX(full_descent, E->get().rect.position.y + E->get().rect.size.y); } else { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.x = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.x = -(E->get().rect.size.x / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.x = (-sd->ascent + sd->descent) / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.x = sd->descent - E->get().rect.size.x; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.x = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.x = sd->descent; } break; } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.x -= E->get().rect.size.x; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.x -= E->get().rect.size.x / 2; + } break; + case INLINE_ALIGN_TOP_TO: { + //NOP + } break; + } + full_ascent = MAX(full_ascent, -E->get().rect.position.x); + full_descent = MAX(full_descent, E->get().rect.position.x + E->get().rect.size.x); } } - + sd->ascent = full_ascent; + sd->descent = full_descent; sd->valid = true; return sd->valid; } @@ -2483,9 +2685,9 @@ Size2 TextServerAdvanced::shaped_text_get_size(RID p_shaped) const { const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); } if (sd->orientation == TextServer::ORIENTATION_HORIZONTAL) { - return Size2(sd->width, sd->ascent + sd->descent); + return Size2((sd->text_trimmed ? sd->width_trimmed : sd->width), sd->ascent + sd->descent); } else { - return Size2(sd->ascent + sd->descent, sd->width); + return Size2(sd->ascent + sd->descent, (sd->text_trimmed ? sd->width_trimmed : sd->width)); } } @@ -2516,7 +2718,7 @@ float TextServerAdvanced::shaped_text_get_width(RID p_shaped) const { if (!sd->valid) { const_cast<TextServerAdvanced *>(this)->shaped_text_shape(p_shaped); } - return sd->width; + return (sd->text_trimmed ? sd->width_trimmed : sd->width); } float TextServerAdvanced::shaped_text_get_underline_position(RID p_shaped) const { diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h index 4ad23ca059..d19ba41a1a 100644 --- a/modules/text_server_adv/text_server_adv.h +++ b/modules/text_server_adv/text_server_adv.h @@ -216,8 +216,8 @@ public: virtual bool shaped_text_get_preserve_control(RID p_shaped) const override; virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override; - virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override; - virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override; + virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align = INLINE_ALIGN_CENTER, int p_length = 1) override; + virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align = INLINE_ALIGN_CENTER) override; virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override; virtual RID shaped_text_get_parent(RID p_shaped) const override; @@ -229,6 +229,9 @@ public: virtual bool shaped_text_update_breaks(RID p_shaped) override; virtual bool shaped_text_update_justification_ops(RID p_shaped) override; + virtual void shaped_text_overrun_trim_to_width(RID p_shaped, float p_width, uint8_t p_trim_flags) override; + virtual TrimData shaped_text_get_trim_data(RID p_shaped) const override; + virtual bool shaped_text_is_ready(RID p_shaped) const override; virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override; diff --git a/modules/text_server_fb/dynamic_font_fb.cpp b/modules/text_server_fb/dynamic_font_fb.cpp index dec1d6f83f..7e77987074 100644 --- a/modules/text_server_fb/dynamic_font_fb.cpp +++ b/modules/text_server_fb/dynamic_font_fb.cpp @@ -65,7 +65,7 @@ DynamicFontDataFallback::DataAtSize *DynamicFontDataFallback::get_data_for_size( ERR_FAIL_V_MSG(nullptr, "Cannot open font file '" + font_path + "'."); } - size_t len = f->get_len(); + uint64_t len = f->get_length(); font_mem_cache.resize(len); f->get_buffer(font_mem_cache.ptrw(), len); font_mem = font_mem_cache.ptr(); @@ -306,7 +306,7 @@ DynamicFontDataFallback::Character DynamicFontDataFallback::bitmap_to_character( Ref<Image> img = memnew(Image(tex.texture_size, tex.texture_size, 0, require_format, tex.imgdata)); if (tex.texture.is_null()) { - tex.texture.instance(); + tex.texture.instantiate(); tex.texture->create_from_image(img); } else { tex.texture->update(img); //update diff --git a/modules/text_server_fb/dynamic_font_fb.h b/modules/text_server_fb/dynamic_font_fb.h index b34c8cbed5..82e59fa607 100644 --- a/modules/text_server_fb/dynamic_font_fb.h +++ b/modules/text_server_fb/dynamic_font_fb.h @@ -34,7 +34,6 @@ #include "font_fb.h" #include "modules/modules_enabled.gen.h" - #ifdef MODULE_FREETYPE_ENABLED #include <ft2build.h> diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp index 98a67ef309..110194c373 100644 --- a/modules/text_server_fb/text_server_fb.cpp +++ b/modules/text_server_fb/text_server_fb.cpp @@ -46,7 +46,11 @@ _FORCE_INLINE_ bool is_linebreak(char32_t p_char) { } _FORCE_INLINE_ bool is_punct(char32_t p_char) { - return (p_char >= 0x0020 && p_char <= 0x002F) || (p_char >= 0x003A && p_char <= 0x0040) || (p_char >= 0x005B && p_char <= 0x0060) || (p_char >= 0x007B && p_char <= 0x007E) || (p_char >= 0x2000 && p_char <= 0x206F) || (p_char >= 0x3000 && p_char <= 0x303F); + return (p_char >= 0x0020 && p_char <= 0x002F) || (p_char >= 0x003A && p_char <= 0x0040) || (p_char >= 0x005B && p_char <= 0x005E) || (p_char == 0x0060) || (p_char >= 0x007B && p_char <= 0x007E) || (p_char >= 0x2000 && p_char <= 0x206F) || (p_char >= 0x3000 && p_char <= 0x303F); +} + +_FORCE_INLINE_ bool is_underscore(char32_t p_char) { + return (p_char == 0x005F); } /*************************************************************************/ @@ -469,8 +473,8 @@ void TextServerFallback::font_set_oversampling(float p_oversampling) { oversampling = p_oversampling; List<RID> fonts; font_owner.get_owned_list(&fonts); - for (List<RID>::Element *E = fonts.front(); E; E = E->next()) { - font_owner.getornull(E->get())->clear_cache(); + for (const RID &E : fonts) { + font_owner.getornull(E)->clear_cache(); } } } @@ -566,7 +570,7 @@ void TextServerFallback::shaped_text_set_orientation(RID p_shaped, TextServer::O } void TextServerFallback::shaped_text_set_bidi_override(RID p_shaped, const Vector<Vector2i> &p_override) { - //No BiDi support, ignore. + // No BiDi support, ignore. } TextServer::Orientation TextServerFallback::shaped_text_get_orientation(RID p_shaped) const { @@ -634,17 +638,17 @@ bool TextServerFallback::shaped_text_add_string(RID p_shaped, const String &p_te span.start = sd->text.length(); span.end = span.start + p_text.length(); // Pre-sort fonts, push fonts with the language support first. - for (int i = 0; i < p_fonts.size(); i++) { + Vector<RID> 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)) { span.fonts.push_back(p_fonts[i]); + } else { + fonts_no_match.push_back(p_fonts[i]); } } - // Push the rest valid fonts. - for (int i = 0; i < p_fonts.size(); i++) { - if (!font_is_language_supported(p_fonts[i], p_language)) { - span.fonts.push_back(p_fonts[i]); - } - } + span.fonts.append_array(fonts_no_match); + ERR_FAIL_COND_V(span.fonts.is_empty(), false); span.font_size = p_size; span.language = p_language; @@ -657,7 +661,7 @@ bool TextServerFallback::shaped_text_add_string(RID p_shaped, const String &p_te return true; } -bool TextServerFallback::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align, int p_length) { +bool TextServerFallback::shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align, int p_length) { _THREAD_SAFE_METHOD_ ShapedTextData *sd = shaped_owner.getornull(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -687,7 +691,7 @@ bool TextServerFallback::shaped_text_add_object(RID p_shaped, Variant p_key, con return true; } -bool TextServerFallback::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align) { +bool TextServerFallback::shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align) { _THREAD_SAFE_METHOD_ ShapedTextData *sd = shaped_owner.getornull(p_shaped); ERR_FAIL_COND_V(!sd, false); @@ -720,34 +724,10 @@ bool TextServerFallback::shaped_text_resize_object(RID p_shaped, Variant p_key, if (sd->orientation == ORIENTATION_HORIZONTAL) { sd->objects[key].rect.position.x = sd->width; sd->width += sd->objects[key].rect.size.x; - switch (sd->objects[key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.y); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.y / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.y / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[key].rect.size.y); - } break; - } sd->glyphs.write[i].advance = sd->objects[key].rect.size.x; } else { sd->objects[key].rect.position.y = sd->width; sd->width += sd->objects[key].rect.size.y; - switch (sd->objects[key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[key].rect.size.x); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[key].rect.size.x / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[key].rect.size.x / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[key].rect.size.x); - } break; - } sd->glyphs.write[i].advance = sd->objects[key].rect.size.y; } } else { @@ -780,35 +760,71 @@ bool TextServerFallback::shaped_text_resize_object(RID p_shaped, Variant p_key, } // Align embedded objects to baseline. + float full_ascent = sd->ascent; + float full_descent = sd->descent; for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { if ((E->get().pos >= sd->start) && (E->get().pos < sd->end)) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.y = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.y = -(E->get().rect.size.y / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.y = (-sd->ascent + sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.y = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.y = sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.y -= E->get().rect.size.y; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.y -= E->get().rect.size.y / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.y = sd->descent - E->get().rect.size.y; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.y); + full_descent = MAX(full_descent, E->get().rect.position.y + E->get().rect.size.y); } else { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.x = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.x = -(E->get().rect.size.x / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.x = (-sd->ascent + sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.x = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.x = sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.x -= E->get().rect.size.x; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.x -= E->get().rect.size.x / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.x = sd->descent - E->get().rect.size.x; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.x); + full_descent = MAX(full_descent, E->get().rect.position.x + E->get().rect.size.x); } } } + sd->ascent = full_ascent; + sd->descent = full_descent; } return true; } @@ -865,33 +881,9 @@ RID TextServerFallback::shaped_text_substr(RID p_shaped, int p_start, int p_leng if (new_sd->orientation == ORIENTATION_HORIZONTAL) { new_sd->objects[key].rect.position.x = new_sd->width; new_sd->width += new_sd->objects[key].rect.size.x; - switch (new_sd->objects[key].inline_align) { - case VALIGN_TOP: { - new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.y); - } break; - case VALIGN_CENTER: { - new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.y / 2)); - new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.y / 2)); - } break; - case VALIGN_BOTTOM: { - new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.y); - } break; - } } else { new_sd->objects[key].rect.position.y = new_sd->width; new_sd->width += new_sd->objects[key].rect.size.y; - switch (new_sd->objects[key].inline_align) { - case VALIGN_TOP: { - new_sd->ascent = MAX(new_sd->ascent, new_sd->objects[key].rect.size.x); - } break; - case VALIGN_CENTER: { - new_sd->ascent = MAX(new_sd->ascent, Math::round(new_sd->objects[key].rect.size.x / 2)); - new_sd->descent = MAX(new_sd->descent, Math::round(new_sd->objects[key].rect.size.x / 2)); - } break; - case VALIGN_BOTTOM: { - new_sd->descent = MAX(new_sd->descent, new_sd->objects[key].rect.size.x); - } break; - } } } else { const FontDataFallback *fd = font_owner.getornull(gl.font_rid); @@ -919,35 +911,72 @@ RID TextServerFallback::shaped_text_substr(RID p_shaped, int p_start, int p_leng } } + // Align embedded objects to baseline. + float full_ascent = new_sd->ascent; + float full_descent = new_sd->descent; for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = new_sd->objects.front(); E; E = E->next()) { if ((E->get().pos >= new_sd->start) && (E->get().pos < new_sd->end)) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.y = -new_sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.y = -(E->get().rect.size.y / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.y = (-new_sd->ascent + new_sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.y = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.y = new_sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.y -= E->get().rect.size.y; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.y -= E->get().rect.size.y / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.y = new_sd->descent - E->get().rect.size.y; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.y); + full_descent = MAX(full_descent, E->get().rect.position.y + E->get().rect.size.y); } else { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.x = -new_sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.x = -(E->get().rect.size.x / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.x = (-new_sd->ascent + new_sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.x = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.x = new_sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.x -= E->get().rect.size.x; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.x -= E->get().rect.size.x / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.x = new_sd->descent - E->get().rect.size.x; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.x); + full_descent = MAX(full_descent, E->get().rect.position.x + E->get().rect.size.x); } } } + new_sd->ascent = full_ascent; + new_sd->descent = full_descent; } new_sd->valid = true; @@ -1108,6 +1137,9 @@ bool TextServerFallback::shaped_text_update_breaks(RID p_shaped) { if (is_punct(c)) { sd->glyphs.write[i].flags |= GRAPHEME_IS_PUNCTUATION; } + if (is_underscore(c)) { + sd->glyphs.write[i].flags |= GRAPHEME_IS_UNDERSCORE; + } if (is_whitespace(c) && !is_linebreak(c)) { sd->glyphs.write[i].flags |= GRAPHEME_IS_SPACE; sd->glyphs.write[i].flags |= GRAPHEME_IS_BREAK_SOFT; @@ -1141,6 +1173,128 @@ bool TextServerFallback::shaped_text_update_justification_ops(RID p_shaped) { return true; } +void TextServerFallback::shaped_text_overrun_trim_to_width(RID p_shaped_line, float p_width, uint8_t p_trim_flags) { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped_line); + ERR_FAIL_COND_MSG(!sd, "ShapedTextDataAdvanced invalid."); + if (!sd->valid) { + shaped_text_shape(p_shaped_line); + } + + sd->overrun_trim_data.ellipsis_glyph_buf.clear(); + + bool add_ellipsis = (p_trim_flags & OVERRUN_ADD_ELLIPSIS) == OVERRUN_ADD_ELLIPSIS; + bool cut_per_word = (p_trim_flags & OVERRUN_TRIM_WORD_ONLY) == OVERRUN_TRIM_WORD_ONLY; + bool enforce_ellipsis = (p_trim_flags & OVERRUN_ENFORCE_ELLIPSIS) == OVERRUN_ENFORCE_ELLIPSIS; + bool justification_aware = (p_trim_flags & OVERRUN_JUSTIFICATION_AWARE) == OVERRUN_JUSTIFICATION_AWARE; + + Glyph *sd_glyphs = sd->glyphs.ptrw(); + + if ((p_trim_flags & OVERRUN_TRIM) == OVERRUN_NO_TRIMMING || sd_glyphs == nullptr || p_width <= 0 || !(sd->width > p_width || enforce_ellipsis)) { + sd->overrun_trim_data.trim_pos = -1; + sd->overrun_trim_data.ellipsis_pos = -1; + return; + } + + if (justification_aware && !sd->fit_width_minimum_reached) { + return; + } + + int sd_size = sd->glyphs.size(); + RID last_gl_font_rid = sd_glyphs[sd_size - 1].font_rid; + int last_gl_font_size = sd_glyphs[sd_size - 1].font_size; + uint32_t dot_gl_idx = font_get_glyph_index(last_gl_font_rid, '.'); + Vector2 dot_adv = font_get_glyph_advance(last_gl_font_rid, dot_gl_idx, last_gl_font_size); + uint32_t whitespace_gl_idx = font_get_glyph_index(last_gl_font_rid, ' '); + Vector2 whitespace_adv = font_get_glyph_advance(last_gl_font_rid, whitespace_gl_idx, last_gl_font_size); + + int ellipsis_width = 0; + if (add_ellipsis) { + ellipsis_width = 3 * dot_adv.x + font_get_spacing_glyph(last_gl_font_rid) + (cut_per_word ? whitespace_adv.x : 0); + } + + int ell_min_characters = 6; + float width = sd->width; + + int trim_pos = 0; + int ellipsis_pos = (enforce_ellipsis) ? 0 : -1; + + 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 (sd_glyphs[i].count > 0) { + bool above_min_char_treshold = (i >= ell_min_characters); + + if (width + (((above_min_char_treshold && add_ellipsis) || enforce_ellipsis) ? ellipsis_width : 0) <= p_width) { + if (cut_per_word && above_min_char_treshold) { + 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; + } + if (found) { + trim_pos = last_valid_cut; + + if (add_ellipsis && (above_min_char_treshold || enforce_ellipsis) && width - ellipsis_width <= p_width) { + ellipsis_pos = trim_pos; + } + break; + } + } + } + } + + sd->overrun_trim_data.trim_pos = trim_pos; + sd->overrun_trim_data.ellipsis_pos = ellipsis_pos; + if (trim_pos == 0 && enforce_ellipsis && add_ellipsis) { + sd->overrun_trim_data.ellipsis_pos = 0; + } + + if ((trim_pos >= 0 && sd->width > p_width) || enforce_ellipsis) { + if (add_ellipsis && (ellipsis_pos > 0 || enforce_ellipsis)) { + // Insert an additional space when cutting word bound for aesthetics. + if (cut_per_word && (ellipsis_pos > 0)) { + TextServer::Glyph gl; + gl.count = 1; + gl.advance = whitespace_adv.x; + gl.index = whitespace_gl_idx; + gl.font_rid = last_gl_font_rid; + gl.font_size = last_gl_font_size; + gl.flags = GRAPHEME_IS_SPACE | GRAPHEME_IS_BREAK_SOFT | GRAPHEME_IS_VIRTUAL; + + sd->overrun_trim_data.ellipsis_glyph_buf.append(gl); + } + // Add ellipsis dots. + TextServer::Glyph gl; + gl.count = 1; + gl.repeat = 3; + gl.advance = dot_adv.x; + gl.index = dot_gl_idx; + gl.font_rid = last_gl_font_rid; + gl.font_size = last_gl_font_size; + gl.flags = GRAPHEME_IS_PUNCTUATION | GRAPHEME_IS_VIRTUAL; + + sd->overrun_trim_data.ellipsis_glyph_buf.append(gl); + } + + sd->text_trimmed = true; + sd->width_trimmed = width + ((ellipsis_pos != -1) ? ellipsis_width : 0); + } +} + +TextServer::TrimData TextServerFallback::shaped_text_get_trim_data(RID p_shaped) const { + _THREAD_SAFE_METHOD_ + ShapedTextData *sd = shaped_owner.getornull(p_shaped); + ERR_FAIL_COND_V_MSG(!sd, TrimData(), "ShapedTextDataAdvanced invalid."); + return sd->overrun_trim_data; +} + bool TextServerFallback::shaped_text_shape(RID p_shaped) { _THREAD_SAFE_METHOD_ ShapedTextData *sd = shaped_owner.getornull(p_shaped); @@ -1174,33 +1328,9 @@ bool TextServerFallback::shaped_text_shape(RID p_shaped) { if (sd->orientation == ORIENTATION_HORIZONTAL) { sd->objects[span.embedded_key].rect.position.x = sd->width; sd->width += sd->objects[span.embedded_key].rect.size.x; - switch (sd->objects[span.embedded_key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.y); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.y / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.y); - } break; - } } else { sd->objects[span.embedded_key].rect.position.y = sd->width; sd->width += sd->objects[span.embedded_key].rect.size.y; - switch (sd->objects[span.embedded_key].inline_align) { - case VALIGN_TOP: { - sd->ascent = MAX(sd->ascent, sd->objects[span.embedded_key].rect.size.x); - } break; - case VALIGN_CENTER: { - sd->ascent = MAX(sd->ascent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2)); - sd->descent = MAX(sd->descent, Math::round(sd->objects[span.embedded_key].rect.size.x / 2)); - } break; - case VALIGN_BOTTOM: { - sd->descent = MAX(sd->descent, sd->objects[span.embedded_key].rect.size.x); - } break; - } } Glyph gl; gl.start = span.start; @@ -1294,34 +1424,69 @@ bool TextServerFallback::shaped_text_shape(RID p_shaped) { } // Align embedded objects to baseline. + float full_ascent = sd->ascent; + float full_descent = sd->descent; for (Map<Variant, ShapedTextData::EmbeddedObject>::Element *E = sd->objects.front(); E; E = E->next()) { if (sd->orientation == ORIENTATION_HORIZONTAL) { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.y = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.y = -(E->get().rect.size.y / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.y = (-sd->ascent + sd->descent) / 2; + } break; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.y = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.y = sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.y -= E->get().rect.size.y; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.y -= E->get().rect.size.y / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.y = sd->descent - E->get().rect.size.y; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.y); + full_descent = MAX(full_descent, E->get().rect.position.y + E->get().rect.size.y); } else { - switch (E->get().inline_align) { - case VALIGN_TOP: { + switch (E->get().inline_align & INLINE_ALIGN_TEXT_MASK) { + case INLINE_ALIGN_TO_TOP: { E->get().rect.position.x = -sd->ascent; } break; - case VALIGN_CENTER: { - E->get().rect.position.x = -(E->get().rect.size.x / 2); + case INLINE_ALIGN_TO_CENTER: { + E->get().rect.position.x = (-sd->ascent + sd->descent) / 2; } break; - case VALIGN_BOTTOM: { - E->get().rect.position.x = sd->descent - E->get().rect.size.x; + case INLINE_ALIGN_TO_BASELINE: { + E->get().rect.position.x = 0; + } break; + case INLINE_ALIGN_TO_BOTTOM: { + E->get().rect.position.x = sd->descent; + } break; + } + switch (E->get().inline_align & INLINE_ALIGN_IMAGE_MASK) { + case INLINE_ALIGN_BOTTOM_TO: { + E->get().rect.position.x -= E->get().rect.size.x; + } break; + case INLINE_ALIGN_CENTER_TO: { + E->get().rect.position.x -= E->get().rect.size.x / 2; + } break; + case INLINE_ALIGN_TOP_TO: { + //NOP } break; } + full_ascent = MAX(full_ascent, -E->get().rect.position.x); + full_descent = MAX(full_descent, E->get().rect.position.x + E->get().rect.size.x); } } - + sd->ascent = full_ascent; + sd->descent = full_descent; sd->valid = true; return sd->valid; } diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h index 8f5eb1d315..d4cab2409a 100644 --- a/modules/text_server_fb/text_server_fb.h +++ b/modules/text_server_fb/text_server_fb.h @@ -165,8 +165,8 @@ public: virtual bool shaped_text_get_preserve_control(RID p_shaped) const override; virtual bool shaped_text_add_string(RID p_shaped, const String &p_text, const Vector<RID> &p_fonts, int p_size, const Dictionary &p_opentype_features = Dictionary(), const String &p_language = "") override; - virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER, int p_length = 1) override; - virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, VAlign p_inline_align = VALIGN_CENTER) override; + virtual bool shaped_text_add_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align = INLINE_ALIGN_CENTER, int p_length = 1) override; + virtual bool shaped_text_resize_object(RID p_shaped, Variant p_key, const Size2 &p_size, InlineAlign p_inline_align = INLINE_ALIGN_CENTER) override; virtual RID shaped_text_substr(RID p_shaped, int p_start, int p_length) const override; virtual RID shaped_text_get_parent(RID p_shaped) const override; @@ -178,6 +178,9 @@ public: virtual bool shaped_text_update_breaks(RID p_shaped) override; virtual bool shaped_text_update_justification_ops(RID p_shaped) override; + virtual void shaped_text_overrun_trim_to_width(RID p_shaped, float p_width, uint8_t p_trim_flags) override; + virtual TrimData shaped_text_get_trim_data(RID p_shaped) const override; + virtual bool shaped_text_is_ready(RID p_shaped) const override; virtual Vector<Glyph> shaped_text_get_glyphs(RID p_shaped) const override; diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp index ef53661557..f0d7c335bd 100644 --- a/modules/tga/image_loader_tga.cpp +++ b/modules/tga/image_loader_tga.cpp @@ -35,7 +35,7 @@ #include "core/os/os.h" #include "core/string/print_string.h" -Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t p_pixel_size, uint8_t *p_uncompressed_buffer, size_t p_output_size) { +Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t p_pixel_size, uint8_t *p_uncompressed_buffer, size_t p_output_size, size_t p_input_size) { Error error; Vector<uint8_t> pixels; @@ -56,11 +56,14 @@ Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t compressed_pos += 1; count = (c & 0x7f) + 1; - if (output_pos + count * p_pixel_size > output_pos) { + if (output_pos + count * p_pixel_size > p_output_size) { return ERR_PARSE_ERROR; } if (c & 0x80) { + if (compressed_pos + p_pixel_size > p_input_size) { + return ERR_PARSE_ERROR; + } for (size_t i = 0; i < p_pixel_size; i++) { pixels_w[i] = p_compressed_buffer[compressed_pos]; compressed_pos += 1; @@ -72,6 +75,9 @@ Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t output_pos += p_pixel_size; } } else { + if (compressed_pos + count * p_pixel_size > p_input_size) { + return ERR_PARSE_ERROR; + } count *= p_pixel_size; for (size_t i = 0; i < count; i++) { p_uncompressed_buffer[output_pos] = p_compressed_buffer[compressed_pos]; @@ -83,7 +89,7 @@ Error ImageLoaderTGA::decode_tga_rle(const uint8_t *p_compressed_buffer, size_t return OK; } -Error ImageLoaderTGA::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_output_size) { +Error ImageLoaderTGA::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) { #define TGA_PUT_PIXEL(r, g, b, a) \ int image_data_ofs = ((y * width) + x); \ image_data_w[image_data_ofs * 4 + 0] = r; \ @@ -134,7 +140,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff if (p_is_monochrome) { while (y != y_end) { while (x != x_end) { - if (i > p_output_size) { + if (i >= p_input_size) { return ERR_PARSE_ERROR; } uint8_t shade = p_buffer[i]; @@ -150,7 +156,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff } else { while (y != y_end) { while (x != x_end) { - if (i > p_output_size) { + if (i >= p_input_size) { return ERR_PARSE_ERROR; } uint8_t index = p_buffer[i]; @@ -181,7 +187,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff } else if (p_header.pixel_depth == 24) { while (y != y_end) { while (x != x_end) { - if (i + 2 > p_output_size) { + if (i + 2 >= p_input_size) { return ERR_PARSE_ERROR; } @@ -200,7 +206,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff } else if (p_header.pixel_depth == 32) { while (y != y_end) { while (x != x_end) { - if (i + 3 > p_output_size) { + if (i + 3 >= p_input_size) { return ERR_PARSE_ERROR; } @@ -226,9 +232,9 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { Vector<uint8_t> src_image; - int src_image_len = f->get_len(); + uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); - ERR_FAIL_COND_V(src_image_len < (int)sizeof(tga_header_s), ERR_FILE_CORRUPT); + ERR_FAIL_COND_V(src_image_len < (int64_t)sizeof(tga_header_s), ERR_FILE_CORRUPT); src_image.resize(src_image_len); Error err = OK; @@ -307,7 +313,7 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force const uint8_t *buffer = nullptr; if (is_encoded) { - err = decode_tga_rle(src_image_r, pixel_size, uncompressed_buffer_w, buffer_size); + err = decode_tga_rle(src_image_r, pixel_size, uncompressed_buffer_w, buffer_size, src_image_len); if (err == OK) { uncompressed_buffer_r = uncompressed_buffer.ptr(); @@ -337,7 +343,7 @@ static Ref<Image> _tga_mem_loader_func(const uint8_t *p_tga, int p_size) { Error open_memfile_error = memfile.open_custom(p_tga, p_size); ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for TGA image buffer."); Ref<Image> img; - img.instance(); + img.instantiate(); Error load_error = ImageLoaderTGA().load_image(img, &memfile, false, 1.0f); ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load TGA image."); return img; diff --git a/modules/tga/image_loader_tga.h b/modules/tga/image_loader_tga.h index cb2ce07edd..e4463a322f 100644 --- a/modules/tga/image_loader_tga.h +++ b/modules/tga/image_loader_tga.h @@ -72,8 +72,8 @@ class ImageLoaderTGA : public ImageFormatLoader { uint8_t pixel_depth = 0; uint8_t image_descriptor = 0; }; - static Error decode_tga_rle(const uint8_t *p_compressed_buffer, size_t p_pixel_size, uint8_t *p_uncompressed_buffer, size_t p_output_size); - 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_output_size); + static Error decode_tga_rle(const uint8_t *p_compressed_buffer, size_t p_pixel_size, uint8_t *p_uncompressed_buffer, size_t p_output_size, size_t p_input_size); + 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, FileAccess *f, bool p_force_linear, float p_scale); diff --git a/modules/theora/doc_classes/VideoStreamTheora.xml b/modules/theora/doc_classes/VideoStreamTheora.xml index cb8852d5ef..e7bf9b202d 100644 --- a/modules/theora/doc_classes/VideoStreamTheora.xml +++ b/modules/theora/doc_classes/VideoStreamTheora.xml @@ -11,17 +11,14 @@ </tutorials> <methods> <method name="get_file"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the Ogg Theora video file handled by this [VideoStreamTheora]. </description> </method> <method name="set_file"> - <return type="void"> - </return> - <argument index="0" name="file" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="file" type="String" /> <description> Sets the Ogg Theora video file that this [VideoStreamTheora] resource handles. The [code]file[/code] name should have the [code].ogv[/code] extension. </description> diff --git a/modules/theora/register_types.cpp b/modules/theora/register_types.cpp index 0218b8c7a4..55148a6b87 100644 --- a/modules/theora/register_types.cpp +++ b/modules/theora/register_types.cpp @@ -35,10 +35,10 @@ static Ref<ResourceFormatLoaderTheora> resource_loader_theora; void register_theora_types() { - resource_loader_theora.instance(); + resource_loader_theora.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_theora, true); - ClassDB::register_class<VideoStreamTheora>(); + GDREGISTER_CLASS(VideoStreamTheora); } void unregister_theora_types() { diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp index 19f26c87cd..2f6faec8ec 100644 --- a/modules/theora/video_stream_theora.cpp +++ b/modules/theora/video_stream_theora.cpp @@ -58,7 +58,7 @@ int VideoStreamPlaybackTheora::buffer_data() { #else - int bytes = file->get_buffer((uint8_t *)buffer, 4096); + uint64_t bytes = file->get_buffer((uint8_t *)buffer, 4096); ogg_sync_wrote(&oy, bytes); return (bytes); @@ -108,7 +108,7 @@ void VideoStreamPlaybackTheora::video_write() { Ref<Image> img = memnew(Image(size.x, size.y, 0, Image::FORMAT_RGBA8, frame_data)); //zero copy image creation - texture->update(img, true); //zero copy send to visual server + texture->update(img); //zero copy send to visual server frames_pending = 1; } @@ -176,7 +176,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { thread_eof = false; //pre-fill buffer int to_read = ring_buffer.space_left(); - int read = file->get_buffer(read_buffer.ptr(), to_read); + uint64_t read = file->get_buffer(read_buffer.ptr(), to_read); ring_buffer.write(read_buffer.ptr(), read); thread.start(_streaming_thread, this); @@ -225,7 +225,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { /* identify the codec: try theora */ if (!theora_p && th_decode_headerin(&ti, &tc, &ts, &op) >= 0) { /* it is theora */ - copymem(&to, &test, sizeof(test)); + memcpy(&to, &test, sizeof(test)); theora_p = 1; } else if (!vorbis_p && vorbis_synthesis_headerin(&vi, &vc, &op) >= 0) { /* it is vorbis */ @@ -238,7 +238,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { audio_track_skip--; } else { - copymem(&vo, &test, sizeof(test)); + memcpy(&vo, &test, sizeof(test)); vorbis_p = 1; } } else { @@ -302,7 +302,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { } } - /* and now we have it all. initialize decoders */ + /* And now we have it all. Initialize decoders. */ if (theora_p) { td = th_decode_alloc(&ti, ts); px_fmt = ti.pixel_fmt; @@ -335,7 +335,7 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { size.y = h; Ref<Image> img; - img.instance(); + img.instantiate(); img->create(w, h, false, Image::FORMAT_RGBA8); } else { @@ -484,10 +484,10 @@ void VideoStreamPlaybackTheora::update(float p_delta) { //printf("frame time %f, play time %f, ready %i\n", (float)videobuf_time, get_time(), videobuf_ready); - /* is it already too old to be useful? This is only actually - useful cosmetically after a SIGSTOP. Note that we have to + /* is it already too old to be useful? This is only actually + useful cosmetically after a SIGSTOP. Note that we have to decode the frame even if we don't show it (for now) due to - keyframing. Soon enough libtheora will be able to deal + keyframing. Soon enough libtheora will be able to deal with non-keyframe seeks. */ if (videobuf_time >= get_time()) { @@ -632,8 +632,8 @@ void VideoStreamPlaybackTheora::_streaming_thread(void *ud) { //just fill back the buffer if (!vs->thread_eof) { int to_read = vs->ring_buffer.space_left(); - if (to_read) { - int read = vs->file->get_buffer(vs->read_buffer.ptr(), to_read); + if (to_read > 0) { + uint64_t read = vs->file->get_buffer(vs->read_buffer.ptr(), to_read); vs->ring_buffer.write(vs->read_buffer.ptr(), read); vs->thread_eof = vs->file->eof_reached(); } diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h index 2685a8a013..760173d0df 100644 --- a/modules/theora/video_stream_theora.h +++ b/modules/theora/video_stream_theora.h @@ -31,8 +31,8 @@ #ifndef VIDEO_STREAM_THEORA_H #define VIDEO_STREAM_THEORA_H +#include "core/io/file_access.h" #include "core/io/resource_loader.h" -#include "core/os/file_access.h" #include "core/os/semaphore.h" #include "core/os/thread.h" #include "core/templates/ring_buffer.h" diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp index 47214e6974..eb7a8597e6 100644 --- a/modules/tinyexr/image_loader_tinyexr.cpp +++ b/modules/tinyexr/image_loader_tinyexr.cpp @@ -37,7 +37,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { Vector<uint8_t> src_image; - int src_image_len = f->get_len(); + uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); src_image.resize(src_image_len); diff --git a/modules/tinyexr/image_saver_tinyexr.cpp b/modules/tinyexr/image_saver_tinyexr.cpp index f747763248..6a2fb0f666 100644 --- a/modules/tinyexr/image_saver_tinyexr.cpp +++ b/modules/tinyexr/image_saver_tinyexr.cpp @@ -169,7 +169,7 @@ Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale) { 0 }, // R { 1, 0 }, // GR { 2, 1, 0 }, // BGR - { 2, 1, 0, 3 } // BGRA + { 3, 2, 1, 0 } // ABGR }; int channel_count = get_channel_count(format); diff --git a/modules/upnp/doc_classes/UPNP.xml b/modules/upnp/doc_classes/UPNP.xml index 785c8dad50..5b1d9dbfd1 100644 --- a/modules/upnp/doc_classes/UPNP.xml +++ b/modules/upnp/doc_classes/UPNP.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="UPNP" inherits="Reference" version="4.0"> +<class name="UPNP" inherits="RefCounted" version="4.0"> <brief_description> UPNP network functions. </brief_description> @@ -21,27 +21,19 @@ </tutorials> <methods> <method name="add_device"> - <return type="void"> - </return> - <argument index="0" name="device" type="UPNPDevice"> - </argument> + <return type="void" /> + <argument index="0" name="device" type="UPNPDevice" /> <description> Adds the given [UPNPDevice] to the list of discovered devices. </description> </method> <method name="add_port_mapping" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="port" type="int"> - </argument> - <argument index="1" name="port_internal" type="int" default="0"> - </argument> - <argument index="2" name="desc" type="String" default=""""> - </argument> - <argument index="3" name="proto" type="String" default=""UDP""> - </argument> - <argument index="4" name="duration" type="int" default="0"> - </argument> + <return type="int" /> + <argument index="0" name="port" type="int" /> + <argument index="1" name="port_internal" type="int" default="0" /> + <argument index="2" name="desc" type="String" default="""" /> + <argument index="3" name="proto" type="String" default=""UDP"" /> + <argument index="4" name="duration" type="int" default="0" /> <description> Adds a mapping to forward the external [code]port[/code] (between 1 and 65535) 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. 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). @@ -50,32 +42,24 @@ </description> </method> <method name="clear_devices"> - <return type="void"> - </return> + <return type="void" /> <description> Clears the list of discovered devices. </description> </method> <method name="delete_port_mapping" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="port" type="int"> - </argument> - <argument index="1" name="proto" type="String" default=""UDP""> - </argument> + <return type="int" /> + <argument index="0" name="port" type="int" /> + <argument 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]. See [enum UPNPResult] for possible return values. </description> </method> <method name="discover"> - <return type="int"> - </return> - <argument index="0" name="timeout" type="int" default="2000"> - </argument> - <argument index="1" name="ttl" type="int" default="2"> - </argument> - <argument index="2" name="device_filter" type="String" default=""InternetGatewayDevice""> - </argument> + <return type="int" /> + <argument index="0" name="timeout" type="int" default="2000" /> + <argument index="1" name="ttl" type="int" default="2" /> + <argument index="2" name="device_filter" type="String" default=""InternetGatewayDevice"" /> <description> Discovers local [UPNPDevice]s. Clears the list of previously discovered devices. Filters for IGD (InternetGatewayDevice) type devices by default, as those manage port forwarding. [code]timeout[/code] is the time to wait for responses in milliseconds. [code]ttl[/code] is the time-to-live; only touch this if you know what you're doing. @@ -83,51 +67,41 @@ </description> </method> <method name="get_device" qualifiers="const"> - <return type="UPNPDevice"> - </return> - <argument index="0" name="index" type="int"> - </argument> + <return type="UPNPDevice" /> + <argument index="0" name="index" type="int" /> <description> Returns the [UPNPDevice] at the given [code]index[/code]. </description> </method> <method name="get_device_count" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Returns the number of discovered [UPNPDevice]s. </description> </method> <method name="get_gateway" qualifiers="const"> - <return type="UPNPDevice"> - </return> + <return type="UPNPDevice" /> <description> Returns the default gateway. That is the first discovered [UPNPDevice] that is also a valid IGD (InternetGatewayDevice). </description> </method> <method name="query_external_address" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the external [IP] address of the default gateway (see [method get_gateway]) as string. Returns an empty string on error. </description> </method> <method name="remove_device"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> <description> Removes the device at [code]index[/code] from the list of discovered devices. </description> </method> <method name="set_device"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> - <argument index="1" name="device" type="UPNPDevice"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> + <argument index="1" name="device" type="UPNPDevice" /> <description> Sets the device at [code]index[/code] from the list of discovered devices to [code]device[/code]. </description> diff --git a/modules/upnp/doc_classes/UPNPDevice.xml b/modules/upnp/doc_classes/UPNPDevice.xml index f3b96bb89d..b7c2ff7dd7 100644 --- a/modules/upnp/doc_classes/UPNPDevice.xml +++ b/modules/upnp/doc_classes/UPNPDevice.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="UPNPDevice" inherits="Reference" version="4.0"> +<class name="UPNPDevice" inherits="RefCounted" version="4.0"> <brief_description> UPNP device. </brief_description> @@ -10,43 +10,32 @@ </tutorials> <methods> <method name="add_port_mapping" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="port" type="int"> - </argument> - <argument index="1" name="port_internal" type="int" default="0"> - </argument> - <argument index="2" name="desc" type="String" default=""""> - </argument> - <argument index="3" name="proto" type="String" default=""UDP""> - </argument> - <argument index="4" name="duration" type="int" default="0"> - </argument> + <return type="int" /> + <argument index="0" name="port" type="int" /> + <argument index="1" name="port_internal" type="int" default="0" /> + <argument index="2" name="desc" type="String" default="""" /> + <argument index="3" name="proto" type="String" default=""UDP"" /> + <argument index="4" name="duration" type="int" default="0" /> <description> Adds a port mapping to forward the given external port on this [UPNPDevice] for the given protocol to the local machine. See [method UPNP.add_port_mapping]. </description> </method> <method name="delete_port_mapping" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="port" type="int"> - </argument> - <argument index="1" name="proto" type="String" default=""UDP""> - </argument> + <return type="int" /> + <argument index="0" name="port" type="int" /> + <argument index="1" name="proto" type="String" default=""UDP"" /> <description> Deletes the port mapping identified by the given port and protocol combination on this device. See [method UPNP.delete_port_mapping]. </description> </method> <method name="is_valid_gateway" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns [code]true[/code] if this is a valid IGD (InternetGatewayDevice) which potentially supports port forwarding. </description> </method> <method name="query_external_address" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the external IP address of this [UPNPDevice] or an empty string. </description> diff --git a/modules/upnp/register_types.cpp b/modules/upnp/register_types.cpp index a5ee39517f..1e5edd3602 100644 --- a/modules/upnp/register_types.cpp +++ b/modules/upnp/register_types.cpp @@ -36,8 +36,8 @@ #include "upnp_device.h" void register_upnp_types() { - ClassDB::register_class<UPNP>(); - ClassDB::register_class<UPNPDevice>(); + GDREGISTER_CLASS(UPNP); + GDREGISTER_CLASS(UPNPDevice); } void unregister_upnp_types() { diff --git a/modules/upnp/upnp.cpp b/modules/upnp/upnp.cpp index 8e4e833d45..efe618012a 100644 --- a/modules/upnp/upnp.cpp +++ b/modules/upnp/upnp.cpp @@ -92,7 +92,7 @@ int UPNP::discover(int timeout, int ttl, const String &device_filter) { void UPNP::add_device_to_list(UPNPDev *dev, UPNPDev *devlist) { Ref<UPNPDevice> new_device; - new_device.instance(); + new_device.instantiate(); new_device->set_description_url(dev->descURL); new_device->set_service_type(dev->st); diff --git a/modules/upnp/upnp.h b/modules/upnp/upnp.h index a0cca96bc8..b961a9667f 100644 --- a/modules/upnp/upnp.h +++ b/modules/upnp/upnp.h @@ -31,14 +31,14 @@ #ifndef GODOT_UPNP_H #define GODOT_UPNP_H -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "upnp_device.h" #include <miniupnpc/miniupnpc.h> -class UPNP : public Reference { - GDCLASS(UPNP, Reference); +class UPNP : public RefCounted { + GDCLASS(UPNP, RefCounted); private: String discover_multicast_if = ""; diff --git a/modules/upnp/upnp_device.h b/modules/upnp/upnp_device.h index 126e761a56..0a66c36ab9 100644 --- a/modules/upnp/upnp_device.h +++ b/modules/upnp/upnp_device.h @@ -31,10 +31,10 @@ #ifndef GODOT_UPNP_DEVICE_H #define GODOT_UPNP_DEVICE_H -#include "core/object/reference.h" +#include "core/object/ref_counted.h" -class UPNPDevice : public Reference { - GDCLASS(UPNPDevice, Reference); +class UPNPDevice : public RefCounted { + GDCLASS(UPNPDevice, RefCounted); public: enum IGDStatus { diff --git a/modules/vhacd/config.py b/modules/vhacd/config.py index d22f9454ed..a42f27fbe1 100644 --- a/modules/vhacd/config.py +++ b/modules/vhacd/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return True + return not env["disable_3d"] def configure(env): diff --git a/modules/vhacd/register_types.cpp b/modules/vhacd/register_types.cpp index daad39bdfb..2b48e94604 100644 --- a/modules/vhacd/register_types.cpp +++ b/modules/vhacd/register_types.cpp @@ -32,8 +32,8 @@ #include "scene/resources/mesh.h" #include "thirdparty/vhacd/public/VHACD.h" -static Vector<Vector<Face3>> convex_decompose(const Vector<Face3> &p_faces) { - Vector<float> vertices; +static Vector<Vector<Face3>> convex_decompose(const Vector<Face3> &p_faces, int p_max_convex_hulls = -1) { + Vector<real_t> vertices; vertices.resize(p_faces.size() * 9); Vector<uint32_t> indices; indices.resize(p_faces.size() * 3); @@ -47,8 +47,12 @@ static Vector<Vector<Face3>> convex_decompose(const Vector<Face3> &p_faces) { } } - VHACD::IVHACD *decomposer = VHACD::CreateVHACD(); VHACD::IVHACD::Parameters params; + if (p_max_convex_hulls > 0) { + params.m_maxConvexHulls = p_max_convex_hulls; + } + + VHACD::IVHACD *decomposer = VHACD::CreateVHACD(); decomposer->Compute(vertices.ptr(), vertices.size() / 3, indices.ptr(), indices.size() / 3, params); int hull_count = decomposer->GetNConvexHulls(); diff --git a/modules/visual_script/doc_classes/VisualScript.xml b/modules/visual_script/doc_classes/VisualScript.xml index 5112ea43a7..2327fc0009 100644 --- a/modules/visual_script/doc_classes/VisualScript.xml +++ b/modules/visual_script/doc_classes/VisualScript.xml @@ -4,7 +4,7 @@ A script implemented in the Visual Script programming environment. </brief_description> <description> - A script implemented in the Visual Script programming environment. The script extends the functionality of all objects that instance it. + A script implemented in the Visual Script programming environment. The script extends the functionality of all objects that instance it. [method Object.set_script] extends an existing object, if that object's class matches one of the script's base classes. You are most likely to use this class via the Visual Script editor or when writing plugins for it. </description> @@ -13,456 +13,334 @@ </tutorials> <methods> <method name="add_custom_signal"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> <description> Add a custom signal with the specified name to the VisualScript. </description> </method> <method name="add_function"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="func_node_id" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="func_node_id" type="int" /> <description> Add a function with the specified name to the VisualScript, and assign the root [VisualScriptFunction] node's id as [code]func_node_id[/code]. </description> </method> <method name="add_node"> - <return type="void"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="node" type="VisualScriptNode"> - </argument> - <argument index="2" name="position" type="Vector2" default="Vector2( 0, 0 )"> - </argument> + <return type="void" /> + <argument index="0" name="id" type="int" /> + <argument index="1" name="node" type="VisualScriptNode" /> + <argument index="2" name="position" type="Vector2" default="Vector2(0, 0)" /> <description> Add a node to the VisualScript. </description> </method> <method name="add_variable"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="default_value" type="Variant" default="null"> - </argument> - <argument index="2" name="export" type="bool" default="false"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="default_value" type="Variant" default="null" /> + <argument index="2" name="export" type="bool" default="false" /> <description> Add a variable to the VisualScript, optionally giving it a default value or marking it as exported. </description> </method> <method name="custom_signal_add_argument"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="type" type="int" enum="Variant.Type"> - </argument> - <argument index="2" name="argname" type="String"> - </argument> - <argument index="3" name="index" type="int" default="-1"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="type" type="int" enum="Variant.Type" /> + <argument index="2" name="argname" type="String" /> + <argument index="3" name="index" type="int" default="-1" /> <description> Add an argument to a custom signal added with [method add_custom_signal]. </description> </method> <method name="custom_signal_get_argument_count" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="int" /> + <argument index="0" name="name" type="StringName" /> <description> Get the count of a custom signal's arguments. </description> </method> <method name="custom_signal_get_argument_name" qualifiers="const"> - <return type="String"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="argidx" type="int"> - </argument> + <return type="String" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="argidx" type="int" /> <description> Get the name of a custom signal's argument. </description> </method> <method name="custom_signal_get_argument_type" qualifiers="const"> - <return type="int" enum="Variant.Type"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="argidx" type="int"> - </argument> + <return type="int" enum="Variant.Type" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="argidx" type="int" /> <description> Get the type of a custom signal's argument. </description> </method> <method name="custom_signal_remove_argument"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="argidx" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="argidx" type="int" /> <description> Remove a specific custom signal's argument. </description> </method> <method name="custom_signal_set_argument_name"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="argidx" type="int"> - </argument> - <argument index="2" name="argname" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="argidx" type="int" /> + <argument index="2" name="argname" type="String" /> <description> Rename a custom signal's argument. </description> </method> <method name="custom_signal_set_argument_type"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="argidx" type="int"> - </argument> - <argument index="2" name="type" type="int" enum="Variant.Type"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="argidx" type="int" /> + <argument index="2" name="type" type="int" enum="Variant.Type" /> <description> Change the type of a custom signal's argument. </description> </method> <method name="custom_signal_swap_argument"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="argidx" type="int"> - </argument> - <argument index="2" name="withidx" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="argidx" type="int" /> + <argument index="2" name="withidx" type="int" /> <description> Swap two of the arguments of a custom signal. </description> </method> <method name="data_connect"> - <return type="void"> - </return> - <argument index="0" name="from_node" type="int"> - </argument> - <argument index="1" name="from_port" type="int"> - </argument> - <argument index="2" name="to_node" type="int"> - </argument> - <argument index="3" name="to_port" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="from_node" type="int" /> + <argument index="1" name="from_port" type="int" /> + <argument index="2" name="to_node" type="int" /> + <argument index="3" name="to_port" type="int" /> <description> Connect two data ports. The value of [code]from_node[/code]'s [code]from_port[/code] would be fed into [code]to_node[/code]'s [code]to_port[/code]. </description> </method> <method name="data_disconnect"> - <return type="void"> - </return> - <argument index="0" name="from_node" type="int"> - </argument> - <argument index="1" name="from_port" type="int"> - </argument> - <argument index="2" name="to_node" type="int"> - </argument> - <argument index="3" name="to_port" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="from_node" type="int" /> + <argument index="1" name="from_port" type="int" /> + <argument index="2" name="to_node" type="int" /> + <argument index="3" name="to_port" type="int" /> <description> Disconnect two data ports previously connected with [method data_connect]. </description> </method> <method name="get_function_node_id" qualifiers="const"> - <return type="int"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="int" /> + <argument index="0" name="name" type="StringName" /> <description> Returns the id of a function's entry point node. </description> </method> <method name="get_node" qualifiers="const"> - <return type="VisualScriptNode"> - </return> - <argument index="0" name="id" type="int"> - </argument> + <return type="VisualScriptNode" /> + <argument index="0" name="id" type="int" /> <description> Returns a node given its id. </description> </method> <method name="get_node_position" qualifiers="const"> - <return type="Vector2"> - </return> - <argument index="0" name="id" type="int"> - </argument> + <return type="Vector2" /> + <argument index="0" name="id" type="int" /> <description> Returns a node's position in pixels. </description> </method> <method name="get_scroll" qualifiers="const"> - <return type="Vector2"> - </return> + <return type="Vector2" /> <description> Returns the current position of the center of the screen. </description> </method> <method name="get_variable_default_value" qualifiers="const"> - <return type="Variant"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="Variant" /> + <argument index="0" name="name" type="StringName" /> <description> Returns the default (initial) value of a variable. </description> </method> <method name="get_variable_export" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="bool" /> + <argument index="0" name="name" type="StringName" /> <description> Returns whether a variable is exported. </description> </method> <method name="get_variable_info" qualifiers="const"> - <return type="Dictionary"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="Dictionary" /> + <argument index="0" name="name" type="StringName" /> <description> Returns the information for a given variable as a dictionary. The information includes its name, type, hint and usage. </description> </method> <method name="has_custom_signal" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="bool" /> + <argument index="0" name="name" type="StringName" /> <description> Returns whether a signal exists with the specified name. </description> </method> <method name="has_data_connection" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="from_node" type="int"> - </argument> - <argument index="1" name="from_port" type="int"> - </argument> - <argument index="2" name="to_node" type="int"> - </argument> - <argument index="3" name="to_port" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="from_node" type="int" /> + <argument index="1" name="from_port" type="int" /> + <argument index="2" name="to_node" type="int" /> + <argument index="3" name="to_port" type="int" /> <description> Returns whether the specified data ports are connected. </description> </method> <method name="has_function" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="bool" /> + <argument index="0" name="name" type="StringName" /> <description> Returns whether a function exists with the specified name. </description> </method> <method name="has_node" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="id" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="id" type="int" /> <description> Returns whether a node exists with the given id. </description> </method> <method name="has_sequence_connection" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="from_node" type="int"> - </argument> - <argument index="1" name="from_output" type="int"> - </argument> - <argument index="2" name="to_node" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="from_node" type="int" /> + <argument index="1" name="from_output" type="int" /> + <argument index="2" name="to_node" type="int" /> <description> Returns whether the specified sequence ports are connected. </description> </method> <method name="has_variable" qualifiers="const"> - <return type="bool"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="bool" /> + <argument index="0" name="name" type="StringName" /> <description> Returns whether a variable exists with the specified name. </description> </method> <method name="remove_custom_signal"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> <description> Remove a custom signal with the given name. </description> </method> <method name="remove_function"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> <description> Remove a specific function and its nodes from the script. </description> </method> <method name="remove_node"> - <return type="void"> - </return> - <argument index="0" name="id" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="id" type="int" /> <description> Remove the node with the specified id. </description> </method> <method name="remove_variable"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> <description> Remove a variable with the given name. </description> </method> <method name="rename_custom_signal"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="new_name" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="new_name" type="StringName" /> <description> Change the name of a custom signal. </description> </method> <method name="rename_function"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="new_name" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="new_name" type="StringName" /> <description> Change the name of a function. </description> </method> <method name="rename_variable"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="new_name" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="new_name" type="StringName" /> <description> Change the name of a variable. </description> </method> <method name="sequence_connect"> - <return type="void"> - </return> - <argument index="0" name="from_node" type="int"> - </argument> - <argument index="1" name="from_output" type="int"> - </argument> - <argument index="2" name="to_node" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="from_node" type="int" /> + <argument index="1" name="from_output" type="int" /> + <argument index="2" name="to_node" type="int" /> <description> Connect two sequence ports. The execution will flow from of [code]from_node[/code]'s [code]from_output[/code] into [code]to_node[/code]. Unlike [method data_connect], there isn't a [code]to_port[/code], since the target node can have only one sequence port. </description> </method> <method name="sequence_disconnect"> - <return type="void"> - </return> - <argument index="0" name="from_node" type="int"> - </argument> - <argument index="1" name="from_output" type="int"> - </argument> - <argument index="2" name="to_node" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="from_node" type="int" /> + <argument index="1" name="from_output" type="int" /> + <argument index="2" name="to_node" type="int" /> <description> Disconnect two sequence ports previously connected with [method sequence_connect]. </description> </method> <method name="set_instance_base_type"> - <return type="void"> - </return> - <argument index="0" name="type" type="StringName"> - </argument> + <return type="void" /> + <argument index="0" name="type" type="StringName" /> <description> Set the base type of the script. </description> </method> <method name="set_node_position"> - <return type="void"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="position" type="Vector2"> - </argument> + <return type="void" /> + <argument index="0" name="id" type="int" /> + <argument index="1" name="position" type="Vector2" /> <description> Set the node position in the VisualScript graph. </description> </method> <method name="set_scroll"> - <return type="void"> - </return> - <argument index="0" name="ofs" type="Vector2"> - </argument> + <return type="void" /> + <argument index="0" name="ofs" type="Vector2" /> <description> Set the screen center to the given position. </description> </method> <method name="set_variable_default_value"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="value" type="Variant"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="value" type="Variant" /> <description> Change the default (initial) value of a variable. </description> </method> <method name="set_variable_export"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="enable" type="bool"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="enable" type="bool" /> <description> Change whether a variable is exported. </description> </method> <method name="set_variable_info"> - <return type="void"> - </return> - <argument index="0" name="name" type="StringName"> - </argument> - <argument index="1" name="value" type="Dictionary"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="value" type="Dictionary" /> <description> Set a variable's info, using the same format as [method get_variable_info]. </description> @@ -470,8 +348,7 @@ </methods> <signals> <signal name="node_ports_changed"> - <argument index="0" name="id" type="int"> - </argument> + <argument index="0" name="id" type="int" /> <description> Emitted when the ports of a node are changed. </description> diff --git a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml index 219ffd01d3..195d766c1d 100644 --- a/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml +++ b/modules/visual_script/doc_classes/VisualScriptBuiltinFunc.xml @@ -105,117 +105,114 @@ <constant name="MATH_MOVE_TOWARD" value="29" enum="BuiltinFunc"> Moves the number toward a value, based on the third input. </constant> - <constant name="MATH_DECTIME" value="30" enum="BuiltinFunc"> - Return the result of [code]value[/code] decreased by [code]step[/code] * [code]amount[/code]. - </constant> - <constant name="MATH_RANDOMIZE" value="31" enum="BuiltinFunc"> + <constant name="MATH_RANDOMIZE" value="30" enum="BuiltinFunc"> Randomize the seed (or the internal state) of the random number generator. Current implementation reseeds using a number based on time. </constant> - <constant name="MATH_RANDI" value="32" enum="BuiltinFunc"> + <constant name="MATH_RANDI" value="31" enum="BuiltinFunc"> Return a random 32 bits integer value. To obtain a random value between 0 to N (where N is smaller than 2^32 - 1), you can use it with the remainder function. </constant> - <constant name="MATH_RANDF" value="33" enum="BuiltinFunc"> + <constant name="MATH_RANDF" value="32" enum="BuiltinFunc"> Return a random floating-point value between 0 and 1. To obtain a random value between 0 to N, you can use it with multiplication. </constant> - <constant name="MATH_RANDF_RANGE" value="34" enum="BuiltinFunc"> + <constant name="MATH_RANDF_RANGE" value="33" enum="BuiltinFunc"> Return a random floating-point value between the two inputs. </constant> - <constant name="MATH_RANDI_RANGE" value="35" enum="BuiltinFunc"> + <constant name="MATH_RANDI_RANGE" value="34" enum="BuiltinFunc"> Return a random 32-bit integer value between the two inputs. </constant> - <constant name="MATH_SEED" value="36" enum="BuiltinFunc"> + <constant name="MATH_SEED" value="35" enum="BuiltinFunc"> Set the seed for the random number generator. </constant> - <constant name="MATH_RANDSEED" value="37" enum="BuiltinFunc"> + <constant name="MATH_RANDSEED" value="36" enum="BuiltinFunc"> Return a random value from the given seed, along with the new seed. </constant> - <constant name="MATH_DEG2RAD" value="38" enum="BuiltinFunc"> + <constant name="MATH_DEG2RAD" value="37" enum="BuiltinFunc"> Convert the input from degrees to radians. </constant> - <constant name="MATH_RAD2DEG" value="39" enum="BuiltinFunc"> + <constant name="MATH_RAD2DEG" value="38" enum="BuiltinFunc"> Convert the input from radians to degrees. </constant> - <constant name="MATH_LINEAR2DB" value="40" enum="BuiltinFunc"> + <constant name="MATH_LINEAR2DB" value="39" enum="BuiltinFunc"> Convert the input from linear volume to decibel volume. </constant> - <constant name="MATH_DB2LINEAR" value="41" enum="BuiltinFunc"> + <constant name="MATH_DB2LINEAR" value="40" enum="BuiltinFunc"> Convert the input from decibel volume to linear volume. </constant> - <constant name="MATH_POLAR2CARTESIAN" value="42" enum="BuiltinFunc"> + <constant name="MATH_POLAR2CARTESIAN" value="41" enum="BuiltinFunc"> Converts a 2D point expressed in the polar coordinate system (a distance from the origin [code]r[/code] and an angle [code]th[/code]) to the cartesian coordinate system (X and Y axis). </constant> - <constant name="MATH_CARTESIAN2POLAR" value="43" enum="BuiltinFunc"> + <constant name="MATH_CARTESIAN2POLAR" value="42" enum="BuiltinFunc"> Converts a 2D point expressed in the cartesian coordinate system (X and Y axis) to the polar coordinate system (a distance from the origin and an angle). </constant> - <constant name="MATH_WRAP" value="44" enum="BuiltinFunc"> + <constant name="MATH_WRAP" value="43" enum="BuiltinFunc"> </constant> - <constant name="MATH_WRAPF" value="45" enum="BuiltinFunc"> + <constant name="MATH_WRAPF" value="44" enum="BuiltinFunc"> </constant> - <constant name="LOGIC_MAX" value="46" enum="BuiltinFunc"> + <constant name="LOGIC_MAX" value="45" enum="BuiltinFunc"> Return the greater of the two numbers, also known as their maximum. </constant> - <constant name="LOGIC_MIN" value="47" enum="BuiltinFunc"> + <constant name="LOGIC_MIN" value="46" enum="BuiltinFunc"> Return the lesser of the two numbers, also known as their minimum. </constant> - <constant name="LOGIC_CLAMP" value="48" enum="BuiltinFunc"> + <constant name="LOGIC_CLAMP" value="47" enum="BuiltinFunc"> Return the input clamped inside the given range, ensuring the result is never outside it. Equivalent to [code]min(max(input, range_low), range_high)[/code]. </constant> - <constant name="LOGIC_NEAREST_PO2" value="49" enum="BuiltinFunc"> + <constant name="LOGIC_NEAREST_PO2" value="48" enum="BuiltinFunc"> Return the nearest power of 2 to the input. </constant> - <constant name="OBJ_WEAKREF" value="50" enum="BuiltinFunc"> + <constant name="OBJ_WEAKREF" value="49" enum="BuiltinFunc"> Create a [WeakRef] from the input. </constant> - <constant name="TYPE_CONVERT" value="51" enum="BuiltinFunc"> + <constant name="TYPE_CONVERT" value="50" enum="BuiltinFunc"> Convert between types. </constant> - <constant name="TYPE_OF" value="52" enum="BuiltinFunc"> + <constant name="TYPE_OF" value="51" enum="BuiltinFunc"> Return the type of the input as an integer. Check [enum Variant.Type] for the integers that might be returned. </constant> - <constant name="TYPE_EXISTS" value="53" enum="BuiltinFunc"> + <constant name="TYPE_EXISTS" value="52" enum="BuiltinFunc"> Checks if a type is registered in the [ClassDB]. </constant> - <constant name="TEXT_CHAR" value="54" enum="BuiltinFunc"> + <constant name="TEXT_CHAR" value="53" enum="BuiltinFunc"> Return a character with the given ascii value. </constant> - <constant name="TEXT_STR" value="55" enum="BuiltinFunc"> + <constant name="TEXT_STR" value="54" enum="BuiltinFunc"> Convert the input to a string. </constant> - <constant name="TEXT_PRINT" value="56" enum="BuiltinFunc"> + <constant name="TEXT_PRINT" value="55" enum="BuiltinFunc"> Print the given string to the output window. </constant> - <constant name="TEXT_PRINTERR" value="57" enum="BuiltinFunc"> + <constant name="TEXT_PRINTERR" value="56" enum="BuiltinFunc"> Print the given string to the standard error output. </constant> - <constant name="TEXT_PRINTRAW" value="58" enum="BuiltinFunc"> + <constant name="TEXT_PRINTRAW" value="57" enum="BuiltinFunc"> Print the given string to the standard output, without adding a newline. </constant> - <constant name="VAR_TO_STR" value="59" enum="BuiltinFunc"> + <constant name="VAR_TO_STR" value="58" enum="BuiltinFunc"> Serialize a [Variant] to a string. </constant> - <constant name="STR_TO_VAR" value="60" enum="BuiltinFunc"> + <constant name="STR_TO_VAR" value="59" enum="BuiltinFunc"> Deserialize a [Variant] from a string serialized using [constant VAR_TO_STR]. </constant> - <constant name="VAR_TO_BYTES" value="61" enum="BuiltinFunc"> + <constant name="VAR_TO_BYTES" value="60" enum="BuiltinFunc"> Serialize a [Variant] to a [PackedByteArray]. </constant> - <constant name="BYTES_TO_VAR" value="62" enum="BuiltinFunc"> + <constant name="BYTES_TO_VAR" value="61" enum="BuiltinFunc"> Deserialize a [Variant] from a [PackedByteArray] serialized using [constant VAR_TO_BYTES]. </constant> - <constant name="MATH_SMOOTHSTEP" value="63" enum="BuiltinFunc"> + <constant name="MATH_SMOOTHSTEP" value="62" enum="BuiltinFunc"> Return a number smoothly interpolated between the first two inputs, based on the third input. Similar to [constant MATH_LERP], but interpolates faster at the beginning and slower at the end. Using Hermite interpolation formula: [codeblock] var t = clamp((weight - from) / (to - from), 0.0, 1.0) return t * t * (3.0 - 2.0 * t) [/codeblock] </constant> - <constant name="MATH_POSMOD" value="64" enum="BuiltinFunc"> + <constant name="MATH_POSMOD" value="63" enum="BuiltinFunc"> </constant> - <constant name="MATH_LERP_ANGLE" value="65" enum="BuiltinFunc"> + <constant name="MATH_LERP_ANGLE" value="64" enum="BuiltinFunc"> </constant> - <constant name="TEXT_ORD" value="66" enum="BuiltinFunc"> + <constant name="TEXT_ORD" value="65" enum="BuiltinFunc"> </constant> - <constant name="FUNC_MAX" value="67" enum="BuiltinFunc"> + <constant name="FUNC_MAX" value="66" enum="BuiltinFunc"> Represents the size of the [enum BuiltinFunc] enum. </constant> </constants> diff --git a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml index de5d731cc0..d6b96957f5 100644 --- a/modules/visual_script/doc_classes/VisualScriptClassConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptClassConstant.xml @@ -15,10 +15,10 @@ <methods> </methods> <members> - <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="@"Object""> + <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&"Object""> The constant's parent class. </member> - <member name="constant" type="StringName" setter="set_class_constant" getter="get_class_constant" default="@"""> + <member name="constant" type="StringName" setter="set_class_constant" getter="get_class_constant" default="&"""> The constant to return. See the given class for its available constants. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptComment.xml b/modules/visual_script/doc_classes/VisualScriptComment.xml index 243338ea52..02cec97b27 100644 --- a/modules/visual_script/doc_classes/VisualScriptComment.xml +++ b/modules/visual_script/doc_classes/VisualScriptComment.xml @@ -15,7 +15,7 @@ <member name="description" type="String" setter="set_description" getter="get_description" default=""""> The text inside the comment node. </member> - <member name="size" type="Vector2" setter="set_size" getter="get_size" default="Vector2( 150, 150 )"> + <member name="size" type="Vector2" setter="set_size" getter="get_size" default="Vector2(150, 150)"> The comment node's size (in pixels). </member> <member name="title" type="String" setter="set_title" getter="get_title" default=""Comment""> diff --git a/modules/visual_script/doc_classes/VisualScriptConstructor.xml b/modules/visual_script/doc_classes/VisualScriptConstructor.xml index 2f162e78b6..4743594ec3 100644 --- a/modules/visual_script/doc_classes/VisualScriptConstructor.xml +++ b/modules/visual_script/doc_classes/VisualScriptConstructor.xml @@ -10,30 +10,24 @@ </tutorials> <methods> <method name="get_constructor" qualifiers="const"> - <return type="Dictionary"> - </return> + <return type="Dictionary" /> <description> </description> </method> <method name="get_constructor_type" qualifiers="const"> - <return type="int" enum="Variant.Type"> - </return> + <return type="int" enum="Variant.Type" /> <description> </description> </method> <method name="set_constructor"> - <return type="void"> - </return> - <argument index="0" name="constructor" type="Dictionary"> - </argument> + <return type="void" /> + <argument index="0" name="constructor" type="Dictionary" /> <description> </description> </method> <method name="set_constructor_type"> - <return type="void"> - </return> - <argument index="0" name="type" type="int" enum="Variant.Type"> - </argument> + <return type="void" /> + <argument index="0" name="type" type="int" enum="Variant.Type" /> <description> </description> </method> diff --git a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml index 1c23b58507..8aa34f8cae 100644 --- a/modules/visual_script/doc_classes/VisualScriptCustomNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptCustomNode.xml @@ -10,117 +10,122 @@ </tutorials> <methods> <method name="_get_caption" qualifiers="virtual"> - <return type="String"> - </return> + <return type="String" /> <description> Return the node's title. </description> </method> <method name="_get_category" qualifiers="virtual"> - <return type="String"> - </return> + <return type="String" /> <description> Return the node's category. </description> </method> <method name="_get_input_value_port_count" qualifiers="virtual"> - <return type="int"> - </return> + <return type="int" /> <description> Return the count of input value ports. </description> </method> + <method name="_get_input_value_port_hint" qualifiers="virtual"> + <return type="int" /> + <argument index="0" name="idx" type="int" /> + <description> + Return the specified input port's hint. See the [enum @GlobalScope.PropertyHint] hints. + </description> + </method> + <method name="_get_input_value_port_hint_string" qualifiers="virtual"> + <return type="String" /> + <argument index="0" name="idx" type="int" /> + <description> + Return the specified input port's hint string. + </description> + </method> <method name="_get_input_value_port_name" qualifiers="virtual"> - <return type="String"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="String" /> + <argument index="0" name="idx" type="int" /> <description> Return the specified input port's name. </description> </method> <method name="_get_input_value_port_type" qualifiers="virtual"> - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="int" /> + <argument index="0" name="idx" type="int" /> <description> Return the specified input port's type. See the [enum Variant.Type] values. </description> </method> <method name="_get_output_sequence_port_count" qualifiers="virtual"> - <return type="int"> - </return> + <return type="int" /> <description> Return the amount of output [b]sequence[/b] ports. </description> </method> <method name="_get_output_sequence_port_text" qualifiers="virtual"> - <return type="String"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="String" /> + <argument index="0" name="idx" type="int" /> <description> Return the specified [b]sequence[/b] output's name. </description> </method> <method name="_get_output_value_port_count" qualifiers="virtual"> - <return type="int"> - </return> + <return type="int" /> <description> Return the amount of output value ports. </description> </method> + <method name="_get_output_value_port_hint" qualifiers="virtual"> + <return type="int" /> + <argument index="0" name="idx" type="int" /> + <description> + Return the specified output port's hint. See the [enum @GlobalScope.PropertyHint] hints. + </description> + </method> + <method name="_get_output_value_port_hint_string" qualifiers="virtual"> + <return type="String" /> + <argument index="0" name="idx" type="int" /> + <description> + Return the specified output port's hint string. + </description> + </method> <method name="_get_output_value_port_name" qualifiers="virtual"> - <return type="String"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="String" /> + <argument index="0" name="idx" type="int" /> <description> - Return the specified output's name. + Return the specified output port's name. </description> </method> <method name="_get_output_value_port_type" qualifiers="virtual"> - <return type="int"> - </return> - <argument index="0" name="idx" type="int"> - </argument> + <return type="int" /> + <argument index="0" name="idx" type="int" /> <description> - Return the specified output's type. See the [enum Variant.Type] values. + Return the specified output port's type. See the [enum Variant.Type] values. </description> </method> <method name="_get_text" qualifiers="virtual"> - <return type="String"> - </return> + <return type="String" /> <description> Return the custom node's text, which is shown right next to the input [b]sequence[/b] port (if there is none, on the place that is usually taken by it). </description> </method> <method name="_get_working_memory_size" qualifiers="virtual"> - <return type="int"> - </return> + <return type="int" /> <description> Return the size of the custom node's working memory. See [method _step] for more details. </description> </method> <method name="_has_input_sequence_port" qualifiers="virtual"> - <return type="bool"> - </return> + <return type="bool" /> <description> Return whether the custom node has an input [b]sequence[/b] port. </description> </method> <method name="_step" qualifiers="virtual"> - <return type="Variant"> - </return> - <argument index="0" name="inputs" type="Array"> - </argument> - <argument index="1" name="outputs" type="Array"> - </argument> - <argument index="2" name="start_mode" type="int"> - </argument> - <argument index="3" name="working_mem" type="Array"> - </argument> + <return type="Variant" /> + <argument index="0" name="inputs" type="Array" /> + <argument index="1" name="outputs" type="Array" /> + <argument index="2" name="start_mode" type="int" /> + <argument index="3" name="working_mem" type="Array" /> <description> Execute the custom node's logic, returning the index of the output sequence port to use or a [String] when there is an error. The [code]inputs[/code] array contains the values of the input ports. diff --git a/modules/visual_script/doc_classes/VisualScriptEditor.xml b/modules/visual_script/doc_classes/VisualScriptEditor.xml index 186cd21239..9ea889c77b 100644 --- a/modules/visual_script/doc_classes/VisualScriptEditor.xml +++ b/modules/visual_script/doc_classes/VisualScriptEditor.xml @@ -8,25 +8,18 @@ </tutorials> <methods> <method name="add_custom_node"> - <return type="void"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="category" type="String"> - </argument> - <argument index="2" name="script" type="Script"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="String" /> + <argument index="1" name="category" type="String" /> + <argument index="2" name="script" type="Script" /> <description> Add a custom Visual Script node to the editor. It'll be placed under "Custom Nodes" with the [code]category[/code] as the parameter. </description> </method> <method name="remove_custom_node"> - <return type="void"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="category" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="name" type="String" /> + <argument index="1" name="category" type="String" /> <description> Remove a custom Visual Script node from the editor. Custom nodes already placed on scripts won't be removed. </description> diff --git a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml index 5c9c8d3eca..df3121d093 100644 --- a/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml +++ b/modules/visual_script/doc_classes/VisualScriptEmitSignal.xml @@ -15,7 +15,7 @@ <methods> </methods> <members> - <member name="signal" type="StringName" setter="set_signal" getter="get_signal" default="@"""> + <member name="signal" type="StringName" setter="set_signal" getter="get_signal" default="&"""> The signal to emit. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptExpression.xml b/modules/visual_script/doc_classes/VisualScriptExpression.xml index 5253f7bc7d..223adbbb96 100644 --- a/modules/visual_script/doc_classes/VisualScriptExpression.xml +++ b/modules/visual_script/doc_classes/VisualScriptExpression.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptExpression" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node that can execute a custom expression. </brief_description> <description> + A Visual Script node that can execute a custom expression. Values can be provided for the input and the expression result can be retrieved from the output. </description> <tutorials> </tutorials> diff --git a/modules/visual_script/doc_classes/VisualScriptFunction.xml b/modules/visual_script/doc_classes/VisualScriptFunction.xml index 873d26a5be..652418bd64 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunction.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunction.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptFunction" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node representing a function. </brief_description> <description> + [VisualScriptFunction] represents a function header. It is the starting point for the function body and can be used to tweak the function's properties (e.g. RPC mode). </description> <tutorials> </tutorials> diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml index 2d0fac1fa0..f0b666e57a 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunctionCall.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptFunctionCall" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node for calling a function. </brief_description> <description> + [VisualScriptFunctionCall] is created when you add or drag and drop a function onto the Visual Script graph. It allows to tweak parameters of the call, e.g. what object the function is called on. </description> <tutorials> </tutorials> @@ -10,46 +12,66 @@ </methods> <members> <member name="base_script" type="String" setter="set_base_script" getter="get_base_script"> + The script to be used when [member call_mode] is set to [constant CALL_MODE_INSTANCE]. </member> - <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="@"Object""> + <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&"Object""> + The base type to be used when [member call_mode] is set to [constant CALL_MODE_INSTANCE]. </member> <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type"> + The type to be used when [member call_mode] is set to [constant CALL_MODE_BASIC_TYPE]. </member> <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptFunctionCall.CallMode" default="0"> + [code]call_mode[/code] determines the target object on which the method will be called. See [enum CallMode] for options. </member> - <member name="function" type="StringName" setter="set_function" getter="get_function" default="@"""> + <member name="function" type="StringName" setter="set_function" getter="get_function" default="&"""> + The name of the function to be called. </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> + The node path to use when [member call_mode] is set to [constant CALL_MODE_NODE_PATH]. </member> <member name="rpc_call_mode" type="int" setter="set_rpc_call_mode" getter="get_rpc_call_mode" enum="VisualScriptFunctionCall.RPCCallMode" default="0"> + The mode for RPC calls. See [method Node.rpc] for more details and [enum RPCCallMode] for available options. </member> <member name="singleton" type="StringName" setter="set_singleton" getter="get_singleton"> + The singleton to call the method on. Used when [member call_mode] is set to [constant CALL_MODE_SINGLETON]. </member> <member name="use_default_args" type="int" setter="set_use_default_args" getter="get_use_default_args"> + Number of default arguments that will be used when calling the function. Can't be higher than the number of available default arguments in the method's declaration. </member> <member name="validate" type="bool" setter="set_validate" getter="get_validate" default="true"> + If [code]false[/code], call errors (e.g. wrong number of arguments) will be ignored. </member> </members> <constants> <constant name="CALL_MODE_SELF" value="0" enum="CallMode"> + The method will be called on this [Object]. </constant> <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode"> + The method will be called on the given [Node] in the scene tree. </constant> <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode"> + The method will be called on an instanced node with the given type and script. </constant> <constant name="CALL_MODE_BASIC_TYPE" value="3" enum="CallMode"> + The method will be called on a GDScript basic type (e.g. [Vector2]). </constant> <constant name="CALL_MODE_SINGLETON" value="4" enum="CallMode"> + The method will be called on a singleton. </constant> <constant name="RPC_DISABLED" value="0" enum="RPCCallMode"> + The method will be called locally. </constant> <constant name="RPC_RELIABLE" value="1" enum="RPCCallMode"> + The method will be called remotely. </constant> <constant name="RPC_UNRELIABLE" value="2" enum="RPCCallMode"> + The method will be called remotely using an unreliable protocol. </constant> <constant name="RPC_RELIABLE_TO_ID" value="3" enum="RPCCallMode"> + The method will be called remotely for the given peer. </constant> <constant name="RPC_UNRELIABLE_TO_ID" value="4" enum="RPCCallMode"> + The method will be called remotely for the given peer, using an unreliable protocol. </constant> </constants> </class> diff --git a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml b/modules/visual_script/doc_classes/VisualScriptFunctionState.xml index 68083614a6..18c3826df8 100644 --- a/modules/visual_script/doc_classes/VisualScriptFunctionState.xml +++ b/modules/visual_script/doc_classes/VisualScriptFunctionState.xml @@ -1,36 +1,34 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="VisualScriptFunctionState" inherits="Reference" version="4.0"> +<class name="VisualScriptFunctionState" inherits="RefCounted" version="4.0"> <brief_description> + A Visual Script node representing a function state. </brief_description> <description> + [VisualScriptFunctionState] is returned from [VisualScriptYield] and can be used to resume a paused function call. </description> <tutorials> </tutorials> <methods> <method name="connect_to_signal"> - <return type="void"> - </return> - <argument index="0" name="obj" type="Object"> - </argument> - <argument index="1" name="signals" type="String"> - </argument> - <argument index="2" name="args" type="Array"> - </argument> + <return type="void" /> + <argument index="0" name="obj" type="Object" /> + <argument index="1" name="signals" type="String" /> + <argument index="2" name="args" type="Array" /> <description> + Connects this [VisualScriptFunctionState] to a signal in the given object to automatically resume when it's emitted. </description> </method> <method name="is_valid" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> + Returns whether the function state is valid. </description> </method> <method name="resume"> - <return type="Variant"> - </return> - <argument index="0" name="args" type="Array" default="null"> - </argument> + <return type="Variant" /> + <argument index="0" name="args" type="Array" default="[]" /> <description> + Resumes the function to run from the point it was yielded. </description> </method> </methods> diff --git a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml index ef17bd8a28..87fdfd4e53 100644 --- a/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml +++ b/modules/visual_script/doc_classes/VisualScriptGlobalConstant.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptGlobalConstant" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node returning a constant from [@GlobalScope]. </brief_description> <description> + A Visual Script node returning a constant from [@GlobalScope]. </description> <tutorials> </tutorials> @@ -10,6 +12,7 @@ </methods> <members> <member name="constant" type="int" setter="set_global_constant" getter="get_global_constant" default="0"> + The constant to be used. </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml b/modules/visual_script/doc_classes/VisualScriptIndexGet.xml index bb1618a655..b348048298 100644 --- a/modules/visual_script/doc_classes/VisualScriptIndexGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptIndexGet.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptIndexGet" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node for getting a value from an array or a dictionary. </brief_description> <description> + [VisualScriptIndexGet] will return the value stored in an array or a dictionary under the given index. </description> <tutorials> </tutorials> diff --git a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml b/modules/visual_script/doc_classes/VisualScriptIndexSet.xml index 4ff96f7211..d7fe7340ad 100644 --- a/modules/visual_script/doc_classes/VisualScriptIndexSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptIndexSet.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptIndexSet" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node for setting a value in an array or a dictionary. </brief_description> <description> + [VisualScriptIndexSet] will set the value stored in an array or a dictionary under the given index to the provided new value. </description> <tutorials> </tutorials> diff --git a/modules/visual_script/doc_classes/VisualScriptInputAction.xml b/modules/visual_script/doc_classes/VisualScriptInputAction.xml index 6c296fdb4b..d6fa111500 100644 --- a/modules/visual_script/doc_classes/VisualScriptInputAction.xml +++ b/modules/visual_script/doc_classes/VisualScriptInputAction.xml @@ -1,27 +1,35 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptInputAction" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node returning a state of an action. </brief_description> <description> + [VisualScriptInputAction] can be used to check if an action is pressed or released. </description> <tutorials> </tutorials> <methods> </methods> <members> - <member name="action" type="StringName" setter="set_action_name" getter="get_action_name" default="@"""> + <member name="action" type="StringName" setter="set_action_name" getter="get_action_name" default="&"""> + Name of the action. </member> <member name="mode" type="int" setter="set_action_mode" getter="get_action_mode" enum="VisualScriptInputAction.Mode" default="0"> + State of the action to check. See [enum Mode] for options. </member> </members> <constants> <constant name="MODE_PRESSED" value="0" enum="Mode"> + [code]True[/code] if action is pressed. </constant> <constant name="MODE_RELEASED" value="1" enum="Mode"> + [code]True[/code] if action is released (i.e. not pressed). </constant> <constant name="MODE_JUST_PRESSED" value="2" enum="Mode"> + [code]True[/code] on the frame the action was pressed. </constant> <constant name="MODE_JUST_RELEASED" value="3" enum="Mode"> + [code]True[/code] on the frame the action was released. </constant> </constants> </class> diff --git a/modules/visual_script/doc_classes/VisualScriptLists.xml b/modules/visual_script/doc_classes/VisualScriptLists.xml index 8a7254b46a..d5bff1341a 100644 --- a/modules/visual_script/doc_classes/VisualScriptLists.xml +++ b/modules/visual_script/doc_classes/VisualScriptLists.xml @@ -10,83 +10,67 @@ </tutorials> <methods> <method name="add_input_data_port"> - <return type="void"> - </return> - <argument index="0" name="type" type="int" enum="Variant.Type"> - </argument> - <argument index="1" name="name" type="String"> - </argument> - <argument index="2" name="index" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="type" type="int" enum="Variant.Type" /> + <argument index="1" name="name" type="String" /> + <argument index="2" name="index" type="int" /> <description> + Adds an input port to the Visual Script node. </description> </method> <method name="add_output_data_port"> - <return type="void"> - </return> - <argument index="0" name="type" type="int" enum="Variant.Type"> - </argument> - <argument index="1" name="name" type="String"> - </argument> - <argument index="2" name="index" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="type" type="int" enum="Variant.Type" /> + <argument index="1" name="name" type="String" /> + <argument index="2" name="index" type="int" /> <description> + Adds an output port to the Visual Script node. </description> </method> <method name="remove_input_data_port"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> <description> + Removes an input port from the Visual Script node. </description> </method> <method name="remove_output_data_port"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> <description> + Removes an output port from the Visual Script node. </description> </method> <method name="set_input_data_port_name"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> - <argument index="1" name="name" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> + <argument index="1" name="name" type="String" /> <description> + Sets the name of an input port. </description> </method> <method name="set_input_data_port_type"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> - <argument index="1" name="type" type="int" enum="Variant.Type"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> + <argument index="1" name="type" type="int" enum="Variant.Type" /> <description> + Sets the type of an input port. </description> </method> <method name="set_output_data_port_name"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> - <argument index="1" name="name" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> + <argument index="1" name="name" type="String" /> <description> + Sets the name of an output port. </description> </method> <method name="set_output_data_port_type"> - <return type="void"> - </return> - <argument index="0" name="index" type="int"> - </argument> - <argument index="1" name="type" type="int" enum="Variant.Type"> - </argument> + <return type="void" /> + <argument index="0" name="index" type="int" /> + <argument index="1" name="type" type="int" enum="Variant.Type" /> <description> + Sets the type of an output port. </description> </method> </methods> diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml index c3741eea89..185f0f1ffb 100644 --- a/modules/visual_script/doc_classes/VisualScriptLocalVar.xml +++ b/modules/visual_script/doc_classes/VisualScriptLocalVar.xml @@ -18,7 +18,7 @@ <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0"> The local variable's type. </member> - <member name="var_name" type="StringName" setter="set_var_name" getter="get_var_name" default="@"new_local""> + <member name="var_name" type="StringName" setter="set_var_name" getter="get_var_name" default="&"new_local""> The local variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml index 619bbb90ca..865f0153c9 100644 --- a/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptLocalVarSet.xml @@ -20,7 +20,7 @@ <member name="type" type="int" setter="set_var_type" getter="get_var_type" enum="Variant.Type" default="0"> The local variable's type. </member> - <member name="var_name" type="StringName" setter="set_var_name" getter="get_var_name" default="@"new_local""> + <member name="var_name" type="StringName" setter="set_var_name" getter="get_var_name" default="&"new_local""> The local variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptNode.xml b/modules/visual_script/doc_classes/VisualScriptNode.xml index 82a023f3e4..23574a5ea8 100644 --- a/modules/visual_script/doc_classes/VisualScriptNode.xml +++ b/modules/visual_script/doc_classes/VisualScriptNode.xml @@ -10,35 +10,28 @@ </tutorials> <methods> <method name="get_default_input_value" qualifiers="const"> - <return type="Variant"> - </return> - <argument index="0" name="port_idx" type="int"> - </argument> + <return type="Variant" /> + <argument index="0" name="port_idx" type="int" /> <description> Returns the default value of a given port. The default value is used when nothing is connected to the port. </description> </method> <method name="get_visual_script" qualifiers="const"> - <return type="VisualScript"> - </return> + <return type="VisualScript" /> <description> Returns the [VisualScript] instance the node is bound to. </description> </method> <method name="ports_changed_notify"> - <return type="void"> - </return> + <return type="void" /> <description> Notify that the node's ports have changed. Usually used in conjunction with [VisualScriptCustomNode] . </description> </method> <method name="set_default_input_value"> - <return type="void"> - </return> - <argument index="0" name="port_idx" type="int"> - </argument> - <argument index="1" name="value" type="Variant"> - </argument> + <return type="void" /> + <argument index="0" name="port_idx" type="int" /> + <argument index="1" name="value" type="Variant" /> <description> Change the default value of a given port. </description> diff --git a/modules/visual_script/doc_classes/VisualScriptOperator.xml b/modules/visual_script/doc_classes/VisualScriptOperator.xml index c8ce0f2732..cbbefa7f71 100644 --- a/modules/visual_script/doc_classes/VisualScriptOperator.xml +++ b/modules/visual_script/doc_classes/VisualScriptOperator.xml @@ -1,6 +1,7 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptOperator" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node that performs an operation on two values. </brief_description> <description> [b]Input Ports:[/b] @@ -15,8 +16,10 @@ </methods> <members> <member name="operator" type="int" setter="set_operator" getter="get_operator" enum="Variant.Operator" default="6"> + The operation to be performed. See [enum Variant.Operator] for available options. </member> <member name="type" type="int" setter="set_typed" getter="get_typed" enum="Variant.Type" default="0"> + The type of the values for this operation. See [enum Variant.Type] for available options. </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml index 1c22070ab1..c1bf443ea3 100644 --- a/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptPropertyGet.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptPropertyGet" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node returning a value of a property from an [Object]. </brief_description> <description> + [VisualScriptPropertyGet] can return a value of any property from the current object or other objects. </description> <tutorials> </tutorials> @@ -10,28 +12,39 @@ </methods> <members> <member name="base_script" type="String" setter="set_base_script" getter="get_base_script"> + The script to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE]. </member> - <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="@"Object""> + <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&"Object""> + The base type to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE]. </member> <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type"> + The type to be used when [member set_mode] is set to [constant CALL_MODE_BASIC_TYPE]. </member> <member name="index" type="StringName" setter="set_index" getter="get_index"> + The indexed name of the property to retrieve. See [method Object.get_indexed] for details. </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> + The node path to use when [member set_mode] is set to [constant CALL_MODE_NODE_PATH]. </member> - <member name="property" type="StringName" setter="set_property" getter="get_property" default="@"""> + <member name="property" type="StringName" setter="set_property" getter="get_property" default="&"""> + The name of the property to retrieve. Changing this will clear [member index]. </member> <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertyGet.CallMode" default="0"> + [code]set_mode[/code] determines the target object from which the property will be retrieved. See [enum CallMode] for options. </member> </members> <constants> <constant name="CALL_MODE_SELF" value="0" enum="CallMode"> + The property will be retrieved from this [Object]. </constant> <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode"> + The property will be retrieved from the given [Node] in the scene tree. </constant> <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode"> + The property will be retrieved from an instanced node with the given type and script. </constant> <constant name="CALL_MODE_BASIC_TYPE" value="3" enum="CallMode"> + The property will be retrieved from a GDScript basic type (e.g. [Vector2]). </constant> </constants> </class> diff --git a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml index 629576e261..75d6a63469 100644 --- a/modules/visual_script/doc_classes/VisualScriptPropertySet.xml +++ b/modules/visual_script/doc_classes/VisualScriptPropertySet.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptPropertySet" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node that sets a property of an [Object]. </brief_description> <description> + [VisualScriptPropertySet] can set the value of any property from the current object or other objects. </description> <tutorials> </tutorials> @@ -10,52 +12,75 @@ </methods> <members> <member name="assign_op" type="int" setter="set_assign_op" getter="get_assign_op" enum="VisualScriptPropertySet.AssignOp" default="0"> + The additional operation to perform when assigning. See [enum AssignOp] for options. </member> <member name="base_script" type="String" setter="set_base_script" getter="get_base_script"> + The script to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE]. </member> - <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="@"Object""> + <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&"Object""> + The base type to be used when [member set_mode] is set to [constant CALL_MODE_INSTANCE]. </member> <member name="basic_type" type="int" setter="set_basic_type" getter="get_basic_type" enum="Variant.Type"> + The type to be used when [member set_mode] is set to [constant CALL_MODE_BASIC_TYPE]. </member> <member name="index" type="StringName" setter="set_index" getter="get_index"> + The indexed name of the property to set. See [method Object.set_indexed] for details. </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> + The node path to use when [member set_mode] is set to [constant CALL_MODE_NODE_PATH]. </member> - <member name="property" type="StringName" setter="set_property" getter="get_property" default="@"""> + <member name="property" type="StringName" setter="set_property" getter="get_property" default="&"""> + The name of the property to set. Changing this will clear [member index]. </member> <member name="set_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptPropertySet.CallMode" default="0"> + [code]set_mode[/code] determines the target object on which the property will be set. See [enum CallMode] for options. </member> </members> <constants> <constant name="CALL_MODE_SELF" value="0" enum="CallMode"> + The property will be set on this [Object]. </constant> <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode"> + The property will be set on the given [Node] in the scene tree. </constant> <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode"> + The property will be set on an instanced node with the given type and script. </constant> <constant name="CALL_MODE_BASIC_TYPE" value="3" enum="CallMode"> + The property will be set on a GDScript basic type (e.g. [Vector2]). </constant> <constant name="ASSIGN_OP_NONE" value="0" enum="AssignOp"> + The property will be assigned regularly. </constant> <constant name="ASSIGN_OP_ADD" value="1" enum="AssignOp"> + The value will be added to the property. Equivalent of doing [code]+=[/code]. </constant> <constant name="ASSIGN_OP_SUB" value="2" enum="AssignOp"> + The value will be subtracted from the property. Equivalent of doing [code]-=[/code]. </constant> <constant name="ASSIGN_OP_MUL" value="3" enum="AssignOp"> + The property will be multiplied by the value. Equivalent of doing [code]*=[/code]. </constant> <constant name="ASSIGN_OP_DIV" value="4" enum="AssignOp"> + The property will be divided by the value. Equivalent of doing [code]/=[/code]. </constant> <constant name="ASSIGN_OP_MOD" value="5" enum="AssignOp"> + A modulo operation will be performed on the property and the value. Equivalent of doing [code]%=[/code]. </constant> <constant name="ASSIGN_OP_SHIFT_LEFT" value="6" enum="AssignOp"> + The property will be binarly shifted to the left by the given value. Equivalent of doing [code]<<[/code]. </constant> <constant name="ASSIGN_OP_SHIFT_RIGHT" value="7" enum="AssignOp"> + The property will be binarly shifted to the right by the given value. Equivalent of doing [code]>>[/code]. </constant> <constant name="ASSIGN_OP_BIT_AND" value="8" enum="AssignOp"> + A binary [code]AND[/code] operation will be performed on the property. Equivalent of doing [code]&=[/code]. </constant> <constant name="ASSIGN_OP_BIT_OR" value="9" enum="AssignOp"> + A binary [code]OR[/code] operation will be performed on the property. Equivalent of doing [code]|=[/code]. </constant> <constant name="ASSIGN_OP_BIT_XOR" value="10" enum="AssignOp"> + A binary [code]XOR[/code] operation will be performed on the property. Equivalent of doing [code]^=[/code]. </constant> </constants> </class> diff --git a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml b/modules/visual_script/doc_classes/VisualScriptSceneTree.xml index 191d4b6977..8cddd02c77 100644 --- a/modules/visual_script/doc_classes/VisualScriptSceneTree.xml +++ b/modules/visual_script/doc_classes/VisualScriptSceneTree.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptSceneTree" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node for accessing [SceneTree] methods. </brief_description> <description> + A Visual Script node for accessing [SceneTree] methods. </description> <tutorials> </tutorials> diff --git a/modules/visual_script/doc_classes/VisualScriptSubCall.xml b/modules/visual_script/doc_classes/VisualScriptSubCall.xml index cb3b04b583..374e7d0f35 100644 --- a/modules/visual_script/doc_classes/VisualScriptSubCall.xml +++ b/modules/visual_script/doc_classes/VisualScriptSubCall.xml @@ -1,18 +1,19 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptSubCall" inherits="VisualScriptNode" version="4.0"> <brief_description> + Calls a method called [code]_subcall[/code] in this object. </brief_description> <description> + [VisualScriptSubCall] will call method named [code]_subcall[/code] in the current script. It will fail if the method doesn't exist or the provided arguments are wrong. </description> <tutorials> </tutorials> <methods> <method name="_subcall" qualifiers="virtual"> - <return type="Variant"> - </return> - <argument index="0" name="arguments" type="Variant"> - </argument> + <return type="Variant" /> + <argument index="0" name="arguments" type="Variant" /> <description> + Called by this node. </description> </method> </methods> diff --git a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml index 80a8d31041..5dd1ad3421 100644 --- a/modules/visual_script/doc_classes/VisualScriptTypeCast.xml +++ b/modules/visual_script/doc_classes/VisualScriptTypeCast.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptTypeCast" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node that casts the given value to another type. </brief_description> <description> + [VisualScriptTypeCast] will perform a type conversion to an [Object]-derived type. </description> <tutorials> </tutorials> @@ -10,8 +12,10 @@ </methods> <members> <member name="base_script" type="String" setter="set_base_script" getter="get_base_script" default=""""> + The target script class to be converted to. If none, only the [member base_type] will be used. </member> - <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="@"Object""> + <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&"Object""> + The target type to be converted to. </member> </members> <constants> diff --git a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml index d182e14e4d..df20ac53f2 100644 --- a/modules/visual_script/doc_classes/VisualScriptVariableGet.xml +++ b/modules/visual_script/doc_classes/VisualScriptVariableGet.xml @@ -15,7 +15,7 @@ <methods> </methods> <members> - <member name="var_name" type="StringName" setter="set_variable" getter="get_variable" default="@"""> + <member name="var_name" type="StringName" setter="set_variable" getter="get_variable" default="&"""> The variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml index 3bd392dd85..eb8ebbe338 100644 --- a/modules/visual_script/doc_classes/VisualScriptVariableSet.xml +++ b/modules/visual_script/doc_classes/VisualScriptVariableSet.xml @@ -16,7 +16,7 @@ <methods> </methods> <members> - <member name="var_name" type="StringName" setter="set_variable" getter="get_variable" default="@"""> + <member name="var_name" type="StringName" setter="set_variable" getter="get_variable" default="&"""> The variable's name. </member> </members> diff --git a/modules/visual_script/doc_classes/VisualScriptYield.xml b/modules/visual_script/doc_classes/VisualScriptYield.xml index 0a8d529a48..b04ab7b014 100644 --- a/modules/visual_script/doc_classes/VisualScriptYield.xml +++ b/modules/visual_script/doc_classes/VisualScriptYield.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptYield" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node used to pause a function execution. </brief_description> <description> + [VisualScriptYield] will pause the function call and return [VisualScriptFunctionState], which can be used to resume the function. </description> <tutorials> </tutorials> @@ -10,16 +12,21 @@ </methods> <members> <member name="mode" type="int" setter="set_yield_mode" getter="get_yield_mode" enum="VisualScriptYield.YieldMode" default="1"> + The mode to use for yielding. See [enum YieldMode] for available options. </member> <member name="wait_time" type="float" setter="set_wait_time" getter="get_wait_time"> + The time to wait when [member mode] is set to [constant YIELD_WAIT]. </member> </members> <constants> <constant name="YIELD_FRAME" value="1" enum="YieldMode"> + Yields during an idle frame. </constant> <constant name="YIELD_PHYSICS_FRAME" value="2" enum="YieldMode"> + Yields during a physics frame. </constant> <constant name="YIELD_WAIT" value="3" enum="YieldMode"> + Yields a function and waits the given time. </constant> </constants> </class> diff --git a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml index 483cdfeaf8..c6c3188d08 100644 --- a/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml +++ b/modules/visual_script/doc_classes/VisualScriptYieldSignal.xml @@ -1,29 +1,38 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="VisualScriptYieldSignal" inherits="VisualScriptNode" version="4.0"> <brief_description> + A Visual Script node yielding for a signal. </brief_description> <description> + [VisualScriptYieldSignal] will pause the function execution until the provided signal is emitted. </description> <tutorials> </tutorials> <methods> </methods> <members> - <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="@"Object""> + <member name="base_type" type="StringName" setter="set_base_type" getter="get_base_type" default="&"Object""> + The base type to be used when [member call_mode] is set to [constant CALL_MODE_INSTANCE]. </member> <member name="call_mode" type="int" setter="set_call_mode" getter="get_call_mode" enum="VisualScriptYieldSignal.CallMode" default="0"> + [code]call_mode[/code] determines the target object to wait for the signal emission. See [enum CallMode] for options. </member> <member name="node_path" type="NodePath" setter="set_base_path" getter="get_base_path"> + The node path to use when [member call_mode] is set to [constant CALL_MODE_NODE_PATH]. </member> - <member name="signal" type="StringName" setter="set_signal" getter="get_signal" default="@"""> + <member name="signal" type="StringName" setter="set_signal" getter="get_signal" default="&"""> + The signal name to be waited for. </member> </members> <constants> <constant name="CALL_MODE_SELF" value="0" enum="CallMode"> + A signal from this [Object] will be used. </constant> <constant name="CALL_MODE_NODE_PATH" value="1" enum="CallMode"> + A signal from the given [Node] in the scene tree will be used. </constant> <constant name="CALL_MODE_INSTANCE" value="2" enum="CallMode"> + A signal from an instanced node with the given type will be used. </constant> </constants> </class> diff --git a/modules/visual_script/register_types.cpp b/modules/visual_script/register_types.cpp index 4c7b66e368..f20ef046a3 100644 --- a/modules/visual_script/register_types.cpp +++ b/modules/visual_script/register_types.cpp @@ -51,59 +51,59 @@ void register_visual_script_types() { //script_language_gd->init(); ScriptServer::register_language(visual_script_language); - ClassDB::register_class<VisualScript>(); - ClassDB::register_virtual_class<VisualScriptNode>(); - ClassDB::register_class<VisualScriptFunctionState>(); - ClassDB::register_class<VisualScriptFunction>(); - ClassDB::register_virtual_class<VisualScriptLists>(); - ClassDB::register_class<VisualScriptComposeArray>(); - ClassDB::register_class<VisualScriptOperator>(); - ClassDB::register_class<VisualScriptVariableSet>(); - ClassDB::register_class<VisualScriptVariableGet>(); - ClassDB::register_class<VisualScriptConstant>(); - ClassDB::register_class<VisualScriptIndexGet>(); - ClassDB::register_class<VisualScriptIndexSet>(); - ClassDB::register_class<VisualScriptGlobalConstant>(); - ClassDB::register_class<VisualScriptClassConstant>(); - ClassDB::register_class<VisualScriptMathConstant>(); - ClassDB::register_class<VisualScriptBasicTypeConstant>(); - ClassDB::register_class<VisualScriptEngineSingleton>(); - ClassDB::register_class<VisualScriptSceneNode>(); - ClassDB::register_class<VisualScriptSceneTree>(); - ClassDB::register_class<VisualScriptResourcePath>(); - ClassDB::register_class<VisualScriptSelf>(); - ClassDB::register_class<VisualScriptCustomNode>(); - ClassDB::register_class<VisualScriptSubCall>(); - ClassDB::register_class<VisualScriptComment>(); - ClassDB::register_class<VisualScriptConstructor>(); - ClassDB::register_class<VisualScriptLocalVar>(); - ClassDB::register_class<VisualScriptLocalVarSet>(); - ClassDB::register_class<VisualScriptInputAction>(); - ClassDB::register_class<VisualScriptDeconstruct>(); - ClassDB::register_class<VisualScriptPreload>(); - ClassDB::register_class<VisualScriptTypeCast>(); - - ClassDB::register_class<VisualScriptFunctionCall>(); - ClassDB::register_class<VisualScriptPropertySet>(); - ClassDB::register_class<VisualScriptPropertyGet>(); + GDREGISTER_CLASS(VisualScript); + GDREGISTER_VIRTUAL_CLASS(VisualScriptNode); + GDREGISTER_CLASS(VisualScriptFunctionState); + GDREGISTER_CLASS(VisualScriptFunction); + GDREGISTER_VIRTUAL_CLASS(VisualScriptLists); + GDREGISTER_CLASS(VisualScriptComposeArray); + GDREGISTER_CLASS(VisualScriptOperator); + GDREGISTER_CLASS(VisualScriptVariableSet); + GDREGISTER_CLASS(VisualScriptVariableGet); + GDREGISTER_CLASS(VisualScriptConstant); + GDREGISTER_CLASS(VisualScriptIndexGet); + GDREGISTER_CLASS(VisualScriptIndexSet); + GDREGISTER_CLASS(VisualScriptGlobalConstant); + GDREGISTER_CLASS(VisualScriptClassConstant); + GDREGISTER_CLASS(VisualScriptMathConstant); + GDREGISTER_CLASS(VisualScriptBasicTypeConstant); + GDREGISTER_CLASS(VisualScriptEngineSingleton); + GDREGISTER_CLASS(VisualScriptSceneNode); + GDREGISTER_CLASS(VisualScriptSceneTree); + GDREGISTER_CLASS(VisualScriptResourcePath); + GDREGISTER_CLASS(VisualScriptSelf); + GDREGISTER_CLASS(VisualScriptCustomNode); + GDREGISTER_CLASS(VisualScriptSubCall); + GDREGISTER_CLASS(VisualScriptComment); + GDREGISTER_CLASS(VisualScriptConstructor); + GDREGISTER_CLASS(VisualScriptLocalVar); + GDREGISTER_CLASS(VisualScriptLocalVarSet); + GDREGISTER_CLASS(VisualScriptInputAction); + GDREGISTER_CLASS(VisualScriptDeconstruct); + GDREGISTER_CLASS(VisualScriptPreload); + GDREGISTER_CLASS(VisualScriptTypeCast); + + GDREGISTER_CLASS(VisualScriptFunctionCall); + GDREGISTER_CLASS(VisualScriptPropertySet); + GDREGISTER_CLASS(VisualScriptPropertyGet); //ClassDB::register_type<VisualScriptScriptCall>(); - ClassDB::register_class<VisualScriptEmitSignal>(); + GDREGISTER_CLASS(VisualScriptEmitSignal); - ClassDB::register_class<VisualScriptReturn>(); - ClassDB::register_class<VisualScriptCondition>(); - ClassDB::register_class<VisualScriptWhile>(); - ClassDB::register_class<VisualScriptIterator>(); - ClassDB::register_class<VisualScriptSequence>(); - //ClassDB::register_class<VisualScriptInputFilter>(); - ClassDB::register_class<VisualScriptSwitch>(); - ClassDB::register_class<VisualScriptSelect>(); + GDREGISTER_CLASS(VisualScriptReturn); + GDREGISTER_CLASS(VisualScriptCondition); + GDREGISTER_CLASS(VisualScriptWhile); + GDREGISTER_CLASS(VisualScriptIterator); + GDREGISTER_CLASS(VisualScriptSequence); + //GDREGISTER_CLASS(VisualScriptInputFilter); + GDREGISTER_CLASS(VisualScriptSwitch); + GDREGISTER_CLASS(VisualScriptSelect); - ClassDB::register_class<VisualScriptYield>(); - ClassDB::register_class<VisualScriptYieldSignal>(); + GDREGISTER_CLASS(VisualScriptYield); + GDREGISTER_CLASS(VisualScriptYieldSignal); - ClassDB::register_class<VisualScriptBuiltinFunc>(); + GDREGISTER_CLASS(VisualScriptBuiltinFunc); - ClassDB::register_class<VisualScriptExpression>(); + GDREGISTER_CLASS(VisualScriptExpression); register_visual_script_nodes(); register_visual_script_func_nodes(); @@ -114,7 +114,7 @@ void register_visual_script_types() { #ifdef TOOLS_ENABLED ClassDB::set_current_api(ClassDB::API_EDITOR); - ClassDB::register_class<_VisualScriptEditor>(); + GDREGISTER_CLASS(_VisualScriptEditor); ClassDB::set_current_api(ClassDB::API_CORE); vs_editor_singleton = memnew(_VisualScriptEditor); Engine::get_singleton()->add_singleton(Engine::Singleton("VisualScriptEditor", _VisualScriptEditor::get_singleton())); diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 6d5fff88d9..86793af77f 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -46,7 +46,7 @@ bool VisualScriptNode::is_breakpoint() const { } void VisualScriptNode::ports_changed_notify() { - emit_signal("ports_changed"); + emit_signal(SNAME("ports_changed")); } void VisualScriptNode::set_default_input_value(int p_port, const Variant &p_value) { @@ -264,13 +264,14 @@ void VisualScript::_node_ports_changed(int p_id) { #ifdef TOOLS_ENABLED set_edited(true); // Something changed, let's set as edited. - emit_signal("node_ports_changed", p_id); + emit_signal(SNAME("node_ports_changed"), p_id); #endif } void VisualScript::add_node(int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos) { ERR_FAIL_COND(instances.size()); ERR_FAIL_COND(nodes.has(p_id)); // ID can exist only one in script. + ERR_FAIL_COND(p_node.is_null()); NodeData nd; nd.node = p_node; @@ -588,14 +589,14 @@ void VisualScript::rename_variable(const StringName &p_name, const StringName &p variables.erase(p_name); List<int> ids; get_node_list(&ids); - for (List<int>::Element *E = ids.front(); E; E = E->next()) { - Ref<VisualScriptVariableGet> nodeget = get_node(E->get()); + for (int &E : ids) { + Ref<VisualScriptVariableGet> nodeget = get_node(E); if (nodeget.is_valid()) { if (nodeget->get_variable() == p_name) { nodeget->set_variable(p_new_name); } } else { - Ref<VisualScriptVariableSet> nodeset = get_node(E->get()); + Ref<VisualScriptVariableSet> nodeset = get_node(E); if (nodeset.is_valid()) { if (nodeset->get_variable() == p_name) { nodeset->set_variable(p_new_name); @@ -715,9 +716,9 @@ int VisualScript::get_available_id() const { List<int> nds; nodes.get_key_list(&nds); int max = -1; - for (const List<int>::Element *E = nds.front(); E; E = E->next()) { - if (E->get() > max) { - max = E->get(); + for (const int &E : nds) { + if (E > max) { + max = E; } } return (max + 1); @@ -725,7 +726,7 @@ int VisualScript::get_available_id() const { ///////////////////////////////// -bool VisualScript::can_instance() const { +bool VisualScript::can_instantiate() const { return true; // ScriptServer::is_scripting_enabled(); } @@ -752,15 +753,15 @@ void VisualScript::_update_placeholders() { List<StringName> keys; variables.get_key_list(&keys); - for (List<StringName>::Element *E = keys.front(); E; E = E->next()) { - if (!variables[E->get()]._export) { + for (const StringName &E : keys) { + if (!variables[E]._export) { continue; } - PropertyInfo p = variables[E->get()].info; - p.name = String(E->get()); + PropertyInfo p = variables[E].info; + p.name = String(E); pinfo.push_back(p); - values[p.name] = variables[E->get()].default_value; + values[p.name] = variables[E].default_value; } for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { @@ -783,15 +784,15 @@ ScriptInstance *VisualScript::instance_create(Object *p_this) { List<StringName> keys; variables.get_key_list(&keys); - for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) { - if (!variables[E->get()]._export) { + for (const StringName &E : keys) { + if (!variables[E]._export) { continue; } - PropertyInfo p = variables[E->get()].info; - p.name = String(E->get()); + PropertyInfo p = variables[E].info; + p.name = String(E); pinfo.push_back(p); - values[p.name] = variables[E->get()].default_value; + values[p.name] = variables[E].default_value; } sins->update(pinfo, values); @@ -874,11 +875,11 @@ void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const { List<StringName> funcs; functions.get_key_list(&funcs); - for (List<StringName>::Element *E = funcs.front(); E; E = E->next()) { + for (const StringName &E : funcs) { MethodInfo mi; - mi.name = E->get(); - if (functions[E->get()].func_id >= 0) { - Ref<VisualScriptFunction> func = nodes[functions[E->get()].func_id].node; + mi.name = E; + if (functions[E].func_id >= 0) { + Ref<VisualScriptFunction> func = nodes[functions[E].func_id].node; if (func.is_valid()) { for (int i = 0; i < func->get_argument_count(); i++) { PropertyInfo arg; @@ -928,10 +929,10 @@ void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const { List<StringName> vars; get_variable_list(&vars); - for (List<StringName>::Element *E = vars.front(); E; E = E->next()) { - //if (!variables[E->get()]._export) + for (const StringName &E : vars) { + //if (!variables[E]._export) // continue; - PropertyInfo pi = variables[E->get()].info; + PropertyInfo pi = variables[E].info; pi.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; p_list->push_back(pi); } @@ -945,8 +946,8 @@ int VisualScript::get_member_line(const StringName &p_member) const { bool VisualScript::are_subnodes_edited() const { List<int> keys; nodes.get_key_list(&keys); - for (const List<int>::Element *F = keys.front(); F; F = F->next()) { - if (nodes[F->get()].node->is_edited()) { + for (const int &F : keys) { + if (nodes[F].node->is_edited()) { return true; } } @@ -954,60 +955,10 @@ bool VisualScript::are_subnodes_edited() const { } #endif -Vector<ScriptNetData> VisualScript::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> VisualScript::get_rpc_methods() const { return rpc_functions; } -uint16_t VisualScript::get_rpc_method_id(const StringName &p_method) const { - for (int i = 0; i < rpc_functions.size(); i++) { - if (rpc_functions[i].name == p_method) { - return i; - } - } - return UINT16_MAX; -} - -StringName VisualScript::get_rpc_method(const uint16_t p_rpc_method_id) const { - ERR_FAIL_COND_V(p_rpc_method_id >= rpc_functions.size(), StringName()); - return rpc_functions[p_rpc_method_id].name; -} - -MultiplayerAPI::RPCMode VisualScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const { - ERR_FAIL_COND_V(p_rpc_method_id >= rpc_functions.size(), MultiplayerAPI::RPC_MODE_DISABLED); - return rpc_functions[p_rpc_method_id].mode; -} - -MultiplayerAPI::RPCMode VisualScript::get_rpc_mode(const StringName &p_method) const { - return get_rpc_mode_by_id(get_rpc_method_id(p_method)); -} - -Vector<ScriptNetData> VisualScript::get_rset_properties() const { - return rpc_variables; -} - -uint16_t VisualScript::get_rset_property_id(const StringName &p_variable) const { - for (int i = 0; i < rpc_variables.size(); i++) { - if (rpc_variables[i].name == p_variable) { - return i; - } - } - return UINT16_MAX; -} - -StringName VisualScript::get_rset_property(const uint16_t p_rset_property_id) const { - ERR_FAIL_COND_V(p_rset_property_id >= rpc_variables.size(), StringName()); - return rpc_variables[p_rset_property_id].name; -} - -MultiplayerAPI::RPCMode VisualScript::get_rset_mode_by_id(const uint16_t p_rset_variable_id) const { - ERR_FAIL_COND_V(p_rset_variable_id >= rpc_variables.size(), MultiplayerAPI::RPC_MODE_DISABLED); - return rpc_variables[p_rset_variable_id].mode; -} - -MultiplayerAPI::RPCMode VisualScript::get_rset_mode(const StringName &p_variable) const { - return get_rset_mode_by_id(get_rset_property_id(p_variable)); -} - void VisualScript::_set_data(const Dictionary &p_data) { Dictionary d = p_data; if (d.has("base_type")) { @@ -1065,17 +1016,17 @@ void VisualScript::_set_data(const Dictionary &p_data) { // Takes all the rpc methods. rpc_functions.clear(); - rpc_variables.clear(); List<StringName> fns; functions.get_key_list(&fns); - for (const List<StringName>::Element *E = fns.front(); E; E = E->next()) { - if (functions[E->get()].func_id >= 0 && nodes.has(functions[E->get()].func_id)) { - Ref<VisualScriptFunction> vsf = nodes[functions[E->get()].func_id].node; + for (const StringName &E : fns) { + if (functions[E].func_id >= 0 && nodes.has(functions[E].func_id)) { + Ref<VisualScriptFunction> vsf = nodes[functions[E].func_id].node; if (vsf.is_valid()) { if (vsf->get_rpc_mode() != MultiplayerAPI::RPC_MODE_DISABLED) { - ScriptNetData nd; - nd.name = E->get(); - nd.mode = vsf->get_rpc_mode(); + MultiplayerAPI::RPCConfig nd; + nd.name = E; + nd.rpc_mode = vsf->get_rpc_mode(); + nd.transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE; // TODO if (rpc_functions.find(nd) == -1) { rpc_functions.push_back(nd); } @@ -1085,7 +1036,7 @@ void VisualScript::_set_data(const Dictionary &p_data) { } // Sort so we are 100% that they are always the same. - rpc_functions.sort_custom<SortNetData>(); + rpc_functions.sort_custom<MultiplayerAPI::SortRPCConfig>(); } Dictionary VisualScript::_get_data() const { @@ -1095,11 +1046,11 @@ Dictionary VisualScript::_get_data() const { Array vars; List<StringName> var_names; variables.get_key_list(&var_names); - for (const List<StringName>::Element *E = var_names.front(); E; E = E->next()) { - Dictionary var = _get_variable_info(E->get()); - var["name"] = E->get(); // Make sure it's the right one. - var["default_value"] = variables[E->get()].default_value; - var["export"] = variables[E->get()]._export; + for (const StringName &E : var_names) { + Dictionary var = _get_variable_info(E); + var["name"] = E; // Make sure it's the right one. + var["default_value"] = variables[E].default_value; + var["export"] = variables[E]._export; vars.push_back(var); } d["variables"] = vars; @@ -1123,10 +1074,10 @@ Dictionary VisualScript::_get_data() const { Array funcs; List<StringName> func_names; functions.get_key_list(&func_names); - for (const List<StringName>::Element *E = func_names.front(); E; E = E->next()) { + for (const StringName &E : func_names) { Dictionary func; - func["name"] = E->get(); - func["function_id"] = functions[E->get()].func_id; + func["name"] = E; + func["function_id"] = functions[E].func_id; funcs.push_back(func); } d["functions"] = funcs; @@ -1134,10 +1085,10 @@ Dictionary VisualScript::_get_data() const { Array nds; List<int> node_ids; nodes.get_key_list(&node_ids); - for (const List<int>::Element *F = node_ids.front(); F; F = F->next()) { - nds.push_back(F->get()); - nds.push_back(nodes[F->get()].pos); - nds.push_back(nodes[F->get()].node); + for (const int &F : node_ids) { + nds.push_back(F); + nds.push_back(nodes[F].pos); + nds.push_back(nodes[F].node); } d["nodes"] = nds; @@ -1252,8 +1203,8 @@ VisualScript::~VisualScript() { // Remove all nodes and stuff that hold data refs. List<int> nds; nodes.get_key_list(&nds); - for (const List<int>::Element *E = nds.front(); E; E = E->next()) { - remove_node(E->get()); + for (const int &E : nds) { + remove_node(E); } } @@ -1283,12 +1234,12 @@ bool VisualScriptInstance::get(const StringName &p_name, Variant &r_ret) const { void VisualScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { List<StringName> vars; script->variables.get_key_list(&vars); - for (const List<StringName>::Element *E = vars.front(); E; E = E->next()) { - if (!script->variables[E->get()]._export) { + for (const StringName &E : vars) { + if (!script->variables[E]._export) { continue; } - PropertyInfo p = script->variables[E->get()].info; - p.name = String(E->get()); + PropertyInfo p = script->variables[E].info; + p.name = String(E); p.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE; p_properties->push_back(p); } @@ -1312,11 +1263,11 @@ Variant::Type VisualScriptInstance::get_property_type(const StringName &p_name, void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const { List<StringName> fns; script->functions.get_key_list(&fns); - for (const List<StringName>::Element *E = fns.front(); E; E = E->next()) { + for (const StringName &E : fns) { MethodInfo mi; - mi.name = E->get(); - if (script->functions[E->get()].func_id >= 0 && script->nodes.has(script->functions[E->get()].func_id)) { - Ref<VisualScriptFunction> vsf = script->nodes[script->functions[E->get()].func_id].node; + mi.name = E; + if (script->functions[E].func_id >= 0 && script->nodes.has(script->functions[E].func_id)) { + Ref<VisualScriptFunction> vsf = script->nodes[script->functions[E].func_id].node; if (vsf.is_valid()) { for (int i = 0; i < vsf->get_argument_count(); i++) { PropertyInfo arg; @@ -1537,7 +1488,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p state->flow_stack_pos = flow_stack_pos; state->stack.resize(p_stack_size); state->pass = p_pass; - copymem(state->stack.ptrw(), p_stack, p_stack_size); + memcpy(state->stack.ptrw(), p_stack, p_stack_size); // Step 2, run away, return directly. r_error.error = Callable::CallError::CALL_OK; @@ -1607,7 +1558,7 @@ Variant VisualScriptInstance::_call_internal(const StringName &p_method, void *p } next = node->sequence_outputs[output]; - VSDEBUG("GOT NEXT NODE - " + (next ? itos(next->get_id()) : "NULL")); + VSDEBUG("GOT NEXT NODE - " + (next ? itos(next->get_id()) : "Null")); } if (flow_stack) { @@ -1802,7 +1753,7 @@ Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p sequence_bits[i] = false; // All starts as false. } - zeromem(pass_stack, f->pass_stack_size * sizeof(int)); + memset(pass_stack, 0, f->pass_stack_size * sizeof(int)); Map<int, VisualScriptNodeInstance *>::Element *E = instances.find(f->node); if (!E) { @@ -1882,46 +1833,10 @@ Ref<Script> VisualScriptInstance::get_script() const { return script; } -Vector<ScriptNetData> VisualScriptInstance::get_rpc_methods() const { +const Vector<MultiplayerAPI::RPCConfig> VisualScriptInstance::get_rpc_methods() const { return script->get_rpc_methods(); } -uint16_t VisualScriptInstance::get_rpc_method_id(const StringName &p_method) const { - return script->get_rpc_method_id(p_method); -} - -StringName VisualScriptInstance::get_rpc_method(const uint16_t p_rpc_method_id) const { - return script->get_rpc_method(p_rpc_method_id); -} - -MultiplayerAPI::RPCMode VisualScriptInstance::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const { - return script->get_rpc_mode_by_id(p_rpc_method_id); -} - -MultiplayerAPI::RPCMode VisualScriptInstance::get_rpc_mode(const StringName &p_method) const { - return script->get_rpc_mode(p_method); -} - -Vector<ScriptNetData> VisualScriptInstance::get_rset_properties() const { - return script->get_rset_properties(); -} - -uint16_t VisualScriptInstance::get_rset_property_id(const StringName &p_variable) const { - return script->get_rset_property_id(p_variable); -} - -StringName VisualScriptInstance::get_rset_property(const uint16_t p_rset_property_id) const { - return script->get_rset_property(p_rset_property_id); -} - -MultiplayerAPI::RPCMode VisualScriptInstance::get_rset_mode_by_id(const uint16_t p_rset_variable_id) const { - return script->get_rset_mode_by_id(p_rset_variable_id); -} - -MultiplayerAPI::RPCMode VisualScriptInstance::get_rset_mode(const StringName &p_variable) const { - return script->get_rset_mode(p_variable); -} - void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_owner) { script = p_script; owner = p_owner; @@ -1954,8 +1869,8 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o { List<StringName> keys; script->variables.get_key_list(&keys); - for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) { - variables[E->get()] = script->variables[E->get()].default_value; + for (const StringName &E : keys) { + variables[E] = script->variables[E].default_value; } } @@ -1963,8 +1878,8 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o { List<StringName> keys; script->functions.get_key_list(&keys); - for (const List<StringName>::Element *E = keys.front(); E; E = E->next()) { - const VisualScript::Function vsfn = p_script->functions[E->get()]; + for (const StringName &E : keys) { + const VisualScript::Function vsfn = p_script->functions[E]; Function function; function.node = vsfn.func_id; function.max_stack = 0; @@ -1975,7 +1890,7 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o Map<StringName, int> local_var_indices; if (function.node < 0) { - VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No start node in function: " + String(E->get())); + VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No start node in function: " + String(E)); ERR_CONTINUE(function.node < 0); } @@ -1983,7 +1898,7 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o Ref<VisualScriptFunction> func_node = script->get_node(vsfn.func_id); if (func_node.is_null()) { - VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E->get())); + VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E)); } ERR_CONTINUE(!func_node.is_valid()); @@ -2024,12 +1939,12 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o while (!nd_queue.is_empty()) { int ky = nd_queue.front()->get(); dc_lut[ky].get_key_list(&dc_keys); - for (const List<int>::Element *F = dc_keys.front(); F; F = F->next()) { + for (const int &F : dc_keys) { VisualScript::DataConnection dc; - dc.from_node = dc_lut[ky][F->get()].first; - dc.from_port = dc_lut[ky][F->get()].second; + dc.from_node = dc_lut[ky][F].first; + dc.from_port = dc_lut[ky][F].second; dc.to_node = ky; - dc.to_port = F->get(); + dc.to_port = F; dataconns.insert(dc); nd_queue.push_back(dc.from_node); node_ids.insert(dc.from_node); @@ -2044,7 +1959,7 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o for (const Set<int>::Element *F = node_ids.front(); F; F = F->next()) { Ref<VisualScriptNode> node = script->nodes[F->get()].node; - VisualScriptNodeInstance *instance = node->instance(this); // Create instance. + VisualScriptNodeInstance *instance = node->instantiate(this); // Create instance. ERR_FAIL_COND(!instance); instance->base = node.ptr(); @@ -2179,7 +2094,7 @@ void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_o } } - functions[E->get()] = function; + functions[E] = function; } } } @@ -2290,7 +2205,7 @@ Variant VisualScriptFunctionState::resume(Array p_args) { void VisualScriptFunctionState::_bind_methods() { ClassDB::bind_method(D_METHOD("connect_to_signal", "obj", "signals", "args"), &VisualScriptFunctionState::connect_to_signal); - ClassDB::bind_method(D_METHOD("resume", "args"), &VisualScriptFunctionState::resume, DEFVAL(Variant())); + ClassDB::bind_method(D_METHOD("resume", "args"), &VisualScriptFunctionState::resume, DEFVAL(Array())); ClassDB::bind_method(D_METHOD("is_valid"), &VisualScriptFunctionState::is_valid); ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &VisualScriptFunctionState::_signal_callback, MethodInfo("_signal_callback")); } @@ -2336,6 +2251,10 @@ void VisualScriptLanguage::finish() { void VisualScriptLanguage::get_reserved_words(List<String> *p_words) const { } +bool VisualScriptLanguage::is_control_flow_keyword(String p_keyword) const { + return false; +} + void VisualScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const { } @@ -2344,7 +2263,7 @@ void VisualScriptLanguage::get_string_delimiters(List<String> *p_delimiters) con Ref<Script> VisualScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { Ref<VisualScript> script; - script.instance(); + script.instantiate(); script->set_instance_base_type(p_base_class_name); return script; } @@ -2358,7 +2277,7 @@ void VisualScriptLanguage::make_template(const String &p_class_name, const Strin script->set_instance_base_type(p_base_class_name); } -bool VisualScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { +bool VisualScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const { return false; } @@ -2549,10 +2468,10 @@ void VisualScriptLanguage::debug_get_stack_level_members(int p_level, List<Strin List<StringName> vars; vs->get_variable_list(&vars); - for (List<StringName>::Element *E = vars.front(); E; E = E->next()) { + for (const StringName &E : vars) { Variant v; - if (_call_stack[l].instance->get_variable(E->get(), &v)) { - p_members->push_back("variables/" + E->get()); + if (_call_stack[l].instance->get_variable(E, &v)) { + p_members->push_back("variables/" + E); p_values->push_back(v); } } diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h index 72362e0ef4..932ebeb27f 100644 --- a/modules/visual_script/visual_script.h +++ b/modules/visual_script/visual_script.h @@ -87,7 +87,7 @@ public: void set_breakpoint(bool p_breakpoint); bool is_breakpoint() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) = 0; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) = 0; struct TypeGuess { Variant::Type type = Variant::NIL; @@ -234,8 +234,7 @@ private: HashMap<StringName, Function> functions; HashMap<StringName, Variable> variables; Map<StringName, Vector<Argument>> custom_signals; - Vector<ScriptNetData> rpc_functions; - Vector<ScriptNetData> rpc_variables; + Vector<MultiplayerAPI::RPCConfig> rpc_functions; Map<Object *, VisualScriptInstance *> instances; @@ -326,7 +325,7 @@ public: void set_instance_base_type(const StringName &p_type); - virtual bool can_instance() const override; + virtual bool can_instantiate() const override; virtual Ref<Script> get_base_script() const override; virtual StringName get_instance_base_type() const override; @@ -363,17 +362,7 @@ public: virtual int get_member_line(const StringName &p_member) const override; - virtual Vector<ScriptNetData> get_rpc_methods() const override; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const override; - virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const override; - - virtual Vector<ScriptNetData> get_rset_properties() const override; - virtual uint16_t get_rset_property_id(const StringName &p_property) const override; - virtual StringName get_rset_property(const uint16_t p_rset_property_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_rpc_method_id) const override; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const override; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const override; #ifdef TOOLS_ENABLED virtual bool are_subnodes_edited() const; @@ -454,24 +443,14 @@ public: virtual ScriptLanguage *get_language(); - virtual Vector<ScriptNetData> get_rpc_methods() const; - virtual uint16_t get_rpc_method_id(const StringName &p_method) const; - virtual StringName get_rpc_method(const uint16_t p_rpc_method_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const; - virtual MultiplayerAPI::RPCMode get_rpc_mode(const StringName &p_method) const; - - virtual Vector<ScriptNetData> get_rset_properties() const; - virtual uint16_t get_rset_property_id(const StringName &p_property) const; - virtual StringName get_rset_property(const uint16_t p_rset_property_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode_by_id(const uint16_t p_rpc_method_id) const; - virtual MultiplayerAPI::RPCMode get_rset_mode(const StringName &p_variable) const; + virtual const Vector<MultiplayerAPI::RPCConfig> get_rpc_methods() const; VisualScriptInstance(); ~VisualScriptInstance(); }; -class VisualScriptFunctionState : public Reference { - GDCLASS(VisualScriptFunctionState, Reference); +class VisualScriptFunctionState : public RefCounted { + GDCLASS(VisualScriptFunctionState, RefCounted); friend class VisualScriptInstance; ObjectID instance_id; @@ -586,12 +565,13 @@ public: /* EDITOR FUNCTIONS */ virtual void get_reserved_words(List<String> *p_words) const; + virtual bool is_control_flow_keyword(String p_keyword) const; virtual void get_comment_delimiters(List<String> *p_delimiters) const; virtual void get_string_delimiters(List<String> *p_delimiters) const; virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; virtual bool is_using_templates(); virtual void make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script); - virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; + virtual bool validate(const String &p_script, const String &p_path = "", List<String> *r_functions = nullptr, List<ScriptLanguage::ScriptError> *r_errors = nullptr, List<ScriptLanguage::Warning> *r_warnings = nullptr, Set<int> *r_safe_lines = nullptr) const; virtual Script *create_script() const; virtual bool has_named_classes() const; virtual bool supports_builtin_mode() const; @@ -639,7 +619,7 @@ public: template <class T> static Ref<VisualScriptNode> create_node_generic(const String &p_name) { Ref<T> node; - node.instance(); + node.instantiate(); return node; } diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp index 7ca14fbca8..c61c3ae272 100644 --- a/modules/visual_script/visual_script_builtin_funcs.cpp +++ b/modules/visual_script/visual_script_builtin_funcs.cpp @@ -33,7 +33,7 @@ #include "core/io/marshalls.h" #include "core/math/math_funcs.h" #include "core/object/class_db.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "core/os/os.h" #include "core/variant/variant_parser.h" @@ -68,7 +68,6 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX "inverse_lerp", "range_lerp", "move_toward", - "dectime", "randomize", "randi", "randf", @@ -132,6 +131,7 @@ bool VisualScriptBuiltinFunc::has_input_sequence_port() const { case TEXT_PRINT: case TEXT_PRINTERR: case TEXT_PRINTRAW: + case MATH_SEED: return true; default: return false; @@ -205,7 +205,6 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) { case MATH_INVERSE_LERP: case MATH_SMOOTHSTEP: case MATH_MOVE_TOWARD: - case MATH_DECTIME: case MATH_WRAP: case MATH_WRAPF: case LOGIC_CLAMP: @@ -348,15 +347,6 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const return PropertyInfo(Variant::FLOAT, "delta"); } } break; - case MATH_DECTIME: { - if (p_idx == 0) { - return PropertyInfo(Variant::FLOAT, "value"); - } else if (p_idx == 1) { - return PropertyInfo(Variant::FLOAT, "amount"); - } else { - return PropertyInfo(Variant::FLOAT, "step"); - } - } break; case MATH_RANDOMIZE: case MATH_RANDI: case MATH_RANDF: { @@ -535,10 +525,6 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons case MATH_RANGE_LERP: case MATH_SMOOTHSTEP: case MATH_MOVE_TOWARD: - case MATH_DECTIME: { - t = Variant::FLOAT; - - } break; case MATH_RANDOMIZE: { } break; case MATH_RANDI: { @@ -723,7 +709,7 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in case VisualScriptBuiltinFunc::MATH_POSMOD: { VALIDATE_ARG_NUM(0); VALIDATE_ARG_NUM(1); - *r_return = Math::posmod((int)*p_inputs[0], (int)*p_inputs[1]); + *r_return = Math::posmod((int64_t)*p_inputs[0], (int64_t)*p_inputs[1]); } break; case VisualScriptBuiltinFunc::MATH_FLOOR: { VALIDATE_ARG_NUM(0); @@ -836,12 +822,6 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in VALIDATE_ARG_NUM(2); *r_return = Math::move_toward((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); } break; - case VisualScriptBuiltinFunc::MATH_DECTIME: { - VALIDATE_ARG_NUM(0); - VALIDATE_ARG_NUM(1); - VALIDATE_ARG_NUM(2); - *r_return = Math::dectime((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); - } break; case VisualScriptBuiltinFunc::MATH_RANDOMIZE: { Math::randomize(); @@ -1186,7 +1166,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptBuiltinFunc::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptBuiltinFunc::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceBuiltinFunc *instance = memnew(VisualScriptNodeInstanceBuiltinFunc); instance->node = this; instance->instance = p_instance; @@ -1238,7 +1218,6 @@ void VisualScriptBuiltinFunc::_bind_methods() { BIND_ENUM_CONSTANT(MATH_INVERSE_LERP); BIND_ENUM_CONSTANT(MATH_RANGE_LERP); BIND_ENUM_CONSTANT(MATH_MOVE_TOWARD); - BIND_ENUM_CONSTANT(MATH_DECTIME); BIND_ENUM_CONSTANT(MATH_RANDOMIZE); BIND_ENUM_CONSTANT(MATH_RANDI); BIND_ENUM_CONSTANT(MATH_RANDF); @@ -1329,7 +1308,6 @@ void register_visual_script_builtin_func_node() { VisualScriptLanguage::singleton->add_register_func("functions/built_in/range_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANGE_LERP>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/smoothstep", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SMOOTHSTEP>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/move_toward", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_MOVE_TOWARD>); - VisualScriptLanguage::singleton->add_register_func("functions/built_in/dectime", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DECTIME>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/randomize", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDOMIZE>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/randi", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDI>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/randf", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDF>); diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h index 1fafaf1d98..f59a7a0f0c 100644 --- a/modules/visual_script/visual_script_builtin_funcs.h +++ b/modules/visual_script/visual_script_builtin_funcs.h @@ -68,7 +68,6 @@ public: MATH_INVERSE_LERP, MATH_RANGE_LERP, MATH_MOVE_TOWARD, - MATH_DECTIME, MATH_RANDOMIZE, MATH_RANDI, MATH_RANDF, @@ -139,7 +138,7 @@ public: void set_func(BuiltinFunc p_which); BuiltinFunc get_func(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptBuiltinFunc(VisualScriptBuiltinFunc::BuiltinFunc func); VisualScriptBuiltinFunc(); diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index 02ec9ccd06..a802e8022d 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -62,7 +62,7 @@ protected: void _sig_changed() { notify_property_list_changed(); - emit_signal("changed"); + emit_signal(SNAME("changed")); } bool _set(const StringName &p_name, const Variant &p_value) { @@ -196,10 +196,10 @@ protected: void _var_changed() { notify_property_list_changed(); - emit_signal("changed"); + emit_signal(SNAME("changed")); } void _var_value_changed() { - emit_signal("changed"); + emit_signal(SNAME("changed")); } bool _set(const StringName &p_name, const Variant &p_value) { @@ -381,7 +381,7 @@ static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) { case Variant::PLANE: color = Color(0.97, 0.44, 0.44); break; - case Variant::QUAT: + case Variant::QUATERNION: color = Color(0.93, 0.41, 0.64); break; case Variant::AABB: @@ -390,7 +390,7 @@ static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) { case Variant::BASIS: color = Color(0.89, 0.93, 0.41); break; - case Variant::TRANSFORM: + case Variant::TRANSFORM3D: color = Color(0.96, 0.66, 0.43); break; @@ -487,7 +487,7 @@ static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) { case Variant::PLANE: color = Color(0.97, 0.44, 0.44); break; - case Variant::QUAT: + case Variant::QUATERNION: color = Color(0.93, 0.41, 0.64); break; case Variant::AABB: @@ -496,7 +496,7 @@ static Color _color_from_type(Variant::Type p_type, bool dark_theme = true) { case Variant::BASIS: color = Color(0.7, 0.73, 0.1); break; - case Variant::TRANSFORM: + case Variant::TRANSFORM3D: color = Color(0.96, 0.56, 0.28); break; @@ -561,18 +561,16 @@ void VisualScriptEditor::_update_graph_connections() { List<VisualScript::SequenceConnection> sequence_conns; script->get_sequence_connection_list(&sequence_conns); - for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0); + for (const VisualScript::SequenceConnection &E : sequence_conns) { + graph->connect_node(itos(E.from_node), E.from_output, itos(E.to_node), 0); } List<VisualScript::DataConnection> data_conns; script->get_data_connection_list(&data_conns); - for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { - VisualScript::DataConnection dc = E->get(); - - Ref<VisualScriptNode> from_node = script->get_node(E->get().from_node); - Ref<VisualScriptNode> to_node = script->get_node(E->get().to_node); + for (VisualScript::DataConnection &dc : data_conns) { + Ref<VisualScriptNode> from_node = script->get_node(dc.from_node); + Ref<VisualScriptNode> to_node = script->get_node(dc.to_node); if (to_node->has_input_sequence_port()) { dc.to_port++; @@ -580,7 +578,7 @@ void VisualScriptEditor::_update_graph_connections() { dc.from_port += from_node->get_output_sequence_port_count(); - graph->connect_node(itos(E->get().from_node), dc.from_port, itos(E->get().to_node), dc.to_port); + graph->connect_node(itos(dc.from_node), dc.from_port, itos(dc.to_node), dc.to_port); } } @@ -611,41 +609,44 @@ void VisualScriptEditor::_update_graph(int p_only_id) { select_func_text->hide(); Ref<Texture2D> type_icons[Variant::VARIANT_MAX] = { - Control::get_theme_icon("Variant", "EditorIcons"), - Control::get_theme_icon("bool", "EditorIcons"), - Control::get_theme_icon("int", "EditorIcons"), - Control::get_theme_icon("float", "EditorIcons"), - Control::get_theme_icon("String", "EditorIcons"), - Control::get_theme_icon("Vector2", "EditorIcons"), - Control::get_theme_icon("Vector2i", "EditorIcons"), - Control::get_theme_icon("Rect2", "EditorIcons"), - Control::get_theme_icon("Rect2i", "EditorIcons"), - Control::get_theme_icon("Vector3", "EditorIcons"), - Control::get_theme_icon("Vector3i", "EditorIcons"), - Control::get_theme_icon("Transform2D", "EditorIcons"), - Control::get_theme_icon("Plane", "EditorIcons"), - Control::get_theme_icon("Quat", "EditorIcons"), - Control::get_theme_icon("AABB", "EditorIcons"), - Control::get_theme_icon("Basis", "EditorIcons"), - Control::get_theme_icon("Transform", "EditorIcons"), - Control::get_theme_icon("Color", "EditorIcons"), - Control::get_theme_icon("NodePath", "EditorIcons"), - Control::get_theme_icon("RID", "EditorIcons"), - Control::get_theme_icon("MiniObject", "EditorIcons"), - Control::get_theme_icon("Callable", "EditorIcons"), - Control::get_theme_icon("Signal", "EditorIcons"), - Control::get_theme_icon("Dictionary", "EditorIcons"), - Control::get_theme_icon("Array", "EditorIcons"), - Control::get_theme_icon("PackedByteArray", "EditorIcons"), - Control::get_theme_icon("PackedInt32Array", "EditorIcons"), - Control::get_theme_icon("PackedFloat32Array", "EditorIcons"), - Control::get_theme_icon("PackedStringArray", "EditorIcons"), - Control::get_theme_icon("PackedVector2Array", "EditorIcons"), - Control::get_theme_icon("PackedVector3Array", "EditorIcons"), - Control::get_theme_icon("PackedColorArray", "EditorIcons") + Control::get_theme_icon(SNAME("Variant"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("bool"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("int"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("float"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("String"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector2"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector2i"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Rect2"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Rect2i"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector3"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector3i"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Transform2D"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Plane"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Quaternion"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("AABB"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Basis"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Transform3D"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Color"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("StringName"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("NodePath"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("RID"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("MiniObject"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Callable"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Signal"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Dictionary"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedByteArray"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedInt32Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedInt64Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedFloat32Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedFloat64Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedStringArray"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedVector2Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedVector3Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedColorArray"), SNAME("EditorIcons")) }; - Ref<Texture2D> seq_port = Control::get_theme_icon("VisualShaderPort", "EditorIcons"); + Ref<Texture2D> seq_port = Control::get_theme_icon(SNAME("VisualShaderPort"), SNAME("EditorIcons")); List<int> node_ids; script->get_node_list(&node_ids); @@ -653,27 +654,27 @@ void VisualScriptEditor::_update_graph(int p_only_id) { script->get_node_list(&ids); StringName editor_icons = "EditorIcons"; - for (List<int>::Element *E = ids.front(); E; E = E->next()) { - if (p_only_id >= 0 && p_only_id != E->get()) { + for (int &E : ids) { + if (p_only_id >= 0 && p_only_id != E) { continue; } - Ref<VisualScriptNode> node = script->get_node(E->get()); - Vector2 pos = script->get_node_position(E->get()); + Ref<VisualScriptNode> node = script->get_node(E); + Vector2 pos = script->get_node_position(E); GraphNode *gnode = memnew(GraphNode); gnode->set_title(node->get_caption()); gnode->set_position_offset(pos * EDSCALE); - if (error_line == E->get()) { + if (error_line == E) { gnode->set_overlay(GraphNode::OVERLAY_POSITION); } else if (node->is_breakpoint()) { gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT); } gnode->set_meta("__vnode", node); - gnode->set_name(itos(E->get())); - gnode->connect("dragged", callable_mp(this, &VisualScriptEditor::_node_moved), varray(E->get())); - gnode->connect("close_request", callable_mp(this, &VisualScriptEditor::_remove_node), varray(E->get()), CONNECT_DEFERRED); + gnode->set_name(itos(E)); + gnode->connect("dragged", callable_mp(this, &VisualScriptEditor::_node_moved), varray(E)); + gnode->connect("close_request", callable_mp(this, &VisualScriptEditor::_remove_node), varray(E), CONNECT_DEFERRED); { Ref<VisualScriptFunction> v = node; @@ -693,7 +694,7 @@ void VisualScriptEditor::_update_graph(int p_only_id) { Button *btn = memnew(Button); btn->set_text(TTR("Add Input Port")); hbnc->add_child(btn); - btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_input_port), varray(E->get()), CONNECT_DEFERRED); + btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_input_port), varray(E), CONNECT_DEFERRED); } if (nd_list->is_output_port_editable()) { if (nd_list->is_input_port_editable()) { @@ -703,7 +704,7 @@ void VisualScriptEditor::_update_graph(int p_only_id) { Button *btn = memnew(Button); btn->set_text(TTR("Add Output Port")); hbnc->add_child(btn); - btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_output_port), varray(E->get()), CONNECT_DEFERRED); + btn->connect("pressed", callable_mp(this, &VisualScriptEditor::_add_output_port), varray(E), CONNECT_DEFERRED); } gnode->add_child(hbnc); } else if (Object::cast_to<VisualScriptExpression>(node.ptr())) { @@ -711,9 +712,9 @@ void VisualScriptEditor::_update_graph(int p_only_id) { LineEdit *line_edit = memnew(LineEdit); line_edit->set_text(node->get_text()); line_edit->set_expand_to_text_length_enabled(true); - line_edit->add_theme_font_override("font", get_theme_font("source", "EditorFonts")); + line_edit->add_theme_font_override("font", get_theme_font(SNAME("source"), SNAME("EditorFonts"))); gnode->add_child(line_edit); - line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed), varray(E->get())); + line_edit->connect("text_changed", callable_mp(this, &VisualScriptEditor::_expression_text_changed), varray(E)); } else { String text = node->get_text(); if (!text.is_empty()) { @@ -729,38 +730,26 @@ void VisualScriptEditor::_update_graph(int p_only_id) { gnode->set_comment(true); gnode->set_resizable(true); gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE); - gnode->connect("resize_request", callable_mp(this, &VisualScriptEditor::_comment_node_resized), varray(E->get())); + gnode->connect("resize_request", callable_mp(this, &VisualScriptEditor::_comment_node_resized), varray(E)); } if (node_styles.has(node->get_category())) { Ref<StyleBoxFlat> sbf = node_styles[node->get_category()]; if (gnode->is_comment()) { - sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox("comment", "GraphNode"); + sbf = EditorNode::get_singleton()->get_theme_base()->get_theme()->get_stylebox(SNAME("comment"), SNAME("GraphNode")); } Color c = sbf->get_border_color(); + c = ((c.r + c.g + c.b) / 3) < 0.7 ? Color(1.0, 1.0, 1.0, 0.85) : Color(0.0, 0.0, 0.0, 0.85); Color ic = c; - c.a = 1; - if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) { - Color mono_color; - if (((c.r + c.g + c.b) / 3) < 0.7) { - mono_color = Color(1.0, 1.0, 1.0); - ic = Color(0.0, 0.0, 0.0, 0.7); - } else { - mono_color = Color(0.0, 0.0, 0.0); - ic = Color(1.0, 1.0, 1.0, 0.7); - } - mono_color.a = 0.85; - c = mono_color; - } gnode->add_theme_color_override("title_color", c); - c.a = 0.7; + c.a = 1; gnode->add_theme_color_override("close_color", c); gnode->add_theme_color_override("resizer_color", ic); gnode->add_theme_style_override("frame", sbf); } - const Color mono_color = get_theme_color("mono_color", "Editor"); + const Color mono_color = get_theme_color(SNAME("mono_color"), SNAME("Editor")); int slot_idx = 0; @@ -844,8 +833,8 @@ void VisualScriptEditor::_update_graph(int p_only_id) { name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); name_box->set_text(left_name); name_box->set_expand_to_text_length_enabled(true); - name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get())); - name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, true)); + name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E)); + name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E, i, true)); } else { hbc->add_child(memnew(Label(left_name))); } @@ -858,18 +847,18 @@ void VisualScriptEditor::_update_graph(int p_only_id) { opbtn->select(left_type); opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); hbc->add_child(opbtn); - opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, true), CONNECT_DEFERRED); + opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E, i, true), CONNECT_DEFERRED); } Button *rmbtn = memnew(Button); - rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); + rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons"))); hbc->add_child(rmbtn); - rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_input_port), varray(E->get(), i), CONNECT_DEFERRED); + rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_input_port), varray(E, i), CONNECT_DEFERRED); } else { hbc->add_child(memnew(Label(left_name))); } - if (left_type != Variant::NIL && !script->is_input_value_port_connected(E->get(), i)) { + if (left_type != Variant::NIL && !script->is_input_value_port_connected(E, i)) { PropertyInfo pi = node->get_input_value_port_info(i); Button *button = memnew(Button); Variant value = node->get_default_input_value(i); @@ -896,7 +885,7 @@ void VisualScriptEditor::_update_graph(int p_only_id) { } else { button->set_text(value); } - button->connect("pressed", callable_mp(this, &VisualScriptEditor::_default_value_edited), varray(button, E->get(), i)); + button->connect("pressed", callable_mp(this, &VisualScriptEditor::_default_value_edited), varray(button, E, i)); hbc2->add_child(button); } } else { @@ -918,9 +907,9 @@ void VisualScriptEditor::_update_graph(int p_only_id) { if (right_ok) { if (is_vslist) { Button *rmbtn = memnew(Button); - rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); + rmbtn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons"))); hbc->add_child(rmbtn); - rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_output_port), varray(E->get(), i), CONNECT_DEFERRED); + rmbtn->connect("pressed", callable_mp(this, &VisualScriptEditor::_remove_output_port), varray(E, i), CONNECT_DEFERRED); if (nd_list->is_output_port_type_editable()) { OptionButton *opbtn = memnew(OptionButton); @@ -930,7 +919,7 @@ void VisualScriptEditor::_update_graph(int p_only_id) { opbtn->select(right_type); opbtn->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); hbc->add_child(opbtn); - opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E->get(), i, false), CONNECT_DEFERRED); + opbtn->connect("item_selected", callable_mp(this, &VisualScriptEditor::_change_port_type), varray(E, i, false), CONNECT_DEFERRED); } if (nd_list->is_output_port_name_editable()) { @@ -939,8 +928,8 @@ void VisualScriptEditor::_update_graph(int p_only_id) { name_box->set_custom_minimum_size(Size2(60 * EDSCALE, 0)); name_box->set_text(right_name); name_box->set_expand_to_text_length_enabled(true); - name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E->get())); - name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E->get(), i, false)); + name_box->connect("resized", callable_mp(this, &VisualScriptEditor::_update_node_size), varray(E)); + name_box->connect("focus_exited", callable_mp(this, &VisualScriptEditor::_port_name_focus_out), varray(name_box, E, i, false)); } else { hbc->add_child(memnew(Label(right_name))); } @@ -962,7 +951,7 @@ void VisualScriptEditor::_update_graph(int p_only_id) { gnode->add_child(vbc); - bool dark_theme = get_theme_constant("dark_theme", "Editor"); + bool dark_theme = get_theme_constant(SNAME("dark_theme"), SNAME("Editor")); if (i < mixed_seq_ports) { gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type, dark_theme), true, TYPE_SEQUENCE, mono_color, Ref<Texture2D>(), seq_port); } else { @@ -985,7 +974,7 @@ void VisualScriptEditor::_update_graph(int p_only_id) { graph->set_minimap_opacity(graph_minimap_opacity); // Use default_func instead of default_func for now I think that should be good stop gap solution to ensure not breaking anything. - graph->call_deferred("set_scroll_ofs", script->get_scroll() * EDSCALE); + graph->call_deferred(SNAME("set_scroll_ofs"), script->get_scroll() * EDSCALE); updating_graph = false; } @@ -995,7 +984,7 @@ void VisualScriptEditor::_change_port_type(int p_select, int p_id, int p_port, b return; } - undo_redo->create_action("Change Port Type"); + undo_redo->create_action(TTR("Change Port Type")); if (is_input) { undo_redo->add_do_method(vsn.ptr(), "set_input_data_port_type", p_port, Variant::Type(p_select)); undo_redo->add_undo_method(vsn.ptr(), "set_input_data_port_type", p_port, vsn->get_input_value_port_info(p_port).type); @@ -1027,7 +1016,7 @@ void VisualScriptEditor::_port_name_focus_out(const Node *p_name_box, int p_id, return; } - undo_redo->create_action("Change Port Name"); + undo_redo->create_action(TTR("Change Port Name")); if (is_input) { undo_redo->add_do_method(vsn.ptr(), "set_input_data_port_name", p_port, text); undo_redo->add_undo_method(vsn.ptr(), "set_input_data_port_name", p_port, vsn->get_input_value_port_info(p_port).name); @@ -1049,20 +1038,20 @@ void VisualScriptEditor::_update_members() { TreeItem *functions = members->create_item(root); functions->set_selectable(0, false); functions->set_text(0, TTR("Functions:")); - functions->add_button(0, Control::get_theme_icon("Override", "EditorIcons"), 1, false, TTR("Override an existing built-in function.")); - functions->add_button(0, Control::get_theme_icon("Add", "EditorIcons"), 0, false, TTR("Create a new function.")); - functions->set_custom_color(0, Control::get_theme_color("mono_color", "Editor")); + functions->add_button(0, Control::get_theme_icon(SNAME("Override"), SNAME("EditorIcons")), 1, false, TTR("Override an existing built-in function.")); + functions->add_button(0, Control::get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), 0, false, TTR("Create a new function.")); + functions->set_custom_color(0, Control::get_theme_color(SNAME("mono_color"), SNAME("Editor"))); List<StringName> func_names; script->get_function_list(&func_names); func_names.sort_custom<StringName::AlphCompare>(); - for (List<StringName>::Element *E = func_names.front(); E; E = E->next()) { + for (const StringName &E : func_names) { TreeItem *ti = members->create_item(functions); - ti->set_text(0, E->get()); + ti->set_text(0, E); ti->set_selectable(0, true); - ti->set_metadata(0, E->get()); - ti->add_button(0, Control::get_theme_icon("Edit", "EditorIcons"), 0); - if (selected == E->get()) { + ti->set_metadata(0, E); + ti->add_button(0, Control::get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")), 0); + if (selected == E) { ti->select(0); } } @@ -1070,58 +1059,58 @@ void VisualScriptEditor::_update_members() { TreeItem *variables = members->create_item(root); variables->set_selectable(0, false); variables->set_text(0, TTR("Variables:")); - variables->add_button(0, Control::get_theme_icon("Add", "EditorIcons"), -1, false, TTR("Create a new variable.")); - variables->set_custom_color(0, Control::get_theme_color("mono_color", "Editor")); + variables->add_button(0, Control::get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), -1, false, TTR("Create a new variable.")); + variables->set_custom_color(0, Control::get_theme_color(SNAME("mono_color"), SNAME("Editor"))); Ref<Texture2D> type_icons[Variant::VARIANT_MAX] = { - Control::get_theme_icon("Variant", "EditorIcons"), - Control::get_theme_icon("bool", "EditorIcons"), - Control::get_theme_icon("int", "EditorIcons"), - Control::get_theme_icon("float", "EditorIcons"), - Control::get_theme_icon("String", "EditorIcons"), - Control::get_theme_icon("Vector2", "EditorIcons"), - Control::get_theme_icon("Vector2i", "EditorIcons"), - Control::get_theme_icon("Rect2", "EditorIcons"), - Control::get_theme_icon("Rect2i", "EditorIcons"), - Control::get_theme_icon("Vector3", "EditorIcons"), - Control::get_theme_icon("Vector3i", "EditorIcons"), - Control::get_theme_icon("Transform2D", "EditorIcons"), - Control::get_theme_icon("Plane", "EditorIcons"), - Control::get_theme_icon("Quat", "EditorIcons"), - Control::get_theme_icon("AABB", "EditorIcons"), - Control::get_theme_icon("Basis", "EditorIcons"), - Control::get_theme_icon("Transform", "EditorIcons"), - Control::get_theme_icon("Color", "EditorIcons"), - Control::get_theme_icon("NodePath", "EditorIcons"), - Control::get_theme_icon("RID", "EditorIcons"), - Control::get_theme_icon("MiniObject", "EditorIcons"), - Control::get_theme_icon("Callable", "EditorIcons"), - Control::get_theme_icon("Signal", "EditorIcons"), - Control::get_theme_icon("Dictionary", "EditorIcons"), - Control::get_theme_icon("Array", "EditorIcons"), - Control::get_theme_icon("PackedByteArray", "EditorIcons"), - Control::get_theme_icon("PackedInt32Array", "EditorIcons"), - Control::get_theme_icon("PackedFloat32Array", "EditorIcons"), - Control::get_theme_icon("PackedStringArray", "EditorIcons"), - Control::get_theme_icon("PackedVector2Array", "EditorIcons"), - Control::get_theme_icon("PackedVector3Array", "EditorIcons"), - Control::get_theme_icon("PackedColorArray", "EditorIcons") + Control::get_theme_icon(SNAME("Variant"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("bool"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("int"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("float"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("String"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector2"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector2i"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Rect2"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Rect2i"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector3"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Vector3i"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Transform2D"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Plane"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Quaternion"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("AABB"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Basis"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Transform3D"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Color"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("NodePath"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("RID"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("MiniObject"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Callable"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Signal"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Dictionary"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedByteArray"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedInt32Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedFloat32Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedStringArray"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedVector2Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedVector3Array"), SNAME("EditorIcons")), + Control::get_theme_icon(SNAME("PackedColorArray"), SNAME("EditorIcons")) }; List<StringName> var_names; script->get_variable_list(&var_names); - for (List<StringName>::Element *E = var_names.front(); E; E = E->next()) { + for (const StringName &E : var_names) { TreeItem *ti = members->create_item(variables); - ti->set_text(0, E->get()); + ti->set_text(0, E); - ti->set_suffix(0, "= " + _sanitized_variant_text(E->get())); - ti->set_icon(0, type_icons[script->get_variable_info(E->get()).type]); + ti->set_suffix(0, "= " + _sanitized_variant_text(E)); + ti->set_icon(0, type_icons[script->get_variable_info(E).type]); ti->set_selectable(0, true); ti->set_editable(0, true); - ti->set_metadata(0, E->get()); - if (selected == E->get()) { + ti->set_metadata(0, E); + if (selected == E) { ti->select(0); } } @@ -1129,30 +1118,30 @@ void VisualScriptEditor::_update_members() { TreeItem *_signals = members->create_item(root); _signals->set_selectable(0, false); _signals->set_text(0, TTR("Signals:")); - _signals->add_button(0, Control::get_theme_icon("Add", "EditorIcons"), -1, false, TTR("Create a new signal.")); - _signals->set_custom_color(0, Control::get_theme_color("mono_color", "Editor")); + _signals->add_button(0, Control::get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), -1, false, TTR("Create a new signal.")); + _signals->set_custom_color(0, Control::get_theme_color(SNAME("mono_color"), SNAME("Editor"))); List<StringName> signal_names; script->get_custom_signal_list(&signal_names); - for (List<StringName>::Element *E = signal_names.front(); E; E = E->next()) { + for (const StringName &E : signal_names) { TreeItem *ti = members->create_item(_signals); - ti->set_text(0, E->get()); + ti->set_text(0, E); ti->set_selectable(0, true); ti->set_editable(0, true); - ti->set_metadata(0, E->get()); - if (selected == E->get()) { + ti->set_metadata(0, E); + if (selected == E) { ti->select(0); } } String base_type = script->get_instance_base_type(); String icon_type = base_type; - if (!Control::has_theme_icon(base_type, "EditorIcons")) { + if (!Control::has_theme_icon(base_type, SNAME("EditorIcons"))) { icon_type = "Object"; } base_type_select->set_text(base_type); - base_type_select->set_icon(Control::get_theme_icon(icon_type, "EditorIcons")); + base_type_select->set_icon(Control::get_theme_icon(icon_type, SNAME("EditorIcons"))); updating_members = false; } @@ -1181,11 +1170,11 @@ void VisualScriptEditor::_member_selected() { selected = ti->get_metadata(0); - if (ti->get_parent() == members->get_root()->get_children()) { + if (ti->get_parent() == members->get_root()->get_first_child()) { #ifdef OSX_ENABLED bool held_ctrl = Input::get_singleton()->is_key_pressed(KEY_META); #else - bool held_ctrl = Input::get_singleton()->is_key_pressed(KEY_CONTROL); + bool held_ctrl = Input::get_singleton()->is_key_pressed(KEY_CTRL); #endif if (held_ctrl) { ERR_FAIL_COND(!script->has_function(selected)); @@ -1227,7 +1216,7 @@ void VisualScriptEditor::_member_edited() { TreeItem *root = members->get_root(); - if (ti->get_parent() == root->get_children()) { + if (ti->get_parent() == root->get_first_child()) { selected = new_name; int node_id = script->get_function_node_id(name); @@ -1246,8 +1235,8 @@ void VisualScriptEditor::_member_edited() { // Also fix all function calls. List<int> lst; script->get_node_list(&lst); - for (List<int>::Element *F = lst.front(); F; F = F->next()) { - Ref<VisualScriptFunctionCall> fncall = script->get_node(F->get()); + for (int &F : lst) { + Ref<VisualScriptFunctionCall> fncall = script->get_node(F); if (!fncall.is_valid()) { continue; } @@ -1268,7 +1257,7 @@ void VisualScriptEditor::_member_edited() { return; // Or crash because it will become invalid. } - if (ti->get_parent() == root->get_children()->get_next()) { + if (ti->get_parent() == root->get_first_child()->get_next()) { selected = new_name; undo_redo->create_action(TTR("Rename Variable")); undo_redo->add_do_method(script.ptr(), "rename_variable", name, new_name); @@ -1284,7 +1273,7 @@ void VisualScriptEditor::_member_edited() { return; // Or crash because it will become invalid. } - if (ti->get_parent() == root->get_children()->get_next()->get_next()) { + if (ti->get_parent() == root->get_first_child()->get_next()->get_next()) { selected = new_name; undo_redo->create_action(TTR("Rename Signal")); undo_redo->add_do_method(script.ptr(), "rename_custom_signal", name, new_name); @@ -1312,10 +1301,10 @@ void VisualScriptEditor::_create_function_dialog() { void VisualScriptEditor::_create_function() { String name = _validate_name((func_name_box->get_text() == "") ? "new_func" : func_name_box->get_text()); selected = name; - Vector2 ofs = _get_available_pos(); + Vector2 pos = _get_available_pos(); Ref<VisualScriptFunction> func_node; - func_node.instance(); + func_node.instantiate(); func_node->set_name(name); for (int i = 0; i < func_input_vbox->get_child_count(); i++) { @@ -1334,7 +1323,7 @@ void VisualScriptEditor::_create_function() { undo_redo->create_action(TTR("Add Function")); undo_redo->add_do_method(script.ptr(), "add_function", name, func_node_id); undo_redo->add_undo_method(script.ptr(), "remove_function", name); - undo_redo->add_do_method(script.ptr(), "add_node", func_node_id, func_node, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", func_node_id, func_node, pos); undo_redo->add_undo_method(script.ptr(), "remove_node", func_node_id); undo_redo->add_do_method(this, "_update_members"); undo_redo->add_undo_method(this, "_update_members"); @@ -1378,7 +1367,7 @@ void VisualScriptEditor::_add_func_input() { hbox->add_child(type_box); Button *delete_button = memnew(Button); - delete_button->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); + delete_button->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons"))); delete_button->set_tooltip(vformat(TTR("Delete input port"))); hbox->add_child(delete_button); @@ -1418,7 +1407,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt if (ti->get_parent() == root) { //main buttons - if (ti == root->get_children()) { + if (ti == root->get_first_child()) { // Add function, this one uses menu. if (p_button == 1) { @@ -1429,18 +1418,18 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt } else if (p_button == 0) { String name = _validate_name("new_function"); selected = name; - Vector2 ofs = _get_available_pos(); + Vector2 pos = _get_available_pos(); Ref<VisualScriptFunction> func_node; - func_node.instance(); + func_node.instantiate(); func_node->set_name(name); int fn_id = script->get_available_id(); undo_redo->create_action(TTR("Add Function")); undo_redo->add_do_method(script.ptr(), "add_function", name, fn_id); - undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, pos); undo_redo->add_undo_method(script.ptr(), "remove_function", name); - undo_redo->add_do_method(script.ptr(), "remove_node", fn_id); + undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id); undo_redo->add_do_method(this, "_update_members"); undo_redo->add_undo_method(this, "_update_members"); undo_redo->add_do_method(this, "_update_graph"); @@ -1455,7 +1444,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt return; // Or crash because it will become invalid. } - if (ti == root->get_children()->get_next()) { + if (ti == root->get_first_child()->get_next()) { // Add variable. String name = _validate_name("new_variable"); selected = name; @@ -1471,7 +1460,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt return; // Or crash because it will become invalid. } - if (ti == root->get_children()->get_next()->get_next()) { + if (ti == root->get_first_child()->get_next()->get_next()) { // Add variable. String name = _validate_name("new_signal"); selected = name; @@ -1486,7 +1475,7 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt undo_redo->commit_action(); return; // Or crash because it will become invalid. } - } else if (ti->get_parent() == root->get_children()) { + } else if (ti->get_parent() == root->get_first_child()) { selected = ti->get_text(0); function_name_edit->set_position(Input::get_singleton()->get_mouse_position() - Vector2(60, -10)); function_name_edit->popup(); @@ -1581,13 +1570,13 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { script->get_data_connection_list(&data_connections); HashMap<int, Set<int>> conn_map; - for (const List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { - if (E->get().from_node == p_id && E->get().from_port == p_port) { + for (const VisualScript::DataConnection &E : data_connections) { + if (E.from_node == p_id && E.from_port == p_port) { // Push into the connections map. - if (!conn_map.has(E->get().to_node)) { - conn_map.set(E->get().to_node, Set<int>()); + if (!conn_map.has(E.to_node)) { + conn_map.set(E.to_node, Set<int>()); } - conn_map[E->get().to_node].insert(E->get().to_port); + conn_map[E.to_node].insert(E.to_port); } } @@ -1596,9 +1585,9 @@ void VisualScriptEditor::_remove_output_port(int p_id, int p_port) { List<int> keys; conn_map.get_key_list(&keys); - for (const List<int>::Element *E = keys.front(); E; E = E->next()) { - for (const Set<int>::Element *F = conn_map[E->get()].front(); F; F = F->next()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", p_id, p_port, E->get(), F->get()); + for (const int &E : keys) { + for (const Set<int>::Element *F = conn_map[E].front(); F; F = F->next()) { + undo_redo->add_undo_method(script.ptr(), "data_connect", p_id, p_port, E, F); } } @@ -1633,26 +1622,28 @@ void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id updating_graph = false; } -Vector2 VisualScriptEditor::_get_available_pos(bool centered, Vector2 ofs) const { - if (centered) { - ofs = graph->get_scroll_ofs() + graph->get_size() * 0.5; - } - +Vector2 VisualScriptEditor::_get_pos_in_graph(Vector2 p_point) const { + Vector2 pos = (graph->get_scroll_ofs() + p_point) / (graph->get_zoom() * EDSCALE); if (graph->is_using_snap()) { int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); + pos = pos.snapped(Vector2(snap, snap)); } + return pos; +} - ofs /= EDSCALE; +Vector2 VisualScriptEditor::_get_available_pos(bool p_centered, Vector2 p_pos) const { + if (p_centered) { + p_pos = _get_pos_in_graph(graph->get_size() * 0.5); + } while (true) { bool exists = false; List<int> existing; script->get_node_list(&existing); - for (List<int>::Element *E = existing.front(); E; E = E->next()) { - Point2 pos = script->get_node_position(E->get()); - if (pos.distance_to(ofs) < 50) { - ofs += Vector2(graph->get_snap(), graph->get_snap()); + for (int &E : existing) { + Point2 pos = script->get_node_position(E); + if (pos.distance_to(p_pos) < 50) { + p_pos += Vector2(graph->get_snap(), graph->get_snap()); exists = true; break; } @@ -1663,7 +1654,7 @@ Vector2 VisualScriptEditor::_get_available_pos(bool centered, Vector2 ofs) const break; } - return ofs; + return p_pos; } String VisualScriptEditor::_validate_name(const String &p_name) const { @@ -1705,8 +1696,8 @@ void VisualScriptEditor::_on_nodes_delete() { undo_redo->create_action(TTR("Remove VisualScript Nodes")); - for (List<int>::Element *F = to_erase.front(); F; F = F->next()) { - int cr_node = F->get(); + for (int &F : to_erase) { + int cr_node = F; undo_redo->add_do_method(script.ptr(), "remove_node", cr_node); undo_redo->add_undo_method(script.ptr(), "add_node", cr_node, script->get_node(cr_node), script->get_node_position(cr_node)); @@ -1714,18 +1705,18 @@ void VisualScriptEditor::_on_nodes_delete() { List<VisualScript::SequenceConnection> sequence_conns; script->get_sequence_connection_list(&sequence_conns); - for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - if (E->get().from_node == cr_node || E->get().to_node == cr_node) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node); + for (const VisualScript::SequenceConnection &E : sequence_conns) { + if (E.from_node == cr_node || E.to_node == cr_node) { + undo_redo->add_undo_method(script.ptr(), "sequence_connect", E.from_node, E.from_output, E.to_node); } } List<VisualScript::DataConnection> data_conns; script->get_data_connection_list(&data_conns); - for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { - if (E->get().from_node == F->get() || E->get().to_node == F->get()) { - undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + for (const VisualScript::DataConnection &E : data_conns) { + if (E.from_node == F || E.to_node == F) { + undo_redo->add_undo_method(script.ptr(), "data_connect", E.from_node, E.from_port, E.to_node, E.to_port); } } } @@ -1774,17 +1765,17 @@ void VisualScriptEditor::_on_nodes_duplicate() { List<VisualScript::SequenceConnection> seqs; script->get_sequence_connection_list(&seqs); - for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) { - if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { - undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]); + for (const VisualScript::SequenceConnection &E : seqs) { + if (to_duplicate.has(E.from_node) && to_duplicate.has(E.to_node)) { + undo_redo->add_do_method(script.ptr(), "sequence_connect", remap[E.from_node], E.from_output, remap[E.to_node]); } } List<VisualScript::DataConnection> data; script->get_data_connection_list(&data); - for (List<VisualScript::DataConnection>::Element *E = data.front(); E; E = E->next()) { - if (to_duplicate.has(E->get().from_node) && to_duplicate.has(E->get().to_node)) { - undo_redo->add_do_method(script.ptr(), "data_connect", remap[E->get().from_node], E->get().from_port, remap[E->get().to_node], E->get().to_port); + for (const VisualScript::DataConnection &E : data) { + if (to_duplicate.has(E.from_node) && to_duplicate.has(E.to_node)) { + undo_redo->add_do_method(script.ptr(), "data_connect", remap[E.from_node], E.from_port, remap[E.to_node], E.to_port); } } @@ -1854,18 +1845,18 @@ void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) { TreeItem *ti = members->get_selected(); if (ti) { TreeItem *root = members->get_root(); - if (ti->get_parent() == root->get_children()) { + if (ti->get_parent() == root->get_first_child()) { member_type = MEMBER_FUNCTION; } - if (ti->get_parent() == root->get_children()->get_next()) { + if (ti->get_parent() == root->get_first_child()->get_next()) { member_type = MEMBER_VARIABLE; } - if (ti->get_parent() == root->get_children()->get_next()->get_next()) { + if (ti->get_parent() == root->get_first_child()->get_next()->get_next()) { member_type = MEMBER_SIGNAL; } member_name = ti->get_text(0); } - if (ED_IS_SHORTCUT("visual_script_editor/delete_selected", p_event)) { + if (ED_IS_SHORTCUT("ui_graph_delete", p_event)) { _member_option(MEMBER_REMOVE); } if (ED_IS_SHORTCUT("visual_script_editor/edit_member", p_event)) { @@ -1875,9 +1866,9 @@ void VisualScriptEditor::_members_gui_input(const Ref<InputEvent> &p_event) { } Ref<InputEventMouseButton> btn = p_event; - if (btn.is_valid() && btn->is_doubleclick()) { + if (btn.is_valid() && btn->is_double_click()) { TreeItem *ti = members->get_selected(); - if (ti && ti->get_parent() == members->get_root()->get_children()) { // to check if it's a function + if (ti && ti->get_parent() == members->get_root()->get_first_child()) { // to check if it's a function _center_on_node(script->get_function_node_id(ti->get_metadata(0))); } } @@ -1910,8 +1901,8 @@ void VisualScriptEditor::_rename_function(const String &name, const String &new_ // Also fix all function calls. List<int> lst; script->get_node_list(&lst); - for (List<int>::Element *F = lst.front(); F; F = F->next()) { - Ref<VisualScriptFunctionCall> fncall = script->get_node(F->get()); + for (int &F : lst) { + Ref<VisualScriptFunctionCall> fncall = script->get_node(F); if (!fncall.is_valid()) { continue; } @@ -1959,13 +1950,13 @@ Variant VisualScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_f Dictionary dd; TreeItem *root = members->get_root(); - if (it->get_parent() == root->get_children()) { + if (it->get_parent() == root->get_first_child()) { dd["type"] = "visual_script_function_drag"; dd["function"] = type; - } else if (it->get_parent() == root->get_children()->get_next()) { + } else if (it->get_parent() == root->get_first_child()->get_next()) { dd["type"] = "visual_script_variable_drag"; dd["variable"] = type; - } else if (it->get_parent() == root->get_children()->get_next()->get_next()) { + } else if (it->get_parent() == root->get_first_child()->get_next()->get_next()) { dd["type"] = "visual_script_signal_drag"; dd["signal"] = type; @@ -2061,16 +2052,9 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da return; } - Vector2 ofs = graph->get_scroll_ofs() + p_point; - - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - - ofs /= EDSCALE; + Vector2 pos = _get_pos_in_graph(p_point); - int new_id = _create_new_node_from_name(d["node_type"], ofs); + int new_id = _create_new_node_from_name(d["node_type"], pos); Node *node = graph->get_node(itos(new_id)); if (node) { @@ -2083,25 +2067,19 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da #ifdef OSX_ENABLED bool use_set = Input::get_singleton()->is_key_pressed(KEY_META); #else - bool use_set = Input::get_singleton()->is_key_pressed(KEY_CONTROL); + bool use_set = Input::get_singleton()->is_key_pressed(KEY_CTRL); #endif - Vector2 ofs = graph->get_scroll_ofs() + p_point; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - - ofs /= EDSCALE; + Vector2 pos = _get_pos_in_graph(p_point); Ref<VisualScriptNode> vnode; if (use_set) { Ref<VisualScriptVariableSet> vnodes; - vnodes.instance(); + vnodes.instantiate(); vnodes->set_variable(d["variable"]); vnode = vnodes; } else { Ref<VisualScriptVariableGet> vnodeg; - vnodeg.instance(); + vnodeg.instantiate(); vnodeg->set_variable(d["variable"]); vnode = vnodeg; } @@ -2109,7 +2087,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos); undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -2123,22 +2101,16 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } if (String(d["type"]) == "visual_script_function_drag") { - Vector2 ofs = graph->get_scroll_ofs() + p_point; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - - ofs /= EDSCALE; + Vector2 pos = _get_pos_in_graph(p_point); Ref<VisualScriptFunctionCall> vnode; - vnode.instance(); + vnode.instantiate(); vnode->set_call_mode(VisualScriptFunctionCall::CALL_MODE_SELF); int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos); undo_redo->add_do_method(vnode.ptr(), "set_base_type", script->get_instance_base_type()); undo_redo->add_do_method(vnode.ptr(), "set_function", d["function"]); @@ -2155,22 +2127,16 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } if (String(d["type"]) == "visual_script_signal_drag") { - Vector2 ofs = graph->get_scroll_ofs() + p_point; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - - ofs /= EDSCALE; + Vector2 pos = _get_pos_in_graph(p_point); Ref<VisualScriptEmitSignal> vnode; - vnode.instance(); + vnode.instantiate(); vnode->set_signal(d["signal"]); int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos); undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -2184,22 +2150,16 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } if (String(d["type"]) == "resource") { - Vector2 ofs = graph->get_scroll_ofs() + p_point; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - - ofs /= EDSCALE; + Vector2 pos = _get_pos_in_graph(p_point); Ref<VisualScriptPreload> prnode; - prnode.instance(); + prnode.instantiate(); prnode->set_preload(d["resource"]); int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Preload Node")); - undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, pos); undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -2213,13 +2173,12 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } if (String(d["type"]) == "files") { - Vector2 ofs = graph->get_scroll_ofs() + p_point; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - - ofs /= EDSCALE; +#ifdef OSX_ENABLED + bool use_preload = Input::get_singleton()->is_key_pressed(KEY_META); +#else + bool use_preload = Input::get_singleton()->is_key_pressed(KEY_CTRL); +#endif + Vector2 pos = _get_pos_in_graph(p_point); Array files = d["files"]; @@ -2227,23 +2186,32 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da int new_id = script->get_available_id(); if (files.size()) { - undo_redo->create_action(TTR("Add Preload Node")); + undo_redo->create_action(TTR("Add Node(s)")); for (int i = 0; i < files.size(); i++) { Ref<Resource> res = ResourceLoader::load(files[i]); if (!res.is_valid()) { continue; } + Ref<Script> drop_script = ResourceLoader::load(files[i]); + if (drop_script.is_valid() && drop_script->is_tool() && drop_script->get_instance_base_type() == "VisualScriptCustomNode" && !use_preload) { + Ref<VisualScriptCustomNode> vscn; + vscn.instantiate(); + vscn->set_script(drop_script); + + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vscn, pos); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); + } else { + Ref<VisualScriptPreload> prnode; + prnode.instantiate(); + prnode->set_preload(res); - Ref<VisualScriptPreload> prnode; - prnode.instance(); - prnode->set_preload(res); - - undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, prnode, pos); + undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); + } new_ids.push_back(new_id); new_id++; - ofs += Vector2(20, 20) * EDSCALE; + pos += Vector2(20, 20); } undo_redo->add_do_method(this, "_update_graph"); @@ -2251,8 +2219,8 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da undo_redo->commit_action(); } - for (List<int>::Element *E = new_ids.front(); E; E = E->next()) { - Node *node = graph->get_node(itos(E->get())); + for (int &E : new_ids) { + Node *node = graph->get_node(itos(E)); if (node) { graph->set_selected(node); _node_selected(node); @@ -2271,57 +2239,45 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da #ifdef OSX_ENABLED bool use_node = Input::get_singleton()->is_key_pressed(KEY_META); #else - bool use_node = Input::get_singleton()->is_key_pressed(KEY_CONTROL); + bool use_node = Input::get_singleton()->is_key_pressed(KEY_CTRL); #endif Array nodes = d["nodes"]; - Vector2 ofs = graph->get_scroll_ofs() + p_point; - - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - ofs /= EDSCALE; + Vector2 pos = _get_pos_in_graph(p_point); undo_redo->create_action(TTR("Add Node(s) From Tree")); int base_id = script->get_available_id(); - if (nodes.size() > 1) { - use_node = true; - } - - for (int i = 0; i < nodes.size(); i++) { - NodePath np = nodes[i]; - Node *node = get_node(np); - if (!node) { - continue; - } + if (use_node || nodes.size() > 1) { + for (int i = 0; i < nodes.size(); i++) { + NodePath np = nodes[i]; + Node *node = get_node(np); + if (!node) { + continue; + } - Ref<VisualScriptNode> n; + Ref<VisualScriptNode> n; - if (use_node) { Ref<VisualScriptSceneNode> scene_node; - scene_node.instance(); + scene_node.instantiate(); scene_node->set_node_path(sn->get_path_to(node)); n = scene_node; - } else { - // ! Doesn't work properly. - Ref<VisualScriptFunctionCall> call; - call.instance(); - call->set_call_mode(VisualScriptFunctionCall::CALL_MODE_NODE_PATH); - call->set_base_path(sn->get_path_to(node)); - call->set_base_type(node->get_class()); - n = call; - method_select->select_from_instance(node, "", true, node->get_class()); - selecting_method_id = base_id; - } - undo_redo->add_do_method(script.ptr(), "add_node", base_id, n, ofs); - undo_redo->add_undo_method(script.ptr(), "remove_node", base_id); + undo_redo->add_do_method(script.ptr(), "add_node", base_id, n, pos); + undo_redo->add_undo_method(script.ptr(), "remove_node", base_id); + + base_id++; + pos += Vector2(25, 25); + } - base_id++; - ofs += Vector2(25, 25); + } else { + NodePath np = nodes[0]; + Node *node = get_node(np); + drop_position = pos; + drop_node = node; + drop_path = sn->get_path_to(node); + new_connect_node_select->select_from_instance(node, "", false, node->get_class()); } undo_redo->add_do_method(this, "_update_graph"); undo_redo->add_undo_method(this, "_update_graph"); @@ -2343,18 +2299,12 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } Node *node = Object::cast_to<Node>(obj); - Vector2 ofs = graph->get_scroll_ofs() + p_point; + Vector2 pos = _get_pos_in_graph(p_point); - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - - ofs /= EDSCALE; #ifdef OSX_ENABLED bool use_get = Input::get_singleton()->is_key_pressed(KEY_META); #else - bool use_get = Input::get_singleton()->is_key_pressed(KEY_CONTROL); + bool use_get = Input::get_singleton()->is_key_pressed(KEY_CTRL); #endif if (!node || Input::get_singleton()->is_key_pressed(KEY_SHIFT)) { @@ -2370,7 +2320,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da if (!use_get) { Ref<VisualScriptPropertySet> pset; - pset.instance(); + pset.instantiate(); pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE); pset->set_base_type(obj->get_class()); /*if (use_value) { @@ -2380,14 +2330,14 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da vnode = pset; } else { Ref<VisualScriptPropertyGet> pget; - pget.instance(); + pget.instantiate(); pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE); pget->set_base_type(obj->get_class()); vnode = pget; } - undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, pos); undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]); if (!use_get) { undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]); @@ -2412,7 +2362,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da if (!use_get) { Ref<VisualScriptPropertySet> pset; - pset.instance(); + pset.instantiate(); if (sn == node) { pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_SELF); } else { @@ -2423,7 +2373,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da vnode = pset; } else { Ref<VisualScriptPropertyGet> pget; - pget.instance(); + pget.instantiate(); if (sn == node) { pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_SELF); } else { @@ -2432,7 +2382,7 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } vnode = pget; } - undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", base_id, vnode, pos); undo_redo->add_do_method(vnode.ptr(), "set_property", d["property"]); if (!use_get) { undo_redo->add_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]); @@ -2446,21 +2396,13 @@ void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da } } -void VisualScriptEditor::_selected_method(const String &p_method, const String &p_type, const bool p_connecting) { - Ref<VisualScriptFunctionCall> vsfc = script->get_node(selecting_method_id); - if (!vsfc.is_valid()) { - return; - } - vsfc->set_function(p_method); -} - void VisualScriptEditor::_draw_color_over_button(Object *obj, Color p_color) { Button *button = Object::cast_to<Button>(obj); if (!button) { return; } - Ref<StyleBox> normal = get_theme_stylebox("normal", "Button"); + Ref<StyleBox> normal = get_theme_stylebox(SNAME("normal"), SNAME("Button")); button->draw_rect(Rect2(normal->get_offset(), button->get_size() - normal->get_minimum_size()), p_color); } @@ -2506,7 +2448,7 @@ void VisualScriptEditor::set_edited_resource(const RES &p_res) { script->connect("node_ports_changed", callable_mp(this, &VisualScriptEditor::_node_ports_changed)); _update_graph(); - call_deferred("_update_members"); + call_deferred(SNAME("_update_members")); } void VisualScriptEditor::enable_editor() { @@ -2540,7 +2482,7 @@ String VisualScriptEditor::get_name() { } Ref<Texture2D> VisualScriptEditor::get_theme_icon() { - return Control::get_theme_icon("VisualScript", "EditorIcons"); + return Control::get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons")); } bool VisualScriptEditor::is_unsaved() { @@ -2610,12 +2552,12 @@ void VisualScriptEditor::goto_line(int p_line, bool p_with_error) { List<StringName> functions; script->get_function_list(&functions); - for (List<StringName>::Element *E = functions.front(); E; E = E->next()) { + for (const StringName &E : functions) { if (script->has_node(p_line)) { _update_graph(); _update_members(); - call_deferred("call_deferred", "_center_on_node", E->get(), p_line); //editor might be just created and size might not exist yet + call_deferred(SNAME("call_deferred"), "_center_on_node", E, p_line); //editor might be just created and size might not exist yet return; } } @@ -2656,13 +2598,13 @@ Array VisualScriptEditor::get_breakpoints() { Array breakpoints; List<StringName> functions; script->get_function_list(&functions); - for (List<StringName>::Element *E = functions.front(); E; E = E->next()) { + for (int i = 0; i < functions.size(); i++) { List<int> nodes; script->get_node_list(&nodes); - for (List<int>::Element *F = nodes.front(); F; F = F->next()) { - Ref<VisualScriptNode> vsn = script->get_node(F->get()); + for (int &F : nodes) { + Ref<VisualScriptNode> vsn = script->get_node(F); if (vsn->is_breakpoint()) { - breakpoints.push_back(F->get() - 1); // Subtract 1 because breakpoints in text start from zero. + breakpoints.push_back(F - 1); // Subtract 1 because breakpoints in text start from zero. } } } @@ -2678,7 +2620,7 @@ void VisualScriptEditor::add_callback(const String &p_function, PackedStringArra } Ref<VisualScriptFunction> func; - func.instance(); + func.instantiate(); for (int i = 0; i < p_args.size(); i++) { String name = p_args[i]; Variant::Type type = Variant::NIL; @@ -2723,6 +2665,10 @@ void VisualScriptEditor::set_debugger_active(bool p_active) { } } +Control *VisualScriptEditor::get_base_editor() const { + return graph; +} + void VisualScriptEditor::set_tooltip_request_func(String p_method, Object *p_obj) { } @@ -2827,18 +2773,18 @@ void VisualScriptEditor::_remove_node(int p_id) { List<VisualScript::SequenceConnection> sequence_conns; script->get_sequence_connection_list(&sequence_conns); - for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - if (E->get().from_node == p_id || E->get().to_node == p_id) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", E->get().from_node, E->get().from_output, E->get().to_node); + for (const VisualScript::SequenceConnection &E : sequence_conns) { + if (E.from_node == p_id || E.to_node == p_id) { + undo_redo->add_undo_method(script.ptr(), "sequence_connect", E.from_node, E.from_output, E.to_node); } } List<VisualScript::DataConnection> data_conns; script->get_data_connection_list(&data_conns); - for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) { - if (E->get().from_node == p_id || E->get().to_node == p_id) { - undo_redo->add_undo_method(script.ptr(), "data_connect", E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + for (const VisualScript::DataConnection &E : data_conns) { + if (E.from_node == p_id || E.to_node == p_id) { + undo_redo->add_undo_method(script.ptr(), "data_connect", E.from_node, E.from_port, E.to_node, E.to_port); } } @@ -2856,9 +2802,9 @@ bool VisualScriptEditor::node_has_sequence_connections(int p_id) { List<VisualScript::SequenceConnection> sequence_conns; script->get_sequence_connection_list(&sequence_conns); - for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) { - int from = E->get().from_node; - int to = E->get().to_node; + for (const VisualScript::SequenceConnection &E : sequence_conns) { + int from = E.from_node; + int to = E.to_node; if (to == p_id || from == p_id) { return true; @@ -2891,6 +2837,20 @@ void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, ERR_FAIL_COND(from_seq != to_seq); + // Checking to prevent warnings. + if (from_seq) { + if (script->has_sequence_connection(p_from.to_int(), from_port, p_to.to_int())) { + return; + } + } else if (script->has_data_connection(p_from.to_int(), from_port, p_to.to_int(), to_port)) { + return; + } + + // Preventing connection to itself. + if (p_from.to_int() == p_to.to_int()) { + return; + } + // Do all the checks here. StringName func; // This the func where we store the one the nodes at the end of the resolution on having multiple nodes. @@ -3017,7 +2977,7 @@ void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_fro if (!vsn.is_valid()) { return; } - if (vsn->get_output_value_port_count()) { + if (vsn->get_output_value_port_count() || vsn->get_output_sequence_port_count()) { port_action_pos = p_release_pos; } @@ -3044,7 +3004,7 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac Ref<VisualScriptNode> node = script->get_node(p_port_action_node); - if (!node.is_valid()) { + if (!node.is_valid() || node->get_output_value_port_count() <= p_port_action_output) { return tg; } @@ -3083,19 +3043,12 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_port_ac } void VisualScriptEditor::_port_action_menu(int p_option) { - Vector2 ofs = graph->get_scroll_ofs() + port_action_pos; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - ofs /= EDSCALE; - Set<int> vn; switch (p_option) { case CREATE_CALL_SET_GET: { Ref<VisualScriptFunctionCall> n; - n.instance(); + n.instantiate(); VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn); @@ -3180,16 +3133,15 @@ void VisualScriptEditor::connect_data(Ref<VisualScriptNode> vnode_old, Ref<Visua } void VisualScriptEditor::_selected_connect_node(const String &p_text, const String &p_category, const bool p_connecting) { - Vector2 ofs = graph->get_scroll_ofs() + port_action_pos; - if (graph->is_using_snap()) { - int snap = graph->get_snap(); - ofs = ofs.snapped(Vector2(snap, snap)); - } - ofs /= EDSCALE; - ofs /= graph->get_zoom(); + Vector2 pos = _get_pos_in_graph(port_action_pos); Set<int> vn; + if (drop_position != Vector2()) { + pos = drop_position; + } + drop_position = Vector2(); + bool port_node_exists = true; // if (func == StringName()) { @@ -3224,7 +3176,7 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri } undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode_new, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode_new, pos); if (vnode_old.is_valid() && p_connecting) { connect_seq(vnode_old, vnode_new, new_id); connect_data(vnode_old, vnode_new, new_id); @@ -3242,52 +3194,96 @@ void VisualScriptEditor::_selected_connect_node(const String &p_text, const Stri if (p_category == String("method")) { Ref<VisualScriptFunctionCall> n; - n.instance(); + n.instantiate(); + if (!drop_path.is_empty()) { + if (drop_path == ".") { + n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_SELF); + } else { + n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_NODE_PATH); + n->set_base_path(drop_path); + } + } + if (drop_node) { + n->set_base_type(drop_node->get_class()); + if (drop_node->get_script_instance()) { + n->set_base_script(drop_node->get_script_instance()->get_script()->get_path()); + } + } vnode = n; } else if (p_category == String("set")) { Ref<VisualScriptPropertySet> n; - n.instance(); + n.instantiate(); + if (!drop_path.is_empty()) { + if (drop_path == ".") { + n->set_call_mode(VisualScriptPropertySet::CALL_MODE_SELF); + } else { + n->set_call_mode(VisualScriptPropertySet::CALL_MODE_NODE_PATH); + n->set_base_path(drop_path); + } + } + if (drop_node) { + n->set_base_type(drop_node->get_class()); + if (drop_node->get_script_instance()) { + n->set_base_script(drop_node->get_script_instance()->get_script()->get_path()); + } + } vnode = n; script_prop_set = n; } else if (p_category == String("get")) { Ref<VisualScriptPropertyGet> n; - n.instance(); + n.instantiate(); n->set_property(p_text); + if (!drop_path.is_empty()) { + if (drop_path == ".") { + n->set_call_mode(VisualScriptPropertyGet::CALL_MODE_SELF); + } else { + n->set_call_mode(VisualScriptPropertyGet::CALL_MODE_NODE_PATH); + n->set_base_path(drop_path); + } + } + if (drop_node) { + n->set_base_type(drop_node->get_class()); + if (drop_node->get_script_instance()) { + n->set_base_script(drop_node->get_script_instance()->get_script()->get_path()); + } + } vnode = n; } + drop_path = String(); + drop_node = nullptr; if (p_category == String("action")) { if (p_text == "VisualScriptCondition") { Ref<VisualScriptCondition> n; - n.instance(); + n.instantiate(); vnode = n; } if (p_text == "VisualScriptSwitch") { Ref<VisualScriptSwitch> n; - n.instance(); + n.instantiate(); vnode = n; } else if (p_text == "VisualScriptSequence") { Ref<VisualScriptSequence> n; - n.instance(); + n.instantiate(); vnode = n; } else if (p_text == "VisualScriptIterator") { Ref<VisualScriptIterator> n; - n.instance(); + n.instantiate(); vnode = n; } else if (p_text == "VisualScriptWhile") { Ref<VisualScriptWhile> n; - n.instance(); + n.instantiate(); vnode = n; } else if (p_text == "VisualScriptReturn") { Ref<VisualScriptReturn> n; - n.instance(); + n.instantiate(); vnode = n; } } int new_id = script->get_available_id(); undo_redo->create_action(TTR("Add Node")); - undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", new_id, vnode, pos); undo_redo->add_undo_method(script.ptr(), "remove_node", new_id); undo_redo->add_do_method(this, "_update_graph", new_id); undo_redo->add_undo_method(this, "_update_graph", new_id); @@ -3464,9 +3460,9 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons List<MethodInfo> methods; bool found = false; ClassDB::get_virtual_methods(script->get_instance_base_type(), &methods); - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().name == name) { - minfo = E->get(); + for (const MethodInfo &E : methods) { + if (E.name == name) { + minfo = E; found = true; } } @@ -3476,7 +3472,7 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons selected = name; Ref<VisualScriptFunction> func_node; - func_node.instance(); + func_node.instantiate(); func_node->set_name(name); int fn_id = script->get_available_id(); undo_redo->create_action(TTR("Add Function")); @@ -3486,18 +3482,18 @@ void VisualScriptEditor::_selected_new_virtual_method(const String &p_text, cons func_node->add_argument(minfo.arguments[i].type, minfo.arguments[i].name, -1, minfo.arguments[i].hint, minfo.arguments[i].hint_string); } - Vector2 ofs = _get_available_pos(); + Vector2 pos = _get_available_pos(); - undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, pos); undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id); if (minfo.return_val.type != Variant::NIL || minfo.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT) { Ref<VisualScriptReturn> ret_node; - ret_node.instance(); + ret_node.instantiate(); ret_node->set_return_type(minfo.return_val.type); ret_node->set_enable_return_value(true); ret_node->set_name(name); int nid = script->get_available_id() + 1; - undo_redo->add_do_method(script.ptr(), "add_node", nid, ret_node, _get_available_pos(false, ofs + Vector2(500, 0))); + undo_redo->add_do_method(script.ptr(), "add_node", nid, ret_node, _get_available_pos(false, pos + Vector2(500, 0))); undo_redo->add_undo_method(script.ptr(), "remove_node", nid); } @@ -3615,40 +3611,41 @@ void VisualScriptEditor::_notification(int p_what) { return; } - edit_variable_edit->add_theme_style_override("bg", get_theme_stylebox("bg", "Tree")); - edit_signal_edit->add_theme_style_override("bg", get_theme_stylebox("bg", "Tree")); - func_input_scroll->add_theme_style_override("bg", get_theme_stylebox("bg", "Tree")); + edit_variable_edit->add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree"))); + edit_signal_edit->add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree"))); + func_input_scroll->add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree"))); Ref<Theme> tm = EditorNode::get_singleton()->get_theme_base()->get_theme(); bool dark_theme = tm->get_constant("dark_theme", "Editor"); - List<Pair<String, Color>> colors; if (dark_theme) { - colors.push_back(Pair<String, Color>("flow_control", Color(0.96, 0.96, 0.96))); - colors.push_back(Pair<String, Color>("functions", Color(0.96, 0.52, 0.51))); - colors.push_back(Pair<String, Color>("data", Color(0.5, 0.96, 0.81))); - colors.push_back(Pair<String, Color>("operators", Color(0.67, 0.59, 0.87))); - colors.push_back(Pair<String, Color>("custom", Color(0.5, 0.73, 0.96))); - colors.push_back(Pair<String, Color>("constants", Color(0.96, 0.5, 0.69))); + node_colors["flow_control"] = Color(0.96, 0.96, 0.96); + node_colors["functions"] = Color(0.96, 0.52, 0.51); + node_colors["data"] = Color(0.5, 0.96, 0.81); + node_colors["operators"] = Color(0.67, 0.59, 0.87); + node_colors["custom"] = Color(0.5, 0.73, 0.96); + node_colors["constants"] = Color(0.96, 0.5, 0.69); } else { - colors.push_back(Pair<String, Color>("flow_control", Color(0.26, 0.26, 0.26))); - colors.push_back(Pair<String, Color>("functions", Color(0.95, 0.4, 0.38))); - colors.push_back(Pair<String, Color>("data", Color(0.07, 0.73, 0.51))); - colors.push_back(Pair<String, Color>("operators", Color(0.51, 0.4, 0.82))); - colors.push_back(Pair<String, Color>("custom", Color(0.31, 0.63, 0.95))); - colors.push_back(Pair<String, Color>("constants", Color(0.94, 0.18, 0.49))); + node_colors["flow_control"] = Color(0.26, 0.26, 0.26); + node_colors["functions"] = Color(0.95, 0.4, 0.38); + node_colors["data"] = Color(0.07, 0.73, 0.51); + node_colors["operators"] = Color(0.51, 0.4, 0.82); + node_colors["custom"] = Color(0.31, 0.63, 0.95); + node_colors["constants"] = Color(0.94, 0.18, 0.49); } - for (List<Pair<String, Color>>::Element *E = colors.front(); E; E = E->next()) { - Ref<StyleBoxFlat> sb = tm->get_stylebox("frame", "GraphNode"); + for (Map<StringName, Color>::Element *E = node_colors.front(); E; E = E->next()) { + const Ref<StyleBoxFlat> sb = tm->get_stylebox(SNAME("frame"), SNAME("GraphNode")); + if (!sb.is_null()) { Ref<StyleBoxFlat> frame_style = sb->duplicate(); - Color c = sb->get_border_color(); - Color cn = E->get().second; - cn.a = c.a; - frame_style->set_border_color(cn); - node_styles[E->get().first] = frame_style; + // Adjust the border color to be close to the GraphNode's background color. + // This keeps the node's title area from being too distracting. + Color color = dark_theme ? E->get().darkened(0.75) : E->get().lightened(0.75); + color.a = 0.9; + frame_style->set_border_color(color); + node_styles[E->key()] = frame_style; } } @@ -3735,8 +3732,8 @@ void VisualScriptEditor::_menu_option(int p_what) { _update_graph(); - for (List<String>::Element *E = reselect.front(); E; E = E->next()) { - GraphNode *gn = Object::cast_to<GraphNode>(graph->get_node(E->get())); + for (const String &E : reselect) { + GraphNode *gn = Object::cast_to<GraphNode>(graph->get_node(E)); gn->set_selected(true); } @@ -3775,18 +3772,18 @@ void VisualScriptEditor::_menu_option(int p_what) { List<VisualScript::SequenceConnection> sequence_connections; script->get_sequence_connection_list(&sequence_connections); - for (List<VisualScript::SequenceConnection>::Element *E = sequence_connections.front(); E; E = E->next()) { - if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { - clipboard->sequence_connections.insert(E->get()); + for (const VisualScript::SequenceConnection &E : sequence_connections) { + if (clipboard->nodes.has(E.from_node) && clipboard->nodes.has(E.to_node)) { + clipboard->sequence_connections.insert(E); } } List<VisualScript::DataConnection> data_connections; script->get_data_connection_list(&data_connections); - for (List<VisualScript::DataConnection>::Element *E = data_connections.front(); E; E = E->next()) { - if (clipboard->nodes.has(E->get().from_node) && clipboard->nodes.has(E->get().to_node)) { - clipboard->data_connections.insert(E->get()); + for (const VisualScript::DataConnection &E : data_connections) { + if (clipboard->nodes.has(E.from_node) && clipboard->nodes.has(E.to_node)) { + clipboard->data_connections.insert(E); } } if (p_what == EDIT_CUT_NODES) { @@ -3812,8 +3809,8 @@ void VisualScriptEditor::_menu_option(int p_what) { { List<int> nodes; script->get_node_list(&nodes); - for (List<int>::Element *E = nodes.front(); E; E = E->next()) { - Vector2 pos = script->get_node_position(E->get()).snapped(Vector2(2, 2)); + for (int &E : nodes) { + Vector2 pos = script->get_node_position(E).snapped(Vector2(2, 2)); existing_positions.insert(pos); } } @@ -3936,22 +3933,22 @@ void VisualScriptEditor::_menu_option(int p_what) { // Pick the node with input sequence. Set<int> nodes_from; Set<int> nodes_to; - for (List<VisualScript::SequenceConnection>::Element *E = seqs.front(); E; E = E->next()) { - if (nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { - seqmove.insert(E->get()); - nodes_from.insert(E->get().from_node); - } else if (nodes.has(E->get().from_node) && !nodes.has(E->get().to_node)) { - seqext.insert(E->get()); - } else if (!nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { + for (const VisualScript::SequenceConnection &E : seqs) { + if (nodes.has(E.from_node) && nodes.has(E.to_node)) { + seqmove.insert(E); + nodes_from.insert(E.from_node); + } else if (nodes.has(E.from_node) && !nodes.has(E.to_node)) { + seqext.insert(E); + } else if (!nodes.has(E.from_node) && nodes.has(E.to_node)) { if (start_node == -1) { - seqext.insert(E->get()); - start_node = E->get().to_node; + seqext.insert(E); + start_node = E.to_node; } else { EditorNode::get_singleton()->show_warning(TTR("Try to only have one sequence input in selection.")); return; } } - nodes_to.insert(E->get().to_node); + nodes_to.insert(E.to_node); } // To use to add return nodes. @@ -3979,20 +3976,20 @@ void VisualScriptEditor::_menu_option(int p_what) { { List<VisualScript::DataConnection> dats; script->get_data_connection_list(&dats); - for (List<VisualScript::DataConnection>::Element *E = dats.front(); E; E = E->next()) { - if (nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { - datamove.insert(E->get()); - } else if (!nodes.has(E->get().from_node) && nodes.has(E->get().to_node)) { + for (const VisualScript::DataConnection &E : dats) { + if (nodes.has(E.from_node) && nodes.has(E.to_node)) { + datamove.insert(E); + } else if (!nodes.has(E.from_node) && nodes.has(E.to_node)) { // Add all these as inputs for the Function. - Ref<VisualScriptNode> node = script->get_node(E->get().to_node); + Ref<VisualScriptNode> node = script->get_node(E.to_node); if (node.is_valid()) { - dataext.insert(E->get()); - PropertyInfo pi = node->get_input_value_port_info(E->get().to_port); + dataext.insert(E); + PropertyInfo pi = node->get_input_value_port_info(E.to_port); inputs.push_back(pi.type); - input_connections.push_back(Pair<int, int>(E->get().to_node, E->get().to_port)); + input_connections.push_back(Pair<int, int>(E.to_node, E.to_port)); } - } else if (nodes.has(E->get().from_node) && !nodes.has(E->get().to_node)) { - dataext.insert(E->get()); + } else if (nodes.has(E.from_node) && !nodes.has(E.to_node)) { + dataext.insert(E); } } } @@ -4000,16 +3997,16 @@ void VisualScriptEditor::_menu_option(int p_what) { { String new_fn = _validate_name("new_function"); - Vector2 ofs = _get_available_pos(false, script->get_node_position(start_node) - Vector2(80, 150)); + Vector2 pos = _get_available_pos(false, script->get_node_position(start_node) - Vector2(80, 150)); Ref<VisualScriptFunction> func_node; - func_node.instance(); + func_node.instantiate(); func_node->set_name(new_fn); undo_redo->create_action(TTR("Create Function")); undo_redo->add_do_method(script.ptr(), "add_function", new_fn, fn_id); - undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, ofs); + undo_redo->add_do_method(script.ptr(), "add_node", fn_id, func_node, pos); undo_redo->add_undo_method(script.ptr(), "remove_function", new_fn); undo_redo->add_undo_method(script.ptr(), "remove_node", fn_id); undo_redo->add_do_method(this, "_update_members"); @@ -4048,12 +4045,12 @@ void VisualScriptEditor::_menu_option(int p_what) { int m = 1; for (Set<int>::Element *G = end_nodes.front(); G; G = G->next()) { Ref<VisualScriptReturn> ret_node; - ret_node.instance(); + ret_node.instantiate(); int ret_id = fn_id + (m++); selections.insert(ret_id); - Vector2 ofsi = _get_available_pos(false, script->get_node_position(G->get()) + Vector2(80, -100)); - undo_redo->add_do_method(script.ptr(), "add_node", ret_id, ret_node, ofsi); + Vector2 posi = _get_available_pos(false, script->get_node_position(G->get()) + Vector2(80, -100)); + undo_redo->add_do_method(script.ptr(), "add_node", ret_id, ret_node, posi); undo_redo->add_undo_method(script.ptr(), "remove_node", ret_id); undo_redo->add_do_method(script.ptr(), "sequence_connect", G->get(), 0, ret_id); @@ -4093,9 +4090,9 @@ void VisualScriptEditor::_menu_option(int p_what) { // but I hope that it will not be a problem considering that we won't be creating functions so frequently, // and cyclic connections would be a problem but hopefully we won't let them get to this point. void VisualScriptEditor::_get_ends(int p_node, const List<VisualScript::SequenceConnection> &p_seqs, const Set<int> &p_selected, Set<int> &r_end_nodes) { - for (const List<VisualScript::SequenceConnection>::Element *E = p_seqs.front(); E; E = E->next()) { - int from = E->get().from_node; - int to = E->get().to_node; + for (const VisualScript::SequenceConnection &E : p_seqs) { + int from = E.from_node; + int to = E.to_node; if (from == p_node && p_selected.has(to)) { // This is an interior connection move forward to the to node. @@ -4119,36 +4116,36 @@ void VisualScriptEditor::_member_rmb_selected(const Vector2 &p_pos) { TreeItem *root = members->get_root(); - Ref<Texture2D> del_icon = Control::get_theme_icon("Remove", "EditorIcons"); + Ref<Texture2D> del_icon = Control::get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")); - Ref<Texture2D> edit_icon = Control::get_theme_icon("Edit", "EditorIcons"); + Ref<Texture2D> edit_icon = Control::get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")); - if (ti->get_parent() == root->get_children()) { + if (ti->get_parent() == root->get_first_child()) { member_type = MEMBER_FUNCTION; member_name = ti->get_text(0); member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT); member_popup->add_separator(); - member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("visual_script_editor/delete_selected"), MEMBER_REMOVE); + member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("ui_graph_delete"), MEMBER_REMOVE); member_popup->popup(); return; } - if (ti->get_parent() == root->get_children()->get_next()) { + if (ti->get_parent() == root->get_first_child()->get_next()) { member_type = MEMBER_VARIABLE; member_name = ti->get_text(0); member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT); member_popup->add_separator(); - member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("visual_script_editor/delete_selected"), MEMBER_REMOVE); + member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("ui_graph_delete"), MEMBER_REMOVE); member_popup->popup(); return; } - if (ti->get_parent() == root->get_children()->get_next()->get_next()) { + if (ti->get_parent() == root->get_first_child()->get_next()->get_next()) { member_type = MEMBER_SIGNAL; member_name = ti->get_text(0); member_popup->add_icon_shortcut(edit_icon, ED_GET_SHORTCUT("visual_script_editor/edit_member"), MEMBER_EDIT); member_popup->add_separator(); - member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("visual_script_editor/delete_selected"), MEMBER_REMOVE); + member_popup->add_icon_shortcut(del_icon, ED_GET_SHORTCUT("ui_graph_delete"), MEMBER_REMOVE); member_popup->popup(); return; } @@ -4169,16 +4166,16 @@ void VisualScriptEditor::_member_option(int p_option) { undo_redo->add_undo_method(script.ptr(), "add_node", fn_node, script->get_node(fn_node), script->get_node_position(fn_node)); List<VisualScript::SequenceConnection> seqcons; script->get_sequence_connection_list(&seqcons); - for (const List<VisualScript::SequenceConnection>::Element *E = seqcons.front(); E; E = E->next()) { - if (E->get().from_node == fn_node) { - undo_redo->add_undo_method(script.ptr(), "sequence_connect", fn_node, E->get().from_output, E->get().to_node); + for (const VisualScript::SequenceConnection &E : seqcons) { + if (E.from_node == fn_node) { + undo_redo->add_undo_method(script.ptr(), "sequence_connect", fn_node, E.from_output, E.to_node); } } List<VisualScript::DataConnection> datcons; script->get_data_connection_list(&datcons); - for (const List<VisualScript::DataConnection>::Element *E = datcons.front(); E; E = E->next()) { - if (E->get().from_node == fn_node) { - undo_redo->add_undo_method(script.ptr(), "data_connect", fn_node, E->get().from_port, E->get().to_node, E->get().to_port); + for (const VisualScript::DataConnection &E : datcons) { + if (E.from_node == fn_node) { + undo_redo->add_undo_method(script.ptr(), "data_connect", fn_node, E.from_port, E.to_node, E.to_port); } } undo_redo->add_do_method(this, "_update_members"); @@ -4250,9 +4247,9 @@ void VisualScriptEditor::_bind_methods() { ClassDB::bind_method("_create_new_node_from_name", &VisualScriptEditor::_create_new_node_from_name); - ClassDB::bind_method("get_drag_data_fw", &VisualScriptEditor::get_drag_data_fw); - ClassDB::bind_method("can_drop_data_fw", &VisualScriptEditor::can_drop_data_fw); - ClassDB::bind_method("drop_data_fw", &VisualScriptEditor::drop_data_fw); + ClassDB::bind_method("_get_drag_data_fw", &VisualScriptEditor::get_drag_data_fw); + ClassDB::bind_method("_can_drop_data_fw", &VisualScriptEditor::can_drop_data_fw); + ClassDB::bind_method("_drop_data_fw", &VisualScriptEditor::drop_data_fw); ClassDB::bind_method("_input", &VisualScriptEditor::_input); @@ -4290,7 +4287,7 @@ VisualScriptEditor::VisualScriptEditor() { members_section = memnew(VBoxContainer); // Add but wait until done setting up this. - ScriptEditor::get_singleton()->get_left_list_split()->call_deferred("add_child", members_section); + ScriptEditor::get_singleton()->get_left_list_split()->call_deferred(SNAME("add_child"), members_section); members_section->set_v_size_flags(SIZE_EXPAND_FILL); CheckButton *tool_script_check = memnew(CheckButton); @@ -4482,11 +4479,6 @@ VisualScriptEditor::VisualScriptEditor() { add_child(default_value_edit); default_value_edit->connect("variant_changed", callable_mp(this, &VisualScriptEditor::_default_value_changed)); - method_select = memnew(VisualScriptPropertySelector); - add_child(method_select); - method_select->connect("selected", callable_mp(this, &VisualScriptEditor::_selected_method)); - error_line = -1; - new_connect_node_select = memnew(VisualScriptPropertySelector); add_child(new_connect_node_select); new_connect_node_select->connect("selected", callable_mp(this, &VisualScriptEditor::_selected_connect_node)); @@ -4536,7 +4528,7 @@ void VisualScriptEditor::register_editor() { Ref<VisualScriptNode> _VisualScriptEditor::create_node_custom(const String &p_name) { Ref<VisualScriptCustomNode> node; - node.instance(); + node.instantiate(); node->set_script(singleton->custom_nodes[p_name]); return node; } @@ -4556,14 +4548,14 @@ void _VisualScriptEditor::add_custom_node(const String &p_name, const String &p_ String node_name = "custom/" + p_category + "/" + p_name; custom_nodes.insert(node_name, p_script); VisualScriptLanguage::singleton->add_register_func(node_name, &_VisualScriptEditor::create_node_custom); - emit_signal("custom_nodes_updated"); + emit_signal(SNAME("custom_nodes_updated")); } void _VisualScriptEditor::remove_custom_node(const String &p_name, const String &p_category) { String node_name = "custom/" + p_category + "/" + p_name; custom_nodes.erase(node_name); VisualScriptLanguage::singleton->remove_register_func(node_name); - emit_signal("custom_nodes_updated"); + emit_signal(SNAME("custom_nodes_updated")); } void _VisualScriptEditor::_bind_methods() { diff --git a/modules/visual_script/visual_script_editor.h b/modules/visual_script/visual_script_editor.h index bb6f194286..962ea380aa 100644 --- a/modules/visual_script/visual_script_editor.h +++ b/modules/visual_script/visual_script_editor.h @@ -60,7 +60,7 @@ class VisualScriptEditor : public ScriptEditorBase { EDIT_CUT_NODES, EDIT_PASTE_NODES, EDIT_CREATE_FUNCTION, - REFRESH_GRAPH + REFRESH_GRAPH, }; enum PortAction { @@ -135,6 +135,7 @@ class VisualScriptEditor : public ScriptEditorBase { Vector<Pair<Variant::Type, String>> args; }; + Map<StringName, Color> node_colors; HashMap<StringName, Ref<StyleBox>> node_styles; void _update_graph_connections(); @@ -178,6 +179,9 @@ class VisualScriptEditor : public ScriptEditorBase { void connect_data(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode, int new_id); + NodePath drop_path; + Node *drop_node = nullptr; + Vector2 drop_position; void _selected_connect_node(const String &p_text, const String &p_category, const bool p_connecting = true); void connect_seq(Ref<VisualScriptNode> vnode_old, Ref<VisualScriptNode> vnode_new, int new_id); @@ -225,7 +229,8 @@ class VisualScriptEditor : public ScriptEditorBase { void _update_node_size(int p_id); void _port_name_focus_out(const Node *p_name_box, int p_id, int p_port, bool is_input); - Vector2 _get_available_pos(bool centered = true, Vector2 ofs = Vector2()) const; + Vector2 _get_pos_in_graph(Vector2 p_point) const; + Vector2 _get_available_pos(bool p_centered = true, Vector2 p_pos = Vector2()) const; bool node_has_sequence_connections(int p_id); @@ -268,9 +273,6 @@ class VisualScriptEditor : public ScriptEditorBase { void _graph_ofs_changed(const Vector2 &p_ofs); void _comment_node_resized(const Vector2 &p_new_size, int p_node); - int selecting_method_id; - void _selected_method(const String &p_method, const String &p_type, const bool p_connecting); - void _draw_color_over_button(Object *obj, Color p_color); void _button_resource_previewed(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, Variant p_ud); @@ -316,9 +318,12 @@ public: virtual void set_tooltip_request_func(String p_method, Object *p_obj) override; virtual Control *get_edit_menu() override; virtual void clear_edit_menu() override; + virtual void set_find_replace_bar(FindReplaceBar *p_bar) override { p_bar->hide(); }; // Not needed here. virtual bool can_lose_focus_on_node_selection() override { return false; } virtual void validate() override; + virtual Control *get_base_editor() const override; + static void register_editor(); static void free_clipboard(); diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp index cb4230bea9..99b7275008 100644 --- a/modules/visual_script/visual_script_expression.cpp +++ b/modules/visual_script/visual_script_expression.cpp @@ -526,10 +526,10 @@ Error VisualScriptExpression::_get_token(Token &r_token) { r_token.value = Math_TAU; } else if (id == "INF") { r_token.type = TK_CONSTANT; - r_token.value = Math_INF; + r_token.value = INFINITY; } else if (id == "NAN") { r_token.type = TK_CONSTANT; - r_token.value = Math_NAN; + r_token.value = NAN; } else if (id == "not") { r_token.type = TK_OP_NOT; } else if (id == "or") { @@ -1498,7 +1498,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptExpression::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptExpression::instantiate(VisualScriptInstance *p_instance) { _compile_expression(); VisualScriptNodeInstanceExpression *instance = memnew(VisualScriptNodeInstanceExpression); instance->instance = p_instance; diff --git a/modules/visual_script/visual_script_expression.h b/modules/visual_script/visual_script_expression.h index c35075ea53..ef16222b42 100644 --- a/modules/visual_script/visual_script_expression.h +++ b/modules/visual_script/visual_script_expression.h @@ -273,7 +273,7 @@ public: virtual String get_text() const override; virtual String get_category() const override { return "operators"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptExpression(); ~VisualScriptExpression(); diff --git a/modules/visual_script/visual_script_flow_control.cpp b/modules/visual_script/visual_script_flow_control.cpp index e977f9c96b..62a4f465cb 100644 --- a/modules/visual_script/visual_script_flow_control.cpp +++ b/modules/visual_script/visual_script_flow_control.cpp @@ -138,7 +138,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptReturn::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptReturn::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceReturn *instance = memnew(VisualScriptNodeInstanceReturn); instance->node = this; instance->instance = p_instance; @@ -154,7 +154,7 @@ VisualScriptReturn::VisualScriptReturn() { template <bool with_value> static Ref<VisualScriptNode> create_return_node(const String &p_name) { Ref<VisualScriptReturn> node; - node.instance(); + node.instantiate(); node->set_enable_return_value(with_value); return node; } @@ -231,7 +231,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptCondition::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptCondition::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceCondition *instance = memnew(VisualScriptNodeInstanceCondition); instance->node = this; instance->instance = p_instance; @@ -311,7 +311,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptWhile::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptWhile::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceWhile *instance = memnew(VisualScriptNodeInstanceWhile); instance->node = this; instance->instance = p_instance; @@ -435,7 +435,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptIterator::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptIterator::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceIterator *instance = memnew(VisualScriptNodeInstanceIterator); instance->node = this; instance->instance = p_instance; @@ -534,7 +534,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptSequence::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptSequence::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSequence *instance = memnew(VisualScriptNodeInstanceSequence); instance->node = this; instance->instance = p_instance; @@ -618,7 +618,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptSwitch::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptSwitch::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSwitch *instance = memnew(VisualScriptNodeInstanceSwitch); instance->instance = p_instance; instance->case_count = case_values.size(); @@ -831,7 +831,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptTypeCast::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptTypeCast::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceTypeCast *instance = memnew(VisualScriptNodeInstanceTypeCast); instance->instance = p_instance; instance->base_type = base_type; @@ -852,11 +852,11 @@ void VisualScriptTypeCast::_bind_methods() { } String script_ext_hint; - for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) { + for (const String &E : script_extensions) { if (script_ext_hint != String()) { script_ext_hint += ","; } - script_ext_hint += "*." + E->get(); + script_ext_hint += "*." + E; } ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type"); diff --git a/modules/visual_script/visual_script_flow_control.h b/modules/visual_script/visual_script_flow_control.h index d9c4dedafd..73822fcc37 100644 --- a/modules/visual_script/visual_script_flow_control.h +++ b/modules/visual_script/visual_script_flow_control.h @@ -64,7 +64,7 @@ public: void set_enable_return_value(bool p_enable); bool is_return_value_enabled() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptReturn(); }; @@ -91,7 +91,7 @@ public: virtual String get_text() const override; virtual String get_category() const override { return "flow_control"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptCondition(); }; @@ -118,7 +118,7 @@ public: virtual String get_text() const override; virtual String get_category() const override { return "flow_control"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptWhile(); }; @@ -145,7 +145,7 @@ public: virtual String get_text() const override; virtual String get_category() const override { return "flow_control"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptIterator(); }; @@ -177,7 +177,7 @@ public: void set_steps(int p_steps); int get_steps() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptSequence(); }; @@ -220,7 +220,7 @@ public: virtual String get_text() const override; virtual String get_category() const override { return "flow_control"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptSwitch(); }; @@ -258,7 +258,7 @@ public: virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptTypeCast(); }; diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp index 9310b86627..6ba5ad4fd6 100644 --- a/modules/visual_script/visual_script_func_nodes.cpp +++ b/modules/visual_script/visual_script_func_nodes.cpp @@ -254,25 +254,32 @@ PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) con } String VisualScriptFunctionCall::get_caption() const { - if (call_mode == CALL_MODE_SELF) { - return " " + String(function) + "()"; - } - if (call_mode == CALL_MODE_SINGLETON) { - return String(singleton) + ":" + String(function) + "()"; - } else if (call_mode == CALL_MODE_BASIC_TYPE) { - return Variant::get_type_name(basic_type) + "." + String(function) + "()"; - } else if (call_mode == CALL_MODE_NODE_PATH) { - return " [" + String(base_path.simplified()) + "]." + String(function) + "()"; - } else { - return " " + base_type + "." + String(function) + "()"; - } + return " " + String(function) + "()"; } String VisualScriptFunctionCall::get_text() const { + String text; + + if (call_mode == CALL_MODE_BASIC_TYPE) { + text = String("On ") + Variant::get_type_name(basic_type); + } else if (call_mode == CALL_MODE_INSTANCE) { + text = String("On ") + base_type; + } else if (call_mode == CALL_MODE_NODE_PATH) { + text = "[" + String(base_path.simplified()) + "]"; + } else if (call_mode == CALL_MODE_SELF) { + text = "On Self"; + } else if (call_mode == CALL_MODE_SINGLETON) { + text = String(singleton) + ":" + String(function) + "()"; + } + if (rpc_call_mode) { - return "RPC"; + text += " RPC"; + if (rpc_call_mode == RPC_UNRELIABLE || rpc_call_mode == RPC_UNRELIABLE_TO_ID) { + text += " UNREL"; + } } - return ""; + + return text; } void VisualScriptFunctionCall::set_basic_type(Variant::Type p_type) { @@ -513,29 +520,29 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const if (property.name == "base_script") { if (call_mode != CALL_MODE_INSTANCE) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } if (property.name == "basic_type") { if (call_mode != CALL_MODE_BASIC_TYPE) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } if (property.name == "singleton") { if (call_mode != CALL_MODE_SINGLETON) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } else { List<Engine::Singleton> names; Engine::get_singleton()->get_singletons(&names); property.hint = PROPERTY_HINT_ENUM; String sl; - for (List<Engine::Singleton>::Element *E = names.front(); E; E = E->next()) { + for (const Engine::Singleton &E : names) { if (sl != String()) { sl += ","; } - sl += E->get().name; + sl += E.name; } property.hint_string = sl; } @@ -543,7 +550,7 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const if (property.name == "node_path") { if (call_mode != CALL_MODE_NODE_PATH) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } else { Node *bnode = _get_base_node(); if (bnode) { @@ -614,7 +621,7 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const } if (mc == 0) { - property.usage = 0; //do not show + property.usage = PROPERTY_USAGE_NONE; //do not show } else { property.hint_string = "0," + itos(mc) + ",1"; } @@ -622,7 +629,7 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const if (property.name == "rpc_call_mode") { if (call_mode == CALL_MODE_BASIC_TYPE) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } } @@ -676,11 +683,11 @@ void VisualScriptFunctionCall::_bind_methods() { } String script_ext_hint; - for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) { + for (const String &E : script_extensions) { if (script_ext_hint != String()) { script_ext_hint += ","; } - script_ext_hint += "*." + E->get(); + script_ext_hint += "*." + E; } ADD_PROPERTY(PropertyInfo(Variant::INT, "call_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type,Singleton"), "set_call_mode", "get_call_mode"); @@ -737,20 +744,22 @@ public: } int to_id = 0; - bool reliable = true; + //bool reliable = true; if (rpc_mode >= VisualScriptFunctionCall::RPC_RELIABLE_TO_ID) { to_id = *p_args[0]; p_args += 1; p_argcount -= 1; - if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE_TO_ID) { - reliable = false; - } - } else if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE) { - reliable = false; + //if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE_TO_ID) { + //reliable = false; + //} } + //else if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE) { + //reliable = false; + //} - node->rpcp(to_id, !reliable, function, p_args, p_argcount); + // TODO reliable? + node->rpcp(to_id, function, p_args, p_argcount); return true; } @@ -854,7 +863,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptFunctionCall::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptFunctionCall::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceFunctionCall *instance = memnew(VisualScriptNodeInstanceFunctionCall); instance->node = this; instance->instance = p_instance; @@ -889,7 +898,7 @@ VisualScriptFunctionCall::VisualScriptFunctionCall() { template <VisualScriptFunctionCall::CallMode cmode> static Ref<VisualScriptNode> create_function_call_node(const String &p_name) { Ref<VisualScriptFunctionCall> node; - node.instance(); + node.instantiate(); node->set_call_mode(cmode); return node; } @@ -899,11 +908,11 @@ static Ref<VisualScriptNode> create_function_call_node(const String &p_name) { ////////////////////////////////////////// int VisualScriptPropertySet::get_output_sequence_port_count() const { - return call_mode != CALL_MODE_BASIC_TYPE ? 1 : 0; + return 1; } bool VisualScriptPropertySet::has_input_sequence_port() const { - return call_mode != CALL_MODE_BASIC_TYPE; + return 1; } Node *VisualScriptPropertySet::_get_base_node() const { @@ -988,31 +997,33 @@ PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const if (p_idx == 0) { PropertyInfo pi; pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type); - pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower()); - _adjust_input_index(pi); + pi.name = "instance"; return pi; } } List<PropertyInfo> props; ClassDB::get_property_list(_get_base_type(), &props, false); - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - if (E->get().name == property) { - PropertyInfo pinfo = PropertyInfo(E->get().type, "value", PROPERTY_HINT_TYPE_STRING, E->get().hint_string); + for (const PropertyInfo &E : props) { + if (E.name == property) { + String detail_prop_name = property; + if (index != StringName()) { + detail_prop_name += "." + String(index); + } + PropertyInfo pinfo = PropertyInfo(E.type, detail_prop_name, PROPERTY_HINT_TYPE_STRING, E.hint_string); _adjust_input_index(pinfo); return pinfo; } } PropertyInfo pinfo = type_cache; - pinfo.name = "value"; _adjust_input_index(pinfo); return pinfo; } PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) const { if (call_mode == CALL_MODE_BASIC_TYPE) { - return PropertyInfo(basic_type, "out"); + return PropertyInfo(basic_type, "pass"); } else if (call_mode == CALL_MODE_INSTANCE) { return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type()); } else { @@ -1034,17 +1045,18 @@ String VisualScriptPropertySet::get_caption() const { } String VisualScriptPropertySet::get_text() const { + if (!has_input_sequence_port()) { + return ""; + } if (call_mode == CALL_MODE_BASIC_TYPE) { return String("On ") + Variant::get_type_name(basic_type); + } else if (call_mode == CALL_MODE_INSTANCE) { + return String("On ") + base_type; + } else if (call_mode == CALL_MODE_NODE_PATH) { + return " [" + String(base_path.simplified()) + "]"; + } else { + return "On Self"; } - - static const char *cname[3] = { - "Self", - "Scene Node", - "Instance" - }; - - return String("On ") + cname[call_mode]; } void VisualScriptPropertySet::_update_base_type() { @@ -1123,9 +1135,9 @@ void VisualScriptPropertySet::_update_cache() { List<PropertyInfo> pinfo; v.get_property_list(&pinfo); - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().name == property) { - type_cache = E->get(); + for (const PropertyInfo &E : pinfo) { + if (E.name == property) { + type_cache = E; } } @@ -1174,9 +1186,9 @@ void VisualScriptPropertySet::_update_cache() { script->get_script_property_list(&pinfo); } - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().name == property) { - type_cache = E->get(); + for (const PropertyInfo &E : pinfo) { + if (E.name == property) { + type_cache = E; return; } } @@ -1276,19 +1288,19 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const { if (property.name == "base_script") { if (call_mode != CALL_MODE_INSTANCE) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } if (property.name == "basic_type") { if (call_mode != CALL_MODE_BASIC_TYPE) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } if (property.name == "node_path") { if (call_mode != CALL_MODE_NODE_PATH) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } else { Node *bnode = _get_base_node(); if (bnode) { @@ -1342,15 +1354,15 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const { List<PropertyInfo> plist; v.get_property_list(&plist); String options = ""; - for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - options += "," + E->get().name; + for (const PropertyInfo &E : plist) { + options += "," + E.name; } property.hint = PROPERTY_HINT_ENUM; property.hint_string = options; property.type = Variant::STRING; if (options == "") { - property.usage = 0; //hide if type has no usable index + property.usage = PROPERTY_USAGE_NONE; //hide if type has no usable index } } } @@ -1398,11 +1410,11 @@ void VisualScriptPropertySet::_bind_methods() { } String script_ext_hint; - for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) { + for (const String &E : script_extensions) { if (script_ext_hint != String()) { script_ext_hint += ","; } - script_ext_hint += "*." + E->get(); + script_ext_hint += "*." + E; } ADD_PROPERTY(PropertyInfo(Variant::INT, "set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode"); @@ -1585,7 +1597,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptPropertySet::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptPropertySet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstancePropertySet *instance = memnew(VisualScriptNodeInstancePropertySet); instance->node = this; instance->instance = p_instance; @@ -1616,7 +1628,7 @@ VisualScriptPropertySet::VisualScriptPropertySet() { template <VisualScriptPropertySet::CallMode cmode> static Ref<VisualScriptNode> create_property_set_node(const String &p_name) { Ref<VisualScriptPropertySet> node; - node.instance(); + node.instantiate(); node->set_call_mode(cmode); return node; } @@ -1705,7 +1717,9 @@ int VisualScriptPropertyGet::get_input_value_port_count() const { } int VisualScriptPropertyGet::get_output_value_port_count() const { - return 1; + int pc = (call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 2 : 1; + + return pc; } String VisualScriptPropertyGet::get_output_sequence_port_text(int p_port) const { @@ -1725,33 +1739,46 @@ PropertyInfo VisualScriptPropertyGet::get_input_value_port_info(int p_idx) const } PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) const { - List<PropertyInfo> props; - ClassDB::get_property_list(_get_base_type(), &props, false); - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - if (E->get().name == property) { - return PropertyInfo(E->get().type, "value." + String(index)); + if (call_mode == CALL_MODE_BASIC_TYPE && p_idx == 0) { + return PropertyInfo(basic_type, "pass"); + } else if (call_mode == CALL_MODE_INSTANCE && p_idx == 0) { + return PropertyInfo(Variant::OBJECT, "pass", PROPERTY_HINT_TYPE_STRING, get_base_type()); + } else { + List<PropertyInfo> props; + ClassDB::get_property_list(_get_base_type(), &props, false); + for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { + if (E->get().name == property) { + PropertyInfo pinfo = PropertyInfo(E->get().type, String(property) + "." + String(index), E->get().hint, E->get().hint_string); + _adjust_input_index(pinfo); + return pinfo; + } } } - return PropertyInfo(type_cache, "value"); + PropertyInfo pinfo = PropertyInfo(type_cache, "value"); + _adjust_input_index(pinfo); + return pinfo; } String VisualScriptPropertyGet::get_caption() const { - return String("Get ") + property; + String prop = String("Get ") + property; + if (index != StringName()) { + prop += "." + String(index); + } + + return prop; } String VisualScriptPropertyGet::get_text() const { if (call_mode == CALL_MODE_BASIC_TYPE) { return String("On ") + Variant::get_type_name(basic_type); + } else if (call_mode == CALL_MODE_INSTANCE) { + return String("On ") + base_type; + } else if (call_mode == CALL_MODE_NODE_PATH) { + return " [" + String(base_path.simplified()) + "]"; + } else { + return "On Self"; } - - static const char *cname[3] = { - "Self", - "Scene Node", - "Instance" - }; - - return String("On ") + cname[call_mode]; } void VisualScriptPropertyGet::set_base_type(const StringName &p_type) { @@ -1793,9 +1820,9 @@ void VisualScriptPropertyGet::_update_cache() { List<PropertyInfo> pinfo; v.get_property_list(&pinfo); - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - if (E->get().name == property) { - type_cache = E->get().type; + for (const PropertyInfo &E : pinfo) { + if (E.name == property) { + type_cache = E.type; return; } } @@ -1931,6 +1958,19 @@ Variant::Type VisualScriptPropertyGet::_get_type_cache() const { return type_cache; } +void VisualScriptPropertyGet::_adjust_input_index(PropertyInfo &pinfo) const { + if (index != StringName()) { + Variant v; + Callable::CallError ce; + Variant::construct(pinfo.type, v, nullptr, 0, ce); + Variant i = v.get(index); + pinfo.type = i.get_type(); + pinfo.name = String(property) + "." + index; + } else { + pinfo.name = String(property); + } +} + void VisualScriptPropertyGet::set_index(const StringName &p_type) { if (index == p_type) { return; @@ -1954,19 +1994,19 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const { if (property.name == "base_script") { if (call_mode != CALL_MODE_INSTANCE) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } if (property.name == "basic_type") { if (call_mode != CALL_MODE_BASIC_TYPE) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } if (property.name == "node_path") { if (call_mode != CALL_MODE_NODE_PATH) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } else { Node *bnode = _get_base_node(); if (bnode) { @@ -2019,15 +2059,15 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const { List<PropertyInfo> plist; v.get_property_list(&plist); String options = ""; - for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - options += "," + E->get().name; + for (const PropertyInfo &E : plist) { + options += "," + E.name; } property.hint = PROPERTY_HINT_ENUM; property.hint_string = options; property.type = Variant::STRING; if (options == "") { - property.usage = 0; //hide if type has no usable index + property.usage = PROPERTY_USAGE_NONE; //hide if type has no usable index } } } @@ -2072,11 +2112,11 @@ void VisualScriptPropertyGet::_bind_methods() { } String script_ext_hint; - for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) { + for (const String &E : script_extensions) { if (script_ext_hint != String()) { script_ext_hint += ","; } - script_ext_hint += "." + E->get(); + script_ext_hint += "." + E; } ADD_PROPERTY(PropertyInfo(Variant::INT, "set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode"); @@ -2157,15 +2197,17 @@ public: bool valid; Variant v = *p_inputs[0]; - *p_outputs[0] = v.get(property, &valid); + *p_outputs[1] = v.get(property, &valid); if (index != StringName()) { - *p_outputs[0] = p_outputs[0]->get_named(index, valid); + *p_outputs[1] = p_outputs[1]->get_named(index, valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("Invalid index property name."); } + + *p_outputs[0] = v; }; } @@ -2173,7 +2215,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptPropertyGet::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptPropertyGet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstancePropertyGet *instance = memnew(VisualScriptNodeInstancePropertyGet); instance->node = this; instance->instance = p_instance; @@ -2195,7 +2237,7 @@ VisualScriptPropertyGet::VisualScriptPropertyGet() { template <VisualScriptPropertyGet::CallMode cmode> static Ref<VisualScriptNode> create_property_get_node(const String &p_name) { Ref<VisualScriptPropertyGet> node; - node.instance(); + node.instantiate(); node->set_call_mode(cmode); return node; } @@ -2281,11 +2323,11 @@ void VisualScriptEmitSignal::_validate_property(PropertyInfo &property) const { } String ml; - for (List<StringName>::Element *E = sigs.front(); E; E = E->next()) { + for (const StringName &E : sigs) { if (ml != String()) { ml += ","; } - ml += E->get(); + ml += E; } property.hint_string = ml; @@ -2319,7 +2361,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptEmitSignal::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptEmitSignal::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceEmitSignal *instance = memnew(VisualScriptNodeInstanceEmitSignal); instance->node = this; instance->instance = p_instance; @@ -2338,7 +2380,7 @@ static Ref<VisualScriptNode> create_basic_type_call_node(const String &p_name) { String method = path[3]; Ref<VisualScriptFunctionCall> node; - node.instance(); + node.instantiate(); Variant::Type type = Variant::VARIANT_MAX; @@ -2376,8 +2418,8 @@ void register_visual_script_func_nodes() { List<MethodInfo> ml; vt.get_method_list(&ml); - for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) { - VisualScriptLanguage::singleton->add_register_func("functions/by_type/" + type_name + "/" + E->get().name, create_basic_type_call_node); + for (const MethodInfo &E : ml) { + VisualScriptLanguage::singleton->add_register_func("functions/by_type/" + type_name + "/" + E.name, create_basic_type_call_node); } } } diff --git a/modules/visual_script/visual_script_func_nodes.h b/modules/visual_script/visual_script_func_nodes.h index 2ff9b7a981..cca08455f9 100644 --- a/modules/visual_script/visual_script_func_nodes.h +++ b/modules/visual_script/visual_script_func_nodes.h @@ -125,7 +125,7 @@ public: void set_rpc_call_mode(RPCCallMode p_mode); RPCCallMode get_rpc_call_mode() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; @@ -231,7 +231,7 @@ public: void set_assign_op(AssignOp p_op); AssignOp get_assign_op() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; VisualScriptPropertySet(); @@ -272,6 +272,8 @@ private: void _set_type_cache(Variant::Type p_type); Variant::Type _get_type_cache() const; + void _adjust_input_index(PropertyInfo &pinfo) const; + protected: virtual void _validate_property(PropertyInfo &property) const override; @@ -314,7 +316,7 @@ public: void set_index(const StringName &p_type); StringName get_index() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptPropertyGet(); }; @@ -351,7 +353,7 @@ public: void set_signal(const StringName &p_type); StringName get_signal() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptEmitSignal(); }; diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp index fed6637acb..c517d89aa5 100644 --- a/modules/visual_script/visual_script_nodes.cpp +++ b/modules/visual_script/visual_script_nodes.cpp @@ -191,7 +191,10 @@ PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const { } PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const { - ERR_FAIL_INDEX_V(p_idx, arguments.size(), PropertyInfo()); + // Need to check it without ERR_FAIL_COND, to prevent warnings from appearing on node creation via dragging. + if (p_idx < 0 || p_idx >= arguments.size()) { + return PropertyInfo(); + } PropertyInfo out; out.type = arguments[p_idx].type; out.name = arguments[p_idx].name; @@ -296,7 +299,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptFunction::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptFunction::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceFunction *instance = memnew(VisualScriptNodeInstanceFunction); instance->node = this; instance->instance = p_instance; @@ -791,7 +794,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptComposeArray::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptComposeArray::instantiate(VisualScriptInstance *p_instance) { VisualScriptComposeArrayNode *instance = memnew(VisualScriptComposeArrayNode); instance->input_count = inputports.size(); return instance; @@ -912,73 +915,135 @@ PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const { return pinfo; } -static const char *op_names[] = { - //comparison - "Are Equal", //OP_EQUAL, - "Are Not Equal", //OP_NOT_EQUAL, - "Less Than", //OP_LESS, - "Less Than or Equal", //OP_LESS_EQUAL, - "Greater Than", //OP_GREATER, - "Greater Than or Equal", //OP_GREATER_EQUAL, - //mathematic - "Add", //OP_ADD, - "Subtract", //OP_SUBTRACT, - "Multiply", //OP_MULTIPLY, - "Divide", //OP_DIVIDE, - "Negate", //OP_NEGATE, - "Positive", //OP_POSITIVE, - "Remainder", //OP_MODULE, - "Concatenate", //OP_STRING_CONCAT, - //bitwise - "Bit Shift Left", //OP_SHIFT_LEFT, - "Bit Shift Right", //OP_SHIFT_RIGHT, - "Bit And", //OP_BIT_AND, - "Bit Or", //OP_BIT_OR, - "Bit Xor", //OP_BIT_XOR, - "Bit Negate", //OP_BIT_NEGATE, - //logic - "And", //OP_AND, - "Or", //OP_OR, - "Xor", //OP_XOR, - "Not", //OP_NOT, - //containment - "In", //OP_IN, -}; - String VisualScriptOperator::get_caption() const { - static const char32_t *op_names[] = { - //comparison - U"A = B", //OP_EQUAL, - U"A \u2260 B", //OP_NOT_EQUAL, - U"A < B", //OP_LESS, - U"A \u2264 B", //OP_LESS_EQUAL, - U"A > B", //OP_GREATER, - U"A \u2265 B", //OP_GREATER_EQUAL, - //mathematic - U"A + B", //OP_ADD, - U"A - B", //OP_SUBTRACT, - U"A \u00D7 B", //OP_MULTIPLY, - U"A \u00F7 B", //OP_DIVIDE, - U"\u00AC A", //OP_NEGATE, - U"+ A", //OP_POSITIVE, - U"A mod B", //OP_MODULE, - U"A .. B", //OP_STRING_CONCAT, - //bitwise - U"A << B", //OP_SHIFT_LEFT, - U"A >> B", //OP_SHIFT_RIGHT, - U"A & B", //OP_BIT_AND, - U"A | B", //OP_BIT_OR, - U"A ^ B", //OP_BIT_XOR, - U"~A", //OP_BIT_NEGATE, - //logic - U"A and B", //OP_AND, - U"A or B", //OP_OR, - U"A xor B", //OP_XOR, - U"not A", //OP_NOT, - U"A in B", //OP_IN, - - }; - return op_names[op]; + switch (op) { + // comparison + case Variant::OP_EQUAL: + return U"A = B"; + case Variant::OP_NOT_EQUAL: + return U"A \u2260 B"; + case Variant::OP_LESS: + return U"A < B"; + case Variant::OP_LESS_EQUAL: + return U"A \u2264 B"; + case Variant::OP_GREATER: + return U"A > B"; + case Variant::OP_GREATER_EQUAL: + return U"A \u2265 B"; + + // mathematic + case Variant::OP_ADD: + return U"A + B"; + case Variant::OP_SUBTRACT: + return U"A - B"; + case Variant::OP_MULTIPLY: + return U"A \u00D7 B"; + case Variant::OP_DIVIDE: + return U"A \u00F7 B"; + case Variant::OP_NEGATE: + return U"\u00AC A"; + case Variant::OP_POSITIVE: + return U"+ A"; + case Variant::OP_MODULE: + return U"A mod B"; + + // bitwise + case Variant::OP_SHIFT_LEFT: + return U"A << B"; + case Variant::OP_SHIFT_RIGHT: + return U"A >> B"; + case Variant::OP_BIT_AND: + return U"A & B"; + case Variant::OP_BIT_OR: + return U"A | B"; + case Variant::OP_BIT_XOR: + return U"A ^ B"; + case Variant::OP_BIT_NEGATE: + return U"~A"; + + // logic + case Variant::OP_AND: + return U"A and B"; + case Variant::OP_OR: + return U"A or B"; + case Variant::OP_XOR: + return U"A xor B"; + case Variant::OP_NOT: + return U"not A"; + case Variant::OP_IN: + return U"A in B"; + + default: { + ERR_FAIL_V_MSG( + U"Unknown node", + U"Unknown node type encountered, caption not available."); + } + } +} + +String VisualScriptOperator::get_operator_name(Variant::Operator p_op) { + switch (p_op) { + // comparison + case Variant::OP_EQUAL: + return "Are Equal"; + case Variant::OP_NOT_EQUAL: + return "Are Not Equal"; + case Variant::OP_LESS: + return "Less Than"; + case Variant::OP_LESS_EQUAL: + return "Less Than or Equal"; + case Variant::OP_GREATER: + return "Greater Than"; + case Variant::OP_GREATER_EQUAL: + return "Greater Than or Equal"; + + // mathematic + case Variant::OP_ADD: + return "Add"; + case Variant::OP_SUBTRACT: + return "Subtract"; + case Variant::OP_MULTIPLY: + return "Multiply"; + case Variant::OP_DIVIDE: + return "Divide"; + case Variant::OP_NEGATE: + return "Negate"; + case Variant::OP_POSITIVE: + return "Positive"; + case Variant::OP_MODULE: + return "Remainder"; + + // bitwise + case Variant::OP_SHIFT_LEFT: + return "Bit Shift Left"; + case Variant::OP_SHIFT_RIGHT: + return "Bit Shift Right"; + case Variant::OP_BIT_AND: + return "Bit And"; + case Variant::OP_BIT_OR: + return "Bit Or"; + case Variant::OP_BIT_XOR: + return "Bit Xor"; + case Variant::OP_BIT_NEGATE: + return "Bit Negate"; + + // logic + case Variant::OP_AND: + return "And"; + case Variant::OP_OR: + return "Or"; + case Variant::OP_XOR: + return "Xor"; + case Variant::OP_NOT: + return "Not"; + case Variant::OP_IN: + return "In"; + + default: { + ERR_FAIL_INDEX_V(p_op, Variant::OP_MAX, ""); + return "Unknown Operator"; + } + } } void VisualScriptOperator::set_operator(Variant::Operator p_op) { @@ -1018,7 +1083,7 @@ void VisualScriptOperator::_bind_methods() { if (i > 0) { types += ","; } - types += op_names[i]; + types += get_operator_name(static_cast<Variant::Operator>(i)); } String argt = "Any"; @@ -1051,9 +1116,9 @@ public: r_error_str = *p_outputs[0]; } else { if (unary) { - r_error_str = String(op_names[op]) + RTR(": Invalid argument of type: ") + Variant::get_type_name(p_inputs[0]->get_type()); + r_error_str = String(Variant::get_operator_name(op)) + RTR(": Invalid argument of type: ") + Variant::get_type_name(p_inputs[0]->get_type()); } else { - r_error_str = String(op_names[op]) + RTR(": Invalid arguments: ") + "A: " + Variant::get_type_name(p_inputs[0]->get_type()) + " B: " + Variant::get_type_name(p_inputs[1]->get_type()); + r_error_str = String(Variant::get_operator_name(op)) + RTR(": Invalid arguments: ") + "A: " + Variant::get_type_name(p_inputs[0]->get_type()) + " B: " + Variant::get_type_name(p_inputs[1]->get_type()); } } } @@ -1062,7 +1127,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptOperator::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptOperator::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceOperator *instance = memnew(VisualScriptNodeInstanceOperator); instance->unary = get_input_value_port_count() == 1; instance->op = op; @@ -1077,7 +1142,7 @@ VisualScriptOperator::VisualScriptOperator() { template <Variant::Operator OP> static Ref<VisualScriptNode> create_op_node(const String &p_name) { Ref<VisualScriptOperator> node; - node.instance(); + node.instantiate(); node->set_operator(OP); return node; } @@ -1169,7 +1234,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptSelect::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptSelect::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSelect *instance = memnew(VisualScriptNodeInstanceSelect); return instance; } @@ -1241,12 +1306,12 @@ void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const { vs->get_variable_list(&vars); String vhint; - for (List<StringName>::Element *E = vars.front(); E; E = E->next()) { + for (const StringName &E : vars) { if (vhint != String()) { vhint += ","; } - vhint += E->get().operator String(); + vhint += E.operator String(); } property.hint = PROPERTY_HINT_ENUM; @@ -1277,7 +1342,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptVariableGet::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptVariableGet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceVariableGet *instance = memnew(VisualScriptNodeInstanceVariableGet); instance->node = this; instance->instance = p_instance; @@ -1351,12 +1416,12 @@ void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const { vs->get_variable_list(&vars); String vhint; - for (List<StringName>::Element *E = vars.front(); E; E = E->next()) { + for (const StringName &E : vars) { if (vhint != String()) { vhint += ","; } - vhint += E->get().operator String(); + vhint += E.operator String(); } property.hint = PROPERTY_HINT_ENUM; @@ -1389,7 +1454,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptVariableSet::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptVariableSet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceVariableSet *instance = memnew(VisualScriptNodeInstanceVariableSet); instance->node = this; instance->instance = p_instance; @@ -1472,7 +1537,7 @@ void VisualScriptConstant::_validate_property(PropertyInfo &property) const { if (property.name == "value") { property.type = type; if (type == Variant::NIL) { - property.usage = 0; //do not save if nil + property.usage = PROPERTY_USAGE_NONE; //do not save if nil } } } @@ -1504,7 +1569,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptConstant::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptConstant::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceConstant *instance = memnew(VisualScriptNodeInstanceConstant); instance->constant = value; return instance; @@ -1597,7 +1662,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptPreload::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptPreload::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstancePreload *instance = memnew(VisualScriptNodeInstancePreload); instance->preload = preload; return instance; @@ -1662,7 +1727,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptIndexGet::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptIndexGet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceIndexGet *instance = memnew(VisualScriptNodeInstanceIndexGet); return instance; } @@ -1732,7 +1797,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptIndexSet::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptIndexSet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceIndexSet *instance = memnew(VisualScriptNodeInstanceIndexSet); return instance; } @@ -1798,7 +1863,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptGlobalConstant::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptGlobalConstant::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceGlobalConstant *instance = memnew(VisualScriptNodeInstanceGlobalConstant); instance->index = index; return instance; @@ -1879,8 +1944,8 @@ void VisualScriptClassConstant::set_base_type(const StringName &p_which) { ClassDB::get_integer_constant_list(base_type, &constants, true); if (constants.size() > 0) { bool found_name = false; - for (List<String>::Element *E = constants.front(); E; E = E->next()) { - if (E->get() == name) { + for (const String &E : constants) { + if (E == name) { found_name = true; break; } @@ -1916,7 +1981,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptClassConstant::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptClassConstant::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceClassConstant *instance = memnew(VisualScriptNodeInstanceClassConstant); instance->value = ClassDB::get_integer_constant(base_type, name, &instance->valid); return instance; @@ -1928,11 +1993,11 @@ void VisualScriptClassConstant::_validate_property(PropertyInfo &property) const ClassDB::get_integer_constant_list(base_type, &constants, true); property.hint_string = ""; - for (List<String>::Element *E = constants.front(); E; E = E->next()) { + for (const String &E : constants) { if (property.hint_string != String()) { property.hint_string += ","; } - property.hint_string += E->get(); + property.hint_string += E; } } } @@ -2013,8 +2078,8 @@ void VisualScriptBasicTypeConstant::set_basic_type(Variant::Type p_which) { Variant::get_constants_for_type(type, &constants); if (constants.size() > 0) { bool found_name = false; - for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { - if (E->get() == name) { + for (const StringName &E : constants) { + if (E == name) { found_name = true; break; } @@ -2050,7 +2115,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptBasicTypeConstant::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptBasicTypeConstant::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceBasicTypeConstant *instance = memnew(VisualScriptNodeInstanceBasicTypeConstant); instance->value = Variant::get_constant_value(type, name, &instance->valid); return instance; @@ -2062,15 +2127,15 @@ void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo &property) c Variant::get_constants_for_type(type, &constants); if (constants.size() == 0) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; return; } property.hint_string = ""; - for (List<StringName>::Element *E = constants.front(); E; E = E->next()) { + for (const StringName &E : constants) { if (property.hint_string != String()) { property.hint_string += ","; } - property.hint_string += String(E->get()); + property.hint_string += String(E); } } } @@ -2117,8 +2182,8 @@ double VisualScriptMathConstant::const_value[MATH_CONSTANT_MAX] = { Math_TAU, 2.71828182845904523536, Math::sqrt(2.0), - Math_INF, - Math_NAN + INFINITY, + NAN }; int VisualScriptMathConstant::get_output_sequence_port_count() const { @@ -2174,7 +2239,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptMathConstant::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptMathConstant::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceMathConstant *instance = memnew(VisualScriptNodeInstanceMathConstant); instance->value = const_value[constant]; return instance; @@ -2268,7 +2333,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptEngineSingleton::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptEngineSingleton::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceEngineSingleton *instance = memnew(VisualScriptNodeInstanceEngineSingleton); instance->singleton = Engine::get_singleton()->get_singleton_object(singleton); return instance; @@ -2293,15 +2358,15 @@ void VisualScriptEngineSingleton::_validate_property(PropertyInfo &property) con Engine::get_singleton()->get_singletons(&singletons); - for (List<Engine::Singleton>::Element *E = singletons.front(); E; E = E->next()) { - if (E->get().name == "VS" || E->get().name == "PS" || E->get().name == "PS2D" || E->get().name == "AS" || E->get().name == "TS" || E->get().name == "SS" || E->get().name == "SS2D") { + for (const Engine::Singleton &E : singletons) { + if (E.name == "VS" || E.name == "PS" || E.name == "PS2D" || E.name == "AS" || E.name == "TS" || E.name == "SS" || E.name == "SS2D") { continue; //skip these, too simple named } if (cc != String()) { cc += ","; } - cc += E->get().name; + cc += E.name; } property.hint = PROPERTY_HINT_ENUM; @@ -2394,7 +2459,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptSceneNode::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptSceneNode::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSceneNode *instance = memnew(VisualScriptNodeInstanceSceneNode); instance->node = this; instance->instance = p_instance; @@ -2574,7 +2639,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptSceneTree::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptSceneTree::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSceneTree *instance = memnew(VisualScriptNodeInstanceSceneTree); instance->node = this; instance->instance = p_instance; @@ -2655,7 +2720,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptResourcePath::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptResourcePath::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceResourcePath *instance = memnew(VisualScriptNodeInstanceResourcePath); instance->path = path; return instance; @@ -2727,7 +2792,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptSelf::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptSelf::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSelf *instance = memnew(VisualScriptNodeInstanceSelf); instance->instance = p_instance; return instance; @@ -2803,6 +2868,12 @@ PropertyInfo VisualScriptCustomNode::get_input_value_port_info(int p_idx) const if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_name")) { info.name = get_script_instance()->call("_get_input_value_port_name", p_idx); } + if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_hint")) { + info.hint = PropertyHint(int(get_script_instance()->call("_get_input_value_port_hint", p_idx))); + } + if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_hint_string")) { + info.hint_string = get_script_instance()->call("_get_input_value_port_hint_string", p_idx); + } return info; } @@ -2814,9 +2885,31 @@ PropertyInfo VisualScriptCustomNode::get_output_value_port_info(int p_idx) const if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_name")) { info.name = get_script_instance()->call("_get_output_value_port_name", p_idx); } + if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_hint")) { + info.hint = PropertyHint(int(get_script_instance()->call("_get_output_value_port_hint", p_idx))); + } + if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_hint_string")) { + info.hint_string = get_script_instance()->call("_get_output_value_port_hint_string", p_idx); + } return info; } +VisualScriptCustomNode::TypeGuess VisualScriptCustomNode::guess_output_type(TypeGuess *p_inputs, int p_output) const { + TypeGuess tg; + PropertyInfo pi = VisualScriptCustomNode::get_output_value_port_info(p_output); + tg.type = pi.type; + if (pi.type == Variant::OBJECT) { + if (pi.hint == PROPERTY_HINT_RESOURCE_TYPE) { + if (pi.hint_string.is_resource_file()) { + tg.script = ResourceLoader::load(pi.hint_string); + } else if (ClassDB::class_exists(pi.hint_string)) { + tg.gdclass = pi.hint_string; + } + } + } + return tg; +} + String VisualScriptCustomNode::get_caption() const { if (get_script_instance() && get_script_instance()->has_method("_get_caption")) { return get_script_instance()->call("_get_caption"); @@ -2908,7 +3001,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptCustomNode::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptCustomNode::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceCustomNode *instance = memnew(VisualScriptNodeInstanceCustomNode); instance->instance = p_instance; instance->node = this; @@ -2925,7 +3018,7 @@ VisualScriptNodeInstance *VisualScriptCustomNode::instance(VisualScriptInstance } void VisualScriptCustomNode::_script_changed() { - call_deferred("ports_changed_notify"); + call_deferred(SNAME("ports_changed_notify")); } void VisualScriptCustomNode::_bind_methods() { @@ -2938,9 +3031,13 @@ void VisualScriptCustomNode::_bind_methods() { BIND_VMETHOD(MethodInfo(Variant::INT, "_get_input_value_port_type", PropertyInfo(Variant::INT, "idx"))); BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_input_value_port_name", PropertyInfo(Variant::INT, "idx"))); + BIND_VMETHOD(MethodInfo(Variant::INT, "_get_input_value_port_hint", PropertyInfo(Variant::INT, "idx"))); + BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_input_value_port_hint_string", PropertyInfo(Variant::INT, "idx"))); BIND_VMETHOD(MethodInfo(Variant::INT, "_get_output_value_port_type", PropertyInfo(Variant::INT, "idx"))); BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_output_value_port_name", PropertyInfo(Variant::INT, "idx"))); + BIND_VMETHOD(MethodInfo(Variant::INT, "_get_output_value_port_hint", PropertyInfo(Variant::INT, "idx"))); + BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_output_value_port_hint_string", PropertyInfo(Variant::INT, "idx"))); BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_caption")); BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_text")); @@ -3059,7 +3156,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptSubCall::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptSubCall::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSubCall *instance = memnew(VisualScriptNodeInstanceSubCall); instance->instance = p_instance; Ref<Script> script = get_script(); @@ -3172,7 +3269,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptComment::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptComment::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceComment *instance = memnew(VisualScriptNodeInstanceComment); instance->instance = p_instance; return instance; @@ -3279,7 +3376,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptConstructor::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptConstructor::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceConstructor *instance = memnew(VisualScriptNodeInstanceConstructor); instance->instance = p_instance; instance->type = type; @@ -3308,7 +3405,7 @@ static Ref<VisualScriptNode> create_constructor_node(const String &p_name) { ERR_FAIL_COND_V(!constructor_map.has(p_name), Ref<VisualScriptNode>()); Ref<VisualScriptConstructor> vsc; - vsc.instance(); + vsc.instantiate(); vsc->set_constructor_type(constructor_map[p_name].first); vsc->set_constructor(constructor_map[p_name].second); @@ -3389,7 +3486,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptLocalVar::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptLocalVar::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceLocalVar *instance = memnew(VisualScriptNodeInstanceLocalVar); instance->instance = p_instance; instance->name = name; @@ -3497,7 +3594,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptLocalVarSet::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptLocalVarSet::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceLocalVarSet *instance = memnew(VisualScriptNodeInstanceLocalVarSet); instance->instance = p_instance; instance->name = name; @@ -3634,7 +3731,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptInputAction::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptInputAction::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceInputAction *instance = memnew(VisualScriptNodeInstanceInputAction); instance->instance = p_instance; instance->action = name; @@ -3652,9 +3749,7 @@ void VisualScriptInputAction::_validate_property(PropertyInfo &property) const { ProjectSettings::get_singleton()->get_property_list(&pinfo); Vector<String> al; - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { - const PropertyInfo &pi = E->get(); - + for (const PropertyInfo &pi : pinfo) { if (!pi.name.begins_with("input/")) { continue; } @@ -3747,10 +3842,10 @@ void VisualScriptDeconstruct::_update_elements() { List<PropertyInfo> pinfo; v.get_property_list(&pinfo); - for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { + for (const PropertyInfo &E : pinfo) { Element e; - e.name = E->get().name; - e.type = E->get().type; + e.name = E.name; + e.type = E.type; elements.push_back(e); } } @@ -3812,7 +3907,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptDeconstruct::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptDeconstruct::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceDeconstruct *instance = memnew(VisualScriptNodeInstanceDeconstruct); instance->instance = p_instance; instance->outputs.resize(elements.size()); @@ -3849,7 +3944,7 @@ VisualScriptDeconstruct::VisualScriptDeconstruct() { template <Variant::Type T> static Ref<VisualScriptNode> create_node_deconst_typed(const String &p_name) { Ref<VisualScriptDeconstruct> node; - node.instance(); + node.instantiate(); node->set_deconstruct_type(T); return node; } @@ -3918,34 +4013,34 @@ void register_visual_script_nodes() { VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::RECT2I), create_node_deconst_typed<Variant::Type::RECT2I>); VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::TRANSFORM2D), create_node_deconst_typed<Variant::Type::TRANSFORM2D>); VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::PLANE), create_node_deconst_typed<Variant::Type::PLANE>); - VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::QUAT), create_node_deconst_typed<Variant::Type::QUAT>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::QUATERNION), create_node_deconst_typed<Variant::Type::QUATERNION>); VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::AABB), create_node_deconst_typed<Variant::Type::AABB>); VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::BASIS), create_node_deconst_typed<Variant::Type::BASIS>); - VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::TRANSFORM), create_node_deconst_typed<Variant::Type::TRANSFORM>); + VisualScriptLanguage::singleton->add_register_func("functions/deconstruct/" + Variant::get_type_name(Variant::Type::TRANSFORM3D), create_node_deconst_typed<Variant::Type::TRANSFORM3D>); VisualScriptLanguage::singleton->add_register_func("functions/compose_array", create_node_generic<VisualScriptComposeArray>); for (int i = 1; i < Variant::VARIANT_MAX; i++) { List<MethodInfo> constructors; Variant::get_constructor_list(Variant::Type(i), &constructors); - for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) { - if (E->get().arguments.size() > 0) { + for (const MethodInfo &E : constructors) { + if (E.arguments.size() > 0) { String name = "functions/constructors/" + Variant::get_type_name(Variant::Type(i)) + "("; - for (int j = 0; j < E->get().arguments.size(); j++) { + for (int j = 0; j < E.arguments.size(); j++) { if (j > 0) { name += ", "; } - if (E->get().arguments.size() == 1) { - name += Variant::get_type_name(E->get().arguments[j].type); + if (E.arguments.size() == 1) { + name += Variant::get_type_name(E.arguments[j].type); } else { - name += E->get().arguments[j].name; + name += E.arguments[j].name; } } name += ")"; VisualScriptLanguage::singleton->add_register_func(name, create_constructor_node); Pair<Variant::Type, MethodInfo> pair; pair.first = Variant::Type(i); - pair.second = E->get(); + pair.second = E; constructor_map[name] = pair; } } diff --git a/modules/visual_script/visual_script_nodes.h b/modules/visual_script/visual_script_nodes.h index 7392443e4e..2390e5c7bc 100644 --- a/modules/visual_script/visual_script_nodes.h +++ b/modules/visual_script/visual_script_nodes.h @@ -97,7 +97,7 @@ public: void set_rpc_mode(MultiplayerAPI::RPCMode p_mode); MultiplayerAPI::RPCMode get_rpc_mode() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; virtual void reset_state() override; @@ -192,7 +192,7 @@ public: virtual String get_text() const override; virtual String get_category() const override { return "functions"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptComposeArray(); }; @@ -227,7 +227,9 @@ public: void set_typed(Variant::Type p_op); Variant::Type get_typed() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + static String get_operator_name(Variant::Operator p_op); + + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptOperator(); }; @@ -259,7 +261,7 @@ public: void set_typed(Variant::Type p_op); Variant::Type get_typed() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptSelect(); }; @@ -291,7 +293,7 @@ public: void set_variable(StringName p_variable); StringName get_variable() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptVariableGet(); }; @@ -323,7 +325,7 @@ public: void set_variable(StringName p_variable); StringName get_variable() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptVariableSet(); }; @@ -359,7 +361,7 @@ public: void set_constant_value(Variant p_value); Variant get_constant_value() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptConstant(); }; @@ -390,7 +392,7 @@ public: void set_preload(const Ref<Resource> &p_preload); Ref<Resource> get_preload() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptPreload(); }; @@ -413,7 +415,7 @@ public: virtual String get_caption() const override; virtual String get_category() const override { return "operators"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptIndexGet(); }; @@ -436,7 +438,7 @@ public: virtual String get_caption() const override; virtual String get_category() const override { return "operators"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptIndexSet(); }; @@ -466,7 +468,7 @@ public: void set_global_constant(int p_which); int get_global_constant(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptGlobalConstant(); }; @@ -502,7 +504,7 @@ public: void set_base_type(const StringName &p_which); StringName get_base_type(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptClassConstant(); }; @@ -539,7 +541,7 @@ public: void set_basic_type(Variant::Type p_which); Variant::Type get_basic_type() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptBasicTypeConstant(); }; @@ -586,7 +588,7 @@ public: void set_math_constant(MathConstant p_which); MathConstant get_math_constant(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptMathConstant(); }; @@ -621,7 +623,7 @@ public: void set_singleton(const String &p_string); String get_singleton(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; @@ -655,7 +657,7 @@ public: void set_node_path(const NodePath &p_path); NodePath get_node_path(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; @@ -684,7 +686,7 @@ public: virtual String get_caption() const override; virtual String get_category() const override { return "data"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; @@ -717,7 +719,7 @@ public: void set_resource_path(const String &p_path); String get_resource_path(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptResourcePath(); }; @@ -743,7 +745,7 @@ public: virtual String get_caption() const override; virtual String get_category() const override { return "data"; } - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; @@ -788,7 +790,9 @@ public: virtual String get_text() const override; virtual String get_category() const override; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; + + virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const override; void _script_changed(); @@ -819,7 +823,7 @@ public: virtual String get_text() const override; virtual String get_category() const override; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptSubCall(); }; @@ -859,7 +863,7 @@ public: void set_size(const Size2 &p_size); Size2 get_size() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptComment(); }; @@ -894,7 +898,7 @@ public: void set_constructor(const Dictionary &p_info); Dictionary get_constructor() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptConstructor(); }; @@ -929,7 +933,7 @@ public: void set_var_type(Variant::Type p_type); Variant::Type get_var_type() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptLocalVar(); }; @@ -965,7 +969,7 @@ public: void set_var_type(Variant::Type p_type); Variant::Type get_var_type() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptLocalVarSet(); }; @@ -1010,7 +1014,7 @@ public: void set_action_mode(Mode p_mode); Mode get_action_mode() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptInputAction(); }; @@ -1056,7 +1060,7 @@ public: void set_deconstruct_type(Variant::Type p_type); Variant::Type get_deconstruct_type() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptDeconstruct(); }; diff --git a/modules/visual_script/visual_script_property_selector.cpp b/modules/visual_script/visual_script_property_selector.cpp index 862cac5c67..bacb1947be 100644 --- a/modules/visual_script/visual_script_property_selector.cpp +++ b/modules/visual_script/visual_script_property_selector.cpp @@ -59,7 +59,7 @@ void VisualScriptPropertySelector::_sbox_input(const Ref<InputEvent> &p_ie) { search_box->accept_event(); TreeItem *root = search_options->get_root(); - if (!root->get_children()) { + if (!root->get_first_child()) { break; } @@ -74,6 +74,8 @@ void VisualScriptPropertySelector::_sbox_input(const Ref<InputEvent> &p_ie) { current->select(0); } break; + default: + break; } } } @@ -93,43 +95,49 @@ void VisualScriptPropertySelector::_update_search() { base = ClassDB::get_parent_class_nocheck(base); } - for (List<StringName>::Element *E = base_list.front(); E; E = E->next()) { + for (const StringName &E : base_list) { List<MethodInfo> methods; List<PropertyInfo> props; TreeItem *category = nullptr; Ref<Texture2D> type_icons[Variant::VARIANT_MAX] = { - vbc->get_theme_icon("Variant", "EditorIcons"), - vbc->get_theme_icon("bool", "EditorIcons"), - vbc->get_theme_icon("int", "EditorIcons"), - vbc->get_theme_icon("float", "EditorIcons"), - vbc->get_theme_icon("String", "EditorIcons"), - vbc->get_theme_icon("Vector2", "EditorIcons"), - vbc->get_theme_icon("Rect2", "EditorIcons"), - vbc->get_theme_icon("Vector3", "EditorIcons"), - vbc->get_theme_icon("Transform2D", "EditorIcons"), - vbc->get_theme_icon("Plane", "EditorIcons"), - vbc->get_theme_icon("Quat", "EditorIcons"), - vbc->get_theme_icon("AABB", "EditorIcons"), - vbc->get_theme_icon("Basis", "EditorIcons"), - vbc->get_theme_icon("Transform", "EditorIcons"), - vbc->get_theme_icon("Color", "EditorIcons"), - vbc->get_theme_icon("Path", "EditorIcons"), - vbc->get_theme_icon("RID", "EditorIcons"), - vbc->get_theme_icon("Object", "EditorIcons"), - vbc->get_theme_icon("Dictionary", "EditorIcons"), - vbc->get_theme_icon("Array", "EditorIcons"), - vbc->get_theme_icon("PackedByteArray", "EditorIcons"), - vbc->get_theme_icon("PackedInt32Array", "EditorIcons"), - vbc->get_theme_icon("PackedFloat32Array", "EditorIcons"), - vbc->get_theme_icon("PackedInt64Array", "EditorIcons"), - vbc->get_theme_icon("PackedFloat64Array", "EditorIcons"), - vbc->get_theme_icon("PackedStringArray", "EditorIcons"), - vbc->get_theme_icon("PackedVector2Array", "EditorIcons"), - vbc->get_theme_icon("PackedVector3Array", "EditorIcons"), - vbc->get_theme_icon("PackedColorArray", "EditorIcons") + vbc->get_theme_icon(SNAME("Variant"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("bool"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("int"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("float"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("String"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Vector2"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Vector2i"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Rect2"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Rect2i"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Vector3"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Vector3i"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Transform2D"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Plane"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Quaternion"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("AABB"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Basis"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Transform3D"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Color"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("StringName"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("NodePath"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("RID"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("MiniObject"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Callable"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Signal"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Dictionary"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("Array"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedByteArray"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedInt32Array"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedInt64Array"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedFloat32Array"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedFloat64Array"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedStringArray"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedVector2Array"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedVector3Array"), SNAME("EditorIcons")), + vbc->get_theme_icon(SNAME("PackedColorArray"), SNAME("EditorIcons")) }; { - String b = String(E->get()); + String b = String(E); category = search_options->create_item(root); if (category) { category->set_text(0, b.replace_first("*", "")); @@ -148,30 +156,30 @@ void VisualScriptPropertySelector::_update_search() { if (Object::cast_to<Script>(obj)) { Object::cast_to<Script>(obj)->get_script_property_list(&props); } else { - ClassDB::get_property_list(E->get(), &props, true); + ClassDB::get_property_list(E, &props, true); } } - for (List<PropertyInfo>::Element *F = props.front(); F; F = F->next()) { - if (!(F->get().usage & PROPERTY_USAGE_EDITOR) && !(F->get().usage & PROPERTY_USAGE_SCRIPT_VARIABLE)) { + for (const PropertyInfo &F : props) { + if (!(F.usage & PROPERTY_USAGE_EDITOR) && !(F.usage & PROPERTY_USAGE_SCRIPT_VARIABLE)) { continue; } - if (type_filter.size() && type_filter.find(F->get().type) == -1) { + if (type_filter.size() && type_filter.find(F.type) == -1) { continue; } // capitalize() also converts underscore to space, we'll match again both possible styles - String get_text_raw = String(vformat(TTR("Get %s"), F->get().name)); + String get_text_raw = String(vformat(TTR("Get %s"), F.name)); String get_text = get_text_raw.capitalize(); - String set_text_raw = String(vformat(TTR("Set %s"), F->get().name)); + String set_text_raw = String(vformat(TTR("Set %s"), F.name)); String set_text = set_text_raw.capitalize(); String input = search_box->get_text().capitalize(); if (input == String() || get_text_raw.findn(input) != -1 || get_text.findn(input) != -1) { TreeItem *item = search_options->create_item(category ? category : root); item->set_text(0, get_text); - item->set_metadata(0, F->get().name); - item->set_icon(0, type_icons[F->get().type]); + item->set_metadata(0, F.name); + item->set_icon(0, type_icons[F.type]); item->set_metadata(1, "get"); item->set_collapsed(true); item->set_selectable(0, true); @@ -183,8 +191,8 @@ void VisualScriptPropertySelector::_update_search() { if (input == String() || set_text_raw.findn(input) != -1 || set_text.findn(input) != -1) { TreeItem *item = search_options->create_item(category ? category : root); item->set_text(0, set_text); - item->set_metadata(0, F->get().name); - item->set_icon(0, type_icons[F->get().type]); + item->set_metadata(0, F.name); + item->set_icon(0, type_icons[F.type]); item->set_metadata(1, "set"); item->set_selectable(0, true); item->set_selectable(1, false); @@ -205,7 +213,7 @@ void VisualScriptPropertySelector::_update_search() { Object::cast_to<Script>(obj)->get_script_method_list(&methods); } - ClassDB::get_method_list(E->get(), &methods, true, true); + ClassDB::get_method_list(E, &methods, true, true); } } for (List<MethodInfo>::Element *M = methods.front(); M; M = M->next()) { @@ -253,7 +261,7 @@ void VisualScriptPropertySelector::_update_search() { TreeItem *item = search_options->create_item(category ? category : root); item->set_text(0, desc); - item->set_icon(0, vbc->get_theme_icon("MemberMethod", "EditorIcons")); + item->set_icon(0, vbc->get_theme_icon(SNAME("MemberMethod"), SNAME("EditorIcons"))); item->set_metadata(0, name); item->set_selectable(0, true); @@ -265,7 +273,7 @@ void VisualScriptPropertySelector::_update_search() { item->set_metadata(2, connecting); } - if (category && category->get_children() == nullptr) { + if (category && category->get_first_child() == nullptr) { memdelete(category); //old category was unused } } @@ -310,14 +318,14 @@ void VisualScriptPropertySelector::_update_search() { found = true; } - get_ok_button()->set_disabled(root->get_children() == nullptr); + get_ok_button()->set_disabled(root->get_first_child() == nullptr); } void VisualScriptPropertySelector::create_visualscript_item(const String &name, TreeItem *const root, const String &search_input, const String &text) { if (search_input == String() || text.findn(search_input) != -1) { TreeItem *item = search_options->create_item(root); item->set_text(0, text); - item->set_icon(0, vbc->get_theme_icon("VisualScript", "EditorIcons")); + item->set_icon(0, vbc->get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons"))); item->set_metadata(0, name); item->set_metadata(1, "action"); item->set_selectable(0, true); @@ -334,11 +342,11 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt List<String> fnodes; VisualScriptLanguage::singleton->get_registered_node_names(&fnodes); - for (List<String>::Element *E = fnodes.front(); E; E = E->next()) { - if (!E->get().begins_with(root_filter)) { + for (const String &E : fnodes) { + if (!E.begins_with(root_filter)) { continue; } - Vector<String> path = E->get().split("/"); + Vector<String> path = E.split("/"); // check if the name has the filter bool in_filter = false; @@ -349,7 +357,7 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt } else { in_filter = false; } - if (E->get().findn(tx_filters[i]) != -1) { + if (E.findn(tx_filters[i]) != -1) { in_filter = true; break; } @@ -360,7 +368,7 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt bool in_modifier = p_modifiers.is_empty(); for (Set<String>::Element *F = p_modifiers.front(); F && in_modifier; F = F->next()) { - if (E->get().findn(F->get()) != -1) { + if (E.findn(F->get()) != -1) { in_modifier = true; } } @@ -369,7 +377,7 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt } TreeItem *item = search_options->create_item(root); - Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(E->get()); + Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(E); Ref<VisualScriptOperator> vnode_operator = vnode; String type_name; if (vnode_operator.is_valid()) { @@ -401,9 +409,9 @@ void VisualScriptPropertySelector::get_visual_node_names(const String &root_filt } item->set_text(0, type_name + String("").join(desc)); - item->set_icon(0, vbc->get_theme_icon("VisualScript", "EditorIcons")); + item->set_icon(0, vbc->get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons"))); item->set_selectable(0, true); - item->set_metadata(0, E->get()); + item->set_metadata(0, E); item->set_selectable(0, true); item->set_metadata(1, "visualscript"); item->set_selectable(1, false); @@ -417,7 +425,7 @@ void VisualScriptPropertySelector::_confirmed() { if (!ti) { return; } - emit_signal("selected", ti->get_metadata(0), ti->get_metadata(1), ti->get_metadata(2)); + emit_signal(SNAME("selected"), ti->get_metadata(0), ti->get_metadata(1), ti->get_metadata(2)); set_visible(false); } @@ -469,10 +477,11 @@ void VisualScriptPropertySelector::_item_selected() { at_class = ClassDB::get_parent_class_nocheck(at_class); } - Map<String, DocData::ClassDoc>::Element *T = dd->class_list.find(class_type); + Vector<String> functions = name.rsplit("/", false); + at_class = functions.size() > 3 ? functions[functions.size() - 2] : class_type; + Map<String, DocData::ClassDoc>::Element *T = dd->class_list.find(at_class); if (T) { for (int i = 0; i < T->get().methods.size(); i++) { - Vector<String> functions = name.rsplit("/", false, 1); if (T->get().methods[i].name == functions[functions.size() - 1]) { text = DTR(T->get().methods[i].description); } diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp index 52fe659983..cded1e587c 100644 --- a/modules/visual_script/visual_script_yield_nodes.cpp +++ b/modules/visual_script/visual_script_yield_nodes.cpp @@ -93,7 +93,7 @@ String VisualScriptYield::get_text() const { class VisualScriptNodeInstanceYield : public VisualScriptNodeInstance { public: VisualScriptYield::YieldMode mode; - float wait_time; + double wait_time; virtual int get_working_memory_size() const { return 1; } //yield needs at least 1 //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } @@ -113,7 +113,7 @@ public: } Ref<VisualScriptFunctionState> state; - state.instance(); + state.instantiate(); int ret = STEP_YIELD_BIT; switch (mode) { @@ -138,7 +138,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptYield::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptYield::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceYield *instance = memnew(VisualScriptNodeInstanceYield); //instance->instance=p_instance; instance->mode = yield_mode; @@ -159,7 +159,7 @@ VisualScriptYield::YieldMode VisualScriptYield::get_yield_mode() { return yield_mode; } -void VisualScriptYield::set_wait_time(float p_time) { +void VisualScriptYield::set_wait_time(double p_time) { if (wait_time == p_time) { return; } @@ -167,14 +167,14 @@ void VisualScriptYield::set_wait_time(float p_time) { ports_changed_notify(); } -float VisualScriptYield::get_wait_time() { +double VisualScriptYield::get_wait_time() { return wait_time; } void VisualScriptYield::_validate_property(PropertyInfo &property) const { if (property.name == "wait_time") { if (yield_mode != YIELD_WAIT) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } } } @@ -202,7 +202,7 @@ VisualScriptYield::VisualScriptYield() { template <VisualScriptYield::YieldMode MODE> static Ref<VisualScriptNode> create_yield_node(const String &p_name) { Ref<VisualScriptYield> node; - node.instance(); + node.instantiate(); node->set_yield_mode(MODE); return node; } @@ -421,7 +421,7 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const { if (property.name == "node_path") { if (call_mode != CALL_MODE_NODE_PATH) { - property.usage = 0; + property.usage = PROPERTY_USAGE_NONE; } else { Node *bnode = _get_base_node(); if (bnode) { @@ -438,21 +438,21 @@ void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const { ClassDB::get_signal_list(_get_base_type(), &methods); List<String> mstring; - for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) { - if (E->get().name.begins_with("_")) { + for (const MethodInfo &E : methods) { + if (E.name.begins_with("_")) { continue; } - mstring.push_back(E->get().name.get_slice(":", 0)); + mstring.push_back(E.name.get_slice(":", 0)); } mstring.sort(); String ml; - for (List<String>::Element *E = mstring.front(); E; E = E->next()) { + for (const String &E : mstring) { if (ml != String()) { ml += ","; } - ml += E->get(); + ml += E; } property.hint_string = ml; @@ -548,7 +548,7 @@ public: } Ref<VisualScriptFunctionState> state; - state.instance(); + state.instantiate(); state->connect_to_signal(object, signal, Array()); @@ -559,7 +559,7 @@ public: } }; -VisualScriptNodeInstance *VisualScriptYieldSignal::instance(VisualScriptInstance *p_instance) { +VisualScriptNodeInstance *VisualScriptYieldSignal::instantiate(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceYieldSignal *instance = memnew(VisualScriptNodeInstanceYieldSignal); instance->node = this; instance->instance = p_instance; @@ -578,7 +578,7 @@ VisualScriptYieldSignal::VisualScriptYieldSignal() { template <VisualScriptYieldSignal::CallMode cmode> static Ref<VisualScriptNode> create_yield_signal_node(const String &p_name) { Ref<VisualScriptYieldSignal> node; - node.instance(); + node.instantiate(); node->set_call_mode(cmode); return node; } diff --git a/modules/visual_script/visual_script_yield_nodes.h b/modules/visual_script/visual_script_yield_nodes.h index cc7ce0a1c6..6005ff30b0 100644 --- a/modules/visual_script/visual_script_yield_nodes.h +++ b/modules/visual_script/visual_script_yield_nodes.h @@ -47,7 +47,7 @@ public: private: YieldMode yield_mode; - float wait_time; + double wait_time; protected: virtual void _validate_property(PropertyInfo &property) const override; @@ -73,10 +73,10 @@ public: void set_yield_mode(YieldMode p_mode); YieldMode get_yield_mode(); - void set_wait_time(float p_time); - float get_wait_time(); + void set_wait_time(double p_time); + double get_wait_time(); - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptYield(); }; @@ -135,7 +135,7 @@ public: void set_call_mode(CallMode p_mode); CallMode get_call_mode() const; - virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) override; + virtual VisualScriptNodeInstance *instantiate(VisualScriptInstance *p_instance) override; VisualScriptYieldSignal(); }; diff --git a/modules/webm/doc_classes/VideoStreamWebm.xml b/modules/webm/doc_classes/VideoStreamWebm.xml index f3e13ba31a..3b9acfd873 100644 --- a/modules/webm/doc_classes/VideoStreamWebm.xml +++ b/modules/webm/doc_classes/VideoStreamWebm.xml @@ -12,17 +12,14 @@ </tutorials> <methods> <method name="get_file"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the WebM video file handled by this [VideoStreamWebm]. </description> </method> <method name="set_file"> - <return type="void"> - </return> - <argument index="0" name="file" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="file" type="String" /> <description> Sets the WebM video file that this [VideoStreamWebm] resource handles. The [code]file[/code] name should have the [code].webm[/code] extension. </description> diff --git a/modules/webm/libvpx/SCsub b/modules/webm/libvpx/SCsub index 67d3f1bebd..4334cf732b 100644 --- a/modules/webm/libvpx/SCsub +++ b/modules/webm/libvpx/SCsub @@ -235,7 +235,7 @@ if env["platform"] == "uwp": else: import platform - is_x11_or_server_arm = (env["platform"] == "linuxbsd" or env["platform"] == "server") and ( + is_x11_or_server_arm = env["platform"] == "linuxbsd" and ( platform.machine().startswith("arm") or platform.machine().startswith("aarch") ) is_macos_x86 = env["platform"] == "osx" and ("arch" in env and (env["arch"] != "arm64")) @@ -314,12 +314,7 @@ if webm_cpu_x86: if webm_cpu_arm: if env["platform"] == "iphone": env_libvpx["ASFLAGS"] = "-arch armv7" - elif ( - env["platform"] == "android" - and env["android_arch"] == "armv7" - or env["platform"] == "linuxbsd" - or env["platform"] == "server" - ): + elif env["platform"] == "android" and env["android_arch"] == "armv7" or env["platform"] == "linuxbsd": env_libvpx["ASFLAGS"] = "-mfpu=neon" elif env["platform"] == "uwp": env_libvpx["AS"] = "armasm" diff --git a/modules/webm/register_types.cpp b/modules/webm/register_types.cpp index 82157a71c9..8f690a6892 100644 --- a/modules/webm/register_types.cpp +++ b/modules/webm/register_types.cpp @@ -35,10 +35,10 @@ static Ref<ResourceFormatLoaderWebm> resource_loader_webm; void register_webm_types() { - resource_loader_webm.instance(); + resource_loader_webm.instantiate(); ResourceLoader::add_resource_format_loader(resource_loader_webm, true); - ClassDB::register_class<VideoStreamWebm>(); + GDREGISTER_CLASS(VideoStreamWebm); } void unregister_webm_types() { diff --git a/modules/webm/video_stream_webm.cpp b/modules/webm/video_stream_webm.cpp index a6b64b342e..12e0f5bd25 100644 --- a/modules/webm/video_stream_webm.cpp +++ b/modules/webm/video_stream_webm.cpp @@ -31,7 +31,7 @@ #include "video_stream_webm.h" #include "core/config/project_settings.h" -#include "core/os/file_access.h" +#include "core/io/file_access.h" #include "core/os/os.h" #include "servers/audio_server.h" @@ -62,10 +62,10 @@ public: virtual int Read(long long pos, long len, unsigned char *buf) { if (file) { - if (file->get_position() != (size_t)pos) { + if (file->get_position() != (uint64_t)pos) { file->seek(pos); } - if (file->get_buffer(buf, len) == len) { + if (file->get_buffer(buf, len) == (uint64_t)len) { return 0; } } @@ -74,7 +74,7 @@ public: virtual int Length(long long *total, long long *available) { if (file) { - const size_t len = file->get_len(); + const uint64_t len = file->get_length(); if (total) { *total = len; } @@ -116,7 +116,7 @@ bool VideoStreamPlaybackWebm::open_file(const String &p_file) { frame_data.resize((webm->getWidth() * webm->getHeight()) << 2); Ref<Image> img; - img.instance(); + img.instantiate(); img->create(webm->getWidth(), webm->getHeight(), false, Image::FORMAT_RGBA8); texture->create_from_image(img); diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp index b304c4824f..5bebad2b53 100644 --- a/modules/webp/image_loader_webp.cpp +++ b/modules/webp/image_loader_webp.cpp @@ -30,6 +30,7 @@ #include "image_loader_webp.h" +#include "core/config/project_settings.h" #include "core/io/marshalls.h" #include "core/os/os.h" #include "core/string/print_string.h" @@ -68,13 +69,78 @@ static Vector<uint8_t> _webp_lossy_pack(const Ref<Image> &p_image, float p_quali w[1] = 'E'; w[2] = 'B'; w[3] = 'P'; - copymem(&w[4], dst_buff, dst_size); - free(dst_buff); + memcpy(&w[4], dst_buff, dst_size); + WebPFree(dst_buff); return dst; } -static Ref<Image> _webp_lossy_unpack(const Vector<uint8_t> &p_buffer) { +static 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"); + compression_level = CLAMP(compression_level, 0, 9); + + Ref<Image> img = p_image->duplicate(); + if (img->detect_alpha()) { + img->convert(Image::FORMAT_RGBA8); + } else { + img->convert(Image::FORMAT_RGB8); + } + + Size2 s(img->get_width(), img->get_height()); + Vector<uint8_t> data = img->get_data(); + const uint8_t *r = data.ptr(); + + // we need to use the more complex API in order to access the 'exact' flag... + + WebPConfig config; + WebPPicture pic; + if (!WebPConfigInit(&config) || !WebPConfigLosslessPreset(&config, compression_level) || !WebPPictureInit(&pic)) { + ERR_FAIL_V(Vector<uint8_t>()); + } + + WebPMemoryWriter wrt; + config.exact = 1; + pic.use_argb = 1; + pic.width = s.width; + pic.height = s.height; + pic.writer = WebPMemoryWrite; + pic.custom_ptr = &wrt; + WebPMemoryWriterInit(&wrt); + + bool success_import = false; + if (img->get_format() == Image::FORMAT_RGB8) { + success_import = WebPPictureImportRGB(&pic, r, 3 * s.width); + } else { + success_import = WebPPictureImportRGBA(&pic, r, 4 * s.width); + } + bool success_encode = false; + if (success_import) { + success_encode = WebPEncode(&config, &pic); + } + WebPPictureFree(&pic); + + if (!success_encode) { + WebPMemoryWriterClear(&wrt); + ERR_FAIL_V_MSG(Vector<uint8_t>(), "WebP packing failed."); + } + + // copy from wrt + Vector<uint8_t> dst; + dst.resize(4 + wrt.size); + uint8_t *w = dst.ptrw(); + w[0] = 'W'; + w[1] = 'E'; + w[2] = 'B'; + w[3] = 'P'; + memcpy(&w[4], wrt.mem, wrt.size); + WebPMemoryWriterClear(&wrt); + + return dst; +} + +static Ref<Image> _webp_unpack(const Vector<uint8_t> &p_buffer) { int size = p_buffer.size() - 4; ERR_FAIL_COND_V(size <= 0, Ref<Image>()); const uint8_t *r = p_buffer.ptr(); @@ -139,7 +205,7 @@ Error webp_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) { Ref<Image> img; - img.instance(); + img.instantiate(); Error err = webp_load_image_from_buffer(img.ptr(), p_png, p_size); ERR_FAIL_COND_V(err, Ref<Image>()); return img; @@ -147,7 +213,7 @@ static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) { Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { Vector<uint8_t> src_image; - int src_image_len = f->get_len(); + uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); src_image.resize(src_image_len); @@ -168,6 +234,7 @@ void ImageLoaderWEBP::get_recognized_extensions(List<String> *p_extensions) cons ImageLoaderWEBP::ImageLoaderWEBP() { Image::_webp_mem_loader_func = _webp_mem_loader_func; - Image::lossy_packer = _webp_lossy_pack; - Image::lossy_unpacker = _webp_lossy_unpack; + Image::webp_lossy_packer = _webp_lossy_pack; + Image::webp_lossless_packer = _webp_lossless_pack; + Image::webp_unpacker = _webp_unpack; } diff --git a/modules/webrtc/config.py b/modules/webrtc/config.py index 0a075ccef1..3281415f38 100644 --- a/modules/webrtc/config.py +++ b/modules/webrtc/config.py @@ -10,7 +10,7 @@ def get_doc_classes(): return [ "WebRTCPeerConnection", "WebRTCDataChannel", - "WebRTCMultiplayer", + "WebRTCMultiplayerPeer", ] diff --git a/modules/webrtc/doc_classes/WebRTCDataChannel.xml b/modules/webrtc/doc_classes/WebRTCDataChannel.xml index 5c90038b9a..cf5735bab5 100644 --- a/modules/webrtc/doc_classes/WebRTCDataChannel.xml +++ b/modules/webrtc/doc_classes/WebRTCDataChannel.xml @@ -8,81 +8,76 @@ </tutorials> <methods> <method name="close"> - <return type="void"> - </return> + <return type="void" /> <description> Closes this data channel, notifying the other peer. </description> </method> + <method name="get_buffered_amount" qualifiers="const"> + <return type="int" /> + <description> + Returns the number of bytes currently queued to be sent over this channel. + </description> + </method> <method name="get_id" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Returns the id assigned to this channel during creation (or auto-assigned during negotiation). If the channel is not negotiated out-of-band the id will only be available after the connection is established (will return [code]65535[/code] until then). </description> </method> <method name="get_label" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the label assigned to this channel during creation. </description> </method> <method name="get_max_packet_life_time" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Returns the [code]maxPacketLifeTime[/code] value assigned to this channel during creation. Will be [code]65535[/code] if not specified. </description> </method> <method name="get_max_retransmits" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Returns the [code]maxRetransmits[/code] value assigned to this channel during creation. Will be [code]65535[/code] if not specified. </description> </method> <method name="get_protocol" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the sub-protocol assigned to this channel during creation. An empty string if not specified. </description> </method> <method name="get_ready_state" qualifiers="const"> - <return type="int" enum="WebRTCDataChannel.ChannelState"> - </return> + <return type="int" enum="WebRTCDataChannel.ChannelState" /> <description> Returns the current state of this channel, see [enum ChannelState]. </description> </method> <method name="is_negotiated" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns [code]true[/code] if this channel was created with out-of-band configuration. </description> </method> <method name="is_ordered" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns [code]true[/code] if this channel was created with ordering enabled (default). </description> </method> <method name="poll"> - <return type="int" enum="Error"> - </return> + <return type="int" enum="Error" /> <description> Reserved, but not used for now. </description> </method> <method name="was_string_packet" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns [code]true[/code] if the last received packet was transferred as text. See [member write_mode]. </description> diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml index 5b9459bc27..c53af22ae1 100644 --- a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml +++ b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml @@ -1,88 +1,75 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebRTCMultiplayer" inherits="NetworkedMultiplayerPeer" version="4.0"> +<class name="WebRTCMultiplayerPeer" inherits="MultiplayerPeer" version="4.0"> <brief_description> A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI]. </brief_description> <description> This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_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 NetworkedMultiplayerPeer.connection_succeeded] and [signal NetworkedMultiplayerPeer.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 [NetworkedMultiplayerPeer]. + [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]. </description> <tutorials> </tutorials> <methods> <method name="add_peer"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="peer" type="WebRTCPeerConnection"> - </argument> - <argument index="1" name="peer_id" type="int"> - </argument> - <argument index="2" name="unreliable_lifetime" type="int" default="1"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="peer" type="WebRTCPeerConnection" /> + <argument index="1" name="peer_id" type="int" /> + <argument index="2" name="unreliable_lifetime" type="int" default="1" /> <description> Add a new peer to the mesh with the given [code]peer_id[/code]. The [WebRTCPeerConnection] must be in state [constant WebRTCPeerConnection.STATE_NEW]. 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"> - </return> + <return type="void" /> <description> Close all the add peer connections and channels, freeing all resources. </description> </method> <method name="get_peer"> - <return type="Dictionary"> - </return> - <argument index="0" name="peer_id" type="int"> - </argument> + <return type="Dictionary" /> + <argument index="0" name="peer_id" type="int" /> <description> Return a dictionary representation of the peer with given [code]peer_id[/code] with three keys. [code]connection[/code] containing the [WebRTCPeerConnection] to this peer, [code]channels[/code] an array of three [WebRTCDataChannel], and [code]connected[/code] a boolean representing if the peer connection is currently connected (all three channels are open). </description> </method> <method name="get_peers"> - <return type="Dictionary"> - </return> + <return type="Dictionary" /> <description> Returns a dictionary which keys are the peer ids and values the peer representation as in [method get_peer]. </description> </method> <method name="has_peer"> - <return type="bool"> - </return> - <argument index="0" name="peer_id" type="int"> - </argument> + <return type="bool" /> + <argument index="0" name="peer_id" type="int" /> <description> 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"> - </return> - <argument index="0" name="peer_id" type="int"> - </argument> - <argument index="1" name="server_compatibility" type="bool" default="false"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="peer_id" type="int" /> + <argument index="1" name="server_compatibility" type="bool" default="false" /> + <argument 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 NetworkedMultiplayerPeer.CONNECTION_CONNECTED] and [signal NetworkedMultiplayerPeer.connection_succeeded] will not be emitted. - If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal NetworkedMultiplayerPeer.peer_connected] signals until a peer with id [constant NetworkedMultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal NetworkedMultiplayerPeer.connection_succeeded]. After that the signal [signal NetworkedMultiplayerPeer.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 NetworkedMultiplayerPeer.server_disconnected] will be emitted and state will become [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED]. + 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"> - </return> - <argument index="0" name="peer_id" type="int"> - </argument> + <return type="void" /> + <argument index="0" name="peer_id" type="int" /> <description> - Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal NetworkedMultiplayerPeer.peer_connected] was emitted for it, then [signal NetworkedMultiplayerPeer.peer_disconnected] will be emitted. + Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal MultiplayerPeer.peer_connected] was emitted for it, then [signal MultiplayerPeer.peer_disconnected] will be emitted. </description> </method> </methods> <members> <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" /> - <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="NetworkedMultiplayerPeer.TransferMode" default="2" /> + <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="MultiplayerPeer.TransferMode" default="2" /> </members> <constants> </constants> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml index e21dee8eff..f6f360503f 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebRTCPeerConnection" inherits="Reference" version="4.0"> +<class name="WebRTCPeerConnection" inherits="RefCounted" version="4.0"> <brief_description> Interface to a WebRTC peer connection. </brief_description> @@ -15,40 +15,32 @@ </tutorials> <methods> <method name="add_ice_candidate"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="media" type="String"> - </argument> - <argument index="1" name="index" type="int"> - </argument> - <argument index="2" name="name" type="String"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="media" type="String" /> + <argument index="1" name="index" type="int" /> + <argument index="2" name="name" type="String" /> <description> Add an ice candidate generated by a remote peer (and received over the signaling server). See [signal ice_candidate_created]. </description> </method> <method name="close"> - <return type="void"> - </return> + <return type="void" /> <description> Close the peer connection and all data channels associated with it. Note, you cannot reuse this object for a new connection unless you call [method initialize]. </description> </method> <method name="create_data_channel"> - <return type="WebRTCDataChannel"> - </return> - <argument index="0" name="label" type="String"> - </argument> + <return type="WebRTCDataChannel" /> + <argument index="0" name="label" type="String" /> <argument index="1" name="options" type="Dictionary" default="{ -}"> - </argument> +}" /> <description> Returns a new [WebRTCDataChannel] (or [code]null[/code] on failure) with given [code]label[/code] and optionally configured via the [code]options[/code] dictionary. This method can only be called when the connection is in state [constant STATE_NEW]. There are two ways to create a working data channel: either call [method create_data_channel] on only one of the peer and listen to [signal data_channel_received] on the other, or call [method create_data_channel] on both peers, with the same values, and the [code]negotiated[/code] option set to [code]true[/code]. Valid [code]options[/code] are: [codeblock] { - "negotiated": true, # When set to true (default off), means the channel is negotiated out of band. "id" must be set too. data_channel_received will not be called. + "negotiated": true, # When set to true (default off), means the channel is negotiated out of band. "id" must be set too. "data_channel_received" will not be called. "id": 1, # When "negotiated" is true this value must also be set to the same value on both peer. # Only one of maxRetransmits and maxPacketLifeTime can be specified, not both. They make the channel unreliable (but also better at real time). @@ -63,26 +55,22 @@ </description> </method> <method name="create_offer"> - <return type="int" enum="Error"> - </return> + <return type="int" enum="Error" /> <description> Creates a new SDP offer to start a WebRTC connection with a remote peer. At least one [WebRTCDataChannel] must have been created before calling this method. If this functions returns [constant OK], [signal session_description_created] will be called when the session is ready to be sent. </description> </method> <method name="get_connection_state" qualifiers="const"> - <return type="int" enum="WebRTCPeerConnection.ConnectionState"> - </return> + <return type="int" enum="WebRTCPeerConnection.ConnectionState" /> <description> Returns the connection state. See [enum ConnectionState]. </description> </method> <method name="initialize"> - <return type="int" enum="Error"> - </return> + <return type="int" enum="Error" /> <argument index="0" name="configuration" type="Dictionary" default="{ -}"> - </argument> +}" /> <description> Re-initialize this peer connection, closing any previously active connection, and going back to state [constant STATE_NEW]. A dictionary of [code]options[/code] can be passed to configure the peer connection. Valid [code]options[/code] are: @@ -103,31 +91,24 @@ </description> </method> <method name="poll"> - <return type="int" enum="Error"> - </return> + <return type="int" enum="Error" /> <description> Call this method frequently (e.g. in [method Node._process] or [method Node._physics_process]) to properly receive signals. </description> </method> <method name="set_local_description"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="type" type="String"> - </argument> - <argument index="1" name="sdp" type="String"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="type" type="String" /> + <argument index="1" name="sdp" type="String" /> <description> Sets the SDP description of the local peer. This should be called in response to [signal session_description_created]. After calling this function the peer will start emitting [signal ice_candidate_created] (unless an [enum Error] different from [constant OK] is returned). </description> </method> <method name="set_remote_description"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="type" type="String"> - </argument> - <argument index="1" name="sdp" type="String"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="type" type="String" /> + <argument index="1" name="sdp" type="String" /> <description> Sets the SDP description of the remote peer. This should be called with the values generated by a remote peer and received over the signaling server. If [code]type[/code] is [code]offer[/code] the peer will emit [signal session_description_created] with the appropriate answer. @@ -137,29 +118,23 @@ </methods> <signals> <signal name="data_channel_received"> - <argument index="0" name="channel" type="Object"> - </argument> + <argument index="0" name="channel" type="Object" /> <description> Emitted when a new in-band channel is received, i.e. when the channel was created with [code]negotiated: false[/code] (default). The object will be an instance of [WebRTCDataChannel]. You must keep a reference of it or it will be closed automatically. See [method create_data_channel]. </description> </signal> <signal name="ice_candidate_created"> - <argument index="0" name="media" type="String"> - </argument> - <argument index="1" name="index" type="int"> - </argument> - <argument index="2" name="name" type="String"> - </argument> + <argument index="0" name="media" type="String" /> + <argument index="1" name="index" type="int" /> + <argument index="2" name="name" type="String" /> <description> Emitted when a new ICE candidate has been created. The three parameters are meant to be passed to the remote peer over the signaling server. </description> </signal> <signal name="session_description_created"> - <argument index="0" name="type" type="String"> - </argument> - <argument index="1" name="sdp" type="String"> - </argument> + <argument index="0" name="type" type="String" /> + <argument index="1" name="sdp" type="String" /> <description> Emitted after a successful call to [method create_offer] or [method set_remote_description] (when it generates an answer). The parameters are meant to be passed to [method set_local_description] on this object, and sent to the remote peer over the signaling server. </description> diff --git a/modules/webrtc/library_godot_webrtc.js b/modules/webrtc/library_godot_webrtc.js index 404a116716..a0a6c21be3 100644 --- a/modules/webrtc/library_godot_webrtc.js +++ b/modules/webrtc/library_godot_webrtc.js @@ -133,12 +133,12 @@ const GodotRTCDataChannel = { godot_js_rtc_datachannel_is_ordered__sig: 'ii', godot_js_rtc_datachannel_is_ordered: function (p_id) { - return IDHandler.get_prop(p_id, 'ordered', true); + return GodotRTCDataChannel.get_prop(p_id, 'ordered', true); }, godot_js_rtc_datachannel_id_get__sig: 'ii', godot_js_rtc_datachannel_id_get: function (p_id) { - return IDHandler.get_prop(p_id, 'id', 65535); + return GodotRTCDataChannel.get_prop(p_id, 'id', 65535); }, godot_js_rtc_datachannel_max_packet_lifetime_get__sig: 'ii', @@ -158,12 +158,17 @@ const GodotRTCDataChannel = { godot_js_rtc_datachannel_max_retransmits_get__sig: 'ii', godot_js_rtc_datachannel_max_retransmits_get: function (p_id) { - return IDHandler.get_prop(p_id, 'maxRetransmits', 65535); + return GodotRTCDataChannel.get_prop(p_id, 'maxRetransmits', 65535); }, godot_js_rtc_datachannel_is_negotiated__sig: 'ii', godot_js_rtc_datachannel_is_negotiated: function (p_id) { - return IDHandler.get_prop(p_id, 'negotiated', 65535); + return GodotRTCDataChannel.get_prop(p_id, 'negotiated', 65535); + }, + + godot_js_rtc_datachannel_get_buffered_amount__sig: 'ii', + godot_js_rtc_datachannel_get_buffered_amount: function (p_id) { + return GodotRTCDataChannel.get_prop(p_id, 'bufferedAmount', 0); }, godot_js_rtc_datachannel_label_get__sig: 'ii', diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp index ecfaed9089..63ecc03a4c 100644 --- a/modules/webrtc/register_types.cpp +++ b/modules/webrtc/register_types.cpp @@ -41,7 +41,7 @@ #include "webrtc_data_channel_gdnative.h" #include "webrtc_peer_connection_gdnative.h" #endif -#include "webrtc_multiplayer.h" +#include "webrtc_multiplayer_peer.h" void register_webrtc_types() { #define _SET_HINT(NAME, _VAL_, _MAX_) \ @@ -58,11 +58,11 @@ void register_webrtc_types() { ClassDB::register_custom_instance_class<WebRTCPeerConnection>(); #ifdef WEBRTC_GDNATIVE_ENABLED - ClassDB::register_class<WebRTCPeerConnectionGDNative>(); - ClassDB::register_class<WebRTCDataChannelGDNative>(); + GDREGISTER_CLASS(WebRTCPeerConnectionGDNative); + GDREGISTER_CLASS(WebRTCDataChannelGDNative); #endif - ClassDB::register_virtual_class<WebRTCDataChannel>(); - ClassDB::register_class<WebRTCMultiplayer>(); + GDREGISTER_VIRTUAL_CLASS(WebRTCDataChannel); + GDREGISTER_CLASS(WebRTCMultiplayerPeer); } void unregister_webrtc_types() {} diff --git a/modules/webrtc/webrtc_data_channel.cpp b/modules/webrtc/webrtc_data_channel.cpp index 004112f992..ca520a733d 100644 --- a/modules/webrtc/webrtc_data_channel.cpp +++ b/modules/webrtc/webrtc_data_channel.cpp @@ -46,6 +46,7 @@ void WebRTCDataChannel::_bind_methods() { ClassDB::bind_method(D_METHOD("get_max_retransmits"), &WebRTCDataChannel::get_max_retransmits); ClassDB::bind_method(D_METHOD("get_protocol"), &WebRTCDataChannel::get_protocol); ClassDB::bind_method(D_METHOD("is_negotiated"), &WebRTCDataChannel::is_negotiated); + ClassDB::bind_method(D_METHOD("get_buffered_amount"), &WebRTCDataChannel::get_buffered_amount); ADD_PROPERTY(PropertyInfo(Variant::INT, "write_mode", PROPERTY_HINT_ENUM), "set_write_mode", "get_write_mode"); diff --git a/modules/webrtc/webrtc_data_channel.h b/modules/webrtc/webrtc_data_channel.h index 20affc513f..809d35c6e3 100644 --- a/modules/webrtc/webrtc_data_channel.h +++ b/modules/webrtc/webrtc_data_channel.h @@ -70,6 +70,8 @@ public: virtual String get_protocol() const = 0; virtual bool is_negotiated() const = 0; + virtual int get_buffered_amount() const = 0; + virtual Error poll() = 0; virtual void close() = 0; diff --git a/modules/webrtc/webrtc_data_channel_gdnative.cpp b/modules/webrtc/webrtc_data_channel_gdnative.cpp index d4cf464c7c..10a3367557 100644 --- a/modules/webrtc/webrtc_data_channel_gdnative.cpp +++ b/modules/webrtc/webrtc_data_channel_gdnative.cpp @@ -31,6 +31,7 @@ #ifdef WEBRTC_GDNATIVE_ENABLED #include "webrtc_data_channel_gdnative.h" + #include "core/io/resource_loader.h" #include "modules/gdnative/nativescript/nativescript.h" @@ -110,6 +111,11 @@ bool WebRTCDataChannelGDNative::is_negotiated() const { return interface->is_negotiated(interface->data); } +int WebRTCDataChannelGDNative::get_buffered_amount() const { + ERR_FAIL_COND_V(interface == NULL, 0); + return interface->get_buffered_amount(interface->data); +} + Error WebRTCDataChannelGDNative::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { ERR_FAIL_COND_V(interface == nullptr, ERR_UNCONFIGURED); return (Error)interface->get_packet(interface->data, r_buffer, &r_buffer_size); diff --git a/modules/webrtc/webrtc_data_channel_gdnative.h b/modules/webrtc/webrtc_data_channel_gdnative.h index 7e02a32046..5c80edd48c 100644 --- a/modules/webrtc/webrtc_data_channel_gdnative.h +++ b/modules/webrtc/webrtc_data_channel_gdnative.h @@ -60,6 +60,7 @@ public: virtual int get_max_retransmits() const override; virtual String get_protocol() const override; virtual bool is_negotiated() const override; + virtual int get_buffered_amount() const override; virtual Error poll() override; virtual void close() override; diff --git a/modules/webrtc/webrtc_data_channel_js.cpp b/modules/webrtc/webrtc_data_channel_js.cpp index dfbec80c86..31d6a0568c 100644 --- a/modules/webrtc/webrtc_data_channel_js.cpp +++ b/modules/webrtc/webrtc_data_channel_js.cpp @@ -46,6 +46,7 @@ extern int godot_js_rtc_datachannel_id_get(int p_id); extern int godot_js_rtc_datachannel_max_packet_lifetime_get(int p_id); extern int godot_js_rtc_datachannel_max_retransmits_get(int p_id); extern int godot_js_rtc_datachannel_is_negotiated(int p_id); +extern int godot_js_rtc_datachannel_get_buffered_amount(int p_id); extern char *godot_js_rtc_datachannel_label_get(int p_id); // Must free the returned string. extern char *godot_js_rtc_datachannel_protocol_get(int p_id); // Must free the returned string. extern void godot_js_rtc_datachannel_destroy(int p_id); @@ -181,6 +182,10 @@ bool WebRTCDataChannelJS::is_negotiated() const { return godot_js_rtc_datachannel_is_negotiated(_js_id); } +int WebRTCDataChannelJS::get_buffered_amount() const { + return godot_js_rtc_datachannel_get_buffered_amount(_js_id); +} + WebRTCDataChannelJS::WebRTCDataChannelJS() { } diff --git a/modules/webrtc/webrtc_data_channel_js.h b/modules/webrtc/webrtc_data_channel_js.h index db58ebccff..5cd6a32ed9 100644 --- a/modules/webrtc/webrtc_data_channel_js.h +++ b/modules/webrtc/webrtc_data_channel_js.h @@ -72,6 +72,7 @@ public: virtual int get_max_retransmits() const override; virtual String get_protocol() const override; virtual bool is_negotiated() const override; + virtual int get_buffered_amount() const override; virtual Error poll() override; virtual void close() override; diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer_peer.cpp index 741cad5640..95c8c13449 100644 --- a/modules/webrtc/webrtc_multiplayer.cpp +++ b/modules/webrtc/webrtc_multiplayer_peer.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* webrtc_multiplayer.cpp */ +/* webrtc_multiplayer_peer.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,43 +28,51 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "webrtc_multiplayer.h" +#include "webrtc_multiplayer_peer.h" #include "core/io/marshalls.h" #include "core/os/os.h" -void WebRTCMultiplayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayer::initialize, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayer::add_peer, DEFVAL(1)); - ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayer::remove_peer); - ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayer::has_peer); - ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayer::get_peer); - ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayer::get_peers); - ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayer::close); +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("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 WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) { +void WebRTCMultiplayerPeer::set_transfer_channel(int p_channel) { + transfer_channel = p_channel; +} + +int WebRTCMultiplayerPeer::get_transfer_channel() const { + return transfer_channel; +} + +void WebRTCMultiplayerPeer::set_transfer_mode(TransferMode p_mode) { transfer_mode = p_mode; } -NetworkedMultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const { +MultiplayerPeer::TransferMode WebRTCMultiplayerPeer::get_transfer_mode() const { return transfer_mode; } -void WebRTCMultiplayer::set_target_peer(int p_peer_id) { +void WebRTCMultiplayerPeer::set_target_peer(int p_peer_id) { target_peer = p_peer_id; } -/* Returns the ID of the NetworkedMultiplayerPeer who sent the most recent packet: */ -int WebRTCMultiplayer::get_packet_peer() const { +/* Returns the ID of the MultiplayerPeer who sent the most recent packet: */ +int WebRTCMultiplayerPeer::get_packet_peer() const { return next_packet_peer; } -bool WebRTCMultiplayer::is_server() const { +bool WebRTCMultiplayerPeer::is_server() const { return unique_id == TARGET_PEER_SERVER; } -void WebRTCMultiplayer::poll() { +void WebRTCMultiplayerPeer::poll() { if (peer_map.size() == 0) { return; } @@ -112,30 +120,30 @@ void WebRTCMultiplayer::poll() { } } // Remove disconnected peers - for (List<int>::Element *E = remove.front(); E; E = E->next()) { - remove_peer(E->get()); - if (next_packet_peer == E->get()) { + for (int &E : remove) { + remove_peer(E); + if (next_packet_peer == E) { next_packet_peer = 0; } } // Signal newly connected peers - for (List<int>::Element *E = add.front(); E; E = E->next()) { + for (int &E : add) { // Already connected to server: simply notify new peer. // NOTE: Mesh is always connected. if (connection_status == CONNECTION_CONNECTED) { - emit_signal("peer_connected", E->get()); + emit_signal(SNAME("peer_connected"), E); } // Server emulation mode suppresses peer_conencted until server connects. - if (server_compat && E->get() == TARGET_PEER_SERVER) { + if (server_compat && E == TARGET_PEER_SERVER) { // Server connected. connection_status = CONNECTION_CONNECTED; - emit_signal("peer_connected", TARGET_PEER_SERVER); - emit_signal("connection_succeeded"); + emit_signal(SNAME("peer_connected"), TARGET_PEER_SERVER); + emit_signal(SNAME("connection_succeeded")); // Notify of all previously connected peers for (Map<int, Ref<ConnectedPeer>>::Element *F = peer_map.front(); F; F = F->next()) { if (F->key() != 1 && F->get()->connected) { - emit_signal("peer_connected", F->key()); + emit_signal(SNAME("peer_connected"), F->key()); } } break; // Because we already notified of all newly added peers. @@ -147,15 +155,15 @@ void WebRTCMultiplayer::poll() { } } -void WebRTCMultiplayer::_find_next_peer() { +void WebRTCMultiplayerPeer::_find_next_peer() { Map<int, Ref<ConnectedPeer>>::Element *E = peer_map.find(next_packet_peer); if (E) { E = E->next(); } // After last. while (E) { - for (List<Ref<WebRTCDataChannel>>::Element *F = E->get()->channels.front(); F; F = F->next()) { - if (F->get()->get_available_packet_count()) { + for (const Ref<WebRTCDataChannel> &F : E->get()->channels) { + if (F->get_available_packet_count()) { next_packet_peer = E->key(); return; } @@ -165,8 +173,8 @@ void WebRTCMultiplayer::_find_next_peer() { E = peer_map.front(); // Before last while (E) { - for (List<Ref<WebRTCDataChannel>>::Element *F = E->get()->channels.front(); F; F = F->next()) { - if (F->get()->get_available_packet_count()) { + for (const Ref<WebRTCDataChannel> &F : E->get()->channels) { + if (F->get_available_packet_count()) { next_packet_peer = E->key(); return; } @@ -180,20 +188,46 @@ void WebRTCMultiplayer::_find_next_peer() { next_packet_peer = 0; } -void WebRTCMultiplayer::set_refuse_new_connections(bool p_enable) { +void WebRTCMultiplayerPeer::set_refuse_new_connections(bool p_enable) { refuse_connections = p_enable; } -bool WebRTCMultiplayer::is_refusing_new_connections() const { +bool WebRTCMultiplayerPeer::is_refusing_new_connections() const { return refuse_connections; } -NetworkedMultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const { +MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status() const { return connection_status; } -Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) { - ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER); +Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Array p_channels_config) { + ERR_FAIL_COND_V(p_self_id < 1 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER); + channels_config.clear(); + 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.TransferMode'"); + int mode = p_channels_config[i].operator int(); + // Initialize data channel configurations. + Dictionary cfg; + cfg["id"] = CH_RESERVED_MAX + i + 1; + cfg["negotiated"] = true; + cfg["ordered"] = true; + + switch (mode) { + case TRANSFER_MODE_UNRELIABLE_ORDERED: + cfg["maxPacketLifetime"] = 1; + break; + case TRANSFER_MODE_UNRELIABLE: + cfg["maxPacketLifetime"] = 1; + cfg["ordered"] = false; + break; + 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.TransferMode'. Got: %d", mode)); + } + channels_config.push_back(cfg); + } + unique_id = p_self_id; server_compat = p_server_compat; @@ -206,33 +240,33 @@ Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) { return OK; } -int WebRTCMultiplayer::get_unique_id() const { +int WebRTCMultiplayerPeer::get_unique_id() const { ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1); return unique_id; } -void WebRTCMultiplayer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) { +void WebRTCMultiplayerPeer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) { Array channels; - for (List<Ref<WebRTCDataChannel>>::Element *F = p_connected_peer->channels.front(); F; F = F->next()) { - channels.push_back(F->get()); + for (Ref<WebRTCDataChannel> &F : p_connected_peer->channels) { + channels.push_back(F); } r_dict["connection"] = p_connected_peer->connection; r_dict["connected"] = p_connected_peer->connected; r_dict["channels"] = channels; } -bool WebRTCMultiplayer::has_peer(int p_peer_id) { +bool WebRTCMultiplayerPeer::has_peer(int p_peer_id) { return peer_map.has(p_peer_id); } -Dictionary WebRTCMultiplayer::get_peer(int p_peer_id) { +Dictionary WebRTCMultiplayerPeer::get_peer(int p_peer_id) { ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary()); Dictionary out; _peer_to_dict(peer_map[p_peer_id], out); return out; } -Dictionary WebRTCMultiplayer::get_peers() { +Dictionary WebRTCMultiplayerPeer::get_peers() { Dictionary out; for (Map<int, Ref<ConnectedPeer>>::Element *E = peer_map.front(); E; E = E->next()) { Dictionary d; @@ -242,7 +276,7 @@ Dictionary WebRTCMultiplayer::get_peers() { return out; } -Error WebRTCMultiplayer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) { +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(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED); @@ -260,46 +294,52 @@ Error WebRTCMultiplayer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_i cfg["id"] = 1; peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg); - ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED); + ERR_FAIL_COND_V(peer->channels[CH_RELIABLE].is_null(), FAILED); cfg["id"] = 2; cfg["maxPacketLifetime"] = p_unreliable_lifetime; peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg); - ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED); + ERR_FAIL_COND_V(peer->channels[CH_ORDERED].is_null(), FAILED); cfg["id"] = 3; cfg["ordered"] = false; peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg); - ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED); + ERR_FAIL_COND_V(peer->channels[CH_UNRELIABLE].is_null(), FAILED); + + for (const Dictionary &dict : channels_config) { + Ref<WebRTCDataChannel> ch = p_peer->create_data_channel(String::num_int64(dict["id"]), dict); + ERR_FAIL_COND_V(ch.is_null(), FAILED); + peer->channels.push_back(ch); + } peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map return OK; } -void WebRTCMultiplayer::remove_peer(int p_peer_id) { +void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) { ERR_FAIL_COND(!peer_map.has(p_peer_id)); Ref<ConnectedPeer> peer = peer_map[p_peer_id]; peer_map.erase(p_peer_id); if (peer->connected) { peer->connected = false; - emit_signal("peer_disconnected", p_peer_id); + emit_signal(SNAME("peer_disconnected"), p_peer_id); if (server_compat && p_peer_id == TARGET_PEER_SERVER) { - emit_signal("server_disconnected"); + emit_signal(SNAME("server_disconnected")); connection_status = CONNECTION_DISCONNECTED; } } } -Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { +Error WebRTCMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { // Peer not available if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) { _find_next_peer(); ERR_FAIL_V(ERR_UNAVAILABLE); } - for (List<Ref<WebRTCDataChannel>>::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) { - if (E->get()->get_available_packet_count()) { - Error err = E->get()->get_packet(r_buffer, r_buffer_size); + for (Ref<WebRTCDataChannel> &E : peer_map[next_packet_peer]->channels) { + if (E->get_available_packet_count()) { + Error err = E->get_packet(r_buffer, r_buffer_size); _find_next_peer(); return err; } @@ -309,20 +349,24 @@ Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size ERR_FAIL_V(ERR_BUG); } -Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { +Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED); - int ch = CH_RELIABLE; - switch (transfer_mode) { - case TRANSFER_MODE_RELIABLE: - ch = CH_RELIABLE; - break; - case TRANSFER_MODE_UNRELIABLE_ORDERED: - ch = CH_ORDERED; - break; - case TRANSFER_MODE_UNRELIABLE: - ch = CH_UNRELIABLE; - break; + int ch = transfer_channel; + if (ch == 0) { + switch (transfer_mode) { + case TRANSFER_MODE_RELIABLE: + ch = CH_RELIABLE; + break; + case TRANSFER_MODE_UNRELIABLE_ORDERED: + ch = CH_ORDERED; + break; + case TRANSFER_MODE_UNRELIABLE: + ch = CH_UNRELIABLE; + break; + } + } else { + ch += CH_RESERVED_MAX - 1; } Map<int, Ref<ConnectedPeer>>::Element *E = nullptr; @@ -331,8 +375,8 @@ Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) E = peer_map.find(target_peer); ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + "."); - ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG); - ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG); + ERR_FAIL_COND_V_MSG(E->value()->channels.size() <= ch, ERR_INVALID_PARAMETER, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value()->channels.size())); + ERR_FAIL_COND_V(E->value()->channels[ch].is_null(), ERR_BUG); return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); } else { @@ -344,49 +388,40 @@ Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) continue; } - ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid()); + ERR_CONTINUE_MSG(F->value()->channels.size() <= ch, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value()->channels.size())); + ERR_CONTINUE(F->value()->channels[ch].is_null()); F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); } } return OK; } -int WebRTCMultiplayer::get_available_packet_count() const { +int WebRTCMultiplayerPeer::get_available_packet_count() const { if (next_packet_peer == 0) { return 0; // To be sure next call to get_packet works if size > 0 . } int size = 0; for (Map<int, Ref<ConnectedPeer>>::Element *E = peer_map.front(); E; E = E->next()) { - for (List<Ref<WebRTCDataChannel>>::Element *F = E->get()->channels.front(); F; F = F->next()) { - size += F->get()->get_available_packet_count(); + for (const Ref<WebRTCDataChannel> &F : E->get()->channels) { + size += F->get_available_packet_count(); } } return size; } -int WebRTCMultiplayer::get_max_packet_size() const { +int WebRTCMultiplayerPeer::get_max_packet_size() const { return 1200; } -void WebRTCMultiplayer::close() { +void WebRTCMultiplayerPeer::close() { peer_map.clear(); + channels_config.clear(); unique_id = 0; next_packet_peer = 0; target_peer = 0; connection_status = CONNECTION_DISCONNECTED; } -WebRTCMultiplayer::WebRTCMultiplayer() { - unique_id = 0; - next_packet_peer = 0; - target_peer = 0; - client_count = 0; - transfer_mode = TRANSFER_MODE_RELIABLE; - refuse_connections = false; - connection_status = CONNECTION_DISCONNECTED; - server_compat = false; -} - -WebRTCMultiplayer::~WebRTCMultiplayer() { +WebRTCMultiplayerPeer::~WebRTCMultiplayerPeer() { close(); } diff --git a/modules/webrtc/webrtc_multiplayer.h b/modules/webrtc/webrtc_multiplayer_peer.h index 6b4ae6fcc8..ef4fe1678c 100644 --- a/modules/webrtc/webrtc_multiplayer.h +++ b/modules/webrtc/webrtc_multiplayer_peer.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* webrtc_multiplayer.h */ +/* webrtc_multiplayer_peer.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -31,11 +31,11 @@ #ifndef WEBRTC_MULTIPLAYER_H #define WEBRTC_MULTIPLAYER_H -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "webrtc_peer_connection.h" -class WebRTCMultiplayer : public NetworkedMultiplayerPeer { - GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer); +class WebRTCMultiplayerPeer : public MultiplayerPeer { + GDCLASS(WebRTCMultiplayerPeer, MultiplayerPeer); protected: static void _bind_methods(); @@ -48,7 +48,7 @@ private: CH_RESERVED_MAX = 3 }; - class ConnectedPeer : public Reference { + class ConnectedPeer : public RefCounted { public: Ref<WebRTCPeerConnection> connection; List<Ref<WebRTCDataChannel>> channels; @@ -62,25 +62,27 @@ private: } }; - uint32_t unique_id; - int target_peer; - int client_count; - bool refuse_connections; - ConnectionStatus connection_status; - TransferMode transfer_mode; - int next_packet_peer; - bool server_compat; + uint32_t unique_id = 0; + int target_peer = 0; + int client_count = 0; + bool refuse_connections = false; + ConnectionStatus connection_status = CONNECTION_DISCONNECTED; + int transfer_channel = 0; + TransferMode transfer_mode = TRANSFER_MODE_RELIABLE; + int next_packet_peer = 0; + bool server_compat = false; Map<int, Ref<ConnectedPeer>> peer_map; + List<Dictionary> channels_config; void _peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict); void _find_next_peer(); public: - WebRTCMultiplayer(); - ~WebRTCMultiplayer(); + WebRTCMultiplayerPeer() {} + ~WebRTCMultiplayerPeer(); - Error initialize(int p_self_id, bool p_server_compat = false); + Error initialize(int p_self_id, bool p_server_compat = false, 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); @@ -94,7 +96,9 @@ public: int get_available_packet_count() const override; int get_max_packet_size() const override; - // NetworkedMultiplayerPeer + // MultiplayerPeer + void set_transfer_channel(int p_channel) override; + int get_transfer_channel() const override; void set_transfer_mode(TransferMode p_mode) override; TransferMode get_transfer_mode() const override; void set_target_peer(int p_peer_id) override; diff --git a/modules/webrtc/webrtc_peer_connection.h b/modules/webrtc/webrtc_peer_connection.h index ae75864489..fcfb9ae9ae 100644 --- a/modules/webrtc/webrtc_peer_connection.h +++ b/modules/webrtc/webrtc_peer_connection.h @@ -34,8 +34,8 @@ #include "core/io/packet_peer.h" #include "modules/webrtc/webrtc_data_channel.h" -class WebRTCPeerConnection : public Reference { - GDCLASS(WebRTCPeerConnection, Reference); +class WebRTCPeerConnection : public RefCounted { + GDCLASS(WebRTCPeerConnection, RefCounted); public: enum ConnectionState { diff --git a/modules/webrtc/webrtc_peer_connection_js.cpp b/modules/webrtc/webrtc_peer_connection_js.cpp index 8879f7d6ec..ed3459d5f8 100644 --- a/modules/webrtc/webrtc_peer_connection_js.cpp +++ b/modules/webrtc/webrtc_peer_connection_js.cpp @@ -34,17 +34,16 @@ #include "webrtc_data_channel_js.h" -#include "core/io/json.h" #include "emscripten.h" void WebRTCPeerConnectionJS::_on_ice_candidate(void *p_obj, const char *p_mid_name, int p_mline_idx, const char *p_candidate) { WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); - peer->emit_signal("ice_candidate_created", String(p_mid_name), p_mline_idx, String(p_candidate)); + peer->emit_signal(SNAME("ice_candidate_created"), String(p_mid_name), p_mline_idx, String(p_candidate)); } void WebRTCPeerConnectionJS::_on_session_created(void *p_obj, const char *p_type, const char *p_session) { WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); - peer->emit_signal("session_description_created", String(p_type), String(p_session)); + peer->emit_signal(SNAME("session_description_created"), String(p_type), String(p_session)); } void WebRTCPeerConnectionJS::_on_connection_state_changed(void *p_obj, int p_state) { @@ -58,7 +57,7 @@ void WebRTCPeerConnectionJS::_on_error(void *p_obj) { void WebRTCPeerConnectionJS::_on_data_channel(void *p_obj, int p_id) { WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); - peer->emit_signal("data_channel_received", Ref<WebRTCDataChannelJS>(new WebRTCDataChannelJS(p_id))); + peer->emit_signal(SNAME("data_channel_received"), Ref<WebRTCDataChannelJS>(new WebRTCDataChannelJS(p_id))); } void WebRTCPeerConnectionJS::close() { @@ -100,7 +99,7 @@ Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) { } _conn_state = STATE_NEW; - String config = JSON::print(p_config); + 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); return _js_id ? OK : FAILED; } @@ -108,7 +107,7 @@ Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) { Ref<WebRTCDataChannel> WebRTCPeerConnectionJS::create_data_channel(String p_channel, Dictionary p_channel_config) { ERR_FAIL_COND_V(_conn_state != STATE_NEW, nullptr); - String config = JSON::print(p_channel_config); + String config = Variant(p_channel_config).to_json_string(); int id = godot_js_rtc_pc_datachannel_create(_js_id, p_channel.utf8().get_data(), config.utf8().get_data()); ERR_FAIL_COND_V(id == 0, nullptr); return memnew(WebRTCDataChannelJS(id)); diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml index d362bcc10f..1549a907b4 100644 --- a/modules/websocket/doc_classes/WebSocketClient.xml +++ b/modules/websocket/doc_classes/WebSocketClient.xml @@ -6,23 +6,18 @@ <description> This class implements a WebSocket client compatible with any RFC 6455-compliant WebSocket server. This client can be optionally used as a network peer for the [MultiplayerAPI]. - After starting the client ([method connect_to_url]), you will need to [method NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). + 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. </description> <tutorials> </tutorials> <methods> <method name="connect_to_url"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="url" type="String"> - </argument> - <argument index="1" name="protocols" type="PackedStringArray" default="PackedStringArray( )"> - </argument> - <argument index="2" name="gd_mp_api" type="bool" default="false"> - </argument> - <argument index="3" name="custom_headers" type="PackedStringArray" default="PackedStringArray( )"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="url" type="String" /> + <argument index="1" name="protocols" type="PackedStringArray" default="PackedStringArray()" /> + <argument index="2" name="gd_mp_api" type="bool" default="false" /> + <argument 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 network peer for the [MultiplayerAPI], connections to non-Godot servers will not work, and [signal data_received] will not be emitted. @@ -33,26 +28,21 @@ </description> </method> <method name="disconnect_from_host"> - <return type="void"> - </return> - <argument index="0" name="code" type="int" default="1000"> - </argument> - <argument index="1" name="reason" type="String" default=""""> - </argument> + <return type="void" /> + <argument index="0" name="code" type="int" default="1000" /> + <argument 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"> - </return> + <return type="String" /> <description> Return the IP address of the currently connected host. </description> </method> <method name="get_connected_port" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Return the IP port of the currently connected host. </description> @@ -70,8 +60,7 @@ </members> <signals> <signal name="connection_closed"> - <argument index="0" name="was_clean_close" type="bool"> - </argument> + <argument 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> @@ -82,8 +71,7 @@ </description> </signal> <signal name="connection_established"> - <argument index="0" name="protocol" type="String"> - </argument> + <argument 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> @@ -95,10 +83,8 @@ </description> </signal> <signal name="server_close_request"> - <argument index="0" name="code" type="int"> - </argument> - <argument index="1" name="reason" type="String"> - </argument> + <argument index="0" name="code" type="int" /> + <argument 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> diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml index 0679acf78a..cd41e9a1fb 100644 --- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml +++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8" ?> -<class name="WebSocketMultiplayerPeer" inherits="NetworkedMultiplayerPeer" version="4.0"> +<class name="WebSocketMultiplayerPeer" inherits="MultiplayerPeer" version="4.0"> <brief_description> Base class for WebSocket server and client. </brief_description> @@ -10,25 +10,18 @@ </tutorials> <methods> <method name="get_peer" qualifiers="const"> - <return type="WebSocketPeer"> - </return> - <argument index="0" name="peer_id" type="int"> - </argument> + <return type="WebSocketPeer" /> + <argument index="0" name="peer_id" type="int" /> <description> Returns the [WebSocketPeer] associated to the given [code]peer_id[/code]. </description> </method> <method name="set_buffers"> - <return type="int" enum="Error"> - </return> - <argument index="0" name="input_buffer_size_kb" type="int"> - </argument> - <argument index="1" name="input_max_packets" type="int"> - </argument> - <argument index="2" name="output_buffer_size_kb" type="int"> - </argument> - <argument index="3" name="output_max_packets" type="int"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="input_buffer_size_kb" type="int" /> + <argument index="1" name="input_max_packets" type="int" /> + <argument index="2" name="output_buffer_size_kb" type="int" /> + <argument index="3" name="output_max_packets" 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. @@ -39,12 +32,11 @@ </methods> <members> <member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" override="true" default="false" /> - <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="NetworkedMultiplayerPeer.TransferMode" default="2" /> + <member name="transfer_mode" type="int" setter="set_transfer_mode" getter="get_transfer_mode" override="true" enum="MultiplayerPeer.TransferMode" default="2" /> </members> <signals> <signal name="peer_packet"> - <argument index="0" name="peer_source" type="int"> - </argument> + <argument index="0" name="peer_source" 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. diff --git a/modules/websocket/doc_classes/WebSocketPeer.xml b/modules/websocket/doc_classes/WebSocketPeer.xml index 5125956416..ab7ef6c4d0 100644 --- a/modules/websocket/doc_classes/WebSocketPeer.xml +++ b/modules/websocket/doc_classes/WebSocketPeer.xml @@ -11,12 +11,9 @@ </tutorials> <methods> <method name="close"> - <return type="void"> - </return> - <argument index="0" name="code" type="int" default="1000"> - </argument> - <argument index="1" name="reason" type="String" default=""""> - </argument> + <return type="void" /> + <argument index="0" name="code" type="int" default="1000" /> + <argument 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. @@ -24,57 +21,54 @@ </description> </method> <method name="get_connected_host" qualifiers="const"> - <return type="String"> - </return> + <return type="String" /> <description> Returns the IP address of the connected peer. [b]Note:[/b] Not available in the HTML5 export. </description> </method> <method name="get_connected_port" qualifiers="const"> - <return type="int"> - </return> + <return type="int" /> <description> Returns the remote port of the connected peer. [b]Note:[/b] Not available in the HTML5 export. </description> </method> + <method name="get_current_outbound_buffered_amount" qualifiers="const"> + <return type="int" /> + <description> + Returns the current amount of data in the outbound websocket buffer. [b]Note:[/b] HTML5 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"> - </return> + <return type="int" enum="WebSocketPeer.WriteMode" /> <description> Gets the current selected write mode. See [enum WriteMode]. </description> </method> <method name="is_connected_to_host" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns [code]true[/code] if this peer is currently connected. </description> </method> <method name="set_no_delay"> - <return type="void"> - </return> - <argument index="0" name="enabled" type="bool"> - </argument> + <return type="void" /> + <argument 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 HTML5 export. </description> </method> <method name="set_write_mode"> - <return type="void"> - </return> - <argument index="0" name="mode" type="int" enum="WebSocketPeer.WriteMode"> - </argument> + <return type="void" /> + <argument index="0" name="mode" type="int" enum="WebSocketPeer.WriteMode" /> <description> Sets the socket to use the given [enum WriteMode]. </description> </method> <method name="was_string_packet" qualifiers="const"> - <return type="bool"> - </return> + <return type="bool" /> <description> Returns [code]true[/code] if the last received packet was sent as a text payload. See [enum WriteMode]. </description> diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml index f7805209e2..90182de4c2 100644 --- a/modules/websocket/doc_classes/WebSocketServer.xml +++ b/modules/websocket/doc_classes/WebSocketServer.xml @@ -5,68 +5,53 @@ </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 NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). When clients connect, disconnect, or send data, you will receive the appropriate signal. + 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 HTML5 exports. </description> <tutorials> </tutorials> <methods> <method name="disconnect_peer"> - <return type="void"> - </return> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="code" type="int" default="1000"> - </argument> - <argument index="2" name="reason" type="String" default=""""> - </argument> + <return type="void" /> + <argument index="0" name="id" type="int" /> + <argument index="1" name="code" type="int" default="1000" /> + <argument 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"> - </return> - <argument index="0" name="id" type="int"> - </argument> + <return type="String" /> + <argument 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"> - </return> - <argument index="0" name="id" type="int"> - </argument> + <return type="int" /> + <argument 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"> - </return> - <argument index="0" name="id" type="int"> - </argument> + <return type="bool" /> + <argument 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"> - </return> + <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"> - </return> - <argument index="0" name="port" type="int"> - </argument> - <argument index="1" name="protocols" type="PackedStringArray" default="PackedStringArray( )"> - </argument> - <argument index="2" name="gd_mp_api" type="bool" default="false"> - </argument> + <return type="int" enum="Error" /> + <argument index="0" name="port" type="int" /> + <argument index="1" name="protocols" type="PackedStringArray" default="PackedStringArray()" /> + <argument 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. @@ -75,8 +60,7 @@ </description> </method> <method name="stop"> - <return type="void"> - </return> + <return type="void" /> <description> Stops the server and clear its state. </description> @@ -89,6 +73,9 @@ <member name="ca_chain" type="X509Certificate" setter="set_ca_chain" getter="get_ca_chain"> When using SSL (see [member private_key] and [member ssl_certificate]), you can set this to a valid [X509Certificate] to be provided as additional CA chain information during the SSL 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 ssl_certificate]) will cause the server to require SSL instead of regular TCP (i.e. the [code]wss://[/code] protocol). </member> @@ -98,37 +85,31 @@ </members> <signals> <signal name="client_close_request"> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="code" type="int"> - </argument> - <argument index="2" name="reason" type="String"> - </argument> + <argument index="0" name="id" type="int" /> + <argument index="1" name="code" type="int" /> + <argument 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"> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="protocol" type="String"> - </argument> + <argument index="0" name="id" type="int" /> + <argument index="1" name="protocol" type="String" /> + <argument index="2" name="resource_name" type="String" /> <description> - Emitted when a new client connects. "protocol" will be the sub-protocol agreed with the client. + 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"> - <argument index="0" name="id" type="int"> - </argument> - <argument index="1" name="was_clean_close" type="bool"> - </argument> + <argument index="0" name="id" type="int" /> + <argument 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"> - <argument index="0" name="id" type="int"> - </argument> + <argument 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. diff --git a/modules/websocket/editor_debugger_server_websocket.cpp b/modules/websocket/editor_debugger_server_websocket.cpp index b02d212c42..2e61cbfc08 100644 --- a/modules/websocket/editor_debugger_server_websocket.cpp +++ b/modules/websocket/editor_debugger_server_websocket.cpp @@ -50,9 +50,9 @@ void EditorDebuggerServerWebSocket::poll() { Error EditorDebuggerServerWebSocket::start() { int remote_port = (int)EditorSettings::get_singleton()->get("network/debug/remote_port"); - Vector<String> protocols; - protocols.push_back("binary"); // compatibility with EMSCRIPTEN TCP-to-WebSocket layer. - return server->listen(remote_port, protocols); + Vector<String> compatible_protocols; + compatible_protocols.push_back("binary"); // compatibility with EMSCRIPTEN TCP-to-WebSocket layer. + return server->listen(remote_port, compatible_protocols); } void EditorDebuggerServerWebSocket::stop() { diff --git a/modules/websocket/editor_debugger_server_websocket.h b/modules/websocket/editor_debugger_server_websocket.h index 2f73b98c3d..d9543bb647 100644 --- a/modules/websocket/editor_debugger_server_websocket.h +++ b/modules/websocket/editor_debugger_server_websocket.h @@ -28,12 +28,11 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef SCRIPT_EDITOR_DEBUGGER_WEBSOCKET_H -#define SCRIPT_EDITOR_DEBUGGER_WEBSOCKET_H - -#include "modules/websocket/websocket_server.h" +#ifndef EDITOR_DEBUGGER_SERVER_WEBSOCKET_H +#define EDITOR_DEBUGGER_SERVER_WEBSOCKET_H #include "editor/debugger/editor_debugger_server.h" +#include "modules/websocket/websocket_server.h" class EditorDebuggerServerWebSocket : public EditorDebuggerServer { GDCLASS(EditorDebuggerServerWebSocket, EditorDebuggerServer); @@ -59,4 +58,4 @@ public: ~EditorDebuggerServerWebSocket(); }; -#endif // SCRIPT_EDITOR_DEBUGGER_WEBSOCKET_H +#endif // EDITOR_DEBUGGER_SERVER_WEBSOCKET_H diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp index 25b6d6ef0e..5cd94e978f 100644 --- a/modules/websocket/emws_client.cpp +++ b/modules/websocket/emws_client.cpp @@ -79,7 +79,7 @@ Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, String str = "ws://"; if (p_custom_headers.size()) { - WARN_PRINT_ONCE("Custom headers are not supported in in HTML5 platform."); + WARN_PRINT_ONCE("Custom headers are not supported in HTML5 platform."); } if (p_ssl) { str = "wss://"; @@ -95,7 +95,7 @@ Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, return FAILED; } - static_cast<Ref<EMWSPeer>>(_peer)->set_sock(_js_id, _in_buf_size, _in_pkt_size); + static_cast<Ref<EMWSPeer>>(_peer)->set_sock(_js_id, _in_buf_size, _in_pkt_size, _out_buf_size); return OK; } @@ -107,7 +107,7 @@ Ref<WebSocketPeer> EMWSClient::get_peer(int p_peer_id) const { return _peer; } -NetworkedMultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const { +MultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const { if (_peer->is_connected_to_host()) { if (_is_connecting) return CONNECTION_CONNECTING; @@ -121,8 +121,8 @@ void EMWSClient::disconnect_from_host(int p_code, String p_reason) { _peer->close(p_code, p_reason); } -IP_Address EMWSClient::get_connected_host() const { - ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export."); +IPAddress EMWSClient::get_connected_host() const { + ERR_FAIL_V_MSG(IPAddress(), "Not supported in HTML5 export."); } uint16_t EMWSClient::get_connected_port() const { @@ -136,6 +136,7 @@ int EMWSClient::get_max_packet_size() const { 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; } diff --git a/modules/websocket/emws_client.h b/modules/websocket/emws_client.h index 2ab7dc83d0..3b0b8395b9 100644 --- a/modules/websocket/emws_client.h +++ b/modules/websocket/emws_client.h @@ -45,6 +45,7 @@ private: 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; 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); @@ -56,7 +57,7 @@ public: Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()); Ref<WebSocketPeer> get_peer(int p_peer_id) const; void disconnect_from_host(int p_code = 1000, String p_reason = ""); - IP_Address get_connected_host() const; + IPAddress get_connected_host() const; uint16_t get_connected_port() const; virtual ConnectionStatus get_connection_status() const; int get_max_packet_size() const; diff --git a/modules/websocket/emws_peer.cpp b/modules/websocket/emws_peer.cpp index 5e75e10d68..d7263dcf43 100644 --- a/modules/websocket/emws_peer.cpp +++ b/modules/websocket/emws_peer.cpp @@ -33,10 +33,11 @@ #include "emws_peer.h" #include "core/io/ip.h" -void EMWSPeer::set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size) { +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::set_write_mode(WriteMode p_mode) { @@ -53,10 +54,13 @@ Error EMWSPeer::read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_strin } 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) >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY); + int is_bin = write_mode == WebSocketPeer::WRITE_MODE_BINARY ? 1 : 0; + godot_js_websocket_send(peer_sock, p_buffer, p_buffer_size, is_bin); return OK; -}; +} Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { if (_in_buffer.packets_left() == 0) @@ -70,19 +74,26 @@ Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { r_buffer_size = read; return OK; -}; +} int EMWSPeer::get_available_packet_count() const { return _in_buffer.packets_left(); -}; +} + +int EMWSPeer::get_current_outbound_buffered_amount() const { + if (peer_sock != -1) { + return godot_js_websocket_buffered_amount(peer_sock); + } + return 0; +} bool EMWSPeer::was_string_packet() const { return _is_string; -}; +} bool EMWSPeer::is_connected_to_host() const { return peer_sock != -1; -}; +} void EMWSPeer::close(int p_code, String p_reason) { if (peer_sock != -1) { @@ -91,15 +102,15 @@ void EMWSPeer::close(int p_code, String p_reason) { _is_string = 0; _in_buffer.clear(); peer_sock = -1; -}; +} -IP_Address EMWSPeer::get_connected_host() const { - ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export."); +IPAddress EMWSPeer::get_connected_host() const { + ERR_FAIL_V_MSG(IPAddress(), "Not supported in HTML5 export."); }; uint16_t EMWSPeer::get_connected_port() const { ERR_FAIL_V_MSG(0, "Not supported in HTML5 export."); -}; +} void EMWSPeer::set_no_delay(bool p_enabled) { ERR_FAIL_MSG("'set_no_delay' is not supported in HTML5 export."); @@ -107,10 +118,10 @@ void EMWSPeer::set_no_delay(bool p_enabled) { EMWSPeer::EMWSPeer() { close(); -}; +} EMWSPeer::~EMWSPeer() { close(); -}; +} #endif // JAVASCRIPT_ENABLED diff --git a/modules/websocket/emws_peer.h b/modules/websocket/emws_peer.h index abe5bf2bdb..6e93ea31a2 100644 --- a/modules/websocket/emws_peer.h +++ b/modules/websocket/emws_peer.h @@ -48,6 +48,7 @@ typedef void (*WSOnError)(void *p_ref); extern int godot_js_websocket_create(void *p_ref, const char *p_url, const char *p_proto, WSOnOpen p_on_open, WSOnMessage p_on_message, WSOnError p_on_error, WSOnClose p_on_close); extern int godot_js_websocket_send(int p_id, const uint8_t *p_buf, int p_buf_len, int p_raw); +extern int godot_js_websocket_buffered_amount(int p_id); extern void godot_js_websocket_close(int p_id, int p_code, const char *p_reason); extern void godot_js_websocket_destroy(int p_id); } @@ -62,18 +63,20 @@ private: Vector<uint8_t> _packet_buffer; PacketBuffer<uint8_t> _in_buffer; uint8_t _is_string = 0; + int _out_buf_size = 0; 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); + void set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size); virtual int get_available_packet_count() const; virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); virtual int get_max_packet_size() const { return _packet_buffer.size(); }; + virtual int get_current_outbound_buffered_amount() const; virtual void close(int p_code = 1000, String p_reason = ""); virtual bool is_connected_to_host() const; - virtual IP_Address get_connected_host() const; + virtual IPAddress get_connected_host() const; virtual uint16_t get_connected_port() const; virtual WriteMode get_write_mode() const; diff --git a/modules/websocket/emws_server.cpp b/modules/websocket/emws_server.cpp index a35d84f372..4a4f09a943 100644 --- a/modules/websocket/emws_server.cpp +++ b/modules/websocket/emws_server.cpp @@ -58,8 +58,8 @@ Vector<String> EMWSServer::get_protocols() const { return out; } -IP_Address EMWSServer::get_peer_address(int p_peer_id) const { - return IP_Address(); +IPAddress EMWSServer::get_peer_address(int p_peer_id) const { + return IPAddress(); } int EMWSServer::get_peer_port(int p_peer_id) const { diff --git a/modules/websocket/emws_server.h b/modules/websocket/emws_server.h index 4179b20ffe..d36e3a3557 100644 --- a/modules/websocket/emws_server.h +++ b/modules/websocket/emws_server.h @@ -33,7 +33,7 @@ #ifdef JAVASCRIPT_ENABLED -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "emws_peer.h" #include "websocket_server.h" @@ -47,7 +47,7 @@ public: bool is_listening() const; bool has_peer(int p_id) const; Ref<WebSocketPeer> get_peer(int p_id) const; - IP_Address get_peer_address(int p_peer_id) const; + IPAddress get_peer_address(int p_peer_id) const; int get_peer_port(int p_peer_id) const; void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = ""); int get_max_packet_size() const; diff --git a/modules/websocket/library_godot_websocket.js b/modules/websocket/library_godot_websocket.js index b182d1ecde..dd2fd1e94f 100644 --- a/modules/websocket/library_godot_websocket.js +++ b/modules/websocket/library_godot_websocket.js @@ -101,6 +101,15 @@ const GodotWebSocket = { return 0; }, + // Get current bufferedAmount + bufferedAmount: function (p_id) { + const ref = IDHandler.get(p_id); + if (!ref) { + return 0; // Godot object is gone. + } + return ref.bufferedAmount; + }, + create: function (socket, p_on_open, p_on_message, p_on_error, p_on_close) { const id = IDHandler.add(socket); socket.onopen = GodotWebSocket._onopen.bind(null, id, p_on_open); @@ -171,6 +180,11 @@ const GodotWebSocket = { return GodotWebSocket.send(p_id, out); }, + godot_js_websocket_buffered_amount__sig: 'ii', + godot_js_websocket_buffered_amount: function (p_id) { + return GodotWebSocket.bufferedAmount(p_id); + }, + godot_js_websocket_close__sig: 'viii', godot_js_websocket_close: function (p_id, p_code, p_reason) { const code = p_code; diff --git a/modules/websocket/packet_buffer.h b/modules/websocket/packet_buffer.h index ed756363cf..e99a379767 100644 --- a/modules/websocket/packet_buffer.h +++ b/modules/websocket/packet_buffer.h @@ -31,7 +31,6 @@ #ifndef PACKET_BUFFER_H #define PACKET_BUFFER_H -#include "core/os/copymem.h" #include "core/templates/ring_buffer.h" template <class T> @@ -66,7 +65,7 @@ public: if (p_info) { _Packet p; p.size = p_size; - copymem(&p.info, p_info, sizeof(T)); + memcpy(&p.info, p_info, sizeof(T)); _packets.write(p); } @@ -86,7 +85,7 @@ public: ERR_FAIL_COND_V(p_bytes < (int)p.size, ERR_OUT_OF_MEMORY); r_read = p.size; - copymem(r_info, &p.info, sizeof(T)); + memcpy(r_info, &p.info, sizeof(T)); _payload.read(r_payload, p.size); return OK; } diff --git a/modules/websocket/register_types.cpp b/modules/websocket/register_types.cpp index 5a02509c4a..7c742b1b89 100644 --- a/modules/websocket/register_types.cpp +++ b/modules/websocket/register_types.cpp @@ -63,7 +63,7 @@ void register_websocket_types() { WSLServer::make_default(); #endif - ClassDB::register_virtual_class<WebSocketMultiplayerPeer>(); + GDREGISTER_VIRTUAL_CLASS(WebSocketMultiplayerPeer); ClassDB::register_custom_instance_class<WebSocketServer>(); ClassDB::register_custom_instance_class<WebSocketClient>(); ClassDB::register_custom_instance_class<WebSocketPeer>(); diff --git a/modules/websocket/remote_debugger_peer_websocket.h b/modules/websocket/remote_debugger_peer_websocket.h index 03c60fb480..590d925dcc 100644 --- a/modules/websocket/remote_debugger_peer_websocket.h +++ b/modules/websocket/remote_debugger_peer_websocket.h @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef SCRIPT_DEBUGGER_WEBSOCKET_H -#define SCRIPT_DEBUGGER_WEBSOCKET_H +#ifndef REMOTE_DEBUGGER_PEER_WEBSOCKET_H +#define REMOTE_DEBUGGER_PEER_WEBSOCKET_H #ifdef JAVASCRIPT_ENABLED #include "modules/websocket/emws_client.h" @@ -62,4 +62,4 @@ public: RemoteDebuggerPeerWebSocket(Ref<WebSocketPeer> p_peer = Ref<WebSocketPeer>()); }; -#endif // SCRIPT_DEBUGGER_WEBSOCKET_H +#endif // REMOTE_DEBUGGER_PEER_WEBSOCKET_H diff --git a/modules/websocket/websocket_client.cpp b/modules/websocket/websocket_client.cpp index 425013f811..f7a8944745 100644 --- a/modules/websocket/websocket_client.cpp +++ b/modules/websocket/websocket_client.cpp @@ -42,35 +42,22 @@ Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_proto _is_multiplayer = gd_mp_api; String host = p_url; - String path = "/"; - int p_len = -1; - int port = 80; + 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 ssl = false; - if (host.begins_with("wss://")) { - ssl = true; // we should implement this - host = host.substr(6, host.length() - 6); - port = 443; - } else { - ssl = false; - if (host.begins_with("ws://")) { - host = host.substr(5, host.length() - 5); - } + if (scheme == "wss://") { + ssl = true; } - - // Path - p_len = host.find("/"); - if (p_len != -1) { - path = host.substr(p_len, host.length() - p_len); - host = host.substr(0, p_len); + if (port == 0) { + port = ssl ? 443 : 80; } - - // Port - p_len = host.rfind(":"); - if (p_len != -1 && p_len == host.find(":")) { - port = host.substr(p_len, host.length() - p_len).to_int(); - host = host.substr(0, p_len); + if (path.is_empty()) { + path = "/"; } - return connect_to_host(host, path, port, ssl, p_protocols, p_custom_headers); } @@ -99,7 +86,7 @@ void WebSocketClient::_on_peer_packet() { if (_is_multiplayer) { _process_multiplayer(get_peer(1), 1); } else { - emit_signal("data_received"); + emit_signal(SNAME("data_received")); } } @@ -107,27 +94,27 @@ void WebSocketClient::_on_connect(String p_protocol) { if (_is_multiplayer) { // need to wait for ID confirmation... } else { - emit_signal("connection_established", p_protocol); + emit_signal(SNAME("connection_established"), p_protocol); } } void WebSocketClient::_on_close_request(int p_code, String p_reason) { - emit_signal("server_close_request", p_code, 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("connection_failed"); + emit_signal(SNAME("connection_failed")); } else { - emit_signal("connection_closed", p_was_clean); + emit_signal(SNAME("connection_closed"), p_was_clean); } } void WebSocketClient::_on_error() { if (_is_multiplayer) { - emit_signal("connection_failed"); + emit_signal(SNAME("connection_failed")); } else { - emit_signal("connection_error"); + emit_signal(SNAME("connection_error")); } } @@ -139,12 +126,12 @@ void WebSocketClient::_bind_methods() { ClassDB::bind_method(D_METHOD("set_verify_ssl_enabled", "enabled"), &WebSocketClient::set_verify_ssl_enabled); ClassDB::bind_method(D_METHOD("is_verify_ssl_enabled"), &WebSocketClient::is_verify_ssl_enabled); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "verify_ssl", PROPERTY_HINT_NONE, "", 0), "set_verify_ssl_enabled", "is_verify_ssl_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "verify_ssl", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_verify_ssl_enabled", "is_verify_ssl_enabled"); ClassDB::bind_method(D_METHOD("get_trusted_ssl_certificate"), &WebSocketClient::get_trusted_ssl_certificate); ClassDB::bind_method(D_METHOD("set_trusted_ssl_certificate"), &WebSocketClient::set_trusted_ssl_certificate); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "trusted_ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", 0), "set_trusted_ssl_certificate", "get_trusted_ssl_certificate"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "trusted_ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_trusted_ssl_certificate", "get_trusted_ssl_certificate"); ADD_SIGNAL(MethodInfo("data_received")); ADD_SIGNAL(MethodInfo("connection_established", PropertyInfo(Variant::STRING, "protocol"))); diff --git a/modules/websocket/websocket_client.h b/modules/websocket/websocket_client.h index 0225c9b3d3..c7f17f1ffb 100644 --- a/modules/websocket/websocket_client.h +++ b/modules/websocket/websocket_client.h @@ -57,7 +57,7 @@ public: virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, 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 IP_Address get_connected_host() const = 0; + virtual IPAddress get_connected_host() const = 0; virtual uint16_t get_connected_port() const = 0; virtual bool is_server() const override; diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp index 758ed66c80..163cc7706b 100644 --- a/modules/websocket/websocket_multiplayer_peer.cpp +++ b/modules/websocket/websocket_multiplayer_peer.cpp @@ -39,35 +39,15 @@ WebSocketMultiplayerPeer::~WebSocketMultiplayerPeer() { _clear(); } -int WebSocketMultiplayerPeer::_gen_unique_id() const { - uint32_t hash = 0; - - while (hash == 0 || hash == 1) { - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_ticks_usec()); - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_unix_time(), hash); - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_data_path().hash64(), hash); - hash = hash_djb2_one_32( - (uint32_t)((uint64_t)this), hash); //rely on aslr heap - hash = hash_djb2_one_32( - (uint32_t)((uint64_t)&hash), hash); //rely on aslr stack - hash = hash & 0x7FFFFFFF; // make it compatible with unsigned, since negative id is used for exclusion - } - - return hash; -} - void WebSocketMultiplayerPeer::_clear() { _peer_map.clear(); if (_current_packet.data != nullptr) { memfree(_current_packet.data); } - for (List<Packet>::Element *E = _incoming_packets.front(); E; E = E->next()) { - memfree(E->get().data); - E->get().data = nullptr; + for (Packet &E : _incoming_packets) { + memfree(E.data); + E.data = nullptr; } _incoming_packets.clear(); @@ -99,6 +79,8 @@ Error WebSocketMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buff _current_packet.data = nullptr; } + ERR_FAIL_COND_V(_incoming_packets.size() == 0, ERR_UNAVAILABLE); + _current_packet = _incoming_packets.front()->get(); _incoming_packets.pop_front(); @@ -121,13 +103,21 @@ Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer } // -// NetworkedMultiplayerPeer +// MultiplayerPeer // +void WebSocketMultiplayerPeer::set_transfer_channel(int p_channel) { + // Websocket does not have channels. +} + +int WebSocketMultiplayerPeer::get_transfer_channel() const { + return 0; +} + void WebSocketMultiplayerPeer::set_transfer_mode(TransferMode p_mode) { // Websocket uses TCP, reliable } -NetworkedMultiplayerPeer::TransferMode WebSocketMultiplayerPeer::get_transfer_mode() const { +MultiplayerPeer::TransferMode WebSocketMultiplayerPeer::get_transfer_mode() const { // Websocket uses TCP, reliable return TRANSFER_MODE_RELIABLE; } @@ -168,10 +158,10 @@ Vector<uint8_t> WebSocketMultiplayerPeer::_make_pkt(uint8_t p_type, int32_t p_fr out.resize(PROTO_SIZE + p_data_size); uint8_t *w = out.ptrw(); - copymem(&w[0], &p_type, 1); - copymem(&w[1], &p_from, 4); - copymem(&w[5], &p_to, 4); - copymem(&w[PROTO_SIZE], p_data, p_data_size); + 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; } @@ -211,9 +201,9 @@ void WebSocketMultiplayerPeer::_store_pkt(int32_t p_source, int32_t p_dest, cons packet.size = p_data_size; packet.source = p_source; packet.destination = p_dest; - copymem(packet.data, &p_data[PROTO_SIZE], p_data_size); + memcpy(packet.data, &p_data[PROTO_SIZE], p_data_size); _incoming_packets.push_back(packet); - emit_signal("peer_packet", p_source); + emit_signal(SNAME("peer_packet"), p_source); } Error WebSocketMultiplayerPeer::_server_relay(int32_t p_from, int32_t p_to, const uint8_t *p_buffer, uint32_t p_buffer_size) { @@ -263,9 +253,9 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u uint8_t type = 0; uint32_t from = 0; int32_t to = 0; - copymem(&type, in_buffer, 1); - copymem(&from, &in_buffer[1], 4); - copymem(&to, &in_buffer[5], 4); + memcpy(&type, in_buffer, 1); + memcpy(&from, &in_buffer[1], 4); + memcpy(&to, &in_buffer[5], 4); if (is_server()) { // Server can resend @@ -299,20 +289,20 @@ void WebSocketMultiplayerPeer::_process_multiplayer(Ref<WebSocketPeer> p_peer, u // System message ERR_FAIL_COND(data_size < 4); int id = 0; - copymem(&id, &in_buffer[PROTO_SIZE], 4); + memcpy(&id, &in_buffer[PROTO_SIZE], 4); switch (type) { case SYS_ADD: // Add peer _peer_map[id] = Ref<WebSocketPeer>(); - emit_signal("peer_connected", id); + emit_signal(SNAME("peer_connected"), id); if (id == 1) { // We just connected to the server - emit_signal("connection_succeeded"); + emit_signal(SNAME("connection_succeeded")); } break; case SYS_DEL: // Remove peer _peer_map.erase(id); - emit_signal("peer_disconnected", id); + emit_signal(SNAME("peer_disconnected"), id); break; case SYS_ID: // Hello, server assigned ID _peer_id = id; diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h index 48a6607d89..0fee196f41 100644 --- a/modules/websocket/websocket_multiplayer_peer.h +++ b/modules/websocket/websocket_multiplayer_peer.h @@ -32,12 +32,12 @@ #define WEBSOCKET_MULTIPLAYER_PEER_H #include "core/error/error_list.h" -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "core/templates/list.h" #include "websocket_peer.h" -class WebSocketMultiplayerPeer : public NetworkedMultiplayerPeer { - GDCLASS(WebSocketMultiplayerPeer, NetworkedMultiplayerPeer); +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); @@ -75,10 +75,11 @@ protected: 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); - int _gen_unique_id() const; public: - /* NetworkedMultiplayerPeer */ + /* MultiplayerPeer */ + void set_transfer_channel(int p_channel) override; + int get_transfer_channel() const override; void set_transfer_mode(TransferMode p_mode) override; TransferMode get_transfer_mode() const override; void set_target_peer(int p_target_peer) override; diff --git a/modules/websocket/websocket_peer.cpp b/modules/websocket/websocket_peer.cpp index e77fdcfed2..ee13040821 100644 --- a/modules/websocket/websocket_peer.cpp +++ b/modules/websocket/websocket_peer.cpp @@ -47,6 +47,7 @@ void WebSocketPeer::_bind_methods() { 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("set_no_delay", "enabled"), &WebSocketPeer::set_no_delay); + ClassDB::bind_method(D_METHOD("get_current_outbound_buffered_amount"), &WebSocketPeer::get_current_outbound_buffered_amount); BIND_ENUM_CONSTANT(WRITE_MODE_TEXT); BIND_ENUM_CONSTANT(WRITE_MODE_BINARY); diff --git a/modules/websocket/websocket_peer.h b/modules/websocket/websocket_peer.h index 2ba83637f9..517b8600d6 100644 --- a/modules/websocket/websocket_peer.h +++ b/modules/websocket/websocket_peer.h @@ -55,10 +55,11 @@ public: virtual void close(int p_code = 1000, String p_reason = "") = 0; virtual bool is_connected_to_host() const = 0; - virtual IP_Address get_connected_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; WebSocketPeer(); ~WebSocketPeer(); diff --git a/modules/websocket/websocket_server.cpp b/modules/websocket/websocket_server.cpp index f57e8d959c..fb838109f3 100644 --- a/modules/websocket/websocket_server.cpp +++ b/modules/websocket/websocket_server.cpp @@ -34,7 +34,7 @@ GDCINULL(WebSocketServer); WebSocketServer::WebSocketServer() { _peer_id = 1; - bind_ip = IP_Address("*"); + bind_ip = IPAddress("*"); } WebSocketServer::~WebSocketServer() { @@ -55,27 +55,31 @@ void WebSocketServer::_bind_methods() { ClassDB::bind_method(D_METHOD("get_private_key"), &WebSocketServer::get_private_key); ClassDB::bind_method(D_METHOD("set_private_key"), &WebSocketServer::set_private_key); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "private_key", PROPERTY_HINT_RESOURCE_TYPE, "CryptoKey", 0), "set_private_key", "get_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_ssl_certificate"), &WebSocketServer::get_ssl_certificate); ClassDB::bind_method(D_METHOD("set_ssl_certificate"), &WebSocketServer::set_ssl_certificate); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", 0), "set_ssl_certificate", "get_ssl_certificate"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_ssl_certificate", "get_ssl_certificate"); ClassDB::bind_method(D_METHOD("get_ca_chain"), &WebSocketServer::get_ca_chain); ClassDB::bind_method(D_METHOD("set_ca_chain"), &WebSocketServer::set_ca_chain); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ca_chain", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", 0), "set_ca_chain", "get_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::BOOL, "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"))); + 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"))); } -IP_Address WebSocketServer::get_bind_ip() const { +IPAddress WebSocketServer::get_bind_ip() const { return bind_ip; } -void WebSocketServer::set_bind_ip(const IP_Address &p_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; @@ -108,7 +112,16 @@ void WebSocketServer::set_ca_chain(Ref<X509Certificate> p_ca_chain) { ca_chain = p_ca_chain; } -NetworkedMultiplayerPeer::ConnectionStatus WebSocketServer::get_connection_status() const { +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; } @@ -124,17 +137,17 @@ 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("data_received", p_peer_id); + emit_signal(SNAME("data_received"), p_peer_id); } } -void WebSocketServer::_on_connect(int32_t p_peer_id, String p_protocol) { +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("peer_connected", p_peer_id); + emit_signal(SNAME("peer_connected"), p_peer_id); } else { - emit_signal("client_connected", p_peer_id, p_protocol); + emit_signal(SNAME("client_connected"), p_peer_id, p_protocol, p_resource_name); } } @@ -142,12 +155,12 @@ 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("peer_disconnected", p_peer_id); + emit_signal(SNAME("peer_disconnected"), p_peer_id); } else { - emit_signal("client_disconnected", p_peer_id, p_was_clean); + 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("client_close_request", p_peer_id, p_code, 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 index 3fbd5e3b95..c4d651471f 100644 --- a/modules/websocket/websocket_server.h +++ b/modules/websocket/websocket_server.h @@ -32,7 +32,7 @@ #define WEBSOCKET_H #include "core/crypto/crypto.h" -#include "core/object/reference.h" +#include "core/object/ref_counted.h" #include "websocket_multiplayer_peer.h" #include "websocket_peer.h" @@ -40,7 +40,7 @@ class WebSocketServer : public WebSocketMultiplayerPeer { GDCLASS(WebSocketServer, WebSocketMultiplayerPeer); GDCICLASS(WebSocketServer); - IP_Address bind_ip; + IPAddress bind_ip; protected: static void _bind_methods(); @@ -48,6 +48,7 @@ protected: Ref<CryptoKey> private_key; Ref<X509Certificate> ssl_cert; Ref<X509Certificate> ca_chain; + uint32_t handshake_timeout = 3000; public: virtual Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) = 0; @@ -57,17 +58,17 @@ public: virtual bool is_server() const override; ConnectionStatus get_connection_status() const override; - virtual IP_Address get_peer_address(int p_peer_id) const = 0; + 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); + 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); - IP_Address get_bind_ip() const; - void set_bind_ip(const IP_Address &p_bind_ip); + 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); @@ -78,6 +79,9 @@ public: 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(); }; diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp index a075ae3982..49997b42d3 100644 --- a/modules/websocket/wsl_client.cpp +++ b/modules/websocket/wsl_client.cpp @@ -158,9 +158,10 @@ bool WSLClient::_verify_headers(String &r_protocol) { Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, 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)); - IP_Address addr; + IPAddress addr; if (!p_host.is_valid_ip_address()) { addr = IP::get_singleton()->resolve_hostname(p_host); @@ -287,7 +288,7 @@ Ref<WebSocketPeer> WSLClient::get_peer(int p_peer_id) const { return _peer; } -NetworkedMultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const { +MultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const { if (_peer->is_connected_to_host()) { return CONNECTION_CONNECTED; } @@ -316,8 +317,8 @@ void WSLClient::disconnect_from_host(int p_code, String p_reason) { _resp_pos = 0; } -IP_Address WSLClient::get_connected_host() const { - ERR_FAIL_COND_V(!_peer->is_connected_to_host(), IP_Address()); +IPAddress WSLClient::get_connected_host() const { + ERR_FAIL_COND_V(!_peer->is_connected_to_host(), IPAddress()); return _peer->get_connected_host(); } @@ -337,8 +338,8 @@ Error WSLClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer } WSLClient::WSLClient() { - _peer.instance(); - _tcp.instance(); + _peer.instantiate(); + _tcp.instantiate(); disconnect_from_host(); } diff --git a/modules/websocket/wsl_client.h b/modules/websocket/wsl_client.h index e7c91ed333..849639ee8b 100644 --- a/modules/websocket/wsl_client.h +++ b/modules/websocket/wsl_client.h @@ -75,7 +75,7 @@ public: int get_max_packet_size() const; Ref<WebSocketPeer> get_peer(int p_peer_id) const; void disconnect_from_host(int p_code = 1000, String p_reason = ""); - IP_Address get_connected_host() const; + IPAddress get_connected_host() const; uint16_t get_connected_port() const; virtual ConnectionStatus get_connection_status() const; virtual void poll(); diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp index dbbf86d0da..7f027e1c0d 100644 --- a/modules/websocket/wsl_peer.cpp +++ b/modules/websocket/wsl_peer.cpp @@ -205,7 +205,9 @@ void WSLPeer::make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigne ERR_FAIL_COND(p_data == nullptr); _in_buffer.resize(p_in_pkt_size, p_in_buf_size); - _packet_buffer.resize((1 << MAX(p_in_buf_size, p_out_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; @@ -239,6 +241,8 @@ void WSLPeer::poll() { 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) >= (1ULL << _out_buf_size)), ERR_OUT_OF_MEMORY); struct wslay_event_msg msg; // Should I use fragmented? msg.opcode = write_mode == WRITE_MODE_TEXT ? WSLAY_TEXT_FRAME : WSLAY_BINARY_FRAME; @@ -280,6 +284,12 @@ int WSLPeer::get_available_packet_count() const { 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; } @@ -305,8 +315,8 @@ void WSLPeer::close(int p_code, String p_reason) { _packet_buffer.resize(0); } -IP_Address WSLPeer::get_connected_host() const { - ERR_FAIL_COND_V(!is_connected_to_host() || _data->tcp.is_null(), IP_Address()); +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(); } diff --git a/modules/websocket/wsl_peer.h b/modules/websocket/wsl_peer.h index 5e6a7e8554..260d4b183d 100644 --- a/modules/websocket/wsl_peer.h +++ b/modules/websocket/wsl_peer.h @@ -77,6 +77,9 @@ private: WriteMode write_mode = WRITE_MODE_BINARY; + int _out_buf_size = 0; + int _out_pkt_size = 0; + public: int close_code = -1; String close_reason; @@ -86,11 +89,12 @@ public: virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); virtual int get_max_packet_size() const { return _packet_buffer.size(); }; + virtual int get_current_outbound_buffered_amount() const; virtual void close_now(); virtual void close(int p_code = 1000, String p_reason = ""); virtual bool is_connected_to_host() const; - virtual IP_Address get_connected_host() const; + virtual IPAddress get_connected_host() const; virtual uint16_t get_connected_port() const; virtual WriteMode get_write_mode() const; diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp index 437eb2061b..7402bbb46e 100644 --- a/modules/websocket/wsl_server.cpp +++ b/modules/websocket/wsl_server.cpp @@ -34,7 +34,7 @@ #include "core/config/project_settings.h" #include "core/os/os.h" -bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) { +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."); @@ -45,6 +45,7 @@ bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) { // 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]; Map<String, String> headers; for (int i = 1; i < len; i++) { Vector<String> header = psa[i].split(":", false, 1); @@ -95,28 +96,33 @@ bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols) { return true; } -Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) { - if (OS::get_singleton()->get_ticks_msec() - time > WSL_SERVER_TIMEOUT) { +Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name) { + 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_ssl) { Ref<StreamPeerSSL> ssl = static_cast<Ref<StreamPeerSSL>>(connection); if (ssl.is_null()) { - return FAILED; + ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerSSL for WebSocket handshake."); } ssl->poll(); if (ssl->get_status() == StreamPeerSSL::STATUS_HANDSHAKING) { return ERR_BUSY; } else if (ssl->get_status() != StreamPeerSSL::STATUS_CONNECTED) { + print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerSSL status code %d).", ssl->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, "Response headers too big."); + 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; @@ -125,7 +131,7 @@ Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) { 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)) { + if (!_parse_request(p_protocols, r_resource_name)) { return FAILED; } String s = "HTTP/1.1 101 Switching Protocols\r\n"; @@ -143,17 +149,21 @@ Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols) { 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; } @@ -180,15 +190,16 @@ void WSLServer::poll() { remove_ids.push_back(E->key()); } } - for (List<int>::Element *E = remove_ids.front(); E; E = E->next()) { - _peer_map.erase(E->get()); + for (int &E : remove_ids) { + _peer_map.erase(E); } remove_ids.clear(); List<Ref<PendingPeer>> remove_peers; - for (List<Ref<PendingPeer>>::Element *E = _pending.front(); E; E = E->next()) { - Ref<PendingPeer> ppeer = E->get(); - Error err = ppeer->do_handshake(_protocols); + for (const Ref<PendingPeer> &E : _pending) { + String resource_name; + Ref<PendingPeer> ppeer = E; + Error err = ppeer->do_handshake(_protocols, handshake_timeout, resource_name); if (err == ERR_BUSY) { continue; } else if (err != OK) { @@ -196,7 +207,7 @@ void WSLServer::poll() { continue; } // Creating new peer - int32_t id = _gen_unique_id(); + int32_t id = generate_unique_id(); WSLPeer::PeerData *data = memnew(struct WSLPeer::PeerData); data->obj = this; @@ -211,10 +222,10 @@ void WSLServer::poll() { _peer_map[id] = ws_peer; remove_peers.push_back(ppeer); - _on_connect(id, ppeer->protocol); + _on_connect(id, ppeer->protocol, resource_name); } - for (List<Ref<PendingPeer>>::Element *E = remove_peers.front(); E; E = E->next()) { - _pending.erase(E->get()); + for (const Ref<PendingPeer> &E : remove_peers) { + _pending.erase(E); } remove_peers.clear(); @@ -272,8 +283,8 @@ Ref<WebSocketPeer> WSLServer::get_peer(int p_id) const { return _peer_map[p_id]; } -IP_Address WSLServer::get_peer_address(int p_peer_id) const { - ERR_FAIL_COND_V(!has_peer(p_peer_id), IP_Address()); +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(); } @@ -301,7 +312,7 @@ Error WSLServer::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer } WSLServer::WSLServer() { - _server.instance(); + _server.instantiate(); } WSLServer::~WSLServer() { diff --git a/modules/websocket/wsl_server.h b/modules/websocket/wsl_server.h index 75669e12ee..93c8bd9604 100644 --- a/modules/websocket/wsl_server.h +++ b/modules/websocket/wsl_server.h @@ -40,15 +40,13 @@ #include "core/io/stream_peer_tcp.h" #include "core/io/tcp_server.h" -#define WSL_SERVER_TIMEOUT 1000 - class WSLServer : public WebSocketServer { GDCIIMPL(WSLServer, WebSocketServer); private: - class PendingPeer : public Reference { + class PendingPeer : public RefCounted { private: - bool _parse_request(const Vector<String> p_protocols); + bool _parse_request(const Vector<String> p_protocols, String &r_resource_name); public: Ref<StreamPeerTCP> tcp; @@ -64,7 +62,7 @@ private: CharString response; int response_sent = 0; - Error do_handshake(const Vector<String> p_protocols); + Error do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name); }; int _in_buf_size = DEF_BUF_SHIFT; @@ -73,7 +71,7 @@ private: int _out_pkt_size = DEF_PKT_SHIFT; List<Ref<PendingPeer>> _pending; - Ref<TCP_Server> _server; + Ref<TCPServer> _server; Vector<String> _protocols; public: @@ -84,7 +82,7 @@ public: int get_max_packet_size() const; bool has_peer(int p_id) const; Ref<WebSocketPeer> get_peer(int p_id) const; - IP_Address get_peer_address(int p_peer_id) const; + IPAddress get_peer_address(int p_peer_id) const; int get_peer_port(int p_peer_id) const; void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = ""); virtual void poll(); diff --git a/modules/webxr/config.py b/modules/webxr/config.py index 9efebed4e6..f676ef3483 100644 --- a/modules/webxr/config.py +++ b/modules/webxr/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return True + return not env["disable_3d"] def configure(env): diff --git a/modules/webxr/doc_classes/WebXRInterface.xml b/modules/webxr/doc_classes/WebXRInterface.xml index 2407d44496..ff7c46bbae 100644 --- a/modules/webxr/doc_classes/WebXRInterface.xml +++ b/modules/webxr/doc_classes/WebXRInterface.xml @@ -7,7 +7,7 @@ WebXR is an open standard that allows creating VR and AR applications that run in the web browser. As such, this interface is only available when running in an HTML5 export. WebXR supports a wide range of devices, from the very capable (like Valve Index, HTC Vive, Oculus Rift and Quest) down to the much less capable (like Google Cardboard, Oculus Go, GearVR, or plain smartphones). - Since WebXR is based on Javascript, it makes extensive use of callbacks, which means that [WebXRInterface] is forced to use signals, where other AR/VR interfaces would instead use functions that return a result immediately. This makes [WebXRInterface] quite a bit more complicated to intialize than other AR/VR interfaces. + Since WebXR is based on Javascript, it makes extensive use of callbacks, which means that [WebXRInterface] is forced to use signals, where other AR/VR interfaces would instead use functions that return a result immediately. This makes [WebXRInterface] quite a bit more complicated to initialize than other AR/VR interfaces. Here's the minimum code required to start an immersive VR session: [codeblock] extends Node3D @@ -88,17 +88,15 @@ - Using [XRController3D] nodes and their [signal XRController3D.button_pressed] and [signal XRController3D.button_released] signals. This is how controllers are typically handled in AR/VR apps in Godot, however, this will only work with advanced VR controllers like the Oculus Touch or Index controllers, for example. The buttons codes are defined by [url=https://immersive-web.github.io/webxr-gamepads-module/#xr-standard-gamepad-mapping]Section 3.3 of the WebXR Gamepads Module[/url]. - Using [method Node._unhandled_input] and [InputEventJoypadButton] or [InputEventJoypadMotion]. This works the same as normal joypads, except the [member InputEvent.device] starts at 100, so the left controller is 100 and the right controller is 101, and the button codes are also defined by [url=https://immersive-web.github.io/webxr-gamepads-module/#xr-standard-gamepad-mapping]Section 3.3 of the WebXR Gamepads Module[/url]. - Using the [signal select], [signal squeeze] and related signals. This method will work for both advanced VR controllers, and non-traditional "controllers" like a tap on the screen, a spoken voice command or a button press on the device itself. The [code]controller_id[/code] passed to these signals is the same id as used in [member XRController3D.controller_id]. - You can use one or all of these methods to allow your game or app to support a wider or narrower set of devices and input methods, or to allow more advanced interations with more advanced devices. + You can use one or all of these methods to allow your game or app to support a wider or narrower set of devices and input methods, or to allow more advanced interactions with more advanced devices. </description> <tutorials> <link title="How to make a VR game for WebXR with Godot">https://www.snopekgames.com/blog/2020/how-make-vr-game-webxr-godot</link> </tutorials> <methods> <method name="get_controller" qualifiers="const"> - <return type="XRPositionalTracker"> - </return> - <argument index="0" name="controller_id" type="int"> - </argument> + <return type="XRPositionalTracker" /> + <argument index="0" name="controller_id" type="int" /> <description> Gets an [XRPositionalTracker] for the given [code]controller_id[/code]. In the context of WebXR, a "controller" can be an advanced VR controller like the Oculus Touch or Index controllers, or even a tap on the screen, a spoken voice command or a button press on the device itself. When a non-traditional controller is used, interpret the position and orientation of the [XRPositionalTracker] as a ray pointing at the object the user wishes to interact with. @@ -112,10 +110,8 @@ </description> </method> <method name="is_session_supported"> - <return type="void"> - </return> - <argument index="0" name="session_mode" type="String"> - </argument> + <return type="void" /> + <argument index="0" name="session_mode" type="String" /> <description> Checks if the given [code]session_mode[/code] is supported by the user's browser. Possible values come from [url=https://developer.mozilla.org/en-US/docs/Web/API/XRSessionMode]WebXR's XRSessionMode[/url], including: [code]"immersive-vr"[/code], [code]"immersive-ar"[/code], and [code]"inline"[/code]. @@ -170,24 +166,21 @@ </description> </signal> <signal name="select"> - <argument index="0" name="controller_id" type="int"> - </argument> + <argument index="0" name="controller_id" type="int" /> <description> Emitted after one of the "controllers" has finished its "primary action". Use [method get_controller] to get more information about the controller. </description> </signal> <signal name="selectend"> - <argument index="0" name="controller_id" type="int"> - </argument> + <argument index="0" name="controller_id" type="int" /> <description> Emitted when one of the "controllers" has finished its "primary action". Use [method get_controller] to get more information about the controller. </description> </signal> <signal name="selectstart"> - <argument index="0" name="controller_id" type="int"> - </argument> + <argument index="0" name="controller_id" type="int" /> <description> Emitted when one of the "controllers" has started its "primary action". Use [method get_controller] to get more information about the controller. @@ -200,8 +193,7 @@ </description> </signal> <signal name="session_failed"> - <argument index="0" name="message" type="String"> - </argument> + <argument index="0" name="message" type="String" /> <description> Emitted by [method XRInterface.initialize] if the session fails to start. [code]message[/code] may optionally contain an error message from WebXR, or an empty string if no message is available. @@ -214,33 +206,28 @@ </description> </signal> <signal name="session_supported"> - <argument index="0" name="session_mode" type="String"> - </argument> - <argument index="1" name="supported" type="bool"> - </argument> + <argument index="0" name="session_mode" type="String" /> + <argument index="1" name="supported" type="bool" /> <description> Emitted by [method is_session_supported] to indicate if the given [code]session_mode[/code] is supported or not. </description> </signal> <signal name="squeeze"> - <argument index="0" name="controller_id" type="int"> - </argument> + <argument index="0" name="controller_id" type="int" /> <description> Emitted after one of the "controllers" has finished its "primary squeeze action". Use [method get_controller] to get more information about the controller. </description> </signal> <signal name="squeezeend"> - <argument index="0" name="controller_id" type="int"> - </argument> + <argument index="0" name="controller_id" type="int" /> <description> Emitted when one of the "controllers" has finished its "primary squeeze action". Use [method get_controller] to get more information about the controller. </description> </signal> <signal name="squeezestart"> - <argument index="0" name="controller_id" type="int"> - </argument> + <argument index="0" name="controller_id" type="int" /> <description> Emitted when one of the "controllers" has started its "primary squeeze action". Use [method get_controller] to get more information about the controller. diff --git a/modules/webxr/native/library_godot_webxr.js b/modules/webxr/native/library_godot_webxr.js index 8e9ef8a73c..6e19a8ac6e 100644 --- a/modules/webxr/native/library_godot_webxr.js +++ b/modules/webxr/native/library_godot_webxr.js @@ -71,10 +71,8 @@ const GodotWebXR = { // enabled or disabled. When using the WebXR API Emulator, this // gets picked up automatically, however, in the Oculus Browser // on the Quest, we need to pause and resume the main loop. - Browser.pauseAsyncCallbacks(); Browser.mainLoop.pause(); window.setTimeout(function () { - Browser.resumeAsyncCallbacks(); Browser.mainLoop.resume(); }, 0); }, diff --git a/modules/webxr/register_types.cpp b/modules/webxr/register_types.cpp index 8baf7e05b8..078a6547cf 100644 --- a/modules/webxr/register_types.cpp +++ b/modules/webxr/register_types.cpp @@ -34,11 +34,11 @@ #include "webxr_interface_js.h" void register_webxr_types() { - ClassDB::register_virtual_class<WebXRInterface>(); + GDREGISTER_VIRTUAL_CLASS(WebXRInterface); #ifdef JAVASCRIPT_ENABLED Ref<WebXRInterfaceJS> webxr; - webxr.instance(); + webxr.instantiate(); XRServer::get_singleton()->add_interface(webxr); #endif } diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp index 4dce2c2b23..099e769303 100644 --- a/modules/webxr/webxr_interface_js.cpp +++ b/modules/webxr/webxr_interface_js.cpp @@ -35,6 +35,7 @@ #include "core/os/os.h" #include "emscripten.h" #include "godot_webxr.h" +#include "servers/rendering/renderer_compositor.h" #include <stdlib.h> void _emwebxr_on_session_supported(char *p_session_mode, int p_supported) { @@ -45,7 +46,7 @@ void _emwebxr_on_session_supported(char *p_session_mode, int p_supported) { ERR_FAIL_COND(interface.is_null()); String session_mode = String(p_session_mode); - interface->emit_signal("session_supported", session_mode, p_supported ? true : false); + interface->emit_signal(SNAME("session_supported"), session_mode, p_supported ? true : false); } void _emwebxr_on_session_started(char *p_reference_space_type) { @@ -57,7 +58,7 @@ void _emwebxr_on_session_started(char *p_reference_space_type) { String reference_space_type = String(p_reference_space_type); ((WebXRInterfaceJS *)interface.ptr())->_set_reference_space_type(reference_space_type); - interface->emit_signal("session_started"); + interface->emit_signal(SNAME("session_started")); } void _emwebxr_on_session_ended() { @@ -68,7 +69,7 @@ void _emwebxr_on_session_ended() { ERR_FAIL_COND(interface.is_null()); interface->uninitialize(); - interface->emit_signal("session_ended"); + interface->emit_signal(SNAME("session_ended")); } void _emwebxr_on_session_failed(char *p_message) { @@ -81,7 +82,7 @@ void _emwebxr_on_session_failed(char *p_message) { interface->uninitialize(); String message = String(p_message); - interface->emit_signal("session_failed", message); + interface->emit_signal(SNAME("session_failed"), message); } void _emwebxr_on_controller_changed() { @@ -202,8 +203,8 @@ int WebXRInterfaceJS::get_capabilities() const { return XRInterface::XR_STEREO | XRInterface::XR_MONO; }; -bool WebXRInterfaceJS::is_stereo() { - return godot_webxr_get_view_count() == 2; +uint32_t WebXRInterfaceJS::get_view_count() { + return godot_webxr_get_view_count(); }; bool WebXRInterfaceJS::is_initialized() const { @@ -253,7 +254,7 @@ bool WebXRInterfaceJS::initialize() { void WebXRInterfaceJS::uninitialize() { if (initialized) { XRServer *xr_server = XRServer::get_singleton(); - if (xr_server != NULL) { + if (xr_server != nullptr) { // no longer our primary interface xr_server->clear_primary_interface_if(this); } @@ -265,8 +266,8 @@ void WebXRInterfaceJS::uninitialize() { }; }; -Transform WebXRInterfaceJS::_js_matrix_to_transform(float *p_js_matrix) { - Transform transform; +Transform3D WebXRInterfaceJS::_js_matrix_to_transform(float *p_js_matrix) { + Transform3D transform; transform.basis.elements[0].x = p_js_matrix[0]; transform.basis.elements[1].x = p_js_matrix[1]; @@ -305,13 +306,30 @@ Size2 WebXRInterfaceJS::get_render_targetsize() { return render_targetsize; }; -Transform WebXRInterfaceJS::get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) { - Transform transform_for_eye; +Transform3D WebXRInterfaceJS::get_camera_transform() { + Transform3D transform_for_eye; XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL_V(xr_server, transform_for_eye); - float *js_matrix = godot_webxr_get_transform_for_eye(p_eye); + float *js_matrix = godot_webxr_get_transform_for_eye(0); + if (!initialized || js_matrix == nullptr) { + return transform_for_eye; + } + + transform_for_eye = _js_matrix_to_transform(js_matrix); + free(js_matrix); + + return xr_server->get_reference_frame() * transform_for_eye; +}; + +Transform3D WebXRInterfaceJS::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) { + Transform3D transform_for_eye; + + XRServer *xr_server = XRServer::get_singleton(); + ERR_FAIL_NULL_V(xr_server, transform_for_eye); + + float *js_matrix = godot_webxr_get_transform_for_eye(p_view + 1); if (!initialized || js_matrix == nullptr) { transform_for_eye = p_cam_transform; return transform_for_eye; @@ -323,10 +341,10 @@ Transform WebXRInterfaceJS::get_transform_for_eye(XRInterface::Eyes p_eye, const return p_cam_transform * xr_server->get_reference_frame() * transform_for_eye; }; -CameraMatrix WebXRInterfaceJS::get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) { +CameraMatrix WebXRInterfaceJS::get_projection_for_view(uint32_t p_view, real_t p_aspect, real_t p_z_near, real_t p_z_far) { CameraMatrix eye; - float *js_matrix = godot_webxr_get_projection_for_eye(p_eye); + float *js_matrix = godot_webxr_get_projection_for_eye(p_view + 1); if (!initialized || js_matrix == nullptr) { return eye; } @@ -359,6 +377,22 @@ void WebXRInterfaceJS::commit_for_eye(XRInterface::Eyes p_eye, RID p_render_targ return; } godot_webxr_commit_for_eye(p_eye); +} + +Vector<BlitToScreen> WebXRInterfaceJS::commit_views(RID p_render_target, const Rect2 &p_screen_rect) { + Vector<BlitToScreen> blit_to_screen; + + if (!initialized) { + return blit_to_screen; + } + + // @todo Refactor this to be based on "views" rather than "eyes". + godot_webxr_commit_for_eye(XRInterface::EYE_LEFT); + if (godot_webxr_get_view_count() > 1) { + godot_webxr_commit_for_eye(XRInterface::EYE_RIGHT); + } + + return blit_to_screen; }; void WebXRInterfaceJS::process() { @@ -383,7 +417,7 @@ void WebXRInterfaceJS::_update_tracker(int p_controller_id) { Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, p_controller_id + 1); if (godot_webxr_is_controller_connected(p_controller_id)) { if (tracker.is_null()) { - tracker.instance(); + tracker.instantiate(); tracker->set_tracker_type(XRServer::TRACKER_CONTROLLER); // Controller id's 0 and 1 are always the left and right hands. if (p_controller_id < 2) { @@ -399,7 +433,7 @@ void WebXRInterfaceJS::_update_tracker(int p_controller_id) { float *tracker_matrix = godot_webxr_get_controller_transform(p_controller_id); if (tracker_matrix) { - Transform transform = _js_matrix_to_transform(tracker_matrix); + Transform3D transform = _js_matrix_to_transform(tracker_matrix); tracker->set_position(transform.origin); tracker->set_orientation(transform.basis); free(tracker_matrix); @@ -408,7 +442,7 @@ void WebXRInterfaceJS::_update_tracker(int p_controller_id) { int *buttons = godot_webxr_get_controller_buttons(p_controller_id); if (buttons) { for (int i = 0; i < buttons[0]; i++) { - input->joy_button(p_controller_id + 100, i, *((float *)buttons + (i + 1))); + input->joy_button(p_controller_id + 100, (JoyButton)i, *((float *)buttons + (i + 1))); } free(buttons); } @@ -419,7 +453,7 @@ void WebXRInterfaceJS::_update_tracker(int p_controller_id) { Input::JoyAxisValue joy_axis; joy_axis.min = -1; joy_axis.value = *((float *)axes + (i + 1)); - input->joy_axis(p_controller_id + 100, i, joy_axis); + input->joy_axis(p_controller_id + 100, (JoyAxis)i, joy_axis); } free(axes); } diff --git a/modules/webxr/webxr_interface_js.h b/modules/webxr/webxr_interface_js.h index 7c841c1911..f9368582b7 100644 --- a/modules/webxr/webxr_interface_js.h +++ b/modules/webxr/webxr_interface_js.h @@ -56,7 +56,7 @@ private: bool controllers_state[2]; Size2 render_targetsize; - Transform _js_matrix_to_transform(float *p_js_matrix); + Transform3D _js_matrix_to_transform(float *p_js_matrix); void _update_tracker(int p_controller_id); public: @@ -83,11 +83,13 @@ public: virtual void uninitialize() override; virtual Size2 get_render_targetsize() override; - virtual bool is_stereo() override; - virtual Transform get_transform_for_eye(XRInterface::Eyes p_eye, const Transform &p_cam_transform) override; - virtual CameraMatrix get_projection_for_eye(XRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) 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 CameraMatrix get_projection_for_view(uint32_t p_view, real_t p_aspect, real_t p_z_near, real_t p_z_far) override; virtual unsigned int get_external_texture_for_eye(XRInterface::Eyes p_eye) override; virtual void commit_for_eye(XRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) override; + virtual Vector<BlitToScreen> commit_views(RID p_render_target, const Rect2 &p_screen_rect) override; virtual void process() override; virtual void notification(int p_what) override; diff --git a/modules/xatlas_unwrap/register_types.cpp b/modules/xatlas_unwrap/register_types.cpp index e1f9521a48..8913ef1b65 100644 --- a/modules/xatlas_unwrap/register_types.cpp +++ b/modules/xatlas_unwrap/register_types.cpp @@ -29,26 +29,19 @@ /*************************************************************************/ #include "register_types.h" - -#include "core/error/error_macros.h" - #include "core/crypto/crypto_core.h" - #include "thirdparty/xatlas/xatlas.h" -#include <stdio.h> -#include <stdlib.h> +extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, int p_index_count, const uint8_t *p_cache_data, bool *r_use_cache, uint8_t **r_mesh_cache, int *r_mesh_cache_size, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y); -extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y, int *&r_cache_data, unsigned int &r_cache_size, bool &r_used_cache); - -bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, int p_index_count, float **r_uvs, int **r_vertices, int *r_vertex_count, int **r_indices, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y, int *&r_cache_data, unsigned int &r_cache_size, bool &r_used_cache) { +bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, int p_index_count, const uint8_t *p_cache_data, bool *r_use_cache, uint8_t **r_mesh_cache, int *r_mesh_cache_size, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y) { CryptoCore::MD5Context ctx; ctx.start(); ctx.update((unsigned char *)&p_texel_size, sizeof(float)); ctx.update((unsigned char *)p_indices, sizeof(int) * p_index_count); - ctx.update((unsigned char *)p_vertices, sizeof(float) * p_vertex_count); - ctx.update((unsigned char *)p_normals, sizeof(float) * p_vertex_count); + ctx.update((unsigned char *)p_vertices, sizeof(float) * p_vertex_count * 3); + ctx.update((unsigned char *)p_normals, sizeof(float) * p_vertex_count * 3); unsigned char hash[16]; ctx.finish(hash); @@ -56,38 +49,37 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver bool cached = false; unsigned int cache_idx = 0; - if (r_used_cache && r_cache_size) { - //Check if hash is in cache data + *r_mesh_cache = nullptr; + *r_mesh_cache_size = 0; - int *cache_data = r_cache_data; + if (p_cache_data) { + //Check if hash is in cache data + int *cache_data = (int *)p_cache_data; int n_entries = cache_data[0]; - unsigned int r_idx = 1; + unsigned int read_idx = 1; for (int i = 0; i < n_entries; ++i) { - if (memcmp(&cache_data[r_idx], hash, 16) == 0) { + if (memcmp(&cache_data[read_idx], hash, 16) == 0) { cached = true; - cache_idx = r_idx; + cache_idx = read_idx; break; } - r_idx += 4; // hash - r_idx += 2; // size hint + read_idx += 4; // hash + read_idx += 2; // size hint - int vertex_count = cache_data[r_idx]; - r_idx += 1; // vertex count - r_idx += vertex_count; // vertex - r_idx += vertex_count * 2; // uvs + int vertex_count = cache_data[read_idx]; + read_idx += 1; // vertex count + read_idx += vertex_count; // vertex + read_idx += vertex_count * 2; // uvs - int index_count = cache_data[r_idx]; - r_idx += 1; // index count - r_idx += index_count; // indices + int index_count = cache_data[read_idx]; + read_idx += 1; // index count + read_idx += index_count; // indices } } - if (r_used_cache && cached) { - int *cache_data = r_cache_data; - - // Return cache data pointer to the caller - r_cache_data = &cache_data[cache_idx]; + if (cached) { + int *cache_data = (int *)p_cache_data; cache_idx += 4; @@ -99,96 +91,92 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver // Load vertices *r_vertex_count = cache_data[cache_idx]; cache_idx++; - *r_vertices = &cache_data[cache_idx]; + *r_vertex = &cache_data[cache_idx]; cache_idx += *r_vertex_count; // Load UVs - *r_uvs = (float *)&cache_data[cache_idx]; + *r_uv = (float *)&cache_data[cache_idx]; cache_idx += *r_vertex_count * 2; // Load indices *r_index_count = cache_data[cache_idx]; cache_idx++; - *r_indices = &cache_data[cache_idx]; - - // Return cache data size to the caller - r_cache_size = sizeof(int) * (4 + 2 + 1 + *r_vertex_count + (*r_vertex_count * 2) + 1 + *r_index_count); // hash + size hint + vertex_count + vertices + uvs + index_count + indices - r_used_cache = true; - return true; - } - - //set up input mesh - xatlas::MeshDecl input_mesh; - input_mesh.indexData = p_indices; - input_mesh.indexCount = p_index_count; - input_mesh.indexFormat = xatlas::IndexFormat::UInt32; - - input_mesh.vertexCount = p_vertex_count; - input_mesh.vertexPositionData = p_vertices; - input_mesh.vertexPositionStride = sizeof(float) * 3; - input_mesh.vertexNormalData = p_normals; - input_mesh.vertexNormalStride = sizeof(uint32_t) * 3; - input_mesh.vertexUvData = nullptr; - input_mesh.vertexUvStride = 0; - - xatlas::ChartOptions chart_options; - xatlas::PackOptions pack_options; - - pack_options.maxChartSize = 4096; - pack_options.blockAlign = true; - pack_options.padding = 1; - pack_options.texelsPerUnit = 1.0 / p_texel_size; + *r_index = &cache_data[cache_idx]; + } else { + // set up input mesh + xatlas::MeshDecl input_mesh; + input_mesh.indexData = p_indices; + input_mesh.indexCount = p_index_count; + input_mesh.indexFormat = xatlas::IndexFormat::UInt32; + + input_mesh.vertexCount = p_vertex_count; + input_mesh.vertexPositionData = p_vertices; + input_mesh.vertexPositionStride = sizeof(float) * 3; + input_mesh.vertexNormalData = p_normals; + input_mesh.vertexNormalStride = sizeof(uint32_t) * 3; + input_mesh.vertexUvData = NULL; + input_mesh.vertexUvStride = 0; + + xatlas::ChartOptions chart_options; + chart_options.fixWinding = true; + + xatlas::PackOptions pack_options; + pack_options.padding = 1; + pack_options.maxChartSize = 4094; // Lightmap atlassing needs 2 for padding between meshes, so 4096-2 + pack_options.blockAlign = true; + pack_options.texelsPerUnit = 1.0 / p_texel_size; + + xatlas::Atlas *atlas = xatlas::Create(); + + xatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh, 1); + ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Success, false, xatlas::StringForEnum(err)); + + xatlas::Generate(atlas, chart_options, pack_options); + + *r_size_hint_x = atlas->width; + *r_size_hint_y = atlas->height; + + float w = *r_size_hint_x; + float h = *r_size_hint_y; + + if (w == 0 || h == 0) { + xatlas::Destroy(atlas); + return false; //could not bake because there is no area + } - xatlas::Atlas *atlas = xatlas::Create(); - printf("Adding mesh..\n"); - xatlas::AddMeshError err = xatlas::AddMesh(atlas, input_mesh, 1); - ERR_FAIL_COND_V_MSG(err != xatlas::AddMeshError::Success, false, xatlas::StringForEnum(err)); + const xatlas::Mesh &output = atlas->meshes[0]; + + *r_vertex = (int *)memalloc(sizeof(int) * output.vertexCount); + ERR_FAIL_NULL_V_MSG(*r_vertex, false, "Out of memory."); + *r_uv = (float *)memalloc(sizeof(float) * output.vertexCount * 2); + ERR_FAIL_NULL_V_MSG(*r_uv, false, "Out of memory."); + *r_index = (int *)memalloc(sizeof(int) * output.indexCount); + ERR_FAIL_NULL_V_MSG(*r_index, false, "Out of memory."); + + float max_x = 0; + float max_y = 0; + for (uint32_t i = 0; i < output.vertexCount; i++) { + (*r_vertex)[i] = output.vertexArray[i].xref; + (*r_uv)[i * 2 + 0] = output.vertexArray[i].uv[0] / w; + (*r_uv)[i * 2 + 1] = output.vertexArray[i].uv[1] / h; + max_x = MAX(max_x, output.vertexArray[i].uv[0]); + max_y = MAX(max_y, output.vertexArray[i].uv[1]); + } - printf("Generate..\n"); - xatlas::Generate(atlas, chart_options, pack_options); + *r_vertex_count = output.vertexCount; - *r_size_hint_x = atlas->width; - *r_size_hint_y = atlas->height; + for (uint32_t i = 0; i < output.indexCount; i++) { + (*r_index)[i] = output.indexArray[i]; + } - float w = *r_size_hint_x; - float h = *r_size_hint_y; + *r_index_count = output.indexCount; - if (w == 0 || h == 0) { xatlas::Destroy(atlas); - return false; //could not bake because there is no area - } - - const xatlas::Mesh &output = atlas->meshes[0]; - - *r_vertices = (int *)malloc(sizeof(int) * output.vertexCount); - ERR_FAIL_NULL_V_MSG(*r_vertices, false, "Out of memory."); - *r_uvs = (float *)malloc(sizeof(float) * output.vertexCount * 2); - ERR_FAIL_NULL_V_MSG(*r_uvs, false, "Out of memory."); - *r_indices = (int *)malloc(sizeof(int) * output.indexCount); - ERR_FAIL_NULL_V_MSG(*r_indices, false, "Out of memory."); - - float max_x = 0.0; - float max_y = 0.0; - for (uint32_t i = 0; i < output.vertexCount; i++) { - (*r_vertices)[i] = output.vertexArray[i].xref; - (*r_uvs)[i * 2 + 0] = output.vertexArray[i].uv[0] / w; - (*r_uvs)[i * 2 + 1] = output.vertexArray[i].uv[1] / h; - max_x = MAX(max_x, output.vertexArray[i].uv[0]); - max_y = MAX(max_y, output.vertexArray[i].uv[1]); } - printf("Final texture size: %f,%f - max %f,%f\n", w, h, max_x, max_y); - *r_vertex_count = output.vertexCount; + if (*r_use_cache) { + // Build cache data for current mesh - for (uint32_t i = 0; i < output.indexCount; i++) { - (*r_indices)[i] = output.indexArray[i]; - } - - *r_index_count = output.indexCount; - - xatlas::Destroy(atlas); - - if (r_used_cache) { unsigned int new_cache_size = 4 + 2 + 1 + *r_vertex_count + (*r_vertex_count * 2) + 1 + *r_index_count; // hash + size hint + vertex_count + vertices + uvs + index_count + indices new_cache_size *= sizeof(int); int *new_cache_data = (int *)memalloc(new_cache_size); @@ -208,11 +196,11 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver new_cache_idx++; // vertices - memcpy(&new_cache_data[new_cache_idx], *r_vertices, sizeof(int) * *r_vertex_count); + memcpy(&new_cache_data[new_cache_idx], *r_vertex, sizeof(int) * (*r_vertex_count)); new_cache_idx += *r_vertex_count; // uvs - memcpy(&new_cache_data[new_cache_idx], *r_uvs, sizeof(float) * *r_vertex_count * 2); + memcpy(&new_cache_data[new_cache_idx], *r_uv, sizeof(float) * (*r_vertex_count) * 2); new_cache_idx += *r_vertex_count * 2; // index count @@ -220,15 +208,15 @@ bool xatlas_mesh_lightmap_unwrap_callback(float p_texel_size, const float *p_ver new_cache_idx++; // indices - memcpy(&new_cache_data[new_cache_idx], *r_indices, sizeof(int) * *r_index_count); - new_cache_idx += *r_index_count; + memcpy(&new_cache_data[new_cache_idx], *r_index, sizeof(int) * (*r_index_count)); // Return cache data to the caller - r_cache_data = new_cache_data; - r_cache_size = new_cache_size; - r_used_cache = false; + *r_mesh_cache = (uint8_t *)new_cache_data; + *r_mesh_cache_size = new_cache_size; } + *r_use_cache = cached; // Return whether cache was used. + return true; } |