diff options
Diffstat (limited to 'scene')
78 files changed, 1637 insertions, 689 deletions
diff --git a/scene/2d/collision_object_2d.cpp b/scene/2d/collision_object_2d.cpp index c503de2d59..50863f2c4d 100644 --- a/scene/2d/collision_object_2d.cpp +++ b/scene/2d/collision_object_2d.cpp @@ -81,7 +81,7 @@ void CollisionObject2D::_notification(int p_what) { return; } - Transform2D global_transform = get_global_transform_with_canvas(); + Transform2D global_transform = get_global_transform(); if (area) { PhysicsServer2D::get_singleton()->area_set_transform(rid, global_transform); diff --git a/scene/2d/node_2d.cpp b/scene/2d/node_2d.cpp index dd88bda304..42c8daa4c7 100644 --- a/scene/2d/node_2d.cpp +++ b/scene/2d/node_2d.cpp @@ -133,7 +133,7 @@ void Node2D::_update_transform() { void Node2D::set_position(const Point2 &p_pos) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } position = p_pos; _update_transform(); @@ -141,7 +141,7 @@ void Node2D::set_position(const Point2 &p_pos) { void Node2D::set_rotation(real_t p_radians) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } rotation = p_radians; _update_transform(); @@ -149,7 +149,7 @@ void Node2D::set_rotation(real_t p_radians) { void Node2D::set_skew(real_t p_radians) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } skew = p_radians; _update_transform(); @@ -157,7 +157,7 @@ void Node2D::set_skew(real_t p_radians) { void Node2D::set_scale(const Size2 &p_scale) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } scale = p_scale; // Avoid having 0 scale values, can lead to errors in physics and rendering. @@ -172,14 +172,14 @@ void Node2D::set_scale(const Size2 &p_scale) { Point2 Node2D::get_position() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return position; } real_t Node2D::get_rotation() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return rotation; @@ -187,7 +187,7 @@ real_t Node2D::get_rotation() const { real_t Node2D::get_skew() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return skew; @@ -195,7 +195,7 @@ real_t Node2D::get_skew() const { Size2 Node2D::get_scale() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return scale; diff --git a/scene/2d/physical_bone_2d.h b/scene/2d/physical_bone_2d.h index 9f31c22031..22d329c320 100644 --- a/scene/2d/physical_bone_2d.h +++ b/scene/2d/physical_bone_2d.h @@ -49,7 +49,7 @@ private: NodePath bone2d_nodepath; bool follow_bone_when_simulating = false; - Joint2D *child_joint; + Joint2D *child_joint = nullptr; bool auto_configure_joint = true; bool simulate_physics = false; diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp index f96c7b512f..c0f2b6f07e 100644 --- a/scene/2d/physics_body_2d.cpp +++ b/scene/2d/physics_body_2d.cpp @@ -277,7 +277,7 @@ void AnimatableBody2D::_update_kinematic_motion() { } void AnimatableBody2D::_body_state_changed_callback(void *p_instance, PhysicsDirectBodyState2D *p_state) { - AnimatableBody2D *body = (AnimatableBody2D *)p_instance; + AnimatableBody2D *body = static_cast<AnimatableBody2D *>(p_instance); body->_body_state_changed(p_state); } @@ -443,7 +443,7 @@ struct _RigidDynamicBody2DInOut { }; void RigidDynamicBody2D::_body_state_changed_callback(void *p_instance, PhysicsDirectBodyState2D *p_state) { - RigidDynamicBody2D *body = (RigidDynamicBody2D *)p_instance; + RigidDynamicBody2D *body = static_cast<RigidDynamicBody2D *>(p_instance); body->_body_state_changed(p_state); } diff --git a/scene/2d/position_2d.cpp b/scene/2d/position_2d.cpp index 518593cee1..d946ea63bf 100644 --- a/scene/2d/position_2d.cpp +++ b/scene/2d/position_2d.cpp @@ -30,8 +30,6 @@ #include "position_2d.h" -const real_t DEFAULT_GIZMO_EXTENTS = 10.0; - void Position2D::_draw_cross() { const real_t extents = get_gizmo_extents(); @@ -103,28 +101,19 @@ void Position2D::_notification(int p_what) { } void Position2D::set_gizmo_extents(real_t p_extents) { - if (p_extents == DEFAULT_GIZMO_EXTENTS) { - set_meta("_gizmo_extents_", Variant()); - } else { - set_meta("_gizmo_extents_", p_extents); - } - + gizmo_extents = p_extents; update(); } real_t Position2D::get_gizmo_extents() const { - if (has_meta("_gizmo_extents_")) { - return get_meta("_gizmo_extents_"); - } else { - return DEFAULT_GIZMO_EXTENTS; - } + return gizmo_extents; } void Position2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("_set_gizmo_extents", "extents"), &Position2D::set_gizmo_extents); - ClassDB::bind_method(D_METHOD("_get_gizmo_extents"), &Position2D::get_gizmo_extents); + ClassDB::bind_method(D_METHOD("set_gizmo_extents", "extents"), &Position2D::set_gizmo_extents); + ClassDB::bind_method(D_METHOD("get_gizmo_extents"), &Position2D::get_gizmo_extents); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gizmo_extents", PROPERTY_HINT_RANGE, "0,1000,0.1,or_greater", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_gizmo_extents", "_get_gizmo_extents"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gizmo_extents", PROPERTY_HINT_RANGE, "0,1000,0.1,or_greater"), "set_gizmo_extents", "get_gizmo_extents"); } Position2D::Position2D() { diff --git a/scene/2d/position_2d.h b/scene/2d/position_2d.h index 4ef07eb05c..99b0266130 100644 --- a/scene/2d/position_2d.h +++ b/scene/2d/position_2d.h @@ -36,6 +36,8 @@ class Position2D : public Node2D { GDCLASS(Position2D, Node2D); + real_t gizmo_extents = 10.0; + void _draw_cross(); protected: diff --git a/scene/3d/camera_3d.cpp b/scene/3d/camera_3d.cpp index 4eace17cc0..1f0c9acef5 100644 --- a/scene/3d/camera_3d.cpp +++ b/scene/3d/camera_3d.cpp @@ -509,7 +509,7 @@ void Camera3D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "projection", PROPERTY_HINT_ENUM, "Perspective,Orthogonal,Frustum"), "set_projection", "get_projection"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "set_current", "is_current"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov", PROPERTY_HINT_RANGE, "1,179,0.1,degrees"), "set_fov", "get_fov"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size", PROPERTY_HINT_RANGE, "0.1,16384,0.01"), "set_size", "get_size"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size", PROPERTY_HINT_RANGE, "0.001,16384,0.001"), "set_size", "get_size"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "frustum_offset"), "set_frustum_offset", "get_frustum_offset"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "near", PROPERTY_HINT_RANGE, "0.001,10,0.001,or_greater,exp"), "set_near", "get_near"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "far", PROPERTY_HINT_RANGE, "0.01,4000,0.01,or_greater,exp"), "set_far", "get_far"); @@ -557,7 +557,7 @@ void Camera3D::set_fov(real_t p_fov) { } void Camera3D::set_size(real_t p_size) { - ERR_FAIL_COND(p_size < 0.1 || p_size > 16384); + ERR_FAIL_COND(p_size < 0.001 || p_size > 16384); size = p_size; _update_camera_mode(); } diff --git a/scene/3d/lightmap_gi.cpp b/scene/3d/lightmap_gi.cpp index 191a04b6a0..8b457b683d 100644 --- a/scene/3d/lightmap_gi.cpp +++ b/scene/3d/lightmap_gi.cpp @@ -884,7 +884,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa Light3D *light = lights_found[i].light; Transform3D xf = lights_found[i].xform; - Color linear_color = light->get_color().to_linear(); + Color linear_color = light->get_color().srgb_to_linear(); if (Object::cast_to<DirectionalLight3D>(light)) { DirectionalLight3D *l = Object::cast_to<DirectionalLight3D>(light); lightmapper->add_directional_light(light->get_bake_mode() == Light3D::BAKE_STATIC, -xf.basis.get_axis(Vector3::AXIS_Z).normalized(), linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_SIZE)); @@ -1101,7 +1101,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa //#define DEBUG_SIMPLICES_AS_OBJ_FILE #ifdef DEBUG_SIMPLICES_AS_OBJ_FILE { - FileAccessRef f = FileAccess::open("res://bsp.obj", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open("res://bsp.obj", FileAccess::WRITE); for (uint32_t i = 0; i < bsp_simplices.size(); i++) { f->store_line("o Simplex" + itos(i)); for (int j = 0; j < 4; j++) { @@ -1118,7 +1118,6 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa f->store_line(vformat("f %d %d %d", 4 * i + face_order[j][0], 4 * i + face_order[j][1], 4 * i + face_order[j][2])); } } - f->close(); } #endif @@ -1150,7 +1149,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa } //#define DEBUG_BSP_TREE #ifdef DEBUG_BSP_TREE - FileAccessRef f = FileAccess::open("res://bsp.txt", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open("res://bsp.txt", FileAccess::WRITE); for (uint32_t i = 0; i < bsp_nodes.size(); i++) { f->store_line(itos(i) + " - plane: " + bsp_nodes[i].plane + " over: " + itos(bsp_nodes[i].over) + " under: " + itos(bsp_nodes[i].under)); } diff --git a/scene/3d/node_3d.cpp b/scene/3d/node_3d.cpp index 62cc7c143b..bbc977647e 100644 --- a/scene/3d/node_3d.cpp +++ b/scene/3d/node_3d.cpp @@ -181,15 +181,6 @@ void Node3D::_notification(int p_what) { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint() && get_tree()->is_node_being_edited(this)) { get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this); - if (!data.gizmos_disabled) { - for (int i = 0; i < data.gizmos.size(); i++) { - data.gizmos.write[i]->create(); - if (is_visible_in_tree()) { - data.gizmos.write[i]->redraw(); - } - data.gizmos.write[i]->transform(); - } - } } #endif } break; @@ -427,6 +418,7 @@ void Node3D::update_gizmos() { } if (data.gizmos.is_empty()) { + get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this); return; } if (data.gizmos_dirty) { diff --git a/scene/3d/skeleton_3d.h b/scene/3d/skeleton_3d.h index 80ff2a1f79..279c3e49a2 100644 --- a/scene/3d/skeleton_3d.h +++ b/scene/3d/skeleton_3d.h @@ -44,13 +44,13 @@ class SkinReference : public RefCounted { GDCLASS(SkinReference, RefCounted) friend class Skeleton3D; - Skeleton3D *skeleton_node; + Skeleton3D *skeleton_node = nullptr; RID skeleton; Ref<Skin> skin; uint32_t bind_count = 0; uint64_t skeleton_version = 0; Vector<uint32_t> skin_bone_indices; - uint32_t *skin_bone_indices_ptrs; + uint32_t *skin_bone_indices_ptrs = nullptr; void _skin_changed(); protected: diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp index 1ab2e2419e..6949e3681c 100644 --- a/scene/animation/animation_player.cpp +++ b/scene/animation/animation_player.cpp @@ -83,8 +83,31 @@ bool AnimationPlayer::_set(const StringName &p_name, const Variant &p_value) { set_current_animation(p_value); } else if (name.begins_with("anims/")) { + // Backwards compatibility with 3.x, add them to "default" library. String which = name.get_slicec('/', 1); - add_animation(which, p_value); + + Ref<Animation> anim = p_value; + Ref<AnimationLibrary> al; + if (!has_animation_library(StringName())) { + al.instantiate(); + add_animation_library(StringName(), al); + } else { + al = get_animation_library(StringName()); + } + al->add_animation(which, anim); + + } else if (name.begins_with("libraries")) { + Dictionary d = p_value; + while (animation_libraries.size()) { + remove_animation_library(animation_libraries[0].name); + } + List<Variant> keys; + d.get_key_list(&keys); + for (const Variant &K : keys) { + StringName lib_name = K; + Ref<AnimationLibrary> lib = d[lib_name]; + add_animation_library(lib_name, lib); + } } else if (name.begins_with("next/")) { String which = name.get_slicec('/', 1); @@ -117,9 +140,13 @@ bool AnimationPlayer::_get(const StringName &p_name, Variant &r_ret) const { r_ret = get_current_animation(); - } else if (name.begins_with("anims/")) { - String which = name.get_slicec('/', 1); - r_ret = get_animation(which); + } else if (name.begins_with("libraries")) { + Dictionary d; + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + d[animation_libraries[i].name] = animation_libraries[i].library; + } + + r_ret = d; } else if (name.begins_with("next/")) { String which = name.get_slicec('/', 1); @@ -173,8 +200,9 @@ void AnimationPlayer::_validate_property(PropertyInfo &property) const { void AnimationPlayer::_get_property_list(List<PropertyInfo> *p_list) const { List<PropertyInfo> anim_names; + anim_names.push_back(PropertyInfo(Variant::DICTIONARY, "libraries")); + for (const KeyValue<StringName, AnimationData> &E : animation_set) { - anim_names.push_back(PropertyInfo(Variant::OBJECT, "anims/" + String(E.key), PROPERTY_HINT_RESOURCE_TYPE, "Animation", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); if (E.value.next != StringName()) { anim_names.push_back(PropertyInfo(Variant::STRING, "next/" + String(E.key), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL)); } @@ -1155,71 +1183,106 @@ void AnimationPlayer::_animation_process(double p_delta) { } } -Error AnimationPlayer::add_animation(const StringName &p_name, const Ref<Animation> &p_animation) { -#ifdef DEBUG_ENABLED - ERR_FAIL_COND_V_MSG(String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("["), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + "."); -#endif +void AnimationPlayer::_animation_set_cache_update() { + // Relatively fast function to update all animations. - ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER); + animation_set_update_pass++; + bool clear_cache_needed = false; - if (animation_set.has(p_name)) { - _unref_anim(animation_set[p_name].animation); - animation_set[p_name].animation = p_animation; - clear_caches(); - } else { - AnimationData ad; - ad.animation = p_animation; - ad.name = p_name; - animation_set[p_name] = ad; - } + // Update changed and add otherwise + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) { + StringName key = animation_libraries[i].name == StringName() ? K.key : StringName(String(animation_libraries[i].name) + "/" + String(K.key)); + if (!animation_set.has(key)) { + AnimationData ad; + ad.animation = K.value; + ad.animation_library = animation_libraries[i].name; + ad.name = key; + ad.last_update = animation_set_update_pass; + animation_set.insert(ad.name, ad); + } else { + AnimationData &ad = animation_set[key]; + if (ad.last_update != animation_set_update_pass) { + // Was not updated, update. If the animation is duplicated, the second one will be ignored. + if (ad.animation != K.value || ad.animation_library != animation_libraries[i].name) { + // Animation changed, update and clear caches. + clear_cache_needed = true; + ad.animation = K.value; + ad.animation_library = animation_libraries[i].name; + } - _ref_anim(p_animation); - notify_property_list_changed(); - return OK; -} + ad.last_update = animation_set_update_pass; + } + } + } + } -void AnimationPlayer::remove_animation(const StringName &p_name) { - ERR_FAIL_COND(!animation_set.has(p_name)); + // Check removed + List<StringName> to_erase; + for (const KeyValue<StringName, AnimationData> &E : animation_set) { + if (E.value.last_update != animation_set_update_pass) { + // Was not updated, must be erased + to_erase.push_back(E.key); + clear_cache_needed = true; + } + } - stop(); - _unref_anim(animation_set[p_name].animation); - animation_set.erase(p_name); + while (to_erase.size()) { + animation_set.erase(to_erase.front()->get()); + to_erase.pop_front(); + } - clear_caches(); - notify_property_list_changed(); + if (clear_cache_needed) { + // If something was modified or removed, caches need to be cleared + clear_caches(); + } } -void AnimationPlayer::_ref_anim(const Ref<Animation> &p_anim) { - Ref<Animation>(p_anim)->connect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed), varray(), CONNECT_REFERENCE_COUNTED); -} +void AnimationPlayer::_animation_added(const StringName &p_name, const StringName &p_library) { + _animation_set_cache_update(); -void AnimationPlayer::_unref_anim(const Ref<Animation> &p_anim) { - Ref<Animation>(p_anim)->disconnect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed)); + update_configuration_warnings(); } -void AnimationPlayer::rename_animation(const StringName &p_name, const StringName &p_new_name) { - ERR_FAIL_COND(!animation_set.has(p_name)); - ERR_FAIL_COND(String(p_new_name).contains("/") || String(p_new_name).contains(":")); - ERR_FAIL_COND(animation_set.has(p_new_name)); +void AnimationPlayer::_animation_removed(const StringName &p_name, const StringName &p_library) { + StringName name = p_library == StringName() ? p_name : StringName(String(p_library) + "/" + String(p_name)); - stop(); - AnimationData ad = animation_set[p_name]; - ad.name = p_new_name; - animation_set.erase(p_name); - animation_set[p_new_name] = ad; + if (!animation_set.has(name)) { + return; // No need to update because not the one from the library being used. + } + _animation_set_cache_update(); + + // Erase blends if needed + List<BlendKey> to_erase; + for (const KeyValue<BlendKey, float> &E : blend_times) { + BlendKey bk = E.key; + if (bk.from == name || bk.to == name) { + to_erase.push_back(bk); + } + } + + while (to_erase.size()) { + blend_times.erase(to_erase.front()->get()); + to_erase.pop_front(); + } + + update_configuration_warnings(); +} +void AnimationPlayer::_rename_animation(const StringName &p_from_name, const StringName &p_to_name) { + // Rename autoplay or blends if needed. List<BlendKey> to_erase; Map<BlendKey, float> to_insert; for (const KeyValue<BlendKey, float> &E : blend_times) { BlendKey bk = E.key; BlendKey new_bk = bk; bool erase = false; - if (bk.from == p_name) { - new_bk.from = p_new_name; + if (bk.from == p_from_name) { + new_bk.from = p_to_name; erase = true; } - if (bk.to == p_name) { - new_bk.to = p_new_name; + if (bk.to == p_from_name) { + new_bk.to = p_to_name; erase = true; } @@ -1239,12 +1302,184 @@ void AnimationPlayer::rename_animation(const StringName &p_name, const StringNam to_insert.erase(to_insert.front()); } - if (autoplay == p_name) { - autoplay = p_new_name; + if (autoplay == p_from_name) { + autoplay = p_to_name; } +} + +void AnimationPlayer::_animation_renamed(const StringName &p_name, const StringName &p_to_name, const StringName &p_library) { + StringName from_name = p_library == StringName() ? p_name : StringName(String(p_library) + "/" + String(p_name)); + StringName to_name = p_library == StringName() ? p_to_name : StringName(String(p_library) + "/" + String(p_to_name)); + + if (!animation_set.has(from_name)) { + return; // No need to update because not the one from the library being used. + } + _animation_set_cache_update(); + + _rename_animation(from_name, to_name); + update_configuration_warnings(); +} + +Error AnimationPlayer::add_animation_library(const StringName &p_name, const Ref<AnimationLibrary> &p_animation_library) { + ERR_FAIL_COND_V(p_animation_library.is_null(), ERR_INVALID_PARAMETER); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_V_MSG(String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("["), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + "."); +#endif + + int insert_pos = 0; + + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + ERR_FAIL_COND_V_MSG(animation_libraries[i].name == p_name, ERR_ALREADY_EXISTS, "Can't add animation library twice with name: " + String(p_name)); + ERR_FAIL_COND_V_MSG(animation_libraries[i].library == p_animation_library, ERR_ALREADY_EXISTS, "Can't add animation library twice (adding as '" + p_name.operator String() + "', exists as '" + animation_libraries[i].name.operator String() + "'."); + + if (animation_libraries[i].name.operator String() >= p_name.operator String()) { + break; + } + + insert_pos++; + } + + AnimationLibraryData ald; + ald.name = p_name; + ald.library = p_animation_library; + + animation_libraries.insert(insert_pos, ald); + + ald.library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_name)); + ald.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_name)); + ald.library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed), varray(p_name)); + + _animation_set_cache_update(); + + notify_property_list_changed(); + + update_configuration_warnings(); + return OK; +} + +void AnimationPlayer::remove_animation_library(const StringName &p_name) { + int at_pos = -1; + + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + if (animation_libraries[i].name == p_name) { + at_pos = i; + break; + } + } + + ERR_FAIL_COND(at_pos == -1); + + animation_libraries[at_pos].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[at_pos].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[at_pos].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed)); + + stop(); + + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[at_pos].library->animations) { + _unref_anim(K.value); + } + + animation_libraries.remove_at(at_pos); + _animation_set_cache_update(); - clear_caches(); notify_property_list_changed(); + update_configuration_warnings(); +} + +void AnimationPlayer::_ref_anim(const Ref<Animation> &p_anim) { + Ref<Animation>(p_anim)->connect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed), varray(), CONNECT_REFERENCE_COUNTED); +} + +void AnimationPlayer::_unref_anim(const Ref<Animation> &p_anim) { + Ref<Animation>(p_anim)->disconnect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed)); +} + +void AnimationPlayer::rename_animation_library(const StringName &p_name, const StringName &p_new_name) { + if (p_name == p_new_name) { + return; + } +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(String(p_new_name).contains("/") || String(p_new_name).contains(":") || String(p_new_name).contains(",") || String(p_new_name).contains("["), "Invalid animation library name: " + String(p_new_name) + "."); +#endif + + bool found = false; + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + ERR_FAIL_COND_MSG(animation_libraries[i].name == p_new_name, "Can't rename animation library to another existing name: " + String(p_new_name)); + if (animation_libraries[i].name == p_name) { + found = true; + animation_libraries[i].name = p_new_name; + // rename connections + animation_libraries[i].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[i].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[i].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed)); + + animation_libraries[i].library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_new_name)); + animation_libraries[i].library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_new_name)); + animation_libraries[i].library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed), varray(p_new_name)); + + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) { + StringName old_name = p_name == StringName() ? K.key : StringName(String(p_name) + "/" + String(K.key)); + StringName new_name = p_new_name == StringName() ? K.key : StringName(String(p_new_name) + "/" + String(K.key)); + _rename_animation(old_name, new_name); + } + } + } + + ERR_FAIL_COND(!found); + + stop(); + + animation_libraries.sort(); // Must keep alphabetical order. + + _animation_set_cache_update(); // Update cache. + + notify_property_list_changed(); +} + +bool AnimationPlayer::has_animation_library(const StringName &p_name) const { + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + if (animation_libraries[i].name == p_name) { + return true; + } + } + + return false; +} + +Ref<AnimationLibrary> AnimationPlayer::get_animation_library(const StringName &p_name) const { + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + if (animation_libraries[i].name == p_name) { + return animation_libraries[i].library; + } + } + ERR_FAIL_V(Ref<AnimationLibrary>()); +} + +TypedArray<StringName> AnimationPlayer::_get_animation_library_list() const { + TypedArray<StringName> ret; + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + ret.push_back(animation_libraries[i].name); + } + return ret; +} + +void AnimationPlayer::get_animation_library_list(List<StringName> *p_libraries) const { + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + p_libraries->push_back(animation_libraries[i].name); + } +} + +TypedArray<String> AnimationPlayer::get_configuration_warnings() const { + TypedArray<String> warnings = Node::get_configuration_warnings(); + + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) { + if (animation_set.has(K.key) && animation_set[K.key].animation_library != animation_libraries[i].name) { + warnings.push_back(vformat(RTR("Animation '%s' in library '%s' is unused because another animation with the same name exists in library '%s'."), K.key, animation_libraries[i].name, animation_set[K.key].animation_library)); + } + } + } + return warnings; } bool AnimationPlayer::has_animation(const StringName &p_name) const { @@ -1585,7 +1820,16 @@ StringName AnimationPlayer::find_animation(const Ref<Animation> &p_animation) co } } - return ""; + return StringName(); +} + +StringName AnimationPlayer::find_animation_library(const Ref<Animation> &p_animation) const { + for (const KeyValue<StringName, AnimationData> &E : animation_set) { + if (E.value.animation == p_animation) { + return E.value.animation_library; + } + } + return StringName(); } void AnimationPlayer::set_autoplay(const String &p_name) { @@ -1764,7 +2008,10 @@ Ref<AnimatedValuesBackup> AnimationPlayer::apply_reset(bool p_user_initiated) { AnimationPlayer *aux_player = memnew(AnimationPlayer); EditorNode::get_singleton()->add_child(aux_player); - aux_player->add_animation(SceneStringNames::get_singleton()->RESET, reset_anim); + Ref<AnimationLibrary> al; + al.instantiate(); + al->add_animation(SceneStringNames::get_singleton()->RESET, reset_anim); + aux_player->add_animation_library("default", al); aux_player->set_assigned_animation(SceneStringNames::get_singleton()->RESET); // Forcing the use of the original root because the scene where original player belongs may be not the active one Node *root = get_node(get_root()); @@ -1792,9 +2039,13 @@ bool AnimationPlayer::can_apply_reset() const { #endif // TOOLS_ENABLED void AnimationPlayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_animation", "name", "animation"), &AnimationPlayer::add_animation); - ClassDB::bind_method(D_METHOD("remove_animation", "name"), &AnimationPlayer::remove_animation); - ClassDB::bind_method(D_METHOD("rename_animation", "name", "newname"), &AnimationPlayer::rename_animation); + ClassDB::bind_method(D_METHOD("add_animation_library", "name", "library"), &AnimationPlayer::add_animation_library); + ClassDB::bind_method(D_METHOD("remove_animation_library", "name"), &AnimationPlayer::remove_animation_library); + ClassDB::bind_method(D_METHOD("rename_animation_library", "name", "newname"), &AnimationPlayer::rename_animation_library); + ClassDB::bind_method(D_METHOD("has_animation_library", "name"), &AnimationPlayer::has_animation_library); + ClassDB::bind_method(D_METHOD("get_animation_library", "name"), &AnimationPlayer::get_animation_library); + ClassDB::bind_method(D_METHOD("get_animation_library_list"), &AnimationPlayer::_get_animation_library_list); + ClassDB::bind_method(D_METHOD("has_animation", "name"), &AnimationPlayer::has_animation); ClassDB::bind_method(D_METHOD("get_animation", "name"), &AnimationPlayer::get_animation); ClassDB::bind_method(D_METHOD("get_animation_list"), &AnimationPlayer::_get_animation_list); @@ -1838,6 +2089,7 @@ void AnimationPlayer::_bind_methods() { ClassDB::bind_method(D_METHOD("get_root"), &AnimationPlayer::get_root); ClassDB::bind_method(D_METHOD("find_animation", "animation"), &AnimationPlayer::find_animation); + ClassDB::bind_method(D_METHOD("find_animation_library", "animation"), &AnimationPlayer::find_animation_library); ClassDB::bind_method(D_METHOD("clear_caches"), &AnimationPlayer::clear_caches); diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h index a68f6b9d5b..1d450175ad 100644 --- a/scene/animation/animation_player.h +++ b/scene/animation/animation_player.h @@ -36,6 +36,7 @@ #include "scene/3d/node_3d.h" #include "scene/3d/skeleton_3d.h" #include "scene/resources/animation.h" +#include "scene/resources/animation_library.h" #ifdef TOOLS_ENABLED class AnimatedValuesBackup : public RefCounted { @@ -184,9 +185,20 @@ private: StringName next; Vector<TrackNodeCache *> node_cache; Ref<Animation> animation; + StringName animation_library; + uint64_t last_update = 0; }; Map<StringName, AnimationData> animation_set; + + struct AnimationLibraryData { + StringName name; + Ref<AnimationLibrary> library; + bool operator<(const AnimationLibraryData &p_data) const { return name.operator String() < p_data.name.operator String(); } + }; + + LocalVector<AnimationLibraryData> animation_libraries; + struct BlendKey { StringName from; StringName to; @@ -261,6 +273,15 @@ private: bool playing = false; + uint64_t animation_set_update_pass = 1; + void _animation_set_cache_update(); + void _animation_added(const StringName &p_name, const StringName &p_library); + void _animation_removed(const StringName &p_name, const StringName &p_library); + void _animation_renamed(const StringName &p_name, const StringName &p_to_name, const StringName &p_library); + void _rename_animation(const StringName &p_from_name, const StringName &p_to_name); + + TypedArray<StringName> _get_animation_library_list() const; + protected: bool _set(const StringName &p_name, const Variant &p_value); bool _get(const StringName &p_name, Variant &r_ret) const; @@ -272,13 +293,18 @@ protected: public: StringName find_animation(const Ref<Animation> &p_animation) const; + StringName find_animation_library(const Ref<Animation> &p_animation) const; + + Error add_animation_library(const StringName &p_name, const Ref<AnimationLibrary> &p_animation_library); + void remove_animation_library(const StringName &p_name); + void rename_animation_library(const StringName &p_name, const StringName &p_new_name); + Ref<AnimationLibrary> get_animation_library(const StringName &p_name) const; + void get_animation_library_list(List<StringName> *p_animations) const; + bool has_animation_library(const StringName &p_name) const; - Error add_animation(const StringName &p_name, const Ref<Animation> &p_animation); - void remove_animation(const StringName &p_name); - void rename_animation(const StringName &p_name, const StringName &p_new_name); - bool has_animation(const StringName &p_name) const; Ref<Animation> get_animation(const StringName &p_name) const; void get_animation_list(List<StringName> *p_animations) const; + bool has_animation(const StringName &p_name) const; void set_blend_time(const StringName &p_animation1, const StringName &p_animation2, float p_time); float get_blend_time(const StringName &p_animation1, const StringName &p_animation2) const; @@ -340,6 +366,8 @@ public: bool can_apply_reset() const; #endif + TypedArray<String> get_configuration_warnings() const override; + AnimationPlayer(); ~AnimationPlayer(); }; diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp index 64c71697a5..60f2623267 100644 --- a/scene/animation/animation_tree.cpp +++ b/scene/animation/animation_tree.cpp @@ -540,6 +540,11 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { List<StringName> sname; player->get_animation_list(&sname); + Ref<Animation> reset_anim; + bool has_reset_anim = player->has_animation("RESET"); + if (has_reset_anim) { + reset_anim = player->get_animation("RESET"); + } for (const StringName &E : sname) { Ref<Animation> anim = player->get_animation(E); for (int i = 0; i < anim->get_track_count(); i++) { @@ -593,6 +598,12 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { track = track_value; + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + track_value->init_value = reset_anim->track_get_key_value(rt, 0); + } + } } break; case Animation::TYPE_POSITION_3D: case Animation::TYPE_ROTATION_3D: @@ -645,6 +656,25 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { } } + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + switch (track_type) { + case Animation::TYPE_POSITION_3D: { + track_xform->init_loc = reset_anim->track_get_key_value(rt, 0); + } break; + case Animation::TYPE_ROTATION_3D: { + track_xform->ref_rot = reset_anim->track_get_key_value(rt, 0); + track_xform->init_rot = track_xform->ref_rot.log(); + } break; + case Animation::TYPE_SCALE_3D: { + track_xform->init_scale = reset_anim->track_get_key_value(rt, 0); + } break; + default: { + } + } + } + } #endif // _3D_DISABLED } break; case Animation::TYPE_BLEND_SHAPE: { @@ -675,6 +705,13 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { track_bshape->object = mesh_3d; track_bshape->object_id = mesh_3d->get_instance_id(); track = track_bshape; + + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + track_bshape->init_value = reset_anim->track_get_key_value(rt, 0); + } + } #endif } break; case Animation::TYPE_METHOD: { @@ -704,6 +741,13 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { track_bezier->object_id = track_bezier->object->get_instance_id(); track = track_bezier; + + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + track_bezier->init_value = reset_anim->track_get_key_value(rt, 0); + } + } } break; case Animation::TYPE_AUDIO: { TrackCacheAudio *track_audio = memnew(TrackCacheAudio); @@ -950,13 +994,13 @@ void AnimationTree::_process_graph(double p_delta) { case Animation::TYPE_POSITION_3D: { #ifndef _3D_DISABLED TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track); - if (t->process_pass != process_pass) { - t->process_pass = process_pass; - t->loc = t->init_loc; - t->rot = t->init_rot; - t->scale = t->init_scale; - } if (track->root_motion) { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = Vector3(0, 0, 0); + t->rot = Quaternion(0, 0, 0, 0); + t->scale = Vector3(0, 0, 0); + } double prev_time = time - delta; if (!backward) { if (prev_time < 0) { @@ -1026,6 +1070,12 @@ void AnimationTree::_process_graph(double p_delta) { prev_time = !backward ? 0 : (double)a->get_length(); } else { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = t->init_loc; + t->rot = t->init_rot; + t->scale = t->init_scale; + } Vector3 loc; Error err = a->position_track_interpolate(i, time, &loc); @@ -1040,13 +1090,13 @@ void AnimationTree::_process_graph(double p_delta) { case Animation::TYPE_ROTATION_3D: { #ifndef _3D_DISABLED TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track); - if (t->process_pass != process_pass) { - t->process_pass = process_pass; - t->loc = t->init_loc; - t->rot = t->init_rot; - t->scale = t->init_scale; - } if (track->root_motion) { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = Vector3(0, 0, 0); + t->rot = Quaternion(0, 0, 0, 0); + t->scale = Vector3(0, 0, 0); + } double prev_time = time - delta; if (!backward) { if (prev_time < 0) { @@ -1116,6 +1166,12 @@ void AnimationTree::_process_graph(double p_delta) { prev_time = !backward ? 0 : (double)a->get_length(); } else { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = t->init_loc; + t->rot = t->init_rot; + t->scale = t->init_scale; + } Quaternion rot; Error err = a->rotation_track_interpolate(i, time, &rot); @@ -1133,13 +1189,13 @@ void AnimationTree::_process_graph(double p_delta) { case Animation::TYPE_SCALE_3D: { #ifndef _3D_DISABLED TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track); - if (t->process_pass != process_pass) { - t->process_pass = process_pass; - t->loc = t->init_loc; - t->rot = t->init_rot; - t->scale = t->init_scale; - } if (track->root_motion) { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = Vector3(0, 0, 0); + t->rot = Quaternion(0, 0, 0, 0); + t->scale = Vector3(0, 0, 0); + } double prev_time = time - delta; if (!backward) { if (prev_time < 0) { @@ -1209,6 +1265,12 @@ void AnimationTree::_process_graph(double p_delta) { prev_time = !backward ? 0 : (double)a->get_length(); } else { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = t->init_loc; + t->rot = t->init_rot; + t->scale = t->init_scale; + } Vector3 scale; Error err = a->scale_track_interpolate(i, time, &scale); @@ -1226,7 +1288,7 @@ void AnimationTree::_process_graph(double p_delta) { if (t->process_pass != process_pass) { t->process_pass = process_pass; - t->value = 0; + t->value = t->init_value; } float value; @@ -1238,7 +1300,7 @@ void AnimationTree::_process_graph(double p_delta) { continue; } - t->value += value * blend; + t->value += (value - t->init_value) * blend; #endif // _3D_DISABLED } break; case Animation::TYPE_VALUE: { @@ -1256,10 +1318,15 @@ void AnimationTree::_process_graph(double p_delta) { if (t->process_pass != process_pass) { t->process_pass = process_pass; - t->value = value; - t->value.zero(); + if (!t->init_value) { + t->init_value = value; + t->init_value.zero(); + } else { + t->value = t->init_value; + } } + Variant::sub(value, t->init_value, value); Variant::blend(t->value, value, blend, t->value); } else { if (blend < CMP_EPSILON) { @@ -1303,10 +1370,10 @@ void AnimationTree::_process_graph(double p_delta) { if (t->process_pass != process_pass) { t->process_pass = process_pass; - t->value = 0; + t->value = t->init_value; } - t->value += bezier * blend; + t->value += (bezier - t->init_value) * blend; } break; case Animation::TYPE_AUDIO: { if (blend < CMP_EPSILON) { @@ -1521,7 +1588,7 @@ void AnimationTree::_process_graph(double p_delta) { if (t->root_motion) { Transform3D xform; xform.origin = t->loc; - xform.basis.set_quaternion_scale(t->rot, t->scale); + xform.basis.set_quaternion_scale(t->rot, Vector3(1, 1, 1) + t->scale); root_motion_transform = xform; diff --git a/scene/animation/animation_tree.h b/scene/animation/animation_tree.h index 3ccb6be073..524f735894 100644 --- a/scene/animation/animation_tree.h +++ b/scene/animation/animation_tree.h @@ -212,12 +212,14 @@ private: struct TrackCacheBlendShape : public TrackCache { MeshInstance3D *mesh_3d = nullptr; + float init_value = 0; float value = 0; int shape_index = -1; TrackCacheBlendShape() { type = Animation::TYPE_BLEND_SHAPE; } }; struct TrackCacheValue : public TrackCache { + Variant init_value; Variant value; Vector<StringName> subpath; TrackCacheValue() { type = Animation::TYPE_VALUE; } @@ -228,6 +230,7 @@ private: }; struct TrackCacheBezier : public TrackCache { + real_t init_value = 0.0; real_t value = 0.0; Vector<StringName> subpath; TrackCacheBezier() { diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp index ab86face7e..789c01adf3 100644 --- a/scene/gui/base_button.cpp +++ b/scene/gui/base_button.cpp @@ -339,14 +339,14 @@ bool BaseButton::is_keep_pressed_outside() const { void BaseButton::set_shortcut(const Ref<Shortcut> &p_shortcut) { shortcut = p_shortcut; - set_process_unhandled_key_input(shortcut.is_valid()); + set_process_shortcut_input(shortcut.is_valid()); } Ref<Shortcut> BaseButton::get_shortcut() const { return shortcut; } -void BaseButton::unhandled_key_input(const Ref<InputEvent> &p_event) { +void BaseButton::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (!_is_focus_owner_in_shortcut_context()) { diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h index a2b6ee0845..f4f9b88868 100644 --- a/scene/gui/base_button.h +++ b/scene/gui/base_button.h @@ -77,7 +77,7 @@ protected: virtual void toggled(bool p_pressed); static void _bind_methods(); virtual void gui_input(const Ref<InputEvent> &p_event) override; - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; void _notification(int p_what); bool _is_focus_owner_in_shortcut_context() const; diff --git a/scene/gui/dialogs.h b/scene/gui/dialogs.h index 11c701b0d5..41fd9c0a10 100644 --- a/scene/gui/dialogs.h +++ b/scene/gui/dialogs.h @@ -45,10 +45,10 @@ class AcceptDialog : public Window { GDCLASS(AcceptDialog, Window); Window *parent_visible = nullptr; - Panel *bg; - HBoxContainer *hbc; - Label *label; - Button *ok; + Panel *bg = nullptr; + HBoxContainer *hbc = nullptr; + Label *label = nullptr; + Button *ok = nullptr; bool hide_on_ok = true; bool close_on_escape = true; @@ -103,7 +103,7 @@ public: class ConfirmationDialog : public AcceptDialog { GDCLASS(ConfirmationDialog, AcceptDialog); - Button *cancel; + Button *cancel = nullptr; protected: static void _bind_methods(); diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp index e71ab64535..c953dbf4c3 100644 --- a/scene/gui/file_dialog.cpp +++ b/scene/gui/file_dialog.cpp @@ -95,7 +95,7 @@ void FileDialog::_notification(int p_what) { switch (p_what) { case NOTIFICATION_VISIBILITY_CHANGED: { if (!is_visible()) { - set_process_unhandled_input(false); + set_process_shortcut_input(false); } } break; @@ -119,7 +119,7 @@ void FileDialog::_notification(int p_what) { } } -void FileDialog::unhandled_input(const Ref<InputEvent> &p_event) { +void FileDialog::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); Ref<InputEventKey> k = p_event; @@ -217,7 +217,7 @@ void FileDialog::_post_popup() { tree->grab_focus(); } - set_process_unhandled_input(true); + set_process_shortcut_input(true); // For open dir mode, deselect all items on file dialog open. if (mode == FILE_MODE_OPEN_DIR) { @@ -798,7 +798,6 @@ void FileDialog::set_access(Access p_access) { if (access == p_access) { return; } - memdelete(dir_access); switch (p_access) { case ACCESS_FILESYSTEM: { dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); @@ -1091,5 +1090,4 @@ FileDialog::~FileDialog() { if (unregister_func) { unregister_func(this); } - memdelete(dir_access); } diff --git a/scene/gui/file_dialog.h b/scene/gui/file_dialog.h index 7a50efe40f..2e326d2949 100644 --- a/scene/gui/file_dialog.h +++ b/scene/gui/file_dialog.h @@ -65,34 +65,34 @@ public: static RegisterFunc unregister_func; private: - ConfirmationDialog *makedialog; - LineEdit *makedirname; + ConfirmationDialog *makedialog = nullptr; + LineEdit *makedirname = nullptr; - Button *makedir; + Button *makedir = nullptr; Access access = ACCESS_RESOURCES; - VBoxContainer *vbox; + VBoxContainer *vbox = nullptr; FileMode mode; - LineEdit *dir; - HBoxContainer *drives_container; - HBoxContainer *shortcuts_container; - OptionButton *drives; - Tree *tree; - HBoxContainer *file_box; - LineEdit *file; - OptionButton *filter; - AcceptDialog *mkdirerr; - AcceptDialog *exterr; - DirAccess *dir_access; - ConfirmationDialog *confirm_save; - - Label *message; - - Button *dir_prev; - Button *dir_next; - Button *dir_up; - - Button *refresh; - Button *show_hidden; + LineEdit *dir = nullptr; + HBoxContainer *drives_container = nullptr; + HBoxContainer *shortcuts_container = nullptr; + OptionButton *drives = nullptr; + Tree *tree = nullptr; + HBoxContainer *file_box = nullptr; + LineEdit *file = nullptr; + OptionButton *filter = nullptr; + AcceptDialog *mkdirerr = nullptr; + AcceptDialog *exterr = nullptr; + Ref<DirAccess> dir_access; + ConfirmationDialog *confirm_save = nullptr; + + Label *message = nullptr; + + Button *dir_prev = nullptr; + Button *dir_next = nullptr; + Button *dir_up = nullptr; + + Button *refresh = nullptr; + Button *show_hidden = nullptr; Vector<String> filters; @@ -133,7 +133,7 @@ private: void _update_drives(bool p_select = true); - virtual void unhandled_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; bool _is_open_should_be_disabled(); diff --git a/scene/gui/gradient_edit.h b/scene/gui/gradient_edit.h index 67531d4f4a..4e3c6525f9 100644 --- a/scene/gui/gradient_edit.h +++ b/scene/gui/gradient_edit.h @@ -38,8 +38,8 @@ class GradientEdit : public Control { GDCLASS(GradientEdit, Control); - PopupPanel *popup; - ColorPicker *picker; + PopupPanel *popup = nullptr; + ColorPicker *picker = nullptr; bool grabbing = false; int grabbed = -1; diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp index 1394b4192f..8b7e0f22b9 100644 --- a/scene/gui/graph_edit.cpp +++ b/scene/gui/graph_edit.cpp @@ -696,7 +696,7 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) { for (int j = 0; j < gn->get_connection_output_count(); j++) { Vector2 pos = gn->get_connection_output_position(j) + gn->get_position(); int type = gn->get_connection_output_type(j); - if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && is_in_output_hotzone(gn, j, mpos, port_size)) { + if ((type == connecting_type || valid_connection_types.has(ConnType(connecting_type, type))) && is_in_output_hotzone(gn, j, mpos, port_size)) { connecting_target = true; connecting_to = pos; connecting_target_to = gn->get_name(); @@ -708,7 +708,7 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) { for (int j = 0; j < gn->get_connection_input_count(); j++) { Vector2 pos = gn->get_connection_input_position(j) + gn->get_position(); int type = gn->get_connection_input_type(j); - if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && is_in_input_hotzone(gn, j, mpos, port_size)) { + if ((type == connecting_type || valid_connection_types.has(ConnType(connecting_type, type))) && is_in_input_hotzone(gn, j, mpos, port_size)) { connecting_target = true; connecting_to = pos; connecting_target_to = gn->get_name(); @@ -1568,26 +1568,17 @@ void GraphEdit::_update_zoom_label() { } void GraphEdit::add_valid_connection_type(int p_type, int p_with_type) { - ConnType ct; - ct.type_a = p_type; - ct.type_b = p_with_type; - + ConnType ct(p_type, p_with_type); valid_connection_types.insert(ct); } void GraphEdit::remove_valid_connection_type(int p_type, int p_with_type) { - ConnType ct; - ct.type_a = p_type; - ct.type_b = p_with_type; - + ConnType ct(p_type, p_with_type); valid_connection_types.erase(ct); } bool GraphEdit::is_valid_connection_type(int p_type, int p_with_type) const { - ConnType ct; - ct.type_a = p_type; - ct.type_b = p_with_type; - + ConnType ct(p_type, p_with_type); return valid_connection_types.has(ct); } @@ -1646,6 +1637,7 @@ float GraphEdit::get_minimap_opacity() const { void GraphEdit::set_minimap_enabled(bool p_enable) { minimap_button->set_pressed(p_enable); + _minimap_toggled(); minimap->update(); } diff --git a/scene/gui/graph_edit.h b/scene/gui/graph_edit.h index b0d1944d6e..18b9eeebd4 100644 --- a/scene/gui/graph_edit.h +++ b/scene/gui/graph_edit.h @@ -46,7 +46,7 @@ class GraphEditFilter : public Control { friend class GraphEdit; friend class GraphEditMinimap; - GraphEdit *ge; + GraphEdit *ge = nullptr; virtual bool has_point(const Point2 &p_point) const override; public: @@ -58,7 +58,7 @@ class GraphEditMinimap : public Control { friend class GraphEdit; friend class GraphEditFilter; - GraphEdit *ge; + GraphEdit *ge = nullptr; protected: public: @@ -109,20 +109,20 @@ public: }; private: - Label *zoom_label; - Button *zoom_minus; - Button *zoom_reset; - Button *zoom_plus; + Label *zoom_label = nullptr; + Button *zoom_minus = nullptr; + Button *zoom_reset = nullptr; + Button *zoom_plus = nullptr; - Button *snap_button; - SpinBox *snap_amount; + Button *snap_button = nullptr; + SpinBox *snap_amount = nullptr; - Button *minimap_button; + Button *minimap_button = nullptr; - Button *layout_button; + Button *layout_button = nullptr; - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; float port_grab_distance_horizontal = 0.0; float port_grab_distance_vertical; @@ -190,9 +190,9 @@ private: void _scroll_moved(double); virtual void gui_input(const Ref<InputEvent> &p_ev) override; - Control *connections_layer; - GraphEditFilter *top_layer; - GraphEditMinimap *minimap; + Control *connections_layer = nullptr; + GraphEditFilter *top_layer = nullptr; + GraphEditMinimap *minimap = nullptr; void _top_layer_input(const Ref<InputEvent> &p_ev); bool is_in_input_hotzone(GraphNode *p_graph_node, int p_slot_index, const Vector2 &p_mouse_pos, const Vector2i &p_port_size); @@ -236,7 +236,7 @@ private: void _set_drag_comment_enclosed_nodes(GraphNode *p_node, HashMap<StringName, Vector<GraphNode *>> &p_comment_enclosed_nodes, bool p_drag); void _set_position_of_comment_enclosed_nodes(GraphNode *p_node, HashMap<StringName, Vector<GraphNode *>> &p_comment_enclosed_nodes, Vector2 p_pos); - HBoxContainer *zoom_hb; + HBoxContainer *zoom_hb = nullptr; friend class GraphEditFilter; bool _filter_input(const Point2 &p_point); diff --git a/scene/gui/graph_node.cpp b/scene/gui/graph_node.cpp index ef0ac75cb4..51fb26b459 100644 --- a/scene/gui/graph_node.cpp +++ b/scene/gui/graph_node.cpp @@ -393,7 +393,6 @@ void GraphNode::_notification(int p_what) { w -= close->get_width(); } - title_buf->set_width(w); title_buf->draw(get_canvas_item(), Point2(sb->get_margin(SIDE_LEFT) + title_h_offset, -title_buf->get_size().y + title_offset), title_color); if (show_close) { Vector2 cpos = Point2(w + sb->get_margin(SIDE_LEFT) + close_h_offset, -close->get_height() + close_offset); diff --git a/scene/gui/item_list.h b/scene/gui/item_list.h index 96735678c1..ffbe7d055a 100644 --- a/scene/gui/item_list.h +++ b/scene/gui/item_list.h @@ -98,7 +98,7 @@ private: SelectMode select_mode = SELECT_SINGLE; IconMode icon_mode = ICON_MODE_LEFT; - VScrollBar *scroll_bar; + VScrollBar *scroll_bar = nullptr; TextParagraph::OverrunBehavior text_overrun_behavior = TextParagraph::OVERRUN_TRIM_ELLIPSIS; uint64_t search_time_msec = 0; diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp index e063d3aeba..b3f051bb75 100644 --- a/scene/gui/line_edit.cpp +++ b/scene/gui/line_edit.cpp @@ -215,6 +215,27 @@ void LineEdit::_delete(bool p_word, bool p_all_to_right) { } } +void LineEdit::unhandled_key_input(const Ref<InputEvent> &p_event) { + Ref<InputEventKey> k = p_event; + + if (k.is_valid()) { + if (!k->is_pressed()) { + return; + } + // Handle Unicode (with modifiers active, process after shortcuts). + if (has_focus() && editable && (k->get_unicode() >= 32)) { + selection_delete(); + char32_t ucodestr[2] = { (char32_t)k->get_unicode(), 0 }; + int prev_len = text.length(); + insert_text_at_caret(ucodestr); + if (text.length() != prev_len) { + _text_changed(); + } + accept_event(); + } + } +} + void LineEdit::gui_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); @@ -2445,6 +2466,7 @@ LineEdit::LineEdit(const String &p_placeholder) { set_focus_mode(FOCUS_ALL); set_default_cursor_shape(CURSOR_IBEAM); set_mouse_filter(MOUSE_FILTER_STOP); + set_process_unhandled_key_input(true); caret_blink_timer = memnew(Timer); add_child(caret_blink_timer, false, INTERNAL_MODE_FRONT); diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h index 444c9a1c50..b86ccd6421 100644 --- a/scene/gui/line_edit.h +++ b/scene/gui/line_edit.h @@ -202,6 +202,7 @@ private: protected: void _notification(int p_what); static void _bind_methods(); + virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; virtual void gui_input(const Ref<InputEvent> &p_event) override; bool _set(const StringName &p_name, const Variant &p_value); diff --git a/scene/gui/menu_button.cpp b/scene/gui/menu_button.cpp index 7e724e4d71..1feee017c2 100644 --- a/scene/gui/menu_button.cpp +++ b/scene/gui/menu_button.cpp @@ -33,7 +33,7 @@ #include "core/os/keyboard.h" #include "scene/main/window.h" -void MenuButton::unhandled_key_input(const Ref<InputEvent> &p_event) { +void MenuButton::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (!_is_focus_owner_in_shortcut_context()) { @@ -232,7 +232,7 @@ MenuButton::MenuButton(const String &p_text) : set_flat(true); set_toggle_mode(true); set_disable_shortcuts(false); - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); set_focus_mode(FOCUS_NONE); set_action_mode(ACTION_MODE_BUTTON_PRESS); diff --git a/scene/gui/menu_button.h b/scene/gui/menu_button.h index 9cfb780255..0a6b46c796 100644 --- a/scene/gui/menu_button.h +++ b/scene/gui/menu_button.h @@ -40,7 +40,7 @@ class MenuButton : public Button { bool clicked = false; bool switch_on_hover = false; bool disable_shortcuts = false; - PopupMenu *popup; + PopupMenu *popup = nullptr; Vector2i mouse_pos_adjusted; @@ -54,7 +54,7 @@ protected: bool _get(const StringName &p_name, Variant &r_ret) const; void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; public: virtual void pressed() override; diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp index 1e8a149e11..307696c44a 100644 --- a/scene/gui/option_button.cpp +++ b/scene/gui/option_button.cpp @@ -203,16 +203,18 @@ void OptionButton::pressed() { } void OptionButton::add_icon_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id) { + bool first_selectable = !has_selectable_items(); popup->add_icon_radio_check_item(p_icon, p_label, p_id); - if (popup->get_item_count() == 1) { - select(0); + if (first_selectable) { + select(get_item_count() - 1); } } void OptionButton::add_item(const String &p_label, int p_id) { + bool first_selectable = !has_selectable_items(); popup->add_radio_check_item(p_label, p_id); - if (popup->get_item_count() == 1) { - select(0); + if (first_selectable) { + select(get_item_count() - 1); } } @@ -280,6 +282,9 @@ bool OptionButton::is_item_disabled(int p_idx) const { return popup->is_item_disabled(p_idx); } +bool OptionButton::is_item_separator(int p_idx) const { + return popup->is_item_separator(p_idx); +} void OptionButton::set_item_count(int p_count) { ERR_FAIL_COND(p_count < 0); @@ -299,12 +304,37 @@ void OptionButton::set_item_count(int p_count) { notify_property_list_changed(); } +bool OptionButton::has_selectable_items() const { + for (int i = 0; i < get_item_count(); i++) { + if (!is_item_disabled(i) && !is_item_separator(i)) { + return true; + } + } + return false; +} +int OptionButton::get_selectable_item(bool p_from_last) const { + if (!p_from_last) { + for (int i = 0; i < get_item_count(); i++) { + if (!is_item_disabled(i) && !is_item_separator(i)) { + return i; + } + } + } else { + for (int i = get_item_count() - 1; i >= 0; i++) { + if (!is_item_disabled(i) && !is_item_separator(i)) { + return i; + } + } + } + return -1; +} + int OptionButton::get_item_count() const { return popup->get_item_count(); } -void OptionButton::add_separator() { - popup->add_separator(); +void OptionButton::add_separator(const String &p_text) { + popup->add_separator(p_text); } void OptionButton::clear() { @@ -407,7 +437,8 @@ void OptionButton::_bind_methods() { ClassDB::bind_method(D_METHOD("get_item_metadata", "idx"), &OptionButton::get_item_metadata); ClassDB::bind_method(D_METHOD("get_item_tooltip", "idx"), &OptionButton::get_item_tooltip); ClassDB::bind_method(D_METHOD("is_item_disabled", "idx"), &OptionButton::is_item_disabled); - ClassDB::bind_method(D_METHOD("add_separator"), &OptionButton::add_separator); + ClassDB::bind_method(D_METHOD("is_item_separator", "idx"), &OptionButton::is_item_separator); + ClassDB::bind_method(D_METHOD("add_separator", "text"), &OptionButton::add_separator, DEFVAL(String())); ClassDB::bind_method(D_METHOD("clear"), &OptionButton::clear); ClassDB::bind_method(D_METHOD("select", "idx"), &OptionButton::select); ClassDB::bind_method(D_METHOD("get_selected"), &OptionButton::get_selected); @@ -420,6 +451,8 @@ void OptionButton::_bind_methods() { ClassDB::bind_method(D_METHOD("set_item_count", "count"), &OptionButton::set_item_count); ClassDB::bind_method(D_METHOD("get_item_count"), &OptionButton::get_item_count); + ClassDB::bind_method(D_METHOD("has_selectable_items"), &OptionButton::has_selectable_items); + ClassDB::bind_method(D_METHOD("get_selectable_item", "from_last"), &OptionButton::get_selectable_item, DEFVAL(false)); // "selected" property must come after "item_count", otherwise GH-10213 occurs. ADD_ARRAY_COUNT("Items", "item_count", "set_item_count", "get_item_count", "popup/item_"); diff --git a/scene/gui/option_button.h b/scene/gui/option_button.h index 732730e0f4..7896132626 100644 --- a/scene/gui/option_button.h +++ b/scene/gui/option_button.h @@ -37,7 +37,7 @@ class OptionButton : public Button { GDCLASS(OptionButton, Button); - PopupMenu *popup; + PopupMenu *popup = nullptr; int current = -1; void _focused(int p_which); @@ -77,12 +77,16 @@ public: int get_item_index(int p_id) const; Variant get_item_metadata(int p_idx) const; bool is_item_disabled(int p_idx) const; + bool is_item_separator(int p_idx) const; String get_item_tooltip(int p_idx) const; + bool has_selectable_items() const; + int get_selectable_item(bool p_from_last = false) const; + void set_item_count(int p_count); int get_item_count() const; - void add_separator(); + void add_separator(const String &p_text = ""); void clear(); diff --git a/scene/gui/popup.h b/scene/gui/popup.h index c45f4ddc24..6211af4d20 100644 --- a/scene/gui/popup.h +++ b/scene/gui/popup.h @@ -65,7 +65,7 @@ public: class PopupPanel : public Popup { GDCLASS(PopupPanel, Popup); - Panel *panel; + Panel *panel = nullptr; protected: void _update_child_rects(); diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp index 9fc1fb072c..b01f45e9ab 100644 --- a/scene/gui/popup_menu.cpp +++ b/scene/gui/popup_menu.cpp @@ -169,7 +169,7 @@ int PopupMenu::_get_mouse_over(const Point2 &p_over) const { return -1; } -void PopupMenu::_activate_submenu(int p_over) { +void PopupMenu::_activate_submenu(int p_over, bool p_by_keyboard) { Node *n = get_node(items[p_over].submenu); ERR_FAIL_COND_MSG(!n, "Item subnode does not exist: " + items[p_over].submenu + "."); Popup *submenu_popup = Object::cast_to<Popup>(n); @@ -213,8 +213,10 @@ void PopupMenu::_activate_submenu(int p_over) { return; } + submenu_pum->activated_by_keyboard = p_by_keyboard; + // If not triggered by the mouse, start the popup with its first item selected. - if (submenu_pum->get_item_count() > 0 && Input::get_singleton()->is_action_just_pressed("ui_accept")) { + if (submenu_pum->get_item_count() > 0 && p_by_keyboard) { submenu_pum->set_current_index(0); } @@ -323,14 +325,14 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) { set_input_as_handled(); } } else if (p_event->is_action("ui_right") && p_event->is_pressed()) { - if (mouse_over >= 0 && mouse_over < items.size() && !!items[mouse_over].separator && items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) { - _activate_submenu(mouse_over); + if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator && !items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) { + _activate_submenu(mouse_over, true); set_input_as_handled(); } } else if (p_event->is_action("ui_accept") && p_event->is_pressed()) { if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator) { if (!items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) { - _activate_submenu(mouse_over); + _activate_submenu(mouse_over, true); } else { activate_item(mouse_over); } @@ -396,6 +398,11 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseMotion> m = p_event; if (m.is_valid()) { + if (m->get_velocity().is_equal_approx(Vector2())) { + return; + } + activated_by_keyboard = false; + for (const Rect2 &E : autohide_areas) { if (!Rect2(Point2(), get_size()).has_point(m->get_position()) && E.has_point(m->get_position())) { _close_pressed(); @@ -687,7 +694,7 @@ void PopupMenu::_draw_background() { void PopupMenu::_minimum_lifetime_timeout() { close_allowed = true; // If the mouse still isn't in this popup after timer expires, close. - if (!get_visible_rect().has_point(get_mouse_position())) { + if (!activated_by_keyboard && !get_visible_rect().has_point(get_mouse_position())) { _close_pressed(); } } @@ -772,7 +779,7 @@ void PopupMenu::_notification(int p_what) { case NOTIFICATION_INTERNAL_PROCESS: { // Only used when using operating system windows. - if (!is_embedded() && autohide_areas.size()) { + if (!activated_by_keyboard && !is_embedded() && autohide_areas.size()) { Point2 mouse_pos = DisplayServer::get_singleton()->mouse_get_position(); mouse_pos -= get_position(); diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h index 5ce55209d4..98d76875cb 100644 --- a/scene/gui/popup_menu.h +++ b/scene/gui/popup_menu.h @@ -87,9 +87,10 @@ class PopupMenu : public Popup { }; bool close_allowed = false; + bool activated_by_keyboard = false; Timer *minimum_lifetime_timer = nullptr; - Timer *submenu_timer; + Timer *submenu_timer = nullptr; List<Rect2> autohide_areas; Vector<Item> items; MouseButton initial_button_mask = MouseButton::NONE; @@ -107,7 +108,7 @@ class PopupMenu : public Popup { void _shape_item(int p_item); virtual void gui_input(const Ref<InputEvent> &p_event); - void _activate_submenu(int p_over); + void _activate_submenu(int p_over, bool p_by_keyboard = false); void _submenu_timeout(); uint64_t popup_time_msec = 0; @@ -125,9 +126,9 @@ class PopupMenu : public Popup { uint64_t search_time_msec = 0; String search_string = ""; - MarginContainer *margin_container; - ScrollContainer *scroll_container; - Control *control; + MarginContainer *margin_container = nullptr; + ScrollContainer *scroll_container = nullptr; + Control *control = nullptr; void _draw_items(); void _draw_background(); diff --git a/scene/gui/range.h b/scene/gui/range.h index 597c50ca26..46b0d39202 100644 --- a/scene/gui/range.h +++ b/scene/gui/range.h @@ -50,7 +50,7 @@ class Range : public Control { void emit_changed(const char *p_what = ""); }; - Shared *shared; + Shared *shared = nullptr; void _ref_shared(Shared *p_shared); void _unref_shared(); diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp index 70755a2870..ec13399f82 100644 --- a/scene/gui/rich_text_label.cpp +++ b/scene/gui/rich_text_label.cpp @@ -30,6 +30,7 @@ #include "rich_text_label.h" +#include "core/input/input_map.h" #include "core/math/math_defs.h" #include "core/os/keyboard.h" #include "core/os/os.h" @@ -142,7 +143,7 @@ RichTextLabel::Item *RichTextLabel::_get_item_at_pos(RichTextLabel::Item *p_item for (Item *it = p_item_from; it && it != p_item_to; it = _get_next_item(it)) { switch (it->type) { case ITEM_TEXT: { - ItemText *t = (ItemText *)it; + ItemText *t = static_cast<ItemText *>(it); offset += t->text.length(); if (offset > p_position) { return it; @@ -166,16 +167,16 @@ String RichTextLabel::_roman(int p_num, bool p_capitalize) const { }; String s; if (p_capitalize) { - String M[] = { "", "M", "MM", "MMM" }; - String C[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; - String X[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; - String I[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; + const String M[] = { "", "M", "MM", "MMM" }; + const String C[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; + const String X[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; + const String I[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; s = M[p_num / 1000] + C[(p_num % 1000) / 100] + X[(p_num % 100) / 10] + I[p_num % 10]; } else { - String M[] = { "", "m", "mm", "mmm" }; - String C[] = { "", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm" }; - String X[] = { "", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc" }; - String I[] = { "", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix" }; + const String M[] = { "", "m", "mm", "mmm" }; + const String C[] = { "", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm" }; + const String X[] = { "", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc" }; + const String I[] = { "", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix" }; s = M[p_num / 1000] + C[(p_num % 1000) / 100] + X[(p_num % 100) / 10] + I[p_num % 10]; } return s; @@ -215,7 +216,7 @@ void RichTextLabel::_update_line_font(ItemFrame *p_frame, int p_line, const Ref< RID t = l.text_buf->get_rid(); int spans = TS->shaped_get_span_count(t); for (int i = 0; i < spans; i++) { - ItemText *it = (ItemText *)(uint64_t)TS->shaped_get_span_meta(t, i); + ItemText *it = reinterpret_cast<ItemText *>((uint64_t)TS->shaped_get_span_meta(t, i)); if (it) { Ref<Font> font = _find_font(it); if (font.is_null()) { @@ -466,15 +467,11 @@ void RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font> switch (it->type) { case ITEM_DROPCAP: { // Add dropcap. - const ItemDropcap *dc = (ItemDropcap *)it; - if (dc != nullptr) { - l.text_buf->set_dropcap(dc->text, dc->font, dc->font_size, dc->dropcap_margins); - l.dc_color = dc->color; - l.dc_ol_size = dc->ol_size; - l.dc_ol_color = dc->ol_color; - } else { - l.text_buf->clear_dropcap(); - } + const ItemDropcap *dc = static_cast<ItemDropcap *>(it); + l.text_buf->set_dropcap(dc->text, dc->font, dc->font_size, dc->dropcap_margins); + l.dc_color = dc->color; + l.dc_ol_size = dc->ol_size; + l.dc_ol_color = dc->ol_color; } break; case ITEM_NEWLINE: { Ref<Font> font = _find_font(it); @@ -491,7 +488,7 @@ void RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font> remaining_characters--; } break; case ITEM_TEXT: { - ItemText *t = (ItemText *)it; + ItemText *t = static_cast<ItemText *>(it); Ref<Font> font = _find_font(it); if (font.is_null()) { font = p_base_font; @@ -513,7 +510,7 @@ void RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font> l.char_count += tx.length(); } break; case ITEM_IMAGE: { - ItemImage *img = (ItemImage *)it; + ItemImage *img = static_cast<ItemImage *>(it); l.text_buf->add_object((uint64_t)it, img->size, img->inline_align, 1); text += String::chr(0xfffc); l.char_count++; @@ -842,7 +839,7 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o // Draw inlined objects. Array objects = TS->shaped_text_get_objects(rid); for (int i = 0; i < objects.size(); i++) { - Item *it = (Item *)(uint64_t)objects[i]; + Item *it = reinterpret_cast<Item *>((uint64_t)objects[i]); if (it != nullptr) { Rect2 rect = TS->shaped_text_get_object_rect(rid, objects[i]); //draw_rect(rect, Color(1,0,0), false, 2); //DEBUG_RECTS @@ -944,8 +941,8 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o } //Apply fx. - float faded_visibility = 1.0f; if (fade) { + float faded_visibility = 1.0f; if (glyphs[i].start >= fade->starting_index) { faded_visibility -= (float)(glyphs[i].start - fade->starting_index) / (float)fade->length; faded_visibility = faded_visibility < 0.0f ? 0.0f : faded_visibility; @@ -1160,8 +1157,8 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o } //Apply fx. - float faded_visibility = 1.0f; if (fade) { + float faded_visibility = 1.0f; if (glyphs[i].start >= fade->starting_index) { faded_visibility -= (float)(glyphs[i].start - fade->starting_index) / (float)fade->length; faded_visibility = faded_visibility < 0.0f ? 0.0f : faded_visibility; @@ -1330,14 +1327,22 @@ void RichTextLabel::_find_click(ItemFrame *p_frame, const Point2i &p_click, Item } } -float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char) { +float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char, bool p_table) { Vector2 off; int char_pos = -1; Line &l = p_frame->lines.write[p_line]; bool rtl = (l.text_buf->get_direction() == TextServer::DIRECTION_RTL); bool lrtl = is_layout_rtl(); + + // Table hit test results. bool table_hit = false; + Vector2i table_range; + float table_offy = 0.f; + ItemFrame *table_click_frame = nullptr; + int table_click_line = -1; + Item *table_click_item = nullptr; + int table_click_char = -1; for (int line = 0; line < l.text_buf->get_line_count(); line++) { RID rid = l.text_buf->get_line_rid(line); @@ -1378,10 +1383,11 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V Array objects = TS->shaped_text_get_objects(rid); for (int i = 0; i < objects.size(); i++) { - Item *it = (Item *)(uint64_t)objects[i]; + Item *it = reinterpret_cast<Item *>((uint64_t)objects[i]); if (it != nullptr) { Rect2 rect = TS->shaped_text_get_object_rect(rid, objects[i]); - if (rect.has_point(p_click - p_ofs - off)) { + rect.position += p_ofs + off; + if (p_click.y >= rect.position.y && p_click.y <= rect.position.y + rect.size.y) { switch (it->type) { case ITEM_TABLE: { int hseparation = get_theme_constant(SNAME("table_hseparation")); @@ -1389,8 +1395,6 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V ItemTable *table = static_cast<ItemTable *>(it); - table_hit = true; - int idx = 0; int col_count = table->columns.size(); int row_count = table->rows.size(); @@ -1406,7 +1410,7 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V if (rtl) { coff.x = rect.size.width - table->columns[col].width - coff.x; } - Rect2 crect = Rect2(p_ofs + off + rect.position + coff - frame->padding.position, Size2(table->columns[col].width + hseparation, table->rows[row] + vseparation) + frame->padding.position + frame->padding.size); + Rect2 crect = Rect2(rect.position + coff - frame->padding.position, Size2(table->columns[col].width + hseparation, table->rows[row] + vseparation) + frame->padding.position + frame->padding.size); if (col == col_count - 1) { if (rtl) { crect.size.x = crect.position.x + crect.size.x; @@ -1417,9 +1421,19 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V } if (crect.has_point(p_click)) { for (int j = 0; j < frame->lines.size(); j++) { - _find_click_in_line(frame, j, p_ofs + off + rect.position + Vector2(0, frame->lines[j].offset.y), rect.size.x, p_click, r_click_frame, r_click_line, r_click_item, r_click_char); - if (((r_click_item != nullptr) && ((*r_click_item) != nullptr)) || ((r_click_frame != nullptr) && ((*r_click_frame) != nullptr))) { - return off.y; + _find_click_in_line(frame, j, rect.position + Vector2(0, frame->lines[j].offset.y), rect.size.x, p_click, &table_click_frame, &table_click_line, &table_click_item, &table_click_char, true); + if (table_click_frame && table_click_item) { + // Save cell detected cell hit data. + table_range = Vector2i(INT32_MAX, 0); + for (Item *F : table->subitems) { + ItemFrame *sub_frame = static_cast<ItemFrame *>(F); + for (int k = 0; k < sub_frame->lines.size(); k++) { + table_range.x = MIN(table_range.x, sub_frame->lines[k].char_offset); + table_range.y = MAX(table_range.y, sub_frame->lines[k].char_offset + sub_frame->lines[k].char_count); + } + } + table_offy = off.y; + table_hit = true; } } } @@ -1433,14 +1447,39 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V } } } - Rect2 rect = Rect2(p_ofs + off - Vector2(0, TS->shaped_text_get_ascent(rid)), Size2(get_size().x, TS->shaped_text_get_size(rid).y)); + Rect2 rect = Rect2(p_ofs + off - Vector2(0, TS->shaped_text_get_ascent(rid)) - p_frame->padding.position, TS->shaped_text_get_size(rid) + p_frame->padding.position + p_frame->padding.size); + if (p_table) { + rect.size.y += get_theme_constant(SNAME("table_vseparation")); + } - if (rect.has_point(p_click) && !table_hit) { + if (p_click.y >= rect.position.y && p_click.y <= rect.position.y + rect.size.y) { char_pos = TS->shaped_text_hit_test_position(rid, p_click.x - rect.position.x); } + + // If table hit was detected, and line hit is in the table bounds use table hit. + if (table_hit && (((char_pos + p_frame->lines[p_line].char_offset) >= table_range.x && (char_pos + p_frame->lines[p_line].char_offset) <= table_range.y) || char_pos == -1)) { + if (r_click_frame != nullptr) { + *r_click_frame = table_click_frame; + } + + if (r_click_line != nullptr) { + *r_click_line = table_click_line; + } + + if (r_click_item != nullptr) { + *r_click_item = table_click_item; + } + + if (r_click_char != nullptr) { + *r_click_char = table_click_char; + } + return table_offy; + } + off.y += TS->shaped_text_get_descent(rid) + l.text_buf->get_spacing_bottom() + get_theme_constant(SNAME("line_separation")); } + // Text line hit. if (char_pos >= 0) { // Find item. if (r_click_item != nullptr) { @@ -1451,7 +1490,7 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V if (it_to != nullptr) { *r_click_item = _get_prev_item(it_to); } else { - for (Item *i = it; i && i != it_to; i = _get_next_item(i)) { + for (Item *i = it; i; i = _get_next_item(i)) { *r_click_item = i; } } @@ -1650,8 +1689,7 @@ void RichTextLabel::_notification(int p_what) { case NOTIFICATION_FOCUS_EXIT: { if (deselect_on_focus_loss_enabled) { - selection.active = false; - update(); + deselect(); } } break; @@ -1684,9 +1722,9 @@ Control::CursorShape RichTextLabel::get_cursor_shape(const Point2 &p_pos) const Item *item = nullptr; bool outside = true; - ((RichTextLabel *)(this))->_find_click(main, p_pos, nullptr, nullptr, &item, nullptr, &outside); + const_cast<RichTextLabel *>(this)->_find_click(main, p_pos, nullptr, nullptr, &item, nullptr, &outside); - if (item && !outside && ((RichTextLabel *)(this))->_find_meta(item, nullptr)) { + if (item && !outside && const_cast<RichTextLabel *>(this)->_find_meta(item, nullptr)) { return CURSOR_POINTING_HAND; } @@ -1742,9 +1780,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { selection.to_line = 0; selection.to_item = nullptr; selection.to_char = 0; - selection.active = false; - - update(); + deselect(); } } } @@ -1802,9 +1838,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { selection.to_line = 0; selection.to_item = nullptr; selection.to_char = 0; - selection.active = false; - - update(); + deselect(); } } @@ -1835,6 +1869,13 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { vscroll->set_value(vscroll->get_value() + vscroll->get_page() * b->get_factor() * 0.5 / 8); } } + if (b->get_button_index() == MouseButton::RIGHT && context_menu_enabled) { + _generate_context_menu(); + menu->set_position(get_screen_position() + b->get_position()); + menu->reset_size(); + menu->popup(); + grab_focus(); + } } Ref<InputEventPanGesture> pan_gesture = p_event; @@ -1876,8 +1917,24 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { vscroll->set_value(vscroll->get_max()); handled = true; } - if (k->is_action("ui_copy")) { - selection_copy(); + if (is_shortcut_keys_enabled()) { + if (k->is_action("ui_text_select_all")) { + select_all(); + handled = true; + } + if (k->is_action("ui_copy")) { + selection_copy(); + handled = true; + } + } + if (k->is_action("ui_menu", true)) { + if (context_menu_enabled) { + _generate_context_menu(); + menu->set_position(get_screen_position()); + menu->reset_size(); + menu->popup(); + menu->grab_focus(); + } handled = true; } @@ -1919,14 +1976,13 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { selection.to_char = c_index; bool swap = false; - if (selection.from_item->index > selection.to_item->index) { - swap = true; - } else if (selection.from_item->index == selection.to_item->index) { - if (selection.from_char > selection.to_char) { + if (selection.click_frame && c_frame) { + const Line &l1 = c_frame->lines[c_line]; + const Line &l2 = selection.click_frame->lines[selection.click_line]; + if (l1.char_offset + c_index < l2.char_offset + selection.click_char) { swap = true; - } else if (selection.from_char == selection.to_char) { - selection.active = false; - update(); + } else if (l1.char_offset + c_index == l2.char_offset + selection.click_char) { + deselect(); return; } } @@ -1988,7 +2044,7 @@ void RichTextLabel::_find_frame(Item *p_item, ItemFrame **r_frame, int *r_line) while (item) { if (item->parent != nullptr && item->parent->type == ITEM_FRAME) { if (r_frame != nullptr) { - *r_frame = (ItemFrame *)item->parent; + *r_frame = static_cast<ItemFrame *>(item->parent); } if (r_line != nullptr) { *r_line = item->line; @@ -2523,7 +2579,7 @@ void RichTextLabel::_add_item(Item *p_item, bool p_enter, bool p_ensure_newline) p_item->index = current_idx++; p_item->char_ofs = current_char_ofs; if (p_item->type == ITEM_TEXT) { - ItemText *t = (ItemText *)p_item; + ItemText *t = static_cast<ItemText *>(p_item); current_char_ofs += t->text.length(); } else if (p_item->type == ITEM_IMAGE) { current_char_ofs++; @@ -2977,11 +3033,10 @@ void RichTextLabel::clear() { main->lines.clear(); main->lines.resize(1); main->first_invalid_line = 0; - update(); selection.click_frame = nullptr; selection.click_item = nullptr; - selection.active = false; + deselect(); current_idx = 1; current_char_ofs = 0; @@ -3890,8 +3945,7 @@ void RichTextLabel::set_selection_enabled(bool p_enabled) { selection.enabled = p_enabled; if (!p_enabled) { if (selection.active) { - selection.active = false; - update(); + deselect(); } set_focus_mode(FOCUS_NONE); } else { @@ -3902,8 +3956,7 @@ void RichTextLabel::set_selection_enabled(bool p_enabled) { void RichTextLabel::set_deselect_on_focus_loss_enabled(const bool p_enabled) { deselect_on_focus_loss_enabled = p_enabled; if (p_enabled && selection.active && !has_focus()) { - selection.active = false; - update(); + deselect(); } } @@ -3967,7 +4020,7 @@ bool RichTextLabel::_search_line(ItemFrame *p_frame, int p_line, const String &p text += "\n"; } break; case ITEM_TEXT: { - ItemText *t = (ItemText *)it; + ItemText *t = static_cast<ItemText *>(it); text += t->text; } break; case ITEM_IMAGE: { @@ -4100,7 +4153,7 @@ String RichTextLabel::_get_line_text(ItemFrame *p_frame, int p_line, Selection p if (it_to != nullptr) { end_idx = it_to->index; } else { - for (Item *it = l.from; it && it != it_to; it = _get_next_item(it)) { + for (Item *it = l.from; it; it = _get_next_item(it)) { end_idx = it->index + 1; } } @@ -4142,6 +4195,32 @@ String RichTextLabel::_get_line_text(ItemFrame *p_frame, int p_line, Selection p return text; } +void RichTextLabel::set_context_menu_enabled(bool p_enabled) { + context_menu_enabled = p_enabled; +} + +bool RichTextLabel::is_context_menu_enabled() const { + return context_menu_enabled; +} + +void RichTextLabel::set_shortcut_keys_enabled(bool p_enabled) { + shortcut_keys_enabled = p_enabled; +} + +bool RichTextLabel::is_shortcut_keys_enabled() const { + return shortcut_keys_enabled; +} + +// Context menu. +PopupMenu *RichTextLabel::get_menu() const { + const_cast<RichTextLabel *>(this)->_generate_context_menu(); + return menu; +} + +bool RichTextLabel::is_menu_visible() const { + return menu && menu->is_visible(); +} + String RichTextLabel::get_selected_text() const { if (!selection.active || !selection.enabled) { return ""; @@ -4154,6 +4233,11 @@ String RichTextLabel::get_selected_text() const { return text; } +void RichTextLabel::deselect() { + selection.active = false; + update(); +} + void RichTextLabel::selection_copy() { String text = get_selected_text(); @@ -4162,6 +4246,53 @@ void RichTextLabel::selection_copy() { } } +void RichTextLabel::select_all() { + if (!selection.enabled) { + return; + } + + Item *it = main; + Item *from_item = nullptr; + Item *to_item = nullptr; + + while (it) { + if (it->type != ITEM_FRAME) { + if (!from_item) { + from_item = it; + } else { + to_item = it; + } + } + it = _get_next_item(it, true); + } + if (!from_item || !to_item) { + return; + } + + ItemFrame *from_frame = nullptr; + int from_line = 0; + _find_frame(from_item, &from_frame, &from_line); + if (!from_frame) { + return; + } + ItemFrame *to_frame = nullptr; + int to_line = 0; + _find_frame(to_item, &to_frame, &to_line); + if (!to_frame) { + return; + } + selection.from_line = from_line; + selection.from_frame = from_frame; + selection.from_char = 0; + selection.from_item = from_item; + selection.to_line = to_line; + selection.to_frame = to_frame; + selection.to_char = to_frame->lines[to_line].char_count; + selection.to_item = to_item; + selection.active = true; + update(); +} + bool RichTextLabel::is_selection_enabled() const { return selection.enabled; } @@ -4218,10 +4349,8 @@ String RichTextLabel::get_parsed_text() const { Item *it = main; while (it) { if (it->type == ITEM_DROPCAP) { - const ItemDropcap *dc = (ItemDropcap *)it; - if (dc != nullptr) { - text += dc->text; - } + ItemDropcap *dc = static_cast<ItemDropcap *>(it); + text += dc->text; } else if (it->type == ITEM_TEXT) { ItemText *t = static_cast<ItemText *>(it); text += t->text; @@ -4453,13 +4582,21 @@ void RichTextLabel::_bind_methods() { ClassDB::bind_method(D_METHOD("set_selection_enabled", "enabled"), &RichTextLabel::set_selection_enabled); ClassDB::bind_method(D_METHOD("is_selection_enabled"), &RichTextLabel::is_selection_enabled); + ClassDB::bind_method(D_METHOD("set_context_menu_enabled", "enabled"), &RichTextLabel::set_context_menu_enabled); + ClassDB::bind_method(D_METHOD("is_context_menu_enabled"), &RichTextLabel::is_context_menu_enabled); + + ClassDB::bind_method(D_METHOD("set_shortcut_keys_enabled", "enabled"), &RichTextLabel::set_shortcut_keys_enabled); + ClassDB::bind_method(D_METHOD("is_shortcut_keys_enabled"), &RichTextLabel::is_shortcut_keys_enabled); + ClassDB::bind_method(D_METHOD("set_deselect_on_focus_loss_enabled", "enable"), &RichTextLabel::set_deselect_on_focus_loss_enabled); ClassDB::bind_method(D_METHOD("is_deselect_on_focus_loss_enabled"), &RichTextLabel::is_deselect_on_focus_loss_enabled); ClassDB::bind_method(D_METHOD("get_selection_from"), &RichTextLabel::get_selection_from); ClassDB::bind_method(D_METHOD("get_selection_to"), &RichTextLabel::get_selection_to); + ClassDB::bind_method(D_METHOD("select_all"), &RichTextLabel::select_all); ClassDB::bind_method(D_METHOD("get_selected_text"), &RichTextLabel::get_selected_text); + ClassDB::bind_method(D_METHOD("deselect"), &RichTextLabel::deselect); ClassDB::bind_method(D_METHOD("parse_bbcode", "bbcode"), &RichTextLabel::parse_bbcode); ClassDB::bind_method(D_METHOD("append_text", "bbcode"), &RichTextLabel::append_text); @@ -4500,6 +4637,9 @@ void RichTextLabel::_bind_methods() { ClassDB::bind_method(D_METHOD("get_effects"), &RichTextLabel::get_effects); ClassDB::bind_method(D_METHOD("install_effect", "effect"), &RichTextLabel::install_effect); + ClassDB::bind_method(D_METHOD("get_menu"), &RichTextLabel::get_menu); + ClassDB::bind_method(D_METHOD("is_menu_visible"), &RichTextLabel::is_menu_visible); + // Note: set "bbcode_enabled" first, to avoid unnecessary "text" resets. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bbcode_enabled"), "set_use_bbcode", "is_using_bbcode"); @@ -4521,6 +4661,9 @@ void RichTextLabel::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "visible_characters_behavior", PROPERTY_HINT_ENUM, "Characters Before Shaping,Characters After Shaping,Glyphs (Layout Direction),Glyphs (Left-to-Right),Glyphs (Right-to-Left)"), "set_visible_characters_behavior", "get_visible_characters_behavior"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "percent_visible", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_percent_visible", "get_percent_visible"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "context_menu_enabled"), "set_context_menu_enabled", "is_context_menu_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_keys_enabled"), "set_shortcut_keys_enabled", "is_shortcut_keys_enabled"); + ADD_GROUP("Locale", ""); ADD_PROPERTY(PropertyInfo(Variant::INT, "text_direction", PROPERTY_HINT_ENUM, "Auto,Left-to-Right,Right-to-Left,Inherited"), "set_text_direction", "get_text_direction"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "language", PROPERTY_HINT_LOCALE_ID, ""), "set_language", "get_language"); @@ -4700,6 +4843,59 @@ Size2 RichTextLabel::get_minimum_size() const { return size; } +// Context menu. +void RichTextLabel::_generate_context_menu() { + if (!menu) { + menu = memnew(PopupMenu); + add_child(menu, false, INTERNAL_MODE_FRONT); + + menu->connect("id_pressed", callable_mp(this, &RichTextLabel::_menu_option)); + } + + // Reorganize context menu. + menu->clear(); + if (selection.enabled) { + menu->add_item(RTR("Copy"), MENU_COPY, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_copy") : Key::NONE); + menu->add_item(RTR("Select All"), MENU_SELECT_ALL, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_text_select_all") : Key::NONE); + } +} + +Key RichTextLabel::_get_menu_action_accelerator(const String &p_action) { + const List<Ref<InputEvent>> *events = InputMap::get_singleton()->action_get_events(p_action); + if (!events) { + return Key::NONE; + } + + // Use first event in the list for the accelerator. + const List<Ref<InputEvent>>::Element *first_event = events->front(); + if (!first_event) { + return Key::NONE; + } + + const Ref<InputEventKey> event = first_event->get(); + if (event.is_null()) { + return Key::NONE; + } + + // Use physical keycode if non-zero + if (event->get_physical_keycode() != Key::NONE) { + return event->get_physical_keycode_with_modifiers(); + } else { + return event->get_keycode_with_modifiers(); + } +} + +void RichTextLabel::_menu_option(int p_option) { + switch (p_option) { + case MENU_COPY: { + selection_copy(); + } break; + case MENU_SELECT_ALL: { + select_all(); + } break; + } +} + void RichTextLabel::_draw_fbg_boxes(RID p_ci, RID p_rid, Vector2 line_off, Item *it_from, Item *it_to, int start, int end, int fbg_flag) { Vector2i fbg_index = Vector2i(end, start); Color last_color = Color(0, 0, 0, 0); @@ -4707,7 +4903,7 @@ void RichTextLabel::_draw_fbg_boxes(RID p_ci, RID p_rid, Vector2 line_off, Item // Draw a box based on color tags associated with glyphs for (int i = start; i < end; i++) { Item *it = _get_item_at_pos(it_from, it_to, i); - Color color = Color(0, 0, 0, 0); + Color color; if (fbg_flag == 0) { color = _find_bgcolor(it); diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h index c9cbbe9d15..856dd52b6e 100644 --- a/scene/gui/rich_text_label.h +++ b/scene/gui/rich_text_label.h @@ -32,6 +32,7 @@ #define RICH_TEXT_LABEL_H #include "rich_text_effect.h" +#include "scene/gui/popup_menu.h" #include "scene/gui/scroll_bar.h" #include "scene/resources/text_paragraph.h" @@ -91,6 +92,11 @@ public: VC_GLYPHS_RTL, }; + enum MenuItems { + MENU_COPY, + MENU_SELECT_ALL, + }; + protected: void _notification(int p_what); static void _bind_methods(); @@ -420,6 +426,15 @@ private: Selection selection; bool deselect_on_focus_loss_enabled = true; + bool context_menu_enabled = false; + bool shortcut_keys_enabled = true; + + // Context menu. + PopupMenu *menu = nullptr; + void _generate_context_menu(); + Key _get_menu_action_accelerator(const String &p_action); + void _menu_option(int p_option); + int visible_characters = -1; float percent_visible = 1.0; VisibleCharactersBehavior visible_chars_behavior = VC_CHARS_BEFORE_SHAPING; @@ -435,7 +450,7 @@ private: void _resize_line(ItemFrame *p_frame, int p_line, const Ref<Font> &p_base_font, int p_base_font_size, int p_width); void _update_line_font(ItemFrame *p_frame, int p_line, const Ref<Font> &p_base_font, int p_base_font_size); int _draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Color &p_base_color, int p_outline_size, const Color &p_outline_color, const Color &p_font_shadow_color, int p_shadow_outline_size, const Point2 &p_shadow_ofs, int &r_processed_glyphs); - float _find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr); + float _find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr, bool p_table = false); String _roman(int p_num, bool p_capitalize) const; String _letters(int p_num, bool p_capitalize) const; @@ -555,6 +570,12 @@ public: void set_tab_size(int p_spaces); int get_tab_size() const; + void set_context_menu_enabled(bool p_enabled); + bool is_context_menu_enabled() const; + + void set_shortcut_keys_enabled(bool p_enabled); + bool is_shortcut_keys_enabled() const; + void set_fit_content_height(bool p_enabled); bool is_fit_content_height_enabled() const; @@ -584,9 +605,15 @@ public: int get_selection_from() const; int get_selection_to() const; String get_selected_text() const; + void select_all(); void selection_copy(); void set_deselect_on_focus_loss_enabled(const bool p_enabled); bool is_deselect_on_focus_loss_enabled() const; + void deselect(); + + // Context menu. + PopupMenu *get_menu() const; + bool is_menu_visible() const; void parse_bbcode(const String &p_bbcode); void append_text(const String &p_bbcode); diff --git a/scene/gui/scroll_container.h b/scene/gui/scroll_container.h index c00df87b18..b9fcf64db6 100644 --- a/scene/gui/scroll_container.h +++ b/scene/gui/scroll_container.h @@ -47,8 +47,8 @@ public: }; private: - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; Size2 child_max_size; diff --git a/scene/gui/spin_box.h b/scene/gui/spin_box.h index a15e3fe5f5..d118b28334 100644 --- a/scene/gui/spin_box.h +++ b/scene/gui/spin_box.h @@ -38,11 +38,11 @@ class SpinBox : public Range { GDCLASS(SpinBox, Range); - LineEdit *line_edit; + LineEdit *line_edit = nullptr; int last_w = 0; bool update_on_text_changed = false; - Timer *range_click_timer; + Timer *range_click_timer = nullptr; void _range_click_timeout(); void _release_mouse(); diff --git a/scene/gui/tab_container.h b/scene/gui/tab_container.h index 225c24c25e..9adaa0d844 100644 --- a/scene/gui/tab_container.h +++ b/scene/gui/tab_container.h @@ -38,7 +38,7 @@ class TabContainer : public Container { GDCLASS(TabContainer, Container); - TabBar *tab_bar; + TabBar *tab_bar = nullptr; bool tabs_visible = true; bool all_tabs_in_front = false; bool menu_hovered = false; diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp index 66c3048f32..ff23e44cb7 100644 --- a/scene/gui/text_edit.cpp +++ b/scene/gui/text_edit.cpp @@ -1542,6 +1542,21 @@ void TextEdit::_notification(int p_what) { } } +void TextEdit::unhandled_key_input(const Ref<InputEvent> &p_event) { + Ref<InputEventKey> k = p_event; + + if (k.is_valid()) { + if (!k->is_pressed()) { + return; + } + // Handle Unicode (with modifiers active, process after shortcuts). + if (has_focus() && editable && (k->get_unicode() >= 32)) { + handle_unicode_input(k->get_unicode()); + accept_event(); + } + } +} + void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) { ERR_FAIL_COND(p_gui_input.is_null()); @@ -1929,44 +1944,45 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) { return; } - // SELECT ALL, SELECT WORD UNDER CARET, CUT, COPY, PASTE. - - if (k->is_action("ui_text_select_all", true)) { - select_all(); - accept_event(); - return; - } - if (k->is_action("ui_text_select_word_under_caret", true)) { - select_word_under_caret(); - accept_event(); - return; - } - if (k->is_action("ui_cut", true)) { - cut(); - accept_event(); - return; - } - if (k->is_action("ui_copy", true)) { - copy(); - accept_event(); - return; - } - if (k->is_action("ui_paste", true)) { - paste(); - accept_event(); - return; - } + if (is_shortcut_keys_enabled()) { + // SELECT ALL, SELECT WORD UNDER CARET, CUT, COPY, PASTE. + if (k->is_action("ui_text_select_all", true)) { + select_all(); + accept_event(); + return; + } + if (k->is_action("ui_text_select_word_under_caret", true)) { + select_word_under_caret(); + accept_event(); + return; + } + if (k->is_action("ui_cut", true)) { + cut(); + accept_event(); + return; + } + if (k->is_action("ui_copy", true)) { + copy(); + accept_event(); + return; + } + if (k->is_action("ui_paste", true)) { + paste(); + accept_event(); + return; + } - // UNDO/REDO. - if (k->is_action("ui_undo", true)) { - undo(); - accept_event(); - return; - } - if (k->is_action("ui_redo", true)) { - redo(); - accept_event(); - return; + // UNDO/REDO. + if (k->is_action("ui_undo", true)) { + undo(); + accept_event(); + return; + } + if (k->is_action("ui_redo", true)) { + redo(); + accept_event(); + return; + } } // MISC. @@ -2138,16 +2154,21 @@ void TextEdit::_move_caret_left(bool p_select, bool p_move_by_word) { if (p_move_by_word) { int cc = caret.column; - + // If the caret is at the start of the line, and not on the first line, move it up to the end of the previous line. if (cc == 0 && caret.line > 0) { set_caret_line(caret.line - 1); set_caret_column(text[caret.line].length()); } else { PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(caret.line)->get_rid()); - for (int i = words.size() - 2; i >= 0; i = i - 2) { - if (words[i] < cc) { - cc = words[i]; - break; + if (words.is_empty() || cc <= words[0]) { + // This solves the scenario where there are no words but glyfs that can be ignored. + cc = 0; + } else { + for (int i = words.size() - 2; i >= 0; i = i - 2) { + if (words[i] < cc) { + cc = words[i]; + break; + } } } set_caret_column(cc); @@ -2189,16 +2210,21 @@ void TextEdit::_move_caret_right(bool p_select, bool p_move_by_word) { if (p_move_by_word) { int cc = caret.column; - + // If the caret is at the end of the line, and not on the last line, move it down to the beginning of the next line. if (cc == text[caret.line].length() && caret.line < text.size() - 1) { set_caret_line(caret.line + 1); set_caret_column(0); } else { PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(caret.line)->get_rid()); - for (int i = 1; i < words.size(); i = i + 2) { - if (words[i] > cc) { - cc = words[i]; - break; + if (words.is_empty() || cc >= words[words.size() - 1]) { + // This solves the scenario where there are no words but glyfs that can be ignored. + cc = text[caret.line].length(); + } else { + for (int i = 1; i < words.size(); i = i + 2) { + if (words[i] > cc) { + cc = words[i]; + break; + } } } set_caret_column(cc); @@ -2369,11 +2395,11 @@ void TextEdit::_move_caret_page_down(bool p_select) { } void TextEdit::_do_backspace(bool p_word, bool p_all_to_left) { - if (!editable) { + if (!editable || (caret.column == 0 && caret.line == 0)) { return; } - if (has_selection() || (!p_all_to_left && !p_word)) { + if (has_selection() || (!p_all_to_left && !p_word) || caret.column == 0) { backspace(); return; } @@ -2386,20 +2412,30 @@ void TextEdit::_do_backspace(bool p_word, bool p_all_to_left) { } if (p_word) { - int line = caret.line; int column = caret.column; - - PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(line)->get_rid()); - for (int i = words.size() - 2; i >= 0; i = i - 2) { - if (words[i] < column) { - column = words[i]; - break; + // Check for the case "<word><space><caret>" and ignore the space. + // No need to check for column being 0 since it is cheked above. + if (is_whitespace(text[caret.line][caret.column - 1])) { + column -= 1; + } + // Get a list with the indices of the word bounds of the given text line. + const PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(caret.line)->get_rid()); + if (words.is_empty() || column <= words[0]) { + // If "words" is empty, meaning no words are left, we can remove everything until the begining of the line. + column = 0; + } else { + // Otherwise search for the first word break that is smaller than the index from we're currentlu deleteing + for (int i = words.size() - 2; i >= 0; i = i - 2) { + if (words[i] < column) { + column = words[i]; + break; + } } } - _remove_text(line, column, caret.line, caret.column); + _remove_text(caret.line, column, caret.line, caret.column); - set_caret_line(line, false); + set_caret_line(caret.line, false); set_caret_column(column); return; } @@ -3466,9 +3502,6 @@ void TextEdit::undo() { TextOperation op = undo_stack_pos->get(); _do_text_op(op, true); - if (op.type != TextOperation::TYPE_INSERT && (op.from_line != op.to_line || op.to_column != op.from_column + 1)) { - select(op.from_line, op.from_column, op.to_line, op.to_column); - } current_op.version = op.prev_version; if (undo_stack_pos->get().chain_backward) { @@ -3484,6 +3517,10 @@ void TextEdit::undo() { } } + if (op.type != TextOperation::TYPE_INSERT && (op.from_line != op.to_line || op.to_column != op.from_column + 1)) { + select(op.from_line, op.from_column, op.to_line, op.to_column); + } + _update_scrollbars(); if (undo_stack_pos->get().type == TextOperation::TYPE_REMOVE) { set_caret_line(undo_stack_pos->get().to_line, false); @@ -6599,6 +6636,7 @@ TextEdit::TextEdit(const String &p_placeholder) { set_focus_mode(FOCUS_ALL); _update_caches(); set_default_cursor_shape(CURSOR_IBEAM); + set_process_unhandled_key_input(true); text.set_tab_size(text.get_tab_size()); diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h index 6deaf76e5e..b365e9c61c 100644 --- a/scene/gui/text_edit.h +++ b/scene/gui/text_edit.h @@ -325,7 +325,7 @@ private: List<TextOperation> undo_stack; List<TextOperation>::Element *undo_stack_pos = nullptr; - Timer *idle_detect; + Timer *idle_detect = nullptr; uint32_t version = 0; uint32_t saved_version = 0; @@ -380,7 +380,7 @@ private: bool draw_caret = true; bool caret_blink_enabled = false; - Timer *caret_blink_timer; + Timer *caret_blink_timer = nullptr; bool move_caret_on_right_click = true; @@ -426,7 +426,7 @@ private: bool dragging_selection = false; - Timer *click_select_held; + Timer *click_select_held = nullptr; uint64_t last_dblclk = 0; Vector2 last_dblclk_pos; void _click_selection_held(); @@ -449,8 +449,8 @@ private: void _update_caret_wrap_offset(); /* Viewport. */ - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; bool scroll_past_end_of_file_enabled = false; @@ -623,6 +623,7 @@ protected: public: /* General overrides. */ + virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; virtual void gui_input(const Ref<InputEvent> &p_gui_input) override; virtual Size2 get_minimum_size() const override; virtual bool is_text_field() const override; diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp index ccd24ed2cf..3c8ea4d6df 100644 --- a/scene/gui/tree.cpp +++ b/scene/gui/tree.cpp @@ -101,6 +101,7 @@ void TreeItem::_change_tree(Tree *p_tree) { if (tree->popup_edited_item == this) { tree->popup_edited_item = nullptr; + tree->popup_pressing_edited_item = nullptr; tree->pressing_for_editor = false; } @@ -2088,7 +2089,6 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 } if (!p_item->collapsed) { /* if not collapsed, check the children */ - TreeItem *c = p_item->first_child; int base_ofs = children_pos.y - cache.offset.y + p_draw_ofs.y; @@ -2096,82 +2096,97 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 int prev_hl_ofs = base_ofs; while (c) { + int child_h = -1; if (htotal >= 0) { - int child_h = draw_item(children_pos, p_draw_ofs, p_draw_size, c); + child_h = draw_item(children_pos, p_draw_ofs, p_draw_size, c); + } - // Draw relationship lines. - if (cache.draw_relationship_lines > 0 && (!hide_root || c->parent != root)) { - int root_ofs = children_pos.x + ((p_item->disable_folding || hide_folding) ? cache.hseparation : cache.item_margin); - int parent_ofs = p_pos.x + cache.item_margin; - Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h / 2) - cache.offset + p_draw_ofs; + // Draw relationship lines. + if (cache.draw_relationship_lines > 0 && (!hide_root || c->parent != root)) { + int root_ofs = children_pos.x + ((p_item->disable_folding || hide_folding) ? cache.hseparation : cache.item_margin); + int parent_ofs = p_pos.x + cache.item_margin; + Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h / 2) - cache.offset + p_draw_ofs; - if (c->get_first_child() != nullptr) { - root_pos -= Point2i(cache.arrow->get_width(), 0); - } + if (c->get_first_child() != nullptr) { + root_pos -= Point2i(cache.arrow->get_width(), 0); + } - float line_width = cache.relationship_line_width * Math::round(cache.base_scale); - float parent_line_width = cache.parent_hl_line_width * Math::round(cache.base_scale); - float children_line_width = cache.children_hl_line_width * Math::round(cache.base_scale); + float line_width = cache.relationship_line_width * Math::round(cache.base_scale); + float parent_line_width = cache.parent_hl_line_width * Math::round(cache.base_scale); + float children_line_width = cache.children_hl_line_width * Math::round(cache.base_scale); - Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width() / 2, p_pos.y + label_h / 2 + cache.arrow->get_height() / 2) - cache.offset + p_draw_ofs; + Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width() / 2, p_pos.y + label_h / 2 + cache.arrow->get_height() / 2) - cache.offset + p_draw_ofs; - int more_prev_ofs = 0; + int more_prev_ofs = 0; - if (root_pos.y + line_width >= 0) { - if (rtl) { - root_pos.x = get_size().width - root_pos.x; - parent_pos.x = get_size().width - parent_pos.x; - } + if (root_pos.y + line_width >= 0) { + if (rtl) { + root_pos.x = get_size().width - root_pos.x; + parent_pos.x = get_size().width - parent_pos.x; + } - // Order of parts on this bend: the horizontal line first, then the vertical line. - if (_is_branch_selected(c)) { - // If this item or one of its children is selected, we draw the line using parent highlight style. + // Order of parts on this bend: the horizontal line first, then the vertical line. + if (_is_branch_selected(c)) { + // If this item or one of its children is selected, we draw the line using parent highlight style. + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(parent_line_width / 2), root_pos.y), cache.parent_hl_line_color, parent_line_width); + } + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); + + more_prev_ofs = cache.parent_hl_line_margin; + prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); + } else if (p_item->is_selected(0)) { + // If parent item is selected (but this item is not), we draw the line using children highlight style. + // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. + if (_is_sibling_branch_selected(c)) { + if (htotal >= 0) { + RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(parent_line_width / 2), root_pos.y), cache.children_hl_line_color, children_line_width); + } RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); - more_prev_ofs = cache.parent_hl_line_margin; prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); - } else if (p_item->is_selected(0)) { - // If parent item is selected (but this item is not), we draw the line using children highlight style. - // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. - if (_is_sibling_branch_selected(c)) { - RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(parent_line_width / 2), root_pos.y), cache.children_hl_line_color, children_line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); - - prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); - } else { + } else { + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(children_line_width / 2), root_pos.y), cache.children_hl_line_color, children_line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(children_line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(children_line_width / 2)), cache.children_hl_line_color, children_line_width); } - } else { - // If nothing of the above is true, we draw the line using normal style. - // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. - if (_is_sibling_branch_selected(c)) { + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(children_line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(children_line_width / 2)), cache.children_hl_line_color, children_line_width); + } + } else { + // If nothing of the above is true, we draw the line using normal style. + // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. + if (_is_sibling_branch_selected(c)) { + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + cache.parent_hl_line_margin, root_pos.y), cache.relationship_line_color, line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); + } + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); - prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); - } else { + prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); + } else { + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(line_width / 2), root_pos.y), cache.relationship_line_color, line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(line_width / 2)), cache.relationship_line_color, line_width); } + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(line_width / 2)), cache.relationship_line_color, line_width); } } - - prev_ofs = root_pos.y + more_prev_ofs; } - if (child_h < 0) { - if (cache.draw_relationship_lines == 0) { - return -1; // break, stop drawing, no need to anymore - } + prev_ofs = root_pos.y + more_prev_ofs; + } - htotal = -1; - children_pos.y = cache.offset.y + p_draw_size.height; - } else { - htotal += child_h; - children_pos.y += child_h; + if (child_h < 0) { + if (htotal == -1) { + break; // Last loop done, stop. + } + + if (cache.draw_relationship_lines == 0) { + return -1; // No need to draw anymore, full stop. } + + htotal = -1; + children_pos.y = cache.offset.y + p_draw_size.height; + } else { + htotal += child_h; + children_pos.y += child_h; } c = c->next; @@ -2670,8 +2685,8 @@ int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, int } click_handled = true; - popup_edited_item = p_item; - popup_edited_item_col = col; + popup_pressing_edited_item = p_item; + popup_pressing_edited_item_column = col; pressing_item_rect = Rect2(get_global_position() + Point2i(col_ofs, _get_title_button_height() + y_ofs) - cache.offset, Size2(col_width, item_h)); pressing_for_editor_text = editor_text; @@ -3206,10 +3221,16 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) { update(); } - if (pressing_for_editor && popup_edited_item && (popup_edited_item->get_cell_mode(popup_edited_item_col) == TreeItem::CELL_MODE_RANGE)) { - //range drag + if (pressing_for_editor && popup_pressing_edited_item && (popup_pressing_edited_item->get_cell_mode(popup_pressing_edited_item_column) == TreeItem::CELL_MODE_RANGE)) { + /* This needs to happen now, because the popup can be closed when pressing another item, and must remain the popup edited item until it actually closes */ + popup_edited_item = popup_pressing_edited_item; + popup_edited_item_col = popup_pressing_edited_item_column; + + popup_pressing_edited_item = nullptr; + popup_pressing_edited_item_column = -1; if (!range_drag_enabled) { + //range drag Vector2 cpos = mm->get_position(); if (rtl) { cpos.x = get_size().width - cpos.x; @@ -3994,6 +4015,7 @@ void Tree::clear() { selected_item = nullptr; edited_item = nullptr; popup_edited_item = nullptr; + popup_pressing_edited_item = nullptr; update(); }; @@ -4309,12 +4331,16 @@ int Tree::get_pressed_button() const { return pressed_button; } -Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column) const { +Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column, int p_button) const { ERR_FAIL_NULL_V(p_item, Rect2()); ERR_FAIL_COND_V(p_item->tree != this, Rect2()); if (p_column != -1) { ERR_FAIL_INDEX_V(p_column, columns.size(), Rect2()); } + if (p_button != -1) { + ERR_FAIL_COND_V(p_column == -1, Rect2()); // pass a column if you want to pass a button + ERR_FAIL_INDEX_V(p_button, p_item->cells[p_column].buttons.size(), Rect2()); + } int ofs = get_item_offset(p_item); int height = compute_item_height(p_item); @@ -4332,6 +4358,19 @@ Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column) const { } r.position.x = accum; r.size.x = get_column_width(p_column); + if (p_button != -1) { + const TreeItem::Cell &c = p_item->cells[p_column]; + Vector2 ofst = Vector2(r.position.x + r.size.x, r.position.y); + for (int j = c.buttons.size() - 1; j >= 0; j--) { + Ref<Texture2D> b = c.buttons[j].texture; + Size2 size = b->get_size() + cache.button_pressed->get_minimum_size(); + ofst.x -= size.x; + + if (j == p_button) { + return Rect2(ofst, size); + } + } + } } return r; @@ -4870,7 +4909,7 @@ void Tree::_bind_methods() { ClassDB::bind_method(D_METHOD("get_edited_column"), &Tree::get_edited_column); ClassDB::bind_method(D_METHOD("edit_selected"), &Tree::edit_selected); ClassDB::bind_method(D_METHOD("get_custom_popup_rect"), &Tree::get_custom_popup_rect); - ClassDB::bind_method(D_METHOD("get_item_area_rect", "item", "column"), &Tree::get_item_rect, DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("get_item_area_rect", "item", "column", "button_index"), &Tree::get_item_rect, DEFVAL(-1), DEFVAL(-1)); ClassDB::bind_method(D_METHOD("get_item_at_position", "position"), &Tree::get_item_at_position); ClassDB::bind_method(D_METHOD("get_column_at_position", "position"), &Tree::get_column_at_position); ClassDB::bind_method(D_METHOD("get_drop_section_at_position", "position"), &Tree::get_drop_section_at_position); diff --git a/scene/gui/tree.h b/scene/gui/tree.h index 04d4b9b935..b704495444 100644 --- a/scene/gui/tree.h +++ b/scene/gui/tree.h @@ -134,7 +134,7 @@ private: Vector<TreeItem *> children_cache; bool is_root = false; // for tree root - Tree *tree; // tree (for reference) + Tree *tree = nullptr; // tree (for reference) TreeItem(Tree *p_tree); @@ -379,6 +379,9 @@ private: TreeItem *selected_item = nullptr; TreeItem *edited_item = nullptr; + TreeItem *popup_pressing_edited_item = nullptr; // Candidate. + int popup_pressing_edited_item_column = -1; + TreeItem *drop_mode_over = nullptr; int drop_mode_section = 0; @@ -428,18 +431,18 @@ private: bool show_column_titles = false; - VBoxContainer *popup_editor_vb; + VBoxContainer *popup_editor_vb = nullptr; - Popup *popup_editor; + Popup *popup_editor = nullptr; LineEdit *text_editor = nullptr; - HSlider *value_editor; + HSlider *value_editor = nullptr; bool updating_value_editor = false; uint64_t focus_in_id = 0; PopupMenu *popup_menu = nullptr; Vector<ColumnInfo> columns; - Timer *range_click_timer; + Timer *range_click_timer = nullptr; TreeItem *range_item_last = nullptr; bool range_up_last = false; void _range_click_timeout(); @@ -553,8 +556,8 @@ private: int _get_title_button_height() const; void _scroll_moved(float p_value); - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; bool h_scroll_enabled = true; bool v_scroll_enabled = true; @@ -673,7 +676,7 @@ public: Rect2 get_custom_popup_rect() const; int get_item_offset(TreeItem *p_item) const; - Rect2 get_item_rect(TreeItem *p_item, int p_column = -1) const; + Rect2 get_item_rect(TreeItem *p_item, int p_column = -1, int p_button = -1) const; bool edit_selected(); bool is_editing(); diff --git a/scene/gui/video_stream_player.cpp b/scene/gui/video_stream_player.cpp index d7c76aa070..ca2dad71af 100644 --- a/scene/gui/video_stream_player.cpp +++ b/scene/gui/video_stream_player.cpp @@ -60,7 +60,7 @@ int VideoStreamPlayer::_audio_mix_callback(void *p_udata, const float *p_data, i ERR_FAIL_NULL_V(p_udata, 0); ERR_FAIL_NULL_V(p_data, 0); - VideoStreamPlayer *vp = (VideoStreamPlayer *)p_udata; + VideoStreamPlayer *vp = static_cast<VideoStreamPlayer *>(p_udata); int todo = MIN(vp->resampler.get_writer_space(), p_frames); @@ -77,7 +77,7 @@ int VideoStreamPlayer::_audio_mix_callback(void *p_udata, const float *p_data, i void VideoStreamPlayer::_mix_audios(void *p_self) { ERR_FAIL_NULL(p_self); - reinterpret_cast<VideoStreamPlayer *>(p_self)->_mix_audio(); + static_cast<VideoStreamPlayer *>(p_self)->_mix_audio(); } // Called from audio thread diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp index 15d36d8230..708359f106 100644 --- a/scene/main/canvas_item.cpp +++ b/scene/main/canvas_item.cpp @@ -463,10 +463,10 @@ void CanvasItem::draw_dashed_line(const Point2 &p_from, const Point2 &p_to, cons RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, off, p_to, p_color, p_width); } -void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width) { +void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width, bool p_antialiased) { ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); - RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, p_from, p_to, p_color, p_width); + RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, p_from, p_to, p_color, p_width, p_antialiased); } void CanvasItem::draw_polyline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width, bool p_antialiased) { @@ -883,10 +883,7 @@ void CanvasItem::_bind_methods() { ClassDB::bind_method(D_METHOD("set_draw_behind_parent", "enable"), &CanvasItem::set_draw_behind_parent); ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"), &CanvasItem::is_draw_behind_parent_enabled); - ClassDB::bind_method(D_METHOD("_set_on_top", "on_top"), &CanvasItem::_set_on_top); - ClassDB::bind_method(D_METHOD("_is_on_top"), &CanvasItem::_is_on_top); - - ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width"), &CanvasItem::draw_line, DEFVAL(1.0)); + ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width", "antialiased"), &CanvasItem::draw_line, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("draw_dashed_line", "from", "to", "color", "width", "dash"), &CanvasItem::draw_dashed_line, DEFVAL(1.0), DEFVAL(2.0)); ClassDB::bind_method(D_METHOD("draw_polyline", "points", "color", "width", "antialiased"), &CanvasItem::draw_polyline, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("draw_polyline_colors", "points", "colors", "width", "antialiased"), &CanvasItem::draw_polyline_colors, DEFVAL(1.0), DEFVAL(false)); @@ -959,7 +956,6 @@ void CanvasItem::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::COLOR, "self_modulate"), "set_self_modulate", "get_self_modulate"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_behind_parent"), "set_draw_behind_parent", "is_draw_behind_parent_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "top_level"), "set_as_top_level", "is_set_as_top_level"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_on_top", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "_set_on_top", "_is_on_top"); //compatibility ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_children"), "set_clip_children", "is_clipping_children"); ADD_PROPERTY(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask", "get_light_mask"); diff --git a/scene/main/canvas_item.h b/scene/main/canvas_item.h index dbc833aa5b..ad64f1ab5e 100644 --- a/scene/main/canvas_item.h +++ b/scene/main/canvas_item.h @@ -120,9 +120,6 @@ private: void _notify_transform(CanvasItem *p_node); - void _set_on_top(bool p_on_top) { set_draw_behind_parent(!p_on_top); } - bool _is_on_top() const { return !is_draw_behind_parent_enabled(); } - static CanvasItem *current_item_drawn; friend class Viewport; void _update_texture_repeat_changed(bool p_propagate); @@ -218,7 +215,7 @@ public: /* DRAWING API */ void draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, real_t p_dash = 2.0); - void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0); + void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); void draw_polyline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); void draw_polyline_colors(const Vector<Point2> &p_points, const Vector<Color> &p_colors, real_t p_width = 1.0, bool p_antialiased = false); void draw_arc(const Vector2 &p_center, real_t p_radius, real_t p_start_angle, real_t p_end_angle, int p_point_count, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); diff --git a/scene/main/http_request.cpp b/scene/main/http_request.cpp index ac10c2bad8..34b0e19d31 100644 --- a/scene/main/http_request.cpp +++ b/scene/main/http_request.cpp @@ -164,7 +164,7 @@ Error HTTPRequest::request_raw(const String &p_url, const Vector<String> &p_cust } void HTTPRequest::_thread_func(void *p_userdata) { - HTTPRequest *hr = (HTTPRequest *)p_userdata; + HTTPRequest *hr = static_cast<HTTPRequest *>(p_userdata); Error err = hr->_request(); @@ -197,10 +197,7 @@ void HTTPRequest::cancel_request() { thread.wait_to_finish(); } - if (file) { - memdelete(file); - file = nullptr; - } + file.unref(); client->close(); body.clear(); got_response = false; @@ -365,7 +362,7 @@ bool HTTPRequest::_update_connection() { if (!download_to_file.is_empty()) { file = FileAccess::open(download_to_file, FileAccess::WRITE); - if (!file) { + if (file.is_null()) { call_deferred(SNAME("_request_done"), RESULT_DOWNLOAD_FILE_CANT_OPEN, response_code, response_headers, PackedByteArray()); return true; } @@ -381,7 +378,7 @@ bool HTTPRequest::_update_connection() { if (chunk.size()) { downloaded.add(chunk.size()); - if (file) { + if (file.is_valid()) { const uint8_t *r = chunk.ptr(); file->store_buffer(r, chunk.size()); if (file->get_error() != OK) { @@ -642,9 +639,3 @@ HTTPRequest::HTTPRequest() { timer->connect("timeout", callable_mp(this, &HTTPRequest::_timeout)); add_child(timer); } - -HTTPRequest::~HTTPRequest() { - if (file) { - memdelete(file); - } -} diff --git a/scene/main/http_request.h b/scene/main/http_request.h index 26d648458f..49b4b1b30c 100644 --- a/scene/main/http_request.h +++ b/scene/main/http_request.h @@ -84,7 +84,7 @@ private: String download_to_file; - FileAccess *file = nullptr; + Ref<FileAccess> file; int body_len = -1; SafeNumeric<int> downloaded; @@ -144,7 +144,7 @@ public: void set_max_redirects(int p_max); int get_max_redirects() const; - Timer *timer; + Timer *timer = nullptr; void set_timeout(double p_timeout); double get_timeout(); @@ -158,7 +158,6 @@ public: void set_https_proxy(const String &p_host, int p_port); HTTPRequest(); - ~HTTPRequest(); }; VARIANT_ENUM_CAST(HTTPRequest::Result); diff --git a/scene/main/node.cpp b/scene/main/node.cpp index 7933045c5f..34bb1cde05 100644 --- a/scene/main/node.cpp +++ b/scene/main/node.cpp @@ -79,6 +79,9 @@ void Node::_notification(int p_notification) { if (data.input) { add_to_group("_vp_input" + itos(get_viewport()->get_instance_id())); } + if (data.shortcut_input) { + add_to_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } if (data.unhandled_input) { add_to_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } @@ -100,6 +103,9 @@ void Node::_notification(int p_notification) { if (data.input) { remove_from_group("_vp_input" + itos(get_viewport()->get_instance_id())); } + if (data.shortcut_input) { + remove_from_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } if (data.unhandled_input) { remove_from_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } @@ -126,6 +132,10 @@ void Node::_notification(int p_notification) { set_process_input(true); } + if (GDVIRTUAL_IS_OVERRIDDEN(_shortcut_input)) { + set_process_shortcut_input(true); + } + if (GDVIRTUAL_IS_OVERRIDDEN(_unhandled_input)) { set_process_unhandled_input(true); } @@ -835,6 +845,26 @@ bool Node::is_processing_input() const { return data.input; } +void Node::set_process_shortcut_input(bool p_enable) { + if (p_enable == data.shortcut_input) { + return; + } + data.shortcut_input = p_enable; + if (!is_inside_tree()) { + return; + } + + if (p_enable) { + add_to_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } else { + remove_from_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } +} + +bool Node::is_processing_shortcut_input() const { + return data.shortcut_input; +} + void Node::set_process_unhandled_input(bool p_enable) { if (p_enable == data.unhandled_input) { return; @@ -2615,6 +2645,15 @@ void Node::_call_input(const Ref<InputEvent> &p_event) { } input(p_event); } + +void Node::_call_shortcut_input(const Ref<InputEvent> &p_event) { + GDVIRTUAL_CALL(_shortcut_input, p_event); + if (!is_inside_tree() || !get_viewport() || get_viewport()->is_input_handled()) { + return; + } + shortcut_input(p_event); +} + void Node::_call_unhandled_input(const Ref<InputEvent> &p_event) { GDVIRTUAL_CALL(_unhandled_input, p_event); if (!is_inside_tree() || !get_viewport() || get_viewport()->is_input_handled()) { @@ -2622,6 +2661,7 @@ void Node::_call_unhandled_input(const Ref<InputEvent> &p_event) { } unhandled_input(p_event); } + void Node::_call_unhandled_key_input(const Ref<InputEvent> &p_event) { GDVIRTUAL_CALL(_unhandled_key_input, p_event); if (!is_inside_tree() || !get_viewport() || get_viewport()->is_input_handled()) { @@ -2633,6 +2673,9 @@ void Node::_call_unhandled_key_input(const Ref<InputEvent> &p_event) { void Node::input(const Ref<InputEvent> &p_event) { } +void Node::shortcut_input(const Ref<InputEvent> &p_key_event) { +} + void Node::unhandled_input(const Ref<InputEvent> &p_event) { } @@ -2694,6 +2737,8 @@ void Node::_bind_methods() { ClassDB::bind_method(D_METHOD("is_processing"), &Node::is_processing); ClassDB::bind_method(D_METHOD("set_process_input", "enable"), &Node::set_process_input); ClassDB::bind_method(D_METHOD("is_processing_input"), &Node::is_processing_input); + ClassDB::bind_method(D_METHOD("set_process_shortcut_input", "enable"), &Node::set_process_shortcut_input); + ClassDB::bind_method(D_METHOD("is_processing_shortcut_input"), &Node::is_processing_shortcut_input); ClassDB::bind_method(D_METHOD("set_process_unhandled_input", "enable"), &Node::set_process_unhandled_input); ClassDB::bind_method(D_METHOD("is_processing_unhandled_input"), &Node::is_processing_unhandled_input); ClassDB::bind_method(D_METHOD("set_process_unhandled_key_input", "enable"), &Node::set_process_unhandled_key_input); @@ -2854,6 +2899,7 @@ void Node::_bind_methods() { GDVIRTUAL_BIND(_ready); GDVIRTUAL_BIND(_get_configuration_warnings); GDVIRTUAL_BIND(_input, "event"); + GDVIRTUAL_BIND(_shortcut_input, "event"); GDVIRTUAL_BIND(_unhandled_input, "event"); GDVIRTUAL_BIND(_unhandled_key_input, "event"); } diff --git a/scene/main/node.h b/scene/main/node.h index 1f973a0cb4..57b150e29a 100644 --- a/scene/main/node.h +++ b/scene/main/node.h @@ -136,6 +136,7 @@ private: bool process_internal = false; bool input = false; + bool shortcut_input = false; bool unhandled_input = false; bool unhandled_key_input = false; @@ -215,11 +216,13 @@ protected: //call from SceneTree void _call_input(const Ref<InputEvent> &p_event); + void _call_shortcut_input(const Ref<InputEvent> &p_event); void _call_unhandled_input(const Ref<InputEvent> &p_event); void _call_unhandled_key_input(const Ref<InputEvent> &p_event); protected: virtual void input(const Ref<InputEvent> &p_event); + virtual void shortcut_input(const Ref<InputEvent> &p_key_event); virtual void unhandled_input(const Ref<InputEvent> &p_event); virtual void unhandled_key_input(const Ref<InputEvent> &p_key_event); @@ -231,6 +234,7 @@ protected: GDVIRTUAL0RC(Vector<String>, _get_configuration_warnings) GDVIRTUAL1(_input, Ref<InputEvent>) + GDVIRTUAL1(_shortcut_input, Ref<InputEvent>) GDVIRTUAL1(_unhandled_input, Ref<InputEvent>) GDVIRTUAL1(_unhandled_key_input, Ref<InputEvent>) @@ -395,6 +399,9 @@ public: void set_process_input(bool p_enable); bool is_processing_input() const; + void set_process_shortcut_input(bool p_enable); + bool is_processing_shortcut_input() const; + void set_process_unhandled_input(bool p_enable); bool is_processing_unhandled_input() const; diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp index 8eeedf51a9..151239c9e7 100644 --- a/scene/main/scene_tree.cpp +++ b/scene/main/scene_tree.cpp @@ -897,6 +897,9 @@ void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_cal case CALL_INPUT_TYPE_INPUT: n->_call_input(p_input); break; + case CALL_INPUT_TYPE_SHORTCUT_INPUT: + n->_call_shortcut_input(p_input); + break; case CALL_INPUT_TYPE_UNHANDLED_INPUT: n->_call_unhandled_input(p_input); break; @@ -1259,7 +1262,7 @@ void SceneTree::add_idle_callback(IdleCallback p_callback) { void SceneTree::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { if (p_function == "change_scene") { - DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES); List<String> directories; directories.push_back(dir_access->get_current_dir()); diff --git a/scene/main/scene_tree.h b/scene/main/scene_tree.h index 10839ca425..705ca6ebd3 100644 --- a/scene/main/scene_tree.h +++ b/scene/main/scene_tree.h @@ -115,7 +115,7 @@ private: int node_count = 0; #ifdef TOOLS_ENABLED - Node *edited_scene_root; + Node *edited_scene_root = nullptr; #endif struct UGCall { StringName group; @@ -138,7 +138,7 @@ private: Array _get_nodes_in_group(const StringName &p_group); - Node *current_scene; + Node *current_scene = nullptr; Color debug_collisions_color; Color debug_collision_contact_color; @@ -204,6 +204,7 @@ private: enum CallInputType { CALL_INPUT_TYPE_INPUT, + CALL_INPUT_TYPE_SHORTCUT_INPUT, CALL_INPUT_TYPE_UNHANDLED_INPUT, CALL_INPUT_TYPE_UNHANDLED_KEY_INPUT, }; diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index a38bed71d1..d93e7b4b0b 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -2744,11 +2744,18 @@ void Viewport::push_unhandled_input(const Ref<InputEvent> &p_event, bool p_local ev = p_event; } + // Shortcut Input. + if (Object::cast_to<InputEventKey>(*ev) != nullptr || Object::cast_to<InputEventShortcut>(*ev) != nullptr) { + get_tree()->_call_input_pause(shortcut_input_group, SceneTree::CALL_INPUT_TYPE_SHORTCUT_INPUT, ev, this); + } + // Unhandled Input. - get_tree()->_call_input_pause(unhandled_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_INPUT, ev, this); + if (!is_input_handled()) { + get_tree()->_call_input_pause(unhandled_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_INPUT, ev, this); + } - // Unhandled key Input - used for performance reasons - This is called a lot less than _unhandled_input since it ignores MouseMotion, etc. - if (!is_input_handled() && (Object::cast_to<InputEventKey>(*ev) != nullptr || Object::cast_to<InputEventShortcut>(*ev) != nullptr)) { + // Unhandled key Input - Used for performance reasons - This is called a lot less than _unhandled_input since it ignores MouseMotion, and to handle Unicode input with Alt / Ctrl modifiers after handling shortcuts. + if (!is_input_handled() && (Object::cast_to<InputEventKey>(*ev) != nullptr)) { get_tree()->_call_input_pause(unhandled_key_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_KEY_INPUT, ev, this); } @@ -3737,7 +3744,7 @@ void Viewport::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "debug_draw", PROPERTY_HINT_ENUM, "Disabled,Unshaded,Overdraw,Wireframe"), "set_debug_draw", "get_debug_draw"); #ifndef _3D_DISABLED ADD_GROUP("Scaling 3D", ""); - ADD_PROPERTY(PropertyInfo(Variant::INT, "scaling_3d_mode", PROPERTY_HINT_ENUM, "Disabled (Slowest),Bilinear (Fastest),FSR (Fast)"), "set_scaling_3d_mode", "get_scaling_3d_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "scaling_3d_mode", PROPERTY_HINT_ENUM, "Bilinear (Fastest),FSR 1.0 (Fast)"), "set_scaling_3d_mode", "get_scaling_3d_mode"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "scaling_3d_scale", PROPERTY_HINT_RANGE, "0.25,2.0,0.01"), "set_scaling_3d_scale", "get_scaling_3d_scale"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fsr_mipmap_bias", PROPERTY_HINT_RANGE, "-2,2,0.1"), "set_fsr_mipmap_bias", "get_fsr_mipmap_bias"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fsr_sharpness", PROPERTY_HINT_RANGE, "0,2,0.1"), "set_fsr_sharpness", "get_fsr_sharpness"); @@ -3879,6 +3886,7 @@ Viewport::Viewport() { input_group = "_vp_input" + id; gui_input_group = "_vp_gui_input" + id; unhandled_input_group = "_vp_unhandled_input" + id; + shortcut_input_group = "_vp_shortcut_input" + id; unhandled_key_input_group = "_vp_unhandled_key_input" + id; // Window tooltip. diff --git a/scene/main/viewport.h b/scene/main/viewport.h index 80be53fab8..32882fbb68 100644 --- a/scene/main/viewport.h +++ b/scene/main/viewport.h @@ -270,6 +270,7 @@ private: Rect2i to_screen_rect; StringName input_group; StringName gui_input_group; + StringName shortcut_input_group; StringName unhandled_input_group; StringName unhandled_key_input_group; diff --git a/scene/main/window.cpp b/scene/main/window.cpp index 2faa107fb4..8b1a4680d2 100644 --- a/scene/main/window.cpp +++ b/scene/main/window.cpp @@ -981,7 +981,7 @@ void Window::_window_input_text(const String &p_text) { } void Window::_window_drop_files(const Vector<String> &p_files) { - emit_signal(SNAME("files_dropped"), p_files, current_screen); + emit_signal(SNAME("files_dropped"), p_files); } Viewport *Window::get_parent_viewport() const { @@ -1066,11 +1066,9 @@ void Window::popup_centered(const Size2i &p_minsize) { } Rect2i popup_rect; - if (p_minsize == Size2i()) { - popup_rect.size = _get_contents_minimum_size(); - } else { - popup_rect.size = p_minsize; - } + Size2 contents_minsize = _get_contents_minimum_size(); + popup_rect.size.x = MAX(p_minsize.x, contents_minsize.x); + popup_rect.size.y = MAX(p_minsize.y, contents_minsize.y); popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2; popup(popup_rect); @@ -1079,6 +1077,7 @@ void Window::popup_centered(const Size2i &p_minsize) { void Window::popup_centered_ratio(float p_ratio) { ERR_FAIL_COND(!is_inside_tree()); ERR_FAIL_COND_MSG(window_id == DisplayServer::MAIN_WINDOW_ID, "Can't popup the main window."); + ERR_FAIL_COND_MSG(p_ratio <= 0.0 || p_ratio > 1.0, "Ratio must be between 0.0 and 1.0!"); Rect2 parent_rect; diff --git a/scene/multiplayer/scene_cache_interface.h b/scene/multiplayer/scene_cache_interface.h index c709d26b51..d53cf387fb 100644 --- a/scene/multiplayer/scene_cache_interface.h +++ b/scene/multiplayer/scene_cache_interface.h @@ -37,7 +37,7 @@ class SceneCacheInterface : public MultiplayerCacheInterface { GDCLASS(SceneCacheInterface, MultiplayerCacheInterface); private: - MultiplayerAPI *multiplayer; + MultiplayerAPI *multiplayer = nullptr; //path sent caches struct PathSentCache { diff --git a/scene/multiplayer/scene_replication_interface.h b/scene/multiplayer/scene_replication_interface.h index 855878d029..60ac95c93c 100644 --- a/scene/multiplayer/scene_replication_interface.h +++ b/scene/multiplayer/scene_replication_interface.h @@ -47,7 +47,7 @@ private: void _free_remotes(int p_peer); Ref<SceneReplicationState> rep_state; - MultiplayerAPI *multiplayer; + MultiplayerAPI *multiplayer = nullptr; PackedByteArray packet_cache; int sync_mtu = 1350; // Highly dependent on underlying protocol. diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index 032f43d9b9..127e734e6c 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -139,6 +139,7 @@ #include "scene/multiplayer/scene_cache_interface.h" #include "scene/multiplayer/scene_replication_interface.h" #include "scene/multiplayer/scene_rpc_interface.h" +#include "scene/resources/animation_library.h" #include "scene/resources/audio_stream_sample.h" #include "scene/resources/bit_map.h" #include "scene/resources/box_shape_3d.h" @@ -834,6 +835,7 @@ void register_scene_types() { GDREGISTER_CLASS(CompressedTexture2DArray); GDREGISTER_CLASS(Animation); + GDREGISTER_CLASS(AnimationLibrary); GDREGISTER_CLASS(FontData); GDREGISTER_CLASS(Font); GDREGISTER_CLASS(Curve); @@ -896,18 +898,16 @@ void register_scene_types() { #ifndef DISABLE_DEPRECATED // Dropped in 4.0, near approximation. ClassDB::add_compatibility_class("AnimationTreePlayer", "AnimationTree"); - ClassDB::add_compatibility_class("AStar", "AStar3D"); + ClassDB::add_compatibility_class("BakedLightmap", "LightmapGI"); + ClassDB::add_compatibility_class("BakedLightmapData", "LightmapGIData"); ClassDB::add_compatibility_class("BitmapFont", "Font"); ClassDB::add_compatibility_class("DynamicFont", "Font"); ClassDB::add_compatibility_class("DynamicFontData", "FontData"); - ClassDB::add_compatibility_class("ToolButton", "Button"); ClassDB::add_compatibility_class("Navigation3D", "Node3D"); ClassDB::add_compatibility_class("Navigation2D", "Node2D"); + ClassDB::add_compatibility_class("OpenSimplexNoise", "FastNoiseLite"); + ClassDB::add_compatibility_class("ToolButton", "Button"); ClassDB::add_compatibility_class("YSort", "Node2D"); - ClassDB::add_compatibility_class("GIProbe", "VoxelGI"); - ClassDB::add_compatibility_class("GIProbeData", "VoxelGIData"); - ClassDB::add_compatibility_class("BakedLightmap", "LightmapGI"); - ClassDB::add_compatibility_class("BakedLightmapData", "LightmapGIData"); // Portal and room occlusion was replaced by raster occlusion (OccluderInstance3D node). ClassDB::add_compatibility_class("Portal", "Node3D"); ClassDB::add_compatibility_class("Room", "Node3D"); @@ -928,6 +928,7 @@ void register_scene_types() { ClassDB::add_compatibility_class("ARVROrigin", "XROrigin3D"); ClassDB::add_compatibility_class("ARVRPositionalTracker", "XRPositionalTracker"); ClassDB::add_compatibility_class("ARVRServer", "XRServer"); + ClassDB::add_compatibility_class("AStar", "AStar3D"); ClassDB::add_compatibility_class("BoneAttachment", "BoneAttachment3D"); ClassDB::add_compatibility_class("BoxShape", "BoxShape3D"); ClassDB::add_compatibility_class("Camera", "Camera3D"); @@ -955,6 +956,8 @@ void register_scene_types() { ClassDB::add_compatibility_class("EditorSpatialGizmo", "EditorNode3DGizmo"); ClassDB::add_compatibility_class("EditorSpatialGizmoPlugin", "EditorNode3DGizmoPlugin"); ClassDB::add_compatibility_class("Generic6DOFJoint", "Generic6DOFJoint3D"); + ClassDB::add_compatibility_class("GIProbe", "VoxelGI"); + ClassDB::add_compatibility_class("GIProbeData", "VoxelGIData"); ClassDB::add_compatibility_class("GradientTexture", "GradientTexture1D"); ClassDB::add_compatibility_class("HeightMapShape", "HeightMapShape3D"); ClassDB::add_compatibility_class("HingeJoint", "HingeJoint3D"); diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp index f6e0df0265..e045a379d2 100644 --- a/scene/resources/animation.cpp +++ b/scene/resources/animation.cpp @@ -3428,7 +3428,6 @@ real_t Animation::bezier_track_interpolate(int p_track, double p_time) const { real_t duration = bt->values[idx + 1].time - bt->values[idx].time; // time duration between our two keyframes real_t low = 0.0; // 0% of the current animation segment real_t high = 1.0; // 100% of the current animation segment - real_t middle; Vector2 start(0, bt->values[idx].value.value); Vector2 start_out = start + bt->values[idx].value.out_handle; @@ -3437,7 +3436,7 @@ real_t Animation::bezier_track_interpolate(int p_track, double p_time) const { //narrow high and low as much as possible for (int i = 0; i < iterations; i++) { - middle = (low + high) / 2; + real_t middle = (low + high) / 2; Vector2 interp = _bezier_interp(middle, start, start_out, end_in, end); @@ -3829,7 +3828,7 @@ void Animation::_bind_methods() { ClassDB::bind_method(D_METHOD("compress", "page_size", "fps", "split_tolerance"), &Animation::compress, DEFVAL(8192), DEFVAL(120), DEFVAL(4.0)); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "length", PROPERTY_HINT_RANGE, "0.001,99999,0.001"), "set_length", "get_length"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode"), "set_loop_mode", "get_loop_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode", PROPERTY_HINT_ENUM, "None,Linear,Ping-Pong"), "set_loop_mode", "get_loop_mode"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "step", PROPERTY_HINT_RANGE, "0,4096,0.001"), "set_step", "get_step"); ADD_SIGNAL(MethodInfo("tracks_changed")); diff --git a/scene/resources/animation_library.cpp b/scene/resources/animation_library.cpp new file mode 100644 index 0000000000..229d9ab218 --- /dev/null +++ b/scene/resources/animation_library.cpp @@ -0,0 +1,134 @@ +/*************************************************************************/ +/* animation_library.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "animation_library.h" + +Error AnimationLibrary::add_animation(const StringName &p_name, const Ref<Animation> &p_animation) { + ERR_FAIL_COND_V_MSG(String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("["), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + "."); + ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER); + + if (animations.has(p_name)) { + animations.erase(p_name); + emit_signal(SNAME("animation_removed"), p_name); + } + + animations.insert(p_name, p_animation); + emit_signal(SNAME("animation_added"), p_name); + notify_property_list_changed(); + return OK; +} + +void AnimationLibrary::remove_animation(const StringName &p_name) { + ERR_FAIL_COND(!animations.has(p_name)); + + animations.erase(p_name); + emit_signal(SNAME("animation_removed"), p_name); + notify_property_list_changed(); +} + +void AnimationLibrary::rename_animation(const StringName &p_name, const StringName &p_new_name) { + ERR_FAIL_COND(!animations.has(p_name)); + ERR_FAIL_COND_MSG(String(p_new_name).contains("/") || String(p_new_name).contains(":") || String(p_new_name).contains(",") || String(p_new_name).contains("["), "Invalid animation name: " + String(p_new_name) + "."); + ERR_FAIL_COND(animations.has(p_new_name)); + + animations.insert(p_new_name, animations[p_name]); + animations.erase(p_name); + emit_signal(SNAME("animation_renamed"), p_name, p_new_name); +} + +bool AnimationLibrary::has_animation(const StringName &p_name) const { + return animations.has(p_name); +} + +Ref<Animation> AnimationLibrary::get_animation(const StringName &p_name) const { + ERR_FAIL_COND_V(!animations.has(p_name), Ref<Animation>()); + + return animations[p_name]; +} + +TypedArray<StringName> AnimationLibrary::_get_animation_list() const { + TypedArray<StringName> ret; + List<StringName> names; + get_animation_list(&names); + for (const StringName &K : names) { + ret.push_back(K); + } + return ret; +} + +void AnimationLibrary::get_animation_list(List<StringName> *p_animations) const { + List<StringName> anims; + + for (const KeyValue<StringName, Ref<Animation>> &E : animations) { + anims.push_back(E.key); + } + + anims.sort_custom<StringName::AlphCompare>(); + + for (const StringName &E : anims) { + p_animations->push_back(E); + } +} + +void AnimationLibrary::_set_data(const Dictionary &p_data) { + animations.clear(); + List<Variant> keys; + p_data.get_key_list(&keys); + for (const Variant &K : keys) { + add_animation(K, p_data[K]); + } +} + +Dictionary AnimationLibrary::_get_data() const { + Dictionary ret; + for (const KeyValue<StringName, Ref<Animation>> &K : animations) { + ret[K.key] = K.value; + } + return ret; +} + +void AnimationLibrary::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_animation", "name", "animation"), &AnimationLibrary::add_animation); + ClassDB::bind_method(D_METHOD("remove_animation", "name"), &AnimationLibrary::remove_animation); + ClassDB::bind_method(D_METHOD("rename_animation", "name", "newname"), &AnimationLibrary::rename_animation); + ClassDB::bind_method(D_METHOD("has_animation", "name"), &AnimationLibrary::has_animation); + ClassDB::bind_method(D_METHOD("get_animation", "name"), &AnimationLibrary::get_animation); + ClassDB::bind_method(D_METHOD("get_animation_list"), &AnimationLibrary::_get_animation_list); + + ClassDB::bind_method(D_METHOD("_set_data", "data"), &AnimationLibrary::_set_data); + ClassDB::bind_method(D_METHOD("_get_data"), &AnimationLibrary::_get_data); + + ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "_set_data", "_get_data"); + ADD_SIGNAL(MethodInfo("animation_added", PropertyInfo(Variant::OBJECT, "name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"))); + ADD_SIGNAL(MethodInfo("animation_removed", PropertyInfo(Variant::OBJECT, "name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"))); + ADD_SIGNAL(MethodInfo("animation_renamed", PropertyInfo(Variant::OBJECT, "name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"), PropertyInfo(Variant::OBJECT, "to_name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"))); +} +AnimationLibrary::AnimationLibrary() { +} diff --git a/scene/resources/animation_library.h b/scene/resources/animation_library.h new file mode 100644 index 0000000000..69ac5a97d2 --- /dev/null +++ b/scene/resources/animation_library.h @@ -0,0 +1,62 @@ +/*************************************************************************/ +/* animation_library.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef ANIMATION_LIBRARY_H +#define ANIMATION_LIBRARY_H + +#include "core/variant/typed_array.h" +#include "scene/resources/animation.h" + +class AnimationLibrary : public Resource { + GDCLASS(AnimationLibrary, Resource) + + void _set_data(const Dictionary &p_data); + Dictionary _get_data() const; + + TypedArray<StringName> _get_animation_list() const; + + friend class AnimationPlayer; //for faster access + Map<StringName, Ref<Animation>> animations; + +protected: + static void _bind_methods(); + +public: + Error add_animation(const StringName &p_name, const Ref<Animation> &p_animation); + void remove_animation(const StringName &p_name); + void rename_animation(const StringName &p_name, const StringName &p_new_name); + bool has_animation(const StringName &p_name) const; + Ref<Animation> get_animation(const StringName &p_name) const; + void get_animation_list(List<StringName> *p_animations) const; + + AnimationLibrary(); +}; + +#endif // ANIMATIONLIBRARY_H diff --git a/scene/resources/audio_stream_sample.cpp b/scene/resources/audio_stream_sample.cpp index 56786ac4b1..30c222bdff 100644 --- a/scene/resources/audio_stream_sample.cpp +++ b/scene/resources/audio_stream_sample.cpp @@ -556,9 +556,9 @@ Error AudioStreamSample::save_to_wav(const String &p_path) { file_path += ".wav"; } - FileAccessRef file = FileAccess::open(file_path, FileAccess::WRITE); //Overrides existing file if present + Ref<FileAccess> file = FileAccess::open(file_path, FileAccess::WRITE); //Overrides existing file if present - ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE); + ERR_FAIL_COND_V(file.is_null(), ERR_FILE_CANT_WRITE); // Create WAV Header file->store_string("RIFF"); //ChunkID @@ -596,8 +596,6 @@ Error AudioStreamSample::save_to_wav(const String &p_path) { break; } - file->close(); - return OK; } diff --git a/scene/resources/convex_polygon_shape_2d.cpp b/scene/resources/convex_polygon_shape_2d.cpp index 667399ee75..c416a03f38 100644 --- a/scene/resources/convex_polygon_shape_2d.cpp +++ b/scene/resources/convex_polygon_shape_2d.cpp @@ -82,7 +82,7 @@ void ConvexPolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) { if (is_collision_outline_enabled()) { RenderingServer::get_singleton()->canvas_item_add_polyline(p_to_rid, points, col); // Draw the last segment as it's not drawn by `canvas_item_add_polyline()`. - RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], p_color); + RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], p_color, 1.0, true); } } diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp index 78698835fc..d92d34437e 100644 --- a/scene/resources/environment.cpp +++ b/scene/resources/environment.cpp @@ -189,6 +189,7 @@ void Environment::_update_ambient_light() { void Environment::set_tonemapper(ToneMapper p_tone_mapper) { tone_mapper = p_tone_mapper; _update_tonemap(); + notify_property_list_changed(); } Environment::ToneMapper Environment::get_tonemapper() const { @@ -1049,6 +1050,10 @@ void Environment::_validate_property(PropertyInfo &property) const { } } + if (property.name == "tonemap_white" && tone_mapper == TONE_MAPPER_LINEAR) { + property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL; + } + if (property.name == "glow_intensity" && glow_blend_mode == GLOW_BLEND_MODE_MIX) { property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL; } @@ -1081,6 +1086,7 @@ void Environment::_validate_property(PropertyInfo &property) const { "auto_exposure_", "ssr_", "ssao_", + "ssil_", "sdfgi_", "glow_", "adjustment_", diff --git a/scene/resources/font.cpp b/scene/resources/font.cpp index 6e6ee7d3ac..efbe9c93f7 100644 --- a/scene/resources/font.cpp +++ b/scene/resources/font.cpp @@ -740,8 +740,8 @@ Error FontData::load_bitmap_font(const String &p_path) { hinting = TextServer::HINTING_NONE; oversampling = 1.0f; - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_CREATE, vformat(RTR("Cannot open font from file: %s."), p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_CREATE, vformat(RTR("Cannot open font from file: %s."), p_path)); int base_size = 16; int height = 0; diff --git a/scene/resources/importer_mesh.cpp b/scene/resources/importer_mesh.cpp index 30deb5ccd5..60a9200176 100644 --- a/scene/resources/importer_mesh.cpp +++ b/scene/resources/importer_mesh.cpp @@ -419,7 +419,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli continue; } - if (new_index_count <= 0 || (new_index_count >= (index_count * 0.75f))) { + if (new_index_count == 0 || (new_index_count >= (index_count * 0.75f))) { break; } @@ -521,7 +521,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli Vector3 normal = n0 * w + n1 * u + n2 * v; Vector2 orig_uv = ray_uvs[j]; - real_t orig_bary[3] = { 1.0f - orig_uv.x - orig_uv.y, orig_uv.x, orig_uv.y }; + const real_t orig_bary[3] = { 1.0f - orig_uv.x - orig_uv.y, orig_uv.x, orig_uv.y }; for (int k = 0; k < 3; k++) { int idx = orig_tri_id * 3 + k; real_t weight = orig_bary[k]; diff --git a/scene/resources/navigation_mesh.cpp b/scene/resources/navigation_mesh.cpp index 47a87bdea5..552fa84bad 100644 --- a/scene/resources/navigation_mesh.cpp +++ b/scene/resources/navigation_mesh.cpp @@ -388,6 +388,10 @@ Ref<Mesh> NavigationMesh::get_debug_mesh() { debug_mesh = Ref<ArrayMesh>(memnew(ArrayMesh)); + if (!lines.size()) { + return debug_mesh; + } + Array arr; arr.resize(Mesh::ARRAY_MAX); arr[Mesh::ARRAY_VERTEX] = varr; diff --git a/scene/resources/primitive_meshes.cpp b/scene/resources/primitive_meshes.cpp index 781e219f1f..40edc5f198 100644 --- a/scene/resources/primitive_meshes.cpp +++ b/scene/resources/primitive_meshes.cpp @@ -270,6 +270,10 @@ PrimitiveMesh::~PrimitiveMesh() { */ void CapsuleMesh::_create_mesh_array(Array &p_arr) const { + create_mesh_array(p_arr, radius, height, radial_segments, rings); +} + +void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const float height, const int radial_segments, const int rings) { int i, j, prevrow, thisrow, point; float x, y, z, u, v, w; float onethird = 1.0 / 3.0; @@ -481,6 +485,10 @@ CapsuleMesh::CapsuleMesh() {} */ void BoxMesh::_create_mesh_array(Array &p_arr) const { + BoxMesh::create_mesh_array(p_arr, size, subdivide_w, subdivide_h, subdivide_d); +} + +void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int subdivide_h, int subdivide_d) { int i, j, prevrow, thisrow, point; float x, y, z; float onethird = 1.0 / 3.0; @@ -732,6 +740,10 @@ BoxMesh::BoxMesh() {} */ void CylinderMesh::_create_mesh_array(Array &p_arr) const { + create_mesh_array(p_arr, top_radius, bottom_radius, height, radial_segments, rings); +} + +void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments, int rings) { int i, j, prevrow, thisrow, point; float x, y, z, u, v, radius; @@ -1431,6 +1443,10 @@ Vector3 QuadMesh::get_center_offset() const { */ void SphereMesh::_create_mesh_array(Array &p_arr) const { + create_mesh_array(p_arr, radius, height, radial_segments, rings, is_hemisphere); +} + +void SphereMesh::create_mesh_array(Array &p_arr, float radius, float height, int radial_segments, int rings, bool is_hemisphere) { int i, j, prevrow, thisrow, point; float x, y, z; diff --git a/scene/resources/primitive_meshes.h b/scene/resources/primitive_meshes.h index eef5eb3f7d..8cd05c1740 100644 --- a/scene/resources/primitive_meshes.h +++ b/scene/resources/primitive_meshes.h @@ -117,6 +117,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 8); + void set_radius(const float p_radius); float get_radius() const; @@ -149,6 +151,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w = 0, int subdivide_h = 0, int subdivide_d = 0); + void set_size(const Vector3 &p_size); Vector3 get_size() const; @@ -183,6 +187,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments = 64, int rings = 4); + void set_top_radius(const float p_radius); float get_top_radius() const; @@ -314,6 +320,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 32, bool is_hemisphere = false); + void set_radius(const float p_radius); float get_radius() const; diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp index fd6f018651..4b0456681b 100644 --- a/scene/resources/resource_format_text.cpp +++ b/scene/resources/resource_format_text.cpp @@ -738,11 +738,7 @@ void ResourceLoaderText::set_translation_remapped(bool p_remapped) { ResourceLoaderText::ResourceLoaderText() {} -ResourceLoaderText::~ResourceLoaderText() { - memdelete(f); -} - -void ResourceLoaderText::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) { +void ResourceLoaderText::get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types) { open(p_f); ignore_resource_parsing = true; ERR_FAIL_COND(error != OK); @@ -798,13 +794,13 @@ void ResourceLoaderText::get_dependencies(FileAccess *p_f, List<String> *p_depen } } -Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map) { +Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const Map<String, String> &p_map) { open(p_f, true); ERR_FAIL_COND_V(error != OK, error); ignore_resource_parsing = true; //FileAccess - FileAccess *fw = nullptr; + Ref<FileAccess> fw; String base_path = local_path.get_base_dir(); @@ -814,23 +810,20 @@ Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_p Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); if (err != OK) { - if (fw) { - memdelete(fw); - } error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } if (next_tag.name != "ext_resource") { //nothing was done - if (!fw) { + if (fw.is_null()) { return OK; } break; } else { - if (!fw) { + if (fw.is_null()) { fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); if (is_scene) { fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n"); @@ -840,7 +833,6 @@ Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_p } if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) { - memdelete(fw); error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } @@ -898,24 +890,22 @@ Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_p fw->store_8(c); c = f->get_8(); } - f->close(); + f.unref(); bool all_ok = fw->get_error() == OK; - memdelete(fw); - if (!all_ok) { return ERR_CANT_CREATE; } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(p_path); da->rename(p_path + ".depren", p_path); return OK; } -void ResourceLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) { +void ResourceLoaderText::open(Ref<FileAccess> p_f, bool p_skip_first_tag) { error = OK; lines = 1; @@ -992,23 +982,23 @@ void ResourceLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) { rp.userdata = this; } -static void bs_save_unicode_string(FileAccess *f, const String &p_string, bool p_bit_on_len = false) { +static void bs_save_unicode_string(Ref<FileAccess> p_f, const String &p_string, bool p_bit_on_len = false) { CharString utf8 = p_string.utf8(); if (p_bit_on_len) { - f->store_32((utf8.length() + 1) | 0x80000000); + p_f->store_32((utf8.length() + 1) | 0x80000000); } else { - f->store_32(utf8.length() + 1); + p_f->store_32(utf8.length() + 1); } - f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); + p_f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } -Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) { +Error ResourceLoaderText::save_as_binary(Ref<FileAccess> p_f, const String &p_path) { if (error) { return error; } - FileAccessRef wf = FileAccess::open(p_path, FileAccess::WRITE); - if (!wf) { + Ref<FileAccess> wf = FileAccess::open(p_path, FileAccess::WRITE); + if (wf.is_null()) { return ERR_CANT_OPEN; } @@ -1023,7 +1013,7 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) static const int save_format_version = 3; //use format version 3 for saving wf->store_32(save_format_version); - bs_save_unicode_string(wf.f, is_scene ? "PackedScene" : resource_type); + bs_save_unicode_string(wf, is_scene ? "PackedScene" : resource_type); wf->store_64(0); //offset to import metadata, this is no longer used wf->store_32(ResourceFormatSaverBinaryInstance::FORMAT_FLAG_NAMED_SCENE_IDS | ResourceFormatSaverBinaryInstance::FORMAT_FLAG_UIDS); @@ -1078,8 +1068,8 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) uid = ResourceUID::get_singleton()->text_to_id(uidt); } - bs_save_unicode_string(wf.f, type); - bs_save_unicode_string(wf.f, path); + bs_save_unicode_string(wf, type); + bs_save_unicode_string(wf, path); wf->store_64(uid); int lindex = dummy_read.external_resources.size(); @@ -1108,146 +1098,145 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) wf->store_32(0); //zero sub resources, still parsing them String temp_file = p_path + ".temp"; - FileAccessRef wf2 = FileAccess::open(temp_file, FileAccess::WRITE); - if (!wf2) { - return ERR_CANT_OPEN; - } - Vector<uint64_t> local_offsets; Vector<uint64_t> local_pointers_pos; + { + Ref<FileAccess> wf2 = FileAccess::open(temp_file, FileAccess::WRITE); + if (wf2.is_null()) { + return ERR_CANT_OPEN; + } - while (next_tag.name == "sub_resource" || next_tag.name == "resource") { - String type; - int id = -1; - bool main_res; + while (next_tag.name == "sub_resource" || next_tag.name == "resource") { + String type; + int id = -1; + bool main_res; - if (next_tag.name == "sub_resource") { - if (!next_tag.fields.has("type")) { - error = ERR_FILE_CORRUPT; - error_text = "Missing 'type' in external resource tag"; - _printerr(); - return error; - } + if (next_tag.name == "sub_resource") { + if (!next_tag.fields.has("type")) { + error = ERR_FILE_CORRUPT; + error_text = "Missing 'type' in external resource tag"; + _printerr(); + return error; + } - if (!next_tag.fields.has("id")) { - error = ERR_FILE_CORRUPT; - error_text = "Missing 'id' in external resource tag"; - _printerr(); - return error; + if (!next_tag.fields.has("id")) { + error = ERR_FILE_CORRUPT; + error_text = "Missing 'id' in external resource tag"; + _printerr(); + return error; + } + + type = next_tag.fields["type"]; + id = next_tag.fields["id"]; + main_res = false; + } else { + type = res_type; + id = 0; //used for last anyway + main_res = true; } - type = next_tag.fields["type"]; - id = next_tag.fields["id"]; - main_res = false; - } else { - type = res_type; - id = 0; //used for last anyway - main_res = true; - } + local_offsets.push_back(wf2->get_position()); - local_offsets.push_back(wf2->get_position()); + bs_save_unicode_string(wf, "local://" + itos(id)); + local_pointers_pos.push_back(wf->get_position()); + wf->store_64(0); //temp local offset - bs_save_unicode_string(wf, "local://" + itos(id)); - local_pointers_pos.push_back(wf->get_position()); - wf->store_64(0); //temp local offset + bs_save_unicode_string(wf2, type); + uint64_t propcount_ofs = wf2->get_position(); + wf2->store_32(0); - bs_save_unicode_string(wf2, type); - uint64_t propcount_ofs = wf2->get_position(); - wf2->store_32(0); + int prop_count = 0; - int prop_count = 0; + while (true) { + String assign; + Variant value; - while (true) { - String assign; - Variant value; + error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp); - error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp); + if (error) { + if (main_res && error == ERR_FILE_EOF) { + next_tag.name = ""; //exit + break; + } - if (error) { - if (main_res && error == ERR_FILE_EOF) { - next_tag.name = ""; //exit - break; + _printerr(); + return error; } - _printerr(); - return error; + if (!assign.is_empty()) { + Map<StringName, int> empty_string_map; //unused + bs_save_unicode_string(wf2, assign, true); + ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); + prop_count++; + + } else if (!next_tag.name.is_empty()) { + error = OK; + break; + } else { + error = ERR_FILE_CORRUPT; + error_text = "Premature end of file while parsing [sub_resource]"; + _printerr(); + return error; + } } - if (!assign.is_empty()) { - Map<StringName, int> empty_string_map; //unused - bs_save_unicode_string(wf2, assign, true); - ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); - prop_count++; + wf2->seek(propcount_ofs); + wf2->store_32(prop_count); + wf2->seek_end(); + } - } else if (!next_tag.name.is_empty()) { - error = OK; - break; - } else { - error = ERR_FILE_CORRUPT; - error_text = "Premature end of file while parsing [sub_resource]"; + if (next_tag.name == "node") { + //this is a node, must save one more! + + if (!is_scene) { + error_text += "found the 'node' tag on a resource file!"; _printerr(); + error = ERR_FILE_CORRUPT; return error; } - } - - wf2->seek(propcount_ofs); - wf2->store_32(prop_count); - wf2->seek_end(); - } - if (next_tag.name == "node") { - //this is a node, must save one more! + Ref<PackedScene> packed_scene = _parse_node_tag(rp); - if (!is_scene) { - error_text += "found the 'node' tag on a resource file!"; - _printerr(); - error = ERR_FILE_CORRUPT; - return error; - } + if (!packed_scene.is_valid()) { + return error; + } - Ref<PackedScene> packed_scene = _parse_node_tag(rp); + error = OK; + //get it here + List<PropertyInfo> props; + packed_scene->get_property_list(&props); - if (!packed_scene.is_valid()) { - return error; - } + bs_save_unicode_string(wf, "local://0"); + local_pointers_pos.push_back(wf->get_position()); + wf->store_64(0); //temp local offset - error = OK; - //get it here - List<PropertyInfo> props; - packed_scene->get_property_list(&props); + local_offsets.push_back(wf2->get_position()); + bs_save_unicode_string(wf2, "PackedScene"); + uint64_t propcount_ofs = wf2->get_position(); + wf2->store_32(0); - bs_save_unicode_string(wf, "local://0"); - local_pointers_pos.push_back(wf->get_position()); - wf->store_64(0); //temp local offset + int prop_count = 0; - local_offsets.push_back(wf2->get_position()); - bs_save_unicode_string(wf2, "PackedScene"); - uint64_t propcount_ofs = wf2->get_position(); - wf2->store_32(0); + for (const PropertyInfo &E : props) { + if (!(E.usage & PROPERTY_USAGE_STORAGE)) { + continue; + } - int prop_count = 0; + String name = E.name; + Variant value = packed_scene->get(name); - for (const PropertyInfo &E : props) { - if (!(E.usage & PROPERTY_USAGE_STORAGE)) { - continue; + Map<StringName, int> empty_string_map; //unused + bs_save_unicode_string(wf2, name, true); + ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); + prop_count++; } - String name = E.name; - Variant value = packed_scene->get(name); - - Map<StringName, int> empty_string_map; //unused - bs_save_unicode_string(wf2, name, true); - ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); - prop_count++; + wf2->seek(propcount_ofs); + wf2->store_32(prop_count); + wf2->seek_end(); } - - wf2->seek(propcount_ofs); - wf2->store_32(prop_count); - wf2->seek_end(); } - wf2->close(); - uint64_t offset_from = wf->get_position(); wf->seek(sub_res_count_pos); //plus one because the saved one wf->store_32(local_offsets.size()); @@ -1262,18 +1251,16 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) Vector<uint8_t> data = FileAccess::get_file_as_array(temp_file); wf->store_buffer(data.ptr(), data.size()); { - DirAccessRef dar = DirAccess::open(temp_file.get_base_dir()); + Ref<DirAccess> dar = DirAccess::open(temp_file.get_base_dir()); dar->remove(temp_file); } wf->store_buffer((const uint8_t *)"RSRC", 4); //magic at end - wf->close(); - return OK; } -String ResourceLoaderText::recognize(FileAccess *p_f) { +String ResourceLoaderText::recognize(Ref<FileAccess> p_f) { error = OK; lines = 1; @@ -1317,7 +1304,7 @@ String ResourceLoaderText::recognize(FileAccess *p_f) { return tag.fields["type"]; } -ResourceUID::ID ResourceLoaderText::get_uid(FileAccess *p_f) { +ResourceUID::ID ResourceLoaderText::get_uid(Ref<FileAccess> p_f) { error = OK; lines = 1; @@ -1352,7 +1339,7 @@ RES ResourceFormatLoaderText::load(const String &p_path, const String &p_origina Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot open file '" + p_path + "'."); @@ -1407,8 +1394,8 @@ String ResourceFormatLoaderText::get_resource_type(const String &p_path) const { // ...for anything else must test... - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { return ""; //could not read } @@ -1426,8 +1413,8 @@ ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) return ResourceUID::INVALID_ID; } - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { return ResourceUID::INVALID_ID; //could not read } @@ -1438,8 +1425,8 @@ ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) } void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { ERR_FAIL(); } @@ -1450,8 +1437,8 @@ void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<Strin } Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { ERR_FAIL_V(ERR_CANT_OPEN); } @@ -1465,7 +1452,7 @@ ResourceFormatLoaderText *ResourceFormatLoaderText::singleton = nullptr; Error ResourceFormatLoaderText::convert_file_to_binary(const String &p_src_path, const String &p_dst_path) { Error err; - FileAccess *f = FileAccess::open(p_src_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_src_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_OPEN, "Cannot open file '" + p_src_path + "'."); @@ -1489,7 +1476,7 @@ Error ResourceFormatLoaderText::convert_file_to_binary(const String &p_src_path, /*****************************************************************************************************/ String ResourceFormatSaverTextInstance::_write_resources(void *ud, const RES &p_resource) { - ResourceFormatSaverTextInstance *rsi = (ResourceFormatSaverTextInstance *)ud; + ResourceFormatSaverTextInstance *rsi = static_cast<ResourceFormatSaverTextInstance *>(ud); return rsi->_write_resource(p_resource); } @@ -1603,9 +1590,9 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_r } Error err; - f = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err, ERR_CANT_OPEN, "Cannot save file '" + p_path + "'."); - FileAccessRef _fref(f); + Ref<FileAccess> _fref(f); local_path = ProjectSettings::get_singleton()->localize_path(p_path); @@ -1942,12 +1929,9 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_r } if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { - f->close(); return ERR_CANT_CREATE; } - f->close(); - return OK; } diff --git a/scene/resources/resource_format_text.h b/scene/resources/resource_format_text.h index 9585b9040f..c6543e616d 100644 --- a/scene/resources/resource_format_text.h +++ b/scene/resources/resource_format_text.h @@ -43,7 +43,7 @@ class ResourceLoaderText { String res_path; String error_text; - FileAccess *f = nullptr; + Ref<FileAccess> f; VariantParser::StreamFile stream; @@ -96,8 +96,8 @@ class ResourceLoaderText { Map<String, RES> resource_map; }; - static Error _parse_sub_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_sub_resource_dummy((DummyReadData *)(p_self), p_stream, r_res, line, r_err_str); } - static Error _parse_ext_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_ext_resource_dummy((DummyReadData *)(p_self), p_stream, r_res, line, r_err_str); } + static Error _parse_sub_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_sub_resource_dummy(static_cast<DummyReadData *>(p_self), p_stream, r_res, line, r_err_str); } + static Error _parse_ext_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_ext_resource_dummy(static_cast<DummyReadData *>(p_self), p_stream, r_res, line, r_err_str); } static Error _parse_sub_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str); static Error _parse_ext_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str); @@ -120,15 +120,14 @@ public: int get_stage_count() const; void set_translation_remapped(bool p_remapped); - void open(FileAccess *p_f, bool p_skip_first_tag = false); - String recognize(FileAccess *p_f); - ResourceUID::ID get_uid(FileAccess *p_f); - void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types); - Error rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map); + void open(Ref<FileAccess> p_f, bool p_skip_first_tag = false); + String recognize(Ref<FileAccess> p_f); + ResourceUID::ID get_uid(Ref<FileAccess> p_f); + void get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types); + Error rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const Map<String, String> &p_map); - Error save_as_binary(FileAccess *p_f, const String &p_path); + Error save_as_binary(Ref<FileAccess> p_f, const String &p_path); ResourceLoaderText(); - ~ResourceLoaderText(); }; class ResourceFormatLoaderText : public ResourceFormatLoader { @@ -157,7 +156,6 @@ class ResourceFormatSaverTextInstance { bool relative_paths = false; bool bundle_resources = false; bool skip_editor = false; - FileAccess *f = nullptr; struct NonPersistentKey { //for resource properties generated on the fly RES base; diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp index ce7fcb199d..25a9278e66 100644 --- a/scene/resources/shader.cpp +++ b/scene/resources/shader.cpp @@ -217,17 +217,14 @@ Error ResourceFormatSaverShader::save(const String &p_path, const RES &p_resourc String source = shader->get_code(); Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err, err, "Cannot save shader '" + p_path + "'."); file->store_string(source); if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { - memdelete(file); return ERR_CANT_CREATE; } - file->close(); - memdelete(file); return OK; } diff --git a/scene/resources/skeleton_modification_2d.h b/scene/resources/skeleton_modification_2d.h index d49f9e7f51..3b9235ffd8 100644 --- a/scene/resources/skeleton_modification_2d.h +++ b/scene/resources/skeleton_modification_2d.h @@ -49,7 +49,7 @@ class SkeletonModification2D : public Resource { protected: static void _bind_methods(); - SkeletonModificationStack2D *stack; + SkeletonModificationStack2D *stack = nullptr; int execution_mode = 0; // 0 = process bool enabled = true; diff --git a/scene/resources/skeleton_modification_3d.h b/scene/resources/skeleton_modification_3d.h index a81c0c38bd..ab736fcbd2 100644 --- a/scene/resources/skeleton_modification_3d.h +++ b/scene/resources/skeleton_modification_3d.h @@ -44,7 +44,7 @@ class SkeletonModification3D : public Resource { protected: static void _bind_methods(); - SkeletonModificationStack3D *stack; + SkeletonModificationStack3D *stack = nullptr; int execution_mode = 0; // 0 = process bool enabled = true; diff --git a/scene/resources/sky_material.cpp b/scene/resources/sky_material.cpp index 54543782f6..4681d3d6e3 100644 --- a/scene/resources/sky_material.cpp +++ b/scene/resources/sky_material.cpp @@ -404,8 +404,11 @@ void PanoramaSkyMaterial::_update_shader() { // Add a comment to describe the shader origin (useful when converting to ShaderMaterial). RS::get_singleton()->shader_set_code(shader_cache[i], vformat(R"( // NOTE: Shader automatically converted from )" VERSION_NAME " " VERSION_FULL_CONFIG R"('s PanoramaSkyMaterial. + shader_type sky; -uniform sampler2D source_panorama : %s, hint_albedo; + +uniform sampler2D source_panorama : %s, hint_black_albedo; + void sky() { COLOR = texture(source_panorama, SKY_COORDS).rgb; } diff --git a/scene/resources/text_file.cpp b/scene/resources/text_file.cpp index cbfee754e2..96a47c37c4 100644 --- a/scene/resources/text_file.cpp +++ b/scene/resources/text_file.cpp @@ -51,7 +51,7 @@ void TextFile::reload_from_file() { Error TextFile::load_text(const String &p_path) { Vector<uint8_t> sourcef; Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err, err, "Cannot open TextFile '" + p_path + "'."); @@ -59,8 +59,7 @@ Error TextFile::load_text(const String &p_path) { sourcef.resize(len + 1); uint8_t *w = sourcef.ptrw(); uint64_t r = f->get_buffer(w, len); - f->close(); - memdelete(f); + ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); w[len] = 0; diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp index a66d9d9f27..4c20e07976 100644 --- a/scene/resources/texture.cpp +++ b/scene/resources/texture.cpp @@ -646,7 +646,7 @@ PortableCompressedTexture2D::~PortableCompressedTexture2D() { ////////////////////////////////////////// -Ref<Image> CompressedTexture2D::load_image_from_file(FileAccess *f, int p_size_limit) { +Ref<Image> CompressedTexture2D::load_image_from_file(Ref<FileAccess> f, int p_size_limit) { uint32_t data_format = f->get_32(); uint32_t w = f->get_16(); uint32_t h = f->get_16(); @@ -821,20 +821,18 @@ Error CompressedTexture2D::_load_data(const String &p_path, int &r_width, int &r ERR_FAIL_COND_V(image.is_null(), ERR_INVALID_PARAMETER); - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); uint8_t header[4]; f->get_buffer(header, 4); if (header[0] != 'G' || header[1] != 'S' || header[2] != 'T' || header[3] != '2') { - memdelete(f); ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Compressed texture file is corrupt (Bad header)."); } uint32_t version = f->get_32(); if (version > FORMAT_VERSION) { - memdelete(f); ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Compressed texture file is too new."); } r_width = f->get_32(); @@ -867,8 +865,6 @@ Error CompressedTexture2D::_load_data(const String &p_path, int &r_width, int &r image = load_image_from_file(f, p_size_limit); - memdelete(f); - if (image.is_null() || image->is_empty()) { return ERR_CANT_OPEN; } @@ -1142,7 +1138,7 @@ bool Texture3D::has_mipmaps() const { if (GDVIRTUAL_REQUIRED_CALL(_has_mipmaps, ret)) { return ret; } - return 0; + return false; } Vector<Ref<Image>> Texture3D::get_data() const { @@ -1272,8 +1268,8 @@ Image::Format CompressedTexture3D::get_format() const { } Error CompressedTexture3D::_load_data(const String &p_path, Vector<Ref<Image>> &r_data, Image::Format &r_format, int &r_width, int &r_height, int &r_depth, bool &r_mipmaps) { - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); uint8_t header[4]; f->get_buffer(header, 4); @@ -3092,8 +3088,8 @@ Image::Format CompressedTextureLayered::get_format() const { Error CompressedTextureLayered::_load_data(const String &p_path, Vector<Ref<Image>> &images, int &mipmap_limit, int p_size_limit) { ERR_FAIL_COND_V(images.size() != 0, ERR_INVALID_PARAMETER); - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); uint8_t header[4]; f->get_buffer(header, 4); diff --git a/scene/resources/texture.h b/scene/resources/texture.h index 7e194fd21d..525e3ff979 100644 --- a/scene/resources/texture.h +++ b/scene/resources/texture.h @@ -253,7 +253,7 @@ protected: void _validate_property(PropertyInfo &property) const override; public: - static Ref<Image> load_image_from_file(FileAccess *p_file, int p_size_limit); + static Ref<Image> load_image_from_file(Ref<FileAccess> p_file, int p_size_limit); typedef void (*TextureFormatRequestCallback)(const Ref<CompressedTexture2D> &); typedef void (*TextureFormatRoughnessRequestCallback)(const Ref<CompressedTexture2D> &, const String &p_normal_path, RS::TextureDetectRoughnessChannel p_roughness_channel); |