summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/core_constants.cpp3
-rw-r--r--core/object/callable_method_pointer.h8
-rw-r--r--core/object/class_db.cpp3
-rw-r--r--core/string/string_name.h12
-rw-r--r--core/string/translation.cpp1
-rw-r--r--core/variant/callable.cpp9
-rw-r--r--core/variant/callable.h1
-rw-r--r--core/variant/callable_bind.cpp14
-rw-r--r--core/variant/callable_bind.h2
-rw-r--r--core/variant/variant_call.cpp3
-rw-r--r--core/variant/variant_op.cpp5
-rw-r--r--doc/classes/@GlobalScope.xml6
-rw-r--r--doc/classes/Color.xml33
-rw-r--r--doc/classes/JavaScript.xml22
-rw-r--r--doc/classes/Mesh.xml2
-rw-r--r--doc/classes/Panel.xml10
-rw-r--r--doc/classes/PopupMenu.xml7
-rw-r--r--doc/classes/RID.xml6
-rw-r--r--doc/classes/RenderingServer.xml2
-rw-r--r--doc/classes/String.xml16
-rw-r--r--doc/classes/StringName.xml24
-rw-r--r--doc/classes/TranslationServer.xml7
-rw-r--r--doc/classes/Tree.xml1
-rw-r--r--doc/classes/Vector3i.xml1
-rw-r--r--doc/classes/VisualShaderNodeParticleRandomness.xml10
-rw-r--r--doc/classes/int.xml7
-rw-r--r--editor/create_dialog.cpp18
-rw-r--r--editor/create_dialog.h2
-rw-r--r--editor/debugger/editor_debugger_node.cpp2
-rw-r--r--editor/editor_autoload_settings.cpp16
-rw-r--r--editor/editor_data.cpp30
-rw-r--r--editor/editor_data.h2
-rw-r--r--editor/editor_feature_profile.cpp10
-rw-r--r--editor/editor_help_search.cpp5
-rw-r--r--editor/editor_inspector.cpp14
-rw-r--r--editor/editor_node.cpp21
-rw-r--r--editor/editor_resource_picker.cpp18
-rw-r--r--editor/editor_settings_dialog.cpp16
-rw-r--r--editor/editor_themes.cpp2
-rw-r--r--editor/editor_toaster.cpp30
-rw-r--r--editor/filesystem_dock.cpp85
-rw-r--r--editor/import/dynamicfont_import_settings.cpp68
-rw-r--r--editor/plugins/animation_blend_tree_editor_plugin.cpp2
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp41
-rw-r--r--editor/plugins/editor_preview_plugins.cpp6
-rw-r--r--editor/plugins/node_3d_editor_plugin.cpp1091
-rw-r--r--editor/plugins/node_3d_editor_plugin.h93
-rw-r--r--editor/plugins/packed_scene_translation_parser_plugin.cpp9
-rw-r--r--editor/plugins/packed_scene_translation_parser_plugin.h4
-rw-r--r--editor/plugins/replication_editor_plugin.cpp4
-rw-r--r--editor/plugins/script_editor_plugin.cpp4
-rw-r--r--editor/plugins/script_text_editor.cpp15
-rw-r--r--editor/plugins/text_control_editor_plugin.cpp156
-rw-r--r--editor/plugins/visual_shader_editor_plugin.cpp10
-rw-r--r--editor/project_export.cpp2
-rw-r--r--editor/project_export.h2
-rw-r--r--editor/property_editor.cpp6
-rw-r--r--editor/property_selector.cpp9
-rw-r--r--editor/scene_tree_dock.cpp14
-rw-r--r--main/main.cpp19
-rw-r--r--misc/dist/html/editor.html36
-rw-r--r--misc/dist/html/service-worker.js112
-rw-r--r--modules/SCsub45
-rw-r--r--modules/camera/camera_osx.h1
-rw-r--r--modules/camera/camera_osx.mm27
-rw-r--r--modules/csg/doc_classes/CSGBox3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGCombiner3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGCylinder3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGMesh3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGPolygon3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGPrimitive3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGShape3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGSphere3D.xml2
-rw-r--r--modules/csg/doc_classes/CSGTorus3D.xml2
-rw-r--r--modules/gdnative/nativescript/nativescript.cpp2
-rw-r--r--modules/gdnative/pluginscript/pluginscript_script.cpp2
-rw-r--r--modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd4
-rw-r--r--modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd4
-rw-r--r--modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd3
-rw-r--r--modules/gdscript/gdscript.cpp9
-rw-r--r--modules/gdscript/gdscript_analyzer.cpp14
-rw-r--r--modules/gdscript/gdscript_editor.cpp16
-rw-r--r--modules/gdscript/gdscript_parser.cpp8
-rw-r--r--modules/gdscript/gdscript_rpc_callable.cpp86
-rw-r--r--modules/gdscript/gdscript_rpc_callable.h61
-rw-r--r--modules/gdscript/tests/gdscript_test_runner.cpp18
-rw-r--r--modules/gridmap/grid_map.cpp1
-rw-r--r--modules/modules_builders.py7
-rw-r--r--modules/mono/editor_templates/CharacterBody2D/basic_movement.cs4
-rw-r--r--modules/mono/editor_templates/CharacterBody3D/basic_movement.cs4
-rw-r--r--modules/mono/editor_templates/VisualShaderNodeCustom/basic.cs5
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs47
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs24
-rw-r--r--modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs25
-rw-r--r--modules/visual_script/editor/visual_script_editor.cpp1
-rw-r--r--modules/visual_script/editor/visual_script_property_selector.cpp4
-rw-r--r--modules/visual_script/visual_script.cpp3
-rw-r--r--modules/visual_script/visual_script_nodes.cpp10
-rw-r--r--platform/javascript/api/api.cpp9
-rw-r--r--platform/javascript/api/javascript_singleton.h2
-rw-r--r--platform/javascript/export/export_plugin.cpp52
-rw-r--r--platform/javascript/godot_js.h2
-rw-r--r--platform/javascript/javascript_singleton.cpp8
-rw-r--r--platform/javascript/js/engine/config.js8
-rw-r--r--platform/javascript/js/engine/engine.js3
-rw-r--r--platform/javascript/js/libs/library_godot_os.js55
-rw-r--r--platform/javascript/os_javascript.cpp16
-rw-r--r--platform/javascript/os_javascript.h5
-rw-r--r--platform/linuxbsd/display_server_x11.cpp2
-rw-r--r--platform/linuxbsd/joypad_linux.cpp5
-rw-r--r--platform/osx/SCsub11
-rw-r--r--platform/osx/detect.py10
-rw-r--r--platform/osx/display_server_osx.h143
-rw-r--r--platform/osx/display_server_osx.mm2772
-rw-r--r--platform/osx/gl_manager_osx_legacy.h (renamed from platform/osx/gl_manager_osx.h)39
-rw-r--r--platform/osx/gl_manager_osx_legacy.mm (renamed from platform/osx/gl_manager_osx.mm)121
-rw-r--r--platform/osx/godot_application.h42
-rw-r--r--platform/osx/godot_application.mm53
-rw-r--r--platform/osx/godot_application_delegate.h45
-rw-r--r--platform/osx/godot_application_delegate.mm132
-rw-r--r--platform/osx/godot_content_view.h65
-rw-r--r--platform/osx/godot_content_view.mm760
-rw-r--r--platform/osx/godot_main_osx.mm23
-rw-r--r--platform/osx/godot_menu_item.h52
-rw-r--r--platform/osx/godot_window.h47
-rw-r--r--platform/osx/godot_window.mm69
-rw-r--r--platform/osx/godot_window_delegate.h47
-rw-r--r--platform/osx/godot_window_delegate.mm254
-rw-r--r--platform/osx/joypad_osx.cpp12
-rw-r--r--platform/osx/joypad_osx.h2
-rw-r--r--platform/osx/key_mapping_osx.h52
-rw-r--r--platform/osx/key_mapping_osx.mm477
-rw-r--r--platform/osx/os_osx.h27
-rw-r--r--platform/osx/os_osx.mm438
-rw-r--r--platform/osx/osx_terminal_logger.h44
-rw-r--r--platform/osx/osx_terminal_logger.mm81
-rw-r--r--platform/osx/vulkan_context_osx.mm2
-rw-r--r--platform/windows/display_server_windows.cpp16
-rw-r--r--scene/2d/navigation_region_2d.cpp8
-rw-r--r--scene/2d/navigation_region_2d.h4
-rw-r--r--scene/2d/ray_cast_2d.cpp7
-rw-r--r--scene/3d/ray_cast_3d.cpp7
-rw-r--r--scene/gui/option_button.cpp44
-rw-r--r--scene/gui/panel.cpp23
-rw-r--r--scene/gui/panel.h15
-rw-r--r--scene/gui/popup_menu.cpp50
-rw-r--r--scene/gui/popup_menu.h3
-rw-r--r--scene/gui/tab_bar.cpp3
-rw-r--r--scene/gui/tree.cpp28
-rw-r--r--scene/gui/tree.h2
-rw-r--r--scene/resources/resource_format_text.cpp10
-rw-r--r--scene/resources/tile_set.cpp2
-rw-r--r--scene/resources/visual_shader.cpp14
-rw-r--r--scene/resources/visual_shader.h4
-rw-r--r--scene/resources/visual_shader_nodes.cpp2
-rw-r--r--scene/resources/visual_shader_nodes.h2
-rw-r--r--scene/resources/visual_shader_particle_nodes.cpp167
-rw-r--r--scene/resources/visual_shader_particle_nodes.h14
-rw-r--r--scene/resources/visual_shader_sdf_nodes.cpp32
-rw-r--r--servers/rendering_server.cpp2
-rw-r--r--servers/rendering_server.h2
-rw-r--r--tests/scene/test_animation.h314
-rw-r--r--tests/test_main.cpp1
163 files changed, 5667 insertions, 3738 deletions
diff --git a/core/core_constants.cpp b/core/core_constants.cpp
index 2f5fd05e6a..63e7323f7a 100644
--- a/core/core_constants.cpp
+++ b/core/core_constants.cpp
@@ -165,6 +165,9 @@ void register_global_constants() {
BIND_CORE_ENUM_CONSTANT(INLINE_ALIGNMENT_CENTER);
BIND_CORE_ENUM_CONSTANT(INLINE_ALIGNMENT_BOTTOM);
+ BIND_CORE_ENUM_CONSTANT(INLINE_ALIGNMENT_IMAGE_MASK);
+ BIND_CORE_ENUM_CONSTANT(INLINE_ALIGNMENT_TEXT_MASK);
+
BIND_CORE_ENUM_CLASS_CONSTANT(Key, KEY, SPECIAL);
BIND_CORE_ENUM_CLASS_CONSTANT(Key, KEY, ESCAPE);
BIND_CORE_ENUM_CLASS_CONSTANT(Key, KEY, TAB);
diff --git a/core/object/callable_method_pointer.h b/core/object/callable_method_pointer.h
index 53410a9acf..3cd9ad3819 100644
--- a/core/object/callable_method_pointer.h
+++ b/core/object/callable_method_pointer.h
@@ -51,6 +51,14 @@ protected:
void _setup(uint32_t *p_base_ptr, uint32_t p_ptr_size);
public:
+ virtual StringName get_method() const {
+#ifdef DEBUG_METHODS_ENABLED
+ return StringName(text);
+#else
+ return StringName();
+#endif
+ }
+
#ifdef DEBUG_METHODS_ENABLED
void set_text(const char *p_text) {
text = p_text;
diff --git a/core/object/class_db.cpp b/core/object/class_db.cpp
index 72a98ca20c..3df4db9c5e 100644
--- a/core/object/class_db.cpp
+++ b/core/object/class_db.cpp
@@ -1632,7 +1632,8 @@ Variant ClassDB::class_get_default_property_value(const StringName &p_class, con
// Some properties may have an instantiated Object as default value,
// (like Path2D's `curve` used to have), but that's not a good practice.
// Instead, those properties should use PROPERTY_USAGE_EDITOR_INSTANTIATE_OBJECT
- // to be auto-instantiated when created in the editor.
+ // to be auto-instantiated when created in the editor with the following method:
+ // EditorNode::get_editor_data().instantiate_object_properties(obj);
if (var.get_type() == Variant::OBJECT) {
Object *obj = var.get_validated_object();
if (obj) {
diff --git a/core/string/string_name.h b/core/string/string_name.h
index 9653d2b4cf..f767f3e1ec 100644
--- a/core/string/string_name.h
+++ b/core/string/string_name.h
@@ -181,6 +181,18 @@ bool operator!=(const char *p_name, const StringName &p_string_name);
StringName _scs_create(const char *p_chr, bool p_static = false);
+/*
+ * The SNAME macro is used to speed up StringName creation, as it allows caching it after the first usage in a very efficient way.
+ * It should NOT be used everywhere, but instead in places where high performance is required and the creation of a StringName
+ * can be costly. Places where it should be used are:
+ * - Control::get_theme_*(<name> and Window::get_theme_*(<name> functions.
+ * - emit_signal(<name>,..) function
+ * - call_deferred(<name>,..) function
+ * - Comparisons to a StringName in overriden _set and _get methods.
+ *
+ * Use in places that can be called hundreds of times per frame (or more) is recommended, but this situation is very rare. If in doubt, do not use.
+ */
+
#define SNAME(m_arg) ([]() -> const StringName & { static StringName sname = _scs_create(m_arg, true); return sname; })()
#endif // STRING_NAME_H
diff --git a/core/string/translation.cpp b/core/string/translation.cpp
index 7cc41df9ef..eeac8b0acf 100644
--- a/core/string/translation.cpp
+++ b/core/string/translation.cpp
@@ -925,6 +925,7 @@ bool TranslationServer::is_placeholder(String &p_message, int p_index) const {
void TranslationServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_locale", "locale"), &TranslationServer::set_locale);
ClassDB::bind_method(D_METHOD("get_locale"), &TranslationServer::get_locale);
+ ClassDB::bind_method(D_METHOD("get_tool_locale"), &TranslationServer::get_tool_locale);
ClassDB::bind_method(D_METHOD("compare_locales", "locale_a", "locale_b"), &TranslationServer::compare_locales);
ClassDB::bind_method(D_METHOD("standardize_locale", "locale"), &TranslationServer::standardize_locale);
diff --git a/core/variant/callable.cpp b/core/variant/callable.cpp
index c6a67f01d5..27792ce111 100644
--- a/core/variant/callable.cpp
+++ b/core/variant/callable.cpp
@@ -114,8 +114,9 @@ ObjectID Callable::get_object_id() const {
}
StringName Callable::get_method() const {
- ERR_FAIL_COND_V_MSG(is_custom(), StringName(),
- vformat("Can't get method on CallableCustom \"%s\".", operator String()));
+ if (is_custom()) {
+ return get_custom()->get_method();
+ }
return method;
}
@@ -310,6 +311,10 @@ Callable::~Callable() {
}
}
+StringName CallableCustom::get_method() const {
+ ERR_FAIL_V_MSG(StringName(), vformat("Can't get method on CallableCustom \"%s\".", get_as_text()));
+}
+
void CallableCustom::rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const {
r_call_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
r_call_error.argument = 0;
diff --git a/core/variant/callable.h b/core/variant/callable.h
index 855ffa9129..c61870f194 100644
--- a/core/variant/callable.h
+++ b/core/variant/callable.h
@@ -125,6 +125,7 @@ public:
virtual String get_as_text() const = 0;
virtual CompareEqualFunc get_compare_equal_func() const = 0;
virtual CompareLessFunc get_compare_less_func() const = 0;
+ virtual StringName get_method() const;
virtual ObjectID get_object() const = 0; //must always be able to provide an object
virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const = 0;
virtual void rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const;
diff --git a/core/variant/callable_bind.cpp b/core/variant/callable_bind.cpp
index 4579621760..797e8afede 100644
--- a/core/variant/callable_bind.cpp
+++ b/core/variant/callable_bind.cpp
@@ -70,12 +70,19 @@ bool CallableCustomBind::_less_func(const CallableCustom *p_a, const CallableCus
CallableCustom::CompareEqualFunc CallableCustomBind::get_compare_equal_func() const {
return _equal_func;
}
+
CallableCustom::CompareLessFunc CallableCustomBind::get_compare_less_func() const {
return _less_func;
}
+
+StringName CallableCustomBind::get_method() const {
+ return callable.get_method();
+}
+
ObjectID CallableCustomBind::get_object() const {
return callable.get_object_id();
}
+
const Callable *CallableCustomBind::get_base_comparator() const {
return &callable;
}
@@ -140,12 +147,19 @@ bool CallableCustomUnbind::_less_func(const CallableCustom *p_a, const CallableC
CallableCustom::CompareEqualFunc CallableCustomUnbind::get_compare_equal_func() const {
return _equal_func;
}
+
CallableCustom::CompareLessFunc CallableCustomUnbind::get_compare_less_func() const {
return _less_func;
}
+
+StringName CallableCustomUnbind::get_method() const {
+ return callable.get_method();
+}
+
ObjectID CallableCustomUnbind::get_object() const {
return callable.get_object_id();
}
+
const Callable *CallableCustomUnbind::get_base_comparator() const {
return &callable;
}
diff --git a/core/variant/callable_bind.h b/core/variant/callable_bind.h
index ac5797e05f..4f79a29629 100644
--- a/core/variant/callable_bind.h
+++ b/core/variant/callable_bind.h
@@ -47,6 +47,7 @@ public:
virtual String get_as_text() const;
virtual CompareEqualFunc get_compare_equal_func() const;
virtual CompareLessFunc get_compare_less_func() const;
+ virtual StringName get_method() const;
virtual ObjectID get_object() const; //must always be able to provide an object
virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const;
virtual const Callable *get_base_comparator() const;
@@ -71,6 +72,7 @@ public:
virtual String get_as_text() const;
virtual CompareEqualFunc get_compare_equal_func() const;
virtual CompareLessFunc get_compare_less_func() const;
+ virtual StringName get_method() const;
virtual ObjectID get_object() const; //must always be able to provide an object
virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const;
virtual const Callable *get_base_comparator() const;
diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp
index 750f23902d..a5e89eec80 100644
--- a/core/variant/variant_call.cpp
+++ b/core/variant/variant_call.cpp
@@ -1371,6 +1371,8 @@ static void _register_variant_builtin_methods() {
bind_method(String, length, sarray(), varray());
bind_method(String, substr, sarray("from", "len"), varray(-1));
bind_method(String, get_slice, sarray("delimiter", "slice"), varray());
+ bind_method(String, get_slicec, sarray("delimiter", "slice"), varray());
+ bind_method(String, get_slice_count, sarray("delimiter"), varray());
bind_methodv(String, find, static_cast<int (String::*)(const String &, int) const>(&String::find), sarray("what", "from"), varray(0));
bind_method(String, count, sarray("what", "from", "to"), varray(0, 0));
bind_method(String, countn, sarray("what", "from", "to"), varray(0, 0));
@@ -1667,6 +1669,7 @@ static void _register_variant_builtin_methods() {
/* RID */
+ bind_method(RID, is_valid, sarray(), varray());
bind_method(RID, get_id, sarray(), varray());
/* NodePath */
diff --git a/core/variant/variant_op.cpp b/core/variant/variant_op.cpp
index f35774204b..cd1ae9f41f 100644
--- a/core/variant/variant_op.cpp
+++ b/core/variant/variant_op.cpp
@@ -176,6 +176,7 @@ void Variant::_register_variant_operators() {
register_op<OperatorEvaluatorAdd<double, double, int64_t>>(Variant::OP_ADD, Variant::FLOAT, Variant::INT);
register_op<OperatorEvaluatorAdd<double, double, double>>(Variant::OP_ADD, Variant::FLOAT, Variant::FLOAT);
register_op<OperatorEvaluatorAdd<String, String, String>>(Variant::OP_ADD, Variant::STRING, Variant::STRING);
+ register_op<OperatorEvaluatorAdd<String, char32_t, String>>(Variant::OP_ADD, Variant::INT, Variant::STRING);
register_op<OperatorEvaluatorAdd<Vector2, Vector2, Vector2>>(Variant::OP_ADD, Variant::VECTOR2, Variant::VECTOR2);
register_op<OperatorEvaluatorAdd<Vector2i, Vector2i, Vector2i>>(Variant::OP_ADD, Variant::VECTOR2I, Variant::VECTOR2I);
register_op<OperatorEvaluatorAdd<Vector3, Vector3, Vector3>>(Variant::OP_ADD, Variant::VECTOR3, Variant::VECTOR3);
@@ -622,6 +623,7 @@ void Variant::_register_variant_operators() {
register_op<OperatorEvaluatorLess<double, int64_t>>(Variant::OP_LESS, Variant::FLOAT, Variant::INT);
register_op<OperatorEvaluatorLess<double, double>>(Variant::OP_LESS, Variant::FLOAT, Variant::FLOAT);
register_op<OperatorEvaluatorLess<String, String>>(Variant::OP_LESS, Variant::STRING, Variant::STRING);
+ register_op<OperatorEvaluatorLess<StringName, StringName>>(Variant::OP_LESS, Variant::STRING_NAME, Variant::STRING_NAME);
register_op<OperatorEvaluatorLess<Vector2, Vector2>>(Variant::OP_LESS, Variant::VECTOR2, Variant::VECTOR2);
register_op<OperatorEvaluatorLess<Vector2i, Vector2i>>(Variant::OP_LESS, Variant::VECTOR2I, Variant::VECTOR2I);
register_op<OperatorEvaluatorLess<Vector3, Vector3>>(Variant::OP_LESS, Variant::VECTOR3, Variant::VECTOR3);
@@ -634,6 +636,7 @@ void Variant::_register_variant_operators() {
register_op<OperatorEvaluatorLessEqual<double, int64_t>>(Variant::OP_LESS_EQUAL, Variant::FLOAT, Variant::INT);
register_op<OperatorEvaluatorLessEqual<double, double>>(Variant::OP_LESS_EQUAL, Variant::FLOAT, Variant::FLOAT);
register_op<OperatorEvaluatorLessEqual<String, String>>(Variant::OP_LESS_EQUAL, Variant::STRING, Variant::STRING);
+ register_op<OperatorEvaluatorLessEqual<StringName, StringName>>(Variant::OP_LESS_EQUAL, Variant::STRING_NAME, Variant::STRING_NAME);
register_op<OperatorEvaluatorLessEqual<Vector2, Vector2>>(Variant::OP_LESS_EQUAL, Variant::VECTOR2, Variant::VECTOR2);
register_op<OperatorEvaluatorLessEqual<Vector2i, Vector2i>>(Variant::OP_LESS_EQUAL, Variant::VECTOR2I, Variant::VECTOR2I);
register_op<OperatorEvaluatorLessEqual<Vector3, Vector3>>(Variant::OP_LESS_EQUAL, Variant::VECTOR3, Variant::VECTOR3);
@@ -647,6 +650,7 @@ void Variant::_register_variant_operators() {
register_op<OperatorEvaluatorGreater<double, int64_t>>(Variant::OP_GREATER, Variant::FLOAT, Variant::INT);
register_op<OperatorEvaluatorGreater<double, double>>(Variant::OP_GREATER, Variant::FLOAT, Variant::FLOAT);
register_op<OperatorEvaluatorGreater<String, String>>(Variant::OP_GREATER, Variant::STRING, Variant::STRING);
+ register_op<OperatorEvaluatorGreater<StringName, StringName>>(Variant::OP_GREATER, Variant::STRING_NAME, Variant::STRING_NAME);
register_op<OperatorEvaluatorGreater<Vector2, Vector2>>(Variant::OP_GREATER, Variant::VECTOR2, Variant::VECTOR2);
register_op<OperatorEvaluatorGreater<Vector2i, Vector2i>>(Variant::OP_GREATER, Variant::VECTOR2I, Variant::VECTOR2I);
register_op<OperatorEvaluatorGreater<Vector3, Vector3>>(Variant::OP_GREATER, Variant::VECTOR3, Variant::VECTOR3);
@@ -659,6 +663,7 @@ void Variant::_register_variant_operators() {
register_op<OperatorEvaluatorGreaterEqual<double, int64_t>>(Variant::OP_GREATER_EQUAL, Variant::FLOAT, Variant::INT);
register_op<OperatorEvaluatorGreaterEqual<double, double>>(Variant::OP_GREATER_EQUAL, Variant::FLOAT, Variant::FLOAT);
register_op<OperatorEvaluatorGreaterEqual<String, String>>(Variant::OP_GREATER_EQUAL, Variant::STRING, Variant::STRING);
+ register_op<OperatorEvaluatorGreaterEqual<StringName, StringName>>(Variant::OP_GREATER_EQUAL, Variant::STRING_NAME, Variant::STRING_NAME);
register_op<OperatorEvaluatorGreaterEqual<Vector2, Vector2>>(Variant::OP_GREATER_EQUAL, Variant::VECTOR2, Variant::VECTOR2);
register_op<OperatorEvaluatorGreaterEqual<Vector2i, Vector2i>>(Variant::OP_GREATER_EQUAL, Variant::VECTOR2I, Variant::VECTOR2I);
register_op<OperatorEvaluatorGreaterEqual<Vector3, Vector3>>(Variant::OP_GREATER_EQUAL, Variant::VECTOR3, Variant::VECTOR3);
diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml
index d8c9ca08e8..4c0f89f14d 100644
--- a/doc/classes/@GlobalScope.xml
+++ b/doc/classes/@GlobalScope.xml
@@ -1267,6 +1267,12 @@
<constant name="INLINE_ALIGNMENT_BOTTOM" value="14" enum="InlineAlignment">
Aligns bottom of the inline object (e.g. image, table) to the bottom of the text. Equivalent to [code]INLINE_ALIGNMENT_BOTTOM_TO | INLINE_ALIGNMENT_TO_BOTTOM[/code].
</constant>
+ <constant name="INLINE_ALIGNMENT_IMAGE_MASK" value="3" enum="InlineAlignment">
+ A bit mask for [code]INLINE_ALIGNMENT_*_TO[/code] alignment constants.
+ </constant>
+ <constant name="INLINE_ALIGNMENT_TEXT_MASK" value="12" enum="InlineAlignment">
+ A bit mask for [code]INLINE_ALIGNMENT_TO_*[/code] alignment constants.
+ </constant>
<constant name="KEY_SPECIAL" value="16777216" enum="Key">
Keycodes with this bit applied are non-printable.
</constant>
diff --git a/doc/classes/Color.xml b/doc/classes/Color.xml
index f3fcd90f51..4e73d4d9d8 100644
--- a/doc/classes/Color.xml
+++ b/doc/classes/Color.xml
@@ -218,12 +218,45 @@
<return type="Color" />
<argument index="0" name="rgba" type="String" />
<description>
+ Returns a new color from [code]rgba[/code], an HTML hexadecimal color string. [code]rgba[/code] is not case sensitive, and may be prefixed with a '#' character.
+ [code]rgba[/code] must be a valid three-digit or six-digit hexadecimal color string, and may contain an alpha channel value. If [code]rgba[/code] does not contain an alpha channel value, an alpha channel value of 1.0 is applied.
+ If [code]rgba[/code] is invalid a Color(0.0, 0.0, 0.0, 1.0) is returned.
+ [codeblocks]
+ [gdscript]
+ var green = Color.html("#00FF00FF") # set green to Color(0.0, 1.0, 0.0, 1.0)
+ var blue = Color.html("#0000FF") # set blue to Color(0.0, 0.0, 1.0, 1.0)
+ [/gdscript]
+ [csharp]
+ var green = Color.Html("#00FF00FF"); // set green to Color(0.0, 1.0, 0.0, 1.0)
+ var blue = Color.Html("#0000FF"); // set blue to Color(0.0, 0.0, 1.0, 1.0)
+ [/csharp]
+ [/codeblocks]
</description>
</method>
<method name="html_is_valid" qualifiers="static">
<return type="bool" />
<argument index="0" name="color" type="String" />
<description>
+ Returns [code]true[/code] if [code]color[/code] is a valid HTML hexadecimal color string. [code]color[/code] is not case sensitive, and may be prefixed with a '#' character.
+ For a string to be valid it must be three-digit or six-digit hexadecimal, and may contain an alpha channel value.
+ [codeblocks]
+ [gdscript]
+ var result = Color.html_is_valid("#55aaFF") # result is true
+ result = Color.html_is_valid("#55AAFF20") # result is true
+ result = Color.html_is_valid("55AAFF") # result is true
+ result = Color.html_is_valid("#F2C") # result is true
+ result = Color.html_is_valid("#AABBC) # result is false
+ result = Color.html_is_valid("#55aaFF5") # result is false
+ [/gdscript]
+ [csharp]
+ var result = Color.HtmlIsValid("#55AAFF"); // result is true
+ result = Color.HtmlIsValid("#55AAFF20"); // result is true
+ result = Color.HtmlIsValid("55AAFF); // result is true
+ result = Color.HtmlIsValid("#F2C"); // result is true
+ result = Color.HtmlIsValid("#AABBC"); // result is false
+ result = Color.HtmlIsValid("#55aaFF5"); // result is false
+ [/csharp]
+ [/codeblocks]
</description>
</method>
<method name="inverted" qualifiers="const">
diff --git a/doc/classes/JavaScript.xml b/doc/classes/JavaScript.xml
index aeaf8ac1f5..4ea60ad867 100644
--- a/doc/classes/JavaScript.xml
+++ b/doc/classes/JavaScript.xml
@@ -53,5 +53,27 @@
Returns an interface to a JavaScript object that can be used by scripts. The [code]interface[/code] must be a valid property of the JavaScript [code]window[/code]. The callback must accept a single [Array] argument, which will contain the JavaScript [code]arguments[/code]. See [JavaScriptObject] for usage.
</description>
</method>
+ <method name="pwa_needs_update" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if a new version of the progressive web app is waiting to be activated.
+ [b]Note:[/b] Only relevant when exported as a Progressive Web App.
+ </description>
+ </method>
+ <method name="pwa_update">
+ <return type="int" enum="Error" />
+ <description>
+ Performs the live update of the progressive web app. Forcing the new version to be installed and the page to be reloaded.
+ [b]Note:[/b] Your application will be [b]reloaded in all browser tabs[/b].
+ [b]Note:[/b] Only relevant when exported as a Progressive Web App and [method pwa_needs_update] returns [code]true[/code].
+ </description>
+ </method>
</methods>
+ <signals>
+ <signal name="pwa_update_available">
+ <description>
+ Emitted when an update for this progressive web app has been detected but is waiting to be activated because a previous version is active. See [method pwa_update] to force the update to take place immediately.
+ </description>
+ </signal>
+ </signals>
</class>
diff --git a/doc/classes/Mesh.xml b/doc/classes/Mesh.xml
index c774528a39..8fbafcdb51 100644
--- a/doc/classes/Mesh.xml
+++ b/doc/classes/Mesh.xml
@@ -206,7 +206,7 @@
<constant name="ARRAY_FORMAT_INDEX" value="4096" enum="ArrayFormat">
Mesh array uses indices.
</constant>
- <constant name="ARRAY_FORMAT_BLEND_SHAPE_MASK" value="2147475463" enum="ArrayFormat">
+ <constant name="ARRAY_FORMAT_BLEND_SHAPE_MASK" value="7" enum="ArrayFormat">
</constant>
<constant name="ARRAY_FORMAT_CUSTOM_BASE" value="13" enum="ArrayFormat">
</constant>
diff --git a/doc/classes/Panel.xml b/doc/classes/Panel.xml
index 21ac7dfac1..3246fa7eba 100644
--- a/doc/classes/Panel.xml
+++ b/doc/classes/Panel.xml
@@ -11,16 +11,6 @@
<link title="2D Finite State Machine Demo">https://godotengine.org/asset-library/asset/516</link>
<link title="3D Inverse Kinematics Demo">https://godotengine.org/asset-library/asset/523</link>
</tutorials>
- <members>
- <member name="mode" type="int" setter="set_mode" getter="get_mode" enum="Panel.Mode" default="0">
- </member>
- </members>
- <constants>
- <constant name="MODE_BACKGROUND" value="0" enum="Mode">
- </constant>
- <constant name="MODE_FOREGROUND" value="1" enum="Mode">
- </constant>
- </constants>
<theme_items>
<theme_item name="panel" data_type="style" type="StyleBox">
The style of this [Panel].
diff --git a/doc/classes/PopupMenu.xml b/doc/classes/PopupMenu.xml
index eb1b0aada7..b316f822f0 100644
--- a/doc/classes/PopupMenu.xml
+++ b/doc/classes/PopupMenu.xml
@@ -331,6 +331,13 @@
[b]Note:[/b] The indices of items after the removed item will be shifted by one.
</description>
</method>
+ <method name="scroll_to_item">
+ <return type="void" />
+ <argument index="0" name="index" type="int" />
+ <description>
+ Moves the scroll view to make the item at the given [code]index[/code] visible.
+ </description>
+ </method>
<method name="set_current_index">
<return type="void" />
<argument index="0" name="index" type="int" />
diff --git a/doc/classes/RID.xml b/doc/classes/RID.xml
index 695b0933fa..990e82593e 100644
--- a/doc/classes/RID.xml
+++ b/doc/classes/RID.xml
@@ -30,6 +30,12 @@
Returns the ID of the referenced resource.
</description>
</method>
+ <method name="is_valid" qualifiers="const">
+ <return type="bool" />
+ <description>
+ Returns [code]true[/code] if [RID] is valid.
+ </description>
+ </method>
</methods>
<operators>
<operator name="operator !=">
diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml
index 446db40dd8..82728c0570 100644
--- a/doc/classes/RenderingServer.xml
+++ b/doc/classes/RenderingServer.xml
@@ -3626,7 +3626,7 @@
<constant name="ARRAY_FORMAT_INDEX" value="4096" enum="ArrayFormat">
Flag used to mark an index array.
</constant>
- <constant name="ARRAY_FORMAT_BLEND_SHAPE_MASK" value="2147475463" enum="ArrayFormat">
+ <constant name="ARRAY_FORMAT_BLEND_SHAPE_MASK" value="7" enum="ArrayFormat">
</constant>
<constant name="ARRAY_FORMAT_CUSTOM_BASE" value="13" enum="ArrayFormat">
</constant>
diff --git a/doc/classes/String.xml b/doc/classes/String.xml
index eeb17c24c0..a6182f5dab 100644
--- a/doc/classes/String.xml
+++ b/doc/classes/String.xml
@@ -222,6 +222,22 @@
[/codeblock]
</description>
</method>
+ <method name="get_slice_count" qualifiers="const">
+ <return type="int" />
+ <argument index="0" name="delimiter" type="String" />
+ <description>
+ Splits a string using a [code]delimiter[/code] and returns a number of slices.
+ </description>
+ </method>
+ <method name="get_slicec" qualifiers="const">
+ <return type="String" />
+ <argument index="0" name="delimiter" type="int" />
+ <argument index="1" name="slice" type="int" />
+ <description>
+ Splits a string using a Unicode character with code [code]delimiter[/code] and returns a substring at index [code]slice[/code]. Returns an empty string if the index doesn't exist.
+ This is a more performant alternative to [method split] for cases when you need only one element from the array at a fixed index.
+ </description>
+ </method>
<method name="hash" qualifiers="const">
<return type="int" />
<description>
diff --git a/doc/classes/StringName.xml b/doc/classes/StringName.xml
index b32665a09f..85c4d7593e 100644
--- a/doc/classes/StringName.xml
+++ b/doc/classes/StringName.xml
@@ -48,6 +48,18 @@
<description>
</description>
</operator>
+ <operator name="operator &lt;">
+ <return type="bool" />
+ <argument index="0" name="right" type="StringName" />
+ <description>
+ </description>
+ </operator>
+ <operator name="operator &lt;=">
+ <return type="bool" />
+ <argument index="0" name="right" type="StringName" />
+ <description>
+ </description>
+ </operator>
<operator name="operator ==">
<return type="bool" />
<description>
@@ -65,5 +77,17 @@
<description>
</description>
</operator>
+ <operator name="operator &gt;">
+ <return type="bool" />
+ <argument index="0" name="right" type="StringName" />
+ <description>
+ </description>
+ </operator>
+ <operator name="operator &gt;=">
+ <return type="bool" />
+ <argument index="0" name="right" type="StringName" />
+ <description>
+ </description>
+ </operator>
</operators>
</class>
diff --git a/doc/classes/TranslationServer.xml b/doc/classes/TranslationServer.xml
index c90cb2987c..6ece42da6b 100644
--- a/doc/classes/TranslationServer.xml
+++ b/doc/classes/TranslationServer.xml
@@ -91,6 +91,13 @@
Returns readable script name for the [code]script[/code] code.
</description>
</method>
+ <method name="get_tool_locale">
+ <return type="String" />
+ <description>
+ Returns the current locale of the editor.
+ [b]Note:[/b] When called from an exported project returns the same value as [method get_locale].
+ </description>
+ </method>
<method name="get_translation_object">
<return type="Translation" />
<argument index="0" name="locale" type="String" />
diff --git a/doc/classes/Tree.xml b/doc/classes/Tree.xml
index 766c740a2c..4b051c4938 100644
--- a/doc/classes/Tree.xml
+++ b/doc/classes/Tree.xml
@@ -240,6 +240,7 @@
<method name="scroll_to_item">
<return type="void" />
<argument index="0" name="item" type="TreeItem" />
+ <argument index="1" name="center_on_item" type="bool" default="false" />
<description>
Causes the [Tree] to jump to the specified [TreeItem].
</description>
diff --git a/doc/classes/Vector3i.xml b/doc/classes/Vector3i.xml
index 8a901fdf37..e0b8a53a3c 100644
--- a/doc/classes/Vector3i.xml
+++ b/doc/classes/Vector3i.xml
@@ -48,6 +48,7 @@
<method name="abs" qualifiers="const">
<return type="Vector3i" />
<description>
+ Returns a new vector with all components in absolute values (i.e. positive).
</description>
</method>
<method name="clamp" qualifiers="const">
diff --git a/doc/classes/VisualShaderNodeParticleRandomness.xml b/doc/classes/VisualShaderNodeParticleRandomness.xml
index 2dec41105c..880208b136 100644
--- a/doc/classes/VisualShaderNodeParticleRandomness.xml
+++ b/doc/classes/VisualShaderNodeParticleRandomness.xml
@@ -8,14 +8,20 @@
</tutorials>
<members>
<member name="op_type" type="int" setter="set_op_type" getter="get_op_type" enum="VisualShaderNodeParticleRandomness.OpType" default="0">
+ A type of operands and returned value.
</member>
</members>
<constants>
<constant name="OP_TYPE_SCALAR" value="0" enum="OpType">
+ A floating-point scalar.
</constant>
- <constant name="OP_TYPE_VECTOR" value="1" enum="OpType">
+ <constant name="OP_TYPE_VECTOR_2D" value="1" enum="OpType">
+ A 2D vector type.
</constant>
- <constant name="OP_TYPE_MAX" value="2" enum="OpType">
+ <constant name="OP_TYPE_VECTOR_3D" value="2" enum="OpType">
+ A 3D vector type.
+ </constant>
+ <constant name="OP_TYPE_MAX" value="3" enum="OpType">
Represents the size of the [enum OpType] enum.
</constant>
</constants>
diff --git a/doc/classes/int.xml b/doc/classes/int.xml
index d212fe42bf..006dc7eb29 100644
--- a/doc/classes/int.xml
+++ b/doc/classes/int.xml
@@ -177,6 +177,13 @@
</description>
</operator>
<operator name="operator +">
+ <return type="String" />
+ <argument index="0" name="right" type="String" />
+ <description>
+ Adds Unicode character with code [int] to the [String].
+ </description>
+ </operator>
+ <operator name="operator +">
<return type="float" />
<argument index="0" name="right" type="float" />
<description>
diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp
index e8fd97fa1a..61ec8abacf 100644
--- a/editor/create_dialog.cpp
+++ b/editor/create_dialog.cpp
@@ -446,14 +446,14 @@ void CreateDialog::_notification(int p_what) {
}
}
-void CreateDialog::select_type(const String &p_type) {
+void CreateDialog::select_type(const String &p_type, bool p_center_on_item) {
if (!search_options_types.has(p_type)) {
return;
}
TreeItem *to_select = search_options_types[p_type];
to_select->select(0);
- search_options->scroll_to_item(to_select);
+ search_options->scroll_to_item(to_select, p_center_on_item);
if (EditorHelp::get_doc_data()->class_list.has(p_type) && !DTR(EditorHelp::get_doc_data()->class_list[p_type].brief_description).is_empty()) {
// Display both class name and description, since the help bit may be displayed
@@ -503,24 +503,14 @@ Variant CreateDialog::instance_selected() {
} else {
obj = ClassDB::instantiate(selected->get_text(0));
}
-
- // Check if any Object-type property should be instantiated.
- List<PropertyInfo> pinfo;
- ((Object *)obj)->get_property_list(&pinfo);
-
- for (const PropertyInfo &pi : pinfo) {
- if (pi.type == Variant::OBJECT && pi.usage & PROPERTY_USAGE_EDITOR_INSTANTIATE_OBJECT) {
- Object *prop = ClassDB::instantiate(pi.class_name);
- ((Object *)obj)->set(pi.name, prop);
- }
- }
+ EditorNode::get_editor_data().instantiate_object_properties(obj);
return obj;
}
void CreateDialog::_item_selected() {
String name = get_selected_type();
- select_type(name);
+ select_type(name, false);
}
void CreateDialog::_hide_requested() {
diff --git a/editor/create_dialog.h b/editor/create_dialog.h
index f905160df3..a82c4db191 100644
--- a/editor/create_dialog.h
+++ b/editor/create_dialog.h
@@ -79,7 +79,7 @@ class CreateDialog : public ConfirmationDialog {
void _sbox_input(const Ref<InputEvent> &p_ie);
void _text_changed(const String &p_newtext);
- void select_type(const String &p_type);
+ void select_type(const String &p_type, bool p_center_on_item = true);
void _item_selected();
void _hide_requested();
diff --git a/editor/debugger/editor_debugger_node.cpp b/editor/debugger/editor_debugger_node.cpp
index 4b6a11f388..8702e773f8 100644
--- a/editor/debugger/editor_debugger_node.cpp
+++ b/editor/debugger/editor_debugger_node.cpp
@@ -683,7 +683,7 @@ EditorDebuggerNode::CameraOverride EditorDebuggerNode::get_camera_override() {
void EditorDebuggerNode::add_debugger_plugin(const Ref<Script> &p_script) {
ERR_FAIL_COND_MSG(debugger_plugins.has(p_script), "Debugger plugin already exists.");
ERR_FAIL_COND_MSG(p_script.is_null(), "Debugger plugin script is null");
- ERR_FAIL_COND_MSG(String(p_script->get_instance_base_type()) == "", "Debugger plugin script has error.");
+ ERR_FAIL_COND_MSG(p_script->get_instance_base_type() == StringName(), "Debugger plugin script has error.");
ERR_FAIL_COND_MSG(String(p_script->get_instance_base_type()) != "EditorDebuggerPlugin", "Base type of debugger plugin is not 'EditorDebuggerPlugin'.");
ERR_FAIL_COND_MSG(!p_script->is_tool(), "Debugger plugin script is not in tool mode.");
debugger_plugins.insert(p_script);
diff --git a/editor/editor_autoload_settings.cpp b/editor/editor_autoload_settings.cpp
index d74a6e12b2..6d31141be7 100644
--- a/editor/editor_autoload_settings.cpp
+++ b/editor/editor_autoload_settings.cpp
@@ -362,21 +362,21 @@ Node *EditorAutoloadSettings::_create_autoload(const String &p_path) {
RES res = ResourceLoader::load(p_path);
ERR_FAIL_COND_V_MSG(res.is_null(), nullptr, "Can't autoload: " + p_path + ".");
Node *n = nullptr;
- if (res->is_class("PackedScene")) {
- Ref<PackedScene> ps = res;
- n = ps->instantiate();
- } else if (res->is_class("Script")) {
- Ref<Script> s = res;
- StringName ibt = s->get_instance_base_type();
+ Ref<PackedScene> scn = res;
+ Ref<Script> script = res;
+ if (scn.is_valid()) {
+ n = scn->instantiate();
+ } else if (script.is_valid()) {
+ StringName ibt = script->get_instance_base_type();
bool valid_type = ClassDB::is_parent_class(ibt, "Node");
ERR_FAIL_COND_V_MSG(!valid_type, nullptr, "Script does not inherit a Node: " + p_path + ".");
Object *obj = ClassDB::instantiate(ibt);
- ERR_FAIL_COND_V_MSG(obj == nullptr, nullptr, "Cannot instance script for AutoLoad, expected 'Node' inheritance, got: " + String(ibt) + ".");
+ ERR_FAIL_COND_V_MSG(!obj, nullptr, "Cannot instance script for AutoLoad, expected 'Node' inheritance, got: " + String(ibt) + ".");
n = Object::cast_to<Node>(obj);
- n->set_script(s);
+ n->set_script(script);
}
ERR_FAIL_COND_V_MSG(!n, nullptr, "Path in AutoLoad not a node or script: " + p_path + ".");
diff --git a/editor/editor_data.cpp b/editor/editor_data.cpp
index 7a0a4abbff..625330ef37 100644
--- a/editor/editor_data.cpp
+++ b/editor/editor_data.cpp
@@ -520,6 +520,21 @@ void EditorData::remove_custom_type(const String &p_type) {
}
}
+void EditorData::instantiate_object_properties(Object *p_object) {
+ ERR_FAIL_NULL(p_object);
+ // Check if any Object-type property should be instantiated.
+ List<PropertyInfo> pinfo;
+ p_object->get_property_list(&pinfo);
+
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ PropertyInfo pi = E->get();
+ if (pi.type == Variant::OBJECT && pi.usage & PROPERTY_USAGE_EDITOR_INSTANTIATE_OBJECT) {
+ Object *prop = ClassDB::instantiate(pi.class_name);
+ p_object->set(pi.name, prop);
+ }
+ }
+}
+
int EditorData::add_edited_scene(int p_at_pos) {
if (p_at_pos < 0) {
p_at_pos = edited_scene.size();
@@ -894,21 +909,12 @@ bool EditorData::script_class_is_parent(const String &p_class, const String &p_i
return false;
}
- Ref<Script> script = script_class_load_script(p_class);
- if (script.is_null()) {
- return false;
- }
-
- String base = script_class_get_base(p_class);
- Ref<Script> base_script = script->get_base_script();
-
- while (p_inherits != base) {
+ String base = p_class;
+ while (base != p_inherits) {
if (ClassDB::class_exists(base)) {
return ClassDB::is_parent_class(base, p_inherits);
} else if (ScriptServer::is_global_class(base)) {
- base = script_class_get_base(base);
- } else if (base_script.is_valid()) {
- return ClassDB::is_parent_class(base_script->get_instance_base_type(), p_inherits);
+ base = ScriptServer::get_global_class_base(base);
} else {
return false;
}
diff --git a/editor/editor_data.h b/editor/editor_data.h
index ccf641ff26..e485d47bf6 100644
--- a/editor/editor_data.h
+++ b/editor/editor_data.h
@@ -182,6 +182,8 @@ public:
void remove_custom_type(const String &p_type);
const Map<String, Vector<CustomType>> &get_custom_types() const { return custom_types; }
+ void instantiate_object_properties(Object *p_object);
+
int add_edited_scene(int p_at_pos);
void move_edited_scene_index(int p_idx, int p_to_idx);
void remove_scene(int p_idx);
diff --git a/editor/editor_feature_profile.cpp b/editor/editor_feature_profile.cpp
index 1d73bdfa6e..2fc29c46af 100644
--- a/editor/editor_feature_profile.cpp
+++ b/editor/editor_feature_profile.cpp
@@ -592,7 +592,15 @@ void EditorFeatureProfileManager::_class_list_item_selected() {
List<PropertyInfo> props;
ClassDB::get_property_list(class_name, &props, true);
- if (props.size() > 0) {
+ bool has_editor_props = false;
+ for (const PropertyInfo &E : props) {
+ if (E.usage & PROPERTY_USAGE_EDITOR) {
+ has_editor_props = true;
+ break;
+ }
+ }
+
+ if (has_editor_props) {
TreeItem *properties = property_list->create_item(root);
properties->set_text(0, TTR("Class Properties:"));
diff --git a/editor/editor_help_search.cpp b/editor/editor_help_search.cpp
index 36d3ac9e66..29bf22a478 100644
--- a/editor/editor_help_search.cpp
+++ b/editor/editor_help_search.cpp
@@ -610,11 +610,6 @@ TreeItem *EditorHelpSearch::Runner::_create_member_item(TreeItem *p_parent, cons
text = p_text;
} else {
icon = ui_service->get_theme_icon(p_icon, SNAME("EditorIcons"));
- /*// In flat mode, show the class icon.
-if (ui_service->has_icon(p_class_name, "EditorIcons"))
-icon = ui_service->get_icon(p_class_name, "EditorIcons");
-else if (ClassDB::is_parent_class(p_class_name, "Object"))
-icon = ui_service->get_icon("Object", "EditorIcons");*/
text = p_class_name + "." + p_text;
}
diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp
index 29d1752578..cbfd6ae6de 100644
--- a/editor/editor_inspector.cpp
+++ b/editor/editor_inspector.cpp
@@ -2425,7 +2425,7 @@ void EditorInspector::update_tree() {
if (!ClassDB::class_exists(type) && !ScriptServer::is_global_class(type) && p.hint_string.length() && FileAccess::exists(p.hint_string)) {
// If we have a category inside a script, search for the first script with a valid icon.
Ref<Script> script = ResourceLoader::load(p.hint_string, "Script");
- String base_type;
+ StringName base_type;
if (script.is_valid()) {
base_type = script->get_instance_base_type();
}
@@ -3020,7 +3020,7 @@ void EditorInspector::_update_inspector_bg() {
n = n->get_parent();
}
count_subinspectors = MIN(15, count_subinspectors);
- add_theme_style_override("bg", get_theme_stylebox("sub_inspector_bg" + itos(count_subinspectors), "Editor"));
+ add_theme_style_override("bg", get_theme_stylebox("sub_inspector_bg" + itos(count_subinspectors), SNAME("Editor")));
} else {
add_theme_style_override("bg", get_theme_stylebox(SNAME("bg"), SNAME("Tree")));
}
@@ -3479,10 +3479,14 @@ void EditorInspector::_update_script_class_properties(const Object &p_object, Li
String path = s->get_path();
String name = EditorNode::get_editor_data().script_class_get_name(path);
if (name.is_empty()) {
- if (!s->is_built_in()) {
- name = path.get_file();
+ if (s->is_built_in()) {
+ if (s->get_name().is_empty()) {
+ name = TTR("Built-in script");
+ } else {
+ name = vformat("%s (%s)", s->get_name(), TTR("Built-in"));
+ }
} else {
- name = TTR("Built-in script");
+ name = path.get_file();
}
}
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index 015b7d0cce..0951199ab8 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -745,7 +745,6 @@ void EditorNode::_notification(int p_what) {
bottom_panel_raise->set_icon(gui_base->get_theme_icon(SNAME("ExpandBottomDock"), SNAME("EditorIcons")));
- // clear_button->set_icon(gui_base->get_icon("Close", "EditorIcons")); don't have access to that node. needs to become a class property
if (gui_base->is_layout_rtl()) {
dock_tab_move_left->set_icon(theme->get_icon(SNAME("Forward"), SNAME("EditorIcons")));
dock_tab_move_right->set_icon(theme->get_icon(SNAME("Back"), SNAME("EditorIcons")));
@@ -2280,7 +2279,7 @@ void EditorNode::_edit_current(bool p_skip_foreign) {
if (main_plugin) {
// special case if use of external editor is true
Resource *current_res = Object::cast_to<Resource>(current_obj);
- if (main_plugin->get_name() == "Script" && current_obj->get_class_name() != StringName("VisualScript") && current_res && !current_res->is_built_in() && (bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor")) || overrides_external_editor(current_obj))) {
+ if (main_plugin->get_name() == "Script" && current_obj->is_class("VisualScript") && current_res && !current_res->is_built_in() && (bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor")) || overrides_external_editor(current_obj))) {
if (!changing_scene) {
main_plugin->edit(current_obj);
}
@@ -3293,8 +3292,8 @@ void EditorNode::set_addon_plugin_enabled(const String &p_addon, bool p_enabled,
return;
}
- // Errors in the script cause the base_type to be an empty string.
- if (String(script->get_instance_base_type()) == "") {
+ // Errors in the script cause the base_type to be an empty StringName.
+ if (script->get_instance_base_type() == StringName()) {
show_warning(vformat(TTR("Unable to load addon script from path: '%s'. This might be due to a code error in that script.\nDisabling the addon at '%s' to prevent further errors."), script_path, p_addon));
_remove_plugin_from_enabled(p_addon);
return;
@@ -3937,7 +3936,7 @@ StringName EditorNode::get_object_custom_type_name(const Object *p_object) const
ERR_FAIL_COND_V(!p_object, StringName());
Ref<Script> script = p_object->get_script();
- if (script.is_null() && p_object->is_class("Script")) {
+ if (script.is_null() && Object::cast_to<Script>(p_object)) {
script = p_object;
}
@@ -4148,13 +4147,12 @@ Ref<Texture2D> EditorNode::_file_dialog_get_icon(const String &p_path) {
void EditorNode::_build_icon_type_cache() {
List<StringName> tl;
- StringName ei = "EditorIcons";
- theme_base->get_theme()->get_icon_list(ei, &tl);
+ theme_base->get_theme()->get_icon_list(SNAME("EditorIcons"), &tl);
for (const StringName &E : tl) {
if (!ClassDB::class_exists(E)) {
continue;
}
- icon_type_cache[E] = theme_base->get_theme()->get_icon(E, ei);
+ icon_type_cache[E] = theme_base->get_theme()->get_icon(E, SNAME("EditorIcons"));
}
}
@@ -4236,8 +4234,9 @@ void EditorNode::_dock_make_float() {
Control *dock = dock_slot[dock_popup_selected]->get_current_tab_control();
ERR_FAIL_COND(!dock);
- const Size2i borders = Size2i(4, 4) * EDSCALE;
- Size2 dock_size = dock->get_size() + borders * 2; // remember size
+ Size2 borders = Size2(4, 4) * EDSCALE;
+ // Remember size and position before removing it from the main window.
+ Size2 dock_size = dock->get_size() + borders * 2;
Point2 dock_screen_pos = dock->get_global_position() + get_tree()->get_root()->get_position() - borders;
int dock_index = dock->get_index();
@@ -4246,7 +4245,7 @@ void EditorNode::_dock_make_float() {
Window *window = memnew(Window);
window->set_title(dock->get_name());
Panel *p = memnew(Panel);
- p->set_mode(Panel::MODE_FOREGROUND);
+ p->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("PanelForeground"), SNAME("EditorStyles")));
p->set_anchors_and_offsets_preset(Control::PRESET_WIDE);
window->add_child(p);
MarginContainer *margin = memnew(MarginContainer);
diff --git a/editor/editor_resource_picker.cpp b/editor/editor_resource_picker.cpp
index 716643f812..398a096550 100644
--- a/editor/editor_resource_picker.cpp
+++ b/editor/editor_resource_picker.cpp
@@ -77,16 +77,16 @@ void EditorResourcePicker::_update_resource_preview(const String &p_path, const
return;
}
- String type = edited_resource->get_class_name();
- if (ClassDB::is_parent_class(type, "Script")) {
- assign_button->set_text(edited_resource->get_path().get_file());
+ Ref<Script> script = edited_resource;
+ if (script.is_valid()) {
+ assign_button->set_text(script->get_path().get_file());
return;
}
if (p_preview.is_valid()) {
preview_rect->set_offset(SIDE_LEFT, assign_button->get_icon()->get_width() + assign_button->get_theme_stylebox(SNAME("normal"))->get_default_margin(SIDE_LEFT) + get_theme_constant(SNAME("hseparation"), SNAME("Button")));
- if (type == "GradientTexture1D") {
+ if (Ref<GradientTexture1D>(edited_resource).is_valid()) {
preview_rect->set_stretch_mode(TextureRect::STRETCH_SCALE);
assign_button->set_custom_minimum_size(Size2(1, 1));
} else {
@@ -377,6 +377,8 @@ void EditorResourcePicker::_edit_menu_cbk(int p_which) {
Resource *resp = Object::cast_to<Resource>(obj);
ERR_BREAK(!resp);
+ EditorNode::get_editor_data().instantiate_object_properties(obj);
+
edited_resource = RES(resp);
emit_signal(SNAME("resource_changed"), edited_resource);
_update_resource();
@@ -640,7 +642,7 @@ void EditorResourcePicker::drop_data_fw(const Point2 &p_point, const Variant &p_
for (Set<String>::Element *E = allowed_types.front(); E; E = E->next()) {
String at = E->get().strip_edges();
- if (at == "BaseMaterial3D" && ClassDB::is_parent_class(dropped_resource->get_class(), "Texture2D")) {
+ if (at == "BaseMaterial3D" && Ref<Texture2D>(dropped_resource).is_valid()) {
// Use existing resource if possible and only replace its data.
Ref<StandardMaterial3D> mat = edited_resource;
if (!mat.is_valid()) {
@@ -651,7 +653,7 @@ void EditorResourcePicker::drop_data_fw(const Point2 &p_point, const Variant &p_
break;
}
- if (at == "ShaderMaterial" && ClassDB::is_parent_class(dropped_resource->get_class(), "Shader")) {
+ if (at == "ShaderMaterial" && Ref<Shader>(dropped_resource).is_valid()) {
Ref<ShaderMaterial> mat = edited_resource;
if (!mat.is_valid()) {
mat.instantiate();
@@ -661,7 +663,7 @@ void EditorResourcePicker::drop_data_fw(const Point2 &p_point, const Variant &p_
break;
}
- if (at == "Font" && ClassDB::is_parent_class(dropped_resource->get_class(), "FontData")) {
+ if (at == "Font" && Ref<FontData>(dropped_resource).is_valid()) {
Ref<Font> font = edited_resource;
if (!font.is_valid()) {
font.instantiate();
@@ -671,7 +673,7 @@ void EditorResourcePicker::drop_data_fw(const Point2 &p_point, const Variant &p_
break;
}
- if (at == "Texture2D" && ClassDB::is_parent_class(dropped_resource->get_class(), "Image")) {
+ if (at == "Texture2D" && Ref<Image>(dropped_resource).is_valid()) {
Ref<ImageTexture> texture = edited_resource;
if (!texture.is_valid()) {
texture.instantiate();
diff --git a/editor/editor_settings_dialog.cpp b/editor/editor_settings_dialog.cpp
index 1cb95226ec..fc37590337 100644
--- a/editor/editor_settings_dialog.cpp
+++ b/editor/editor_settings_dialog.cpp
@@ -272,15 +272,15 @@ void EditorSettingsDialog::_create_shortcut_treeitem(TreeItem *p_parent, const S
shortcut_item->set_text(1, sc_text);
if (sc_text == "None") {
// Fade out unassigned shortcut labels for easier visual grepping.
- shortcut_item->set_custom_color(1, shortcuts->get_theme_color("font_color", "Label") * Color(1, 1, 1, 0.5));
+ shortcut_item->set_custom_color(1, shortcuts->get_theme_color(SNAME("font_color"), SNAME("Label")) * Color(1, 1, 1, 0.5));
}
if (p_allow_revert) {
- shortcut_item->add_button(1, shortcuts->get_theme_icon("Reload", "EditorIcons"), SHORTCUT_REVERT);
+ shortcut_item->add_button(1, shortcuts->get_theme_icon(SNAME("Reload"), SNAME("EditorIcons")), SHORTCUT_REVERT);
}
- shortcut_item->add_button(1, shortcuts->get_theme_icon("Add", "EditorIcons"), SHORTCUT_ADD);
- shortcut_item->add_button(1, shortcuts->get_theme_icon("Close", "EditorIcons"), SHORTCUT_ERASE);
+ shortcut_item->add_button(1, shortcuts->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")), SHORTCUT_ADD);
+ shortcut_item->add_button(1, shortcuts->get_theme_icon(SNAME("Close"), SNAME("EditorIcons")), SHORTCUT_ERASE);
shortcut_item->set_meta("is_action", p_is_action);
shortcut_item->set_meta("type", "shortcut");
@@ -299,11 +299,11 @@ void EditorSettingsDialog::_create_shortcut_treeitem(TreeItem *p_parent, const S
event_item->set_text(0, shortcut_item->get_child_count() == 1 ? "Primary" : "");
event_item->set_text(1, ie->as_text());
- event_item->add_button(1, shortcuts->get_theme_icon("Edit", "EditorIcons"), SHORTCUT_EDIT);
- event_item->add_button(1, shortcuts->get_theme_icon("Close", "EditorIcons"), SHORTCUT_ERASE);
+ event_item->add_button(1, shortcuts->get_theme_icon(SNAME("Edit"), SNAME("EditorIcons")), SHORTCUT_EDIT);
+ event_item->add_button(1, shortcuts->get_theme_icon(SNAME("Close"), SNAME("EditorIcons")), SHORTCUT_ERASE);
- event_item->set_custom_bg_color(0, shortcuts->get_theme_color("dark_color_3", "Editor"));
- event_item->set_custom_bg_color(1, shortcuts->get_theme_color("dark_color_3", "Editor"));
+ event_item->set_custom_bg_color(0, shortcuts->get_theme_color(SNAME("dark_color_3"), SNAME("Editor")));
+ event_item->set_custom_bg_color(1, shortcuts->get_theme_color(SNAME("dark_color_3"), SNAME("Editor")));
event_item->set_meta("is_action", p_is_action);
event_item->set_meta("type", "event");
diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp
index 2a5fefda20..1e373239a6 100644
--- a/editor/editor_themes.cpp
+++ b/editor/editor_themes.cpp
@@ -1279,7 +1279,7 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) {
// Panel
theme->set_stylebox("panel", "Panel", make_flat_stylebox(dark_color_1, 6, 4, 6, 4, corner_width));
- theme->set_stylebox("panel_fg", "Panel", style_default);
+ theme->set_stylebox("PanelForeground", "EditorStyles", style_default);
// Label
theme->set_stylebox("normal", "Label", style_empty);
diff --git a/editor/editor_toaster.cpp b/editor/editor_toaster.cpp
index 6c9e4ab0fc..24227b3a6b 100644
--- a/editor/editor_toaster.cpp
+++ b/editor/editor_toaster.cpp
@@ -113,22 +113,22 @@ void EditorToaster::_notification(int p_what) {
disable_notifications_button->set_icon(get_theme_icon(SNAME("NotificationDisabled"), SNAME("EditorIcons")));
// Styleboxes background.
- info_panel_style_background->set_bg_color(get_theme_color("base_color", "Editor"));
+ info_panel_style_background->set_bg_color(get_theme_color(SNAME("base_color"), SNAME("Editor")));
- warning_panel_style_background->set_bg_color(get_theme_color("base_color", "Editor"));
- warning_panel_style_background->set_border_color(get_theme_color("warning_color", "Editor"));
+ warning_panel_style_background->set_bg_color(get_theme_color(SNAME("base_color"), SNAME("Editor")));
+ warning_panel_style_background->set_border_color(get_theme_color(SNAME("warning_color"), SNAME("Editor")));
- error_panel_style_background->set_bg_color(get_theme_color("base_color", "Editor"));
- error_panel_style_background->set_border_color(get_theme_color("error_color", "Editor"));
+ error_panel_style_background->set_bg_color(get_theme_color(SNAME("base_color"), SNAME("Editor")));
+ error_panel_style_background->set_border_color(get_theme_color(SNAME("error_color"), SNAME("Editor")));
// Styleboxes progress.
- info_panel_style_progress->set_bg_color(get_theme_color("base_color", "Editor").lightened(0.03));
+ info_panel_style_progress->set_bg_color(get_theme_color(SNAME("base_color"), SNAME("Editor")).lightened(0.03));
- warning_panel_style_progress->set_bg_color(get_theme_color("base_color", "Editor").lightened(0.03));
- warning_panel_style_progress->set_border_color(get_theme_color("warning_color", "Editor"));
+ warning_panel_style_progress->set_bg_color(get_theme_color(SNAME("base_color"), SNAME("Editor")).lightened(0.03));
+ warning_panel_style_progress->set_border_color(get_theme_color(SNAME("warning_color"), SNAME("Editor")));
- error_panel_style_progress->set_bg_color(get_theme_color("base_color", "Editor").lightened(0.03));
- error_panel_style_progress->set_border_color(get_theme_color("error_color", "Editor"));
+ error_panel_style_progress->set_bg_color(get_theme_color(SNAME("base_color"), SNAME("Editor")).lightened(0.03));
+ error_panel_style_progress->set_border_color(get_theme_color(SNAME("error_color"), SNAME("Editor")));
main_button->update();
disable_notifications_button->update();
@@ -256,13 +256,13 @@ void EditorToaster::_draw_button() {
real_t button_radius = main_button->get_size().x / 8;
switch (highest_severity) {
case SEVERITY_INFO:
- color = get_theme_color("accent_color", "Editor");
+ color = get_theme_color(SNAME("accent_color"), SNAME("Editor"));
break;
case SEVERITY_WARNING:
- color = get_theme_color("warning_color", "Editor");
+ color = get_theme_color(SNAME("warning_color"), SNAME("Editor"));
break;
case SEVERITY_ERROR:
- color = get_theme_color("error_color", "Editor");
+ color = get_theme_color(SNAME("error_color"), SNAME("Editor"));
break;
default:
break;
@@ -360,7 +360,7 @@ Control *EditorToaster::popup(Control *p_control, Severity p_severity, double p_
if (p_time > 0.0) {
Button *close_button = memnew(Button);
close_button->set_flat(true);
- close_button->set_icon(get_theme_icon("Close", "EditorIcons"));
+ close_button->set_icon(get_theme_icon(SNAME("Close"), SNAME("EditorIcons")));
close_button->connect("pressed", callable_bind(callable_mp(this, &EditorToaster::close), panel));
close_button->connect("theme_changed", callable_bind(callable_mp(this, &EditorToaster::_close_button_theme_changed), close_button));
hbox_container->add_child(close_button);
@@ -442,7 +442,7 @@ void EditorToaster::close(Control *p_control) {
void EditorToaster::_close_button_theme_changed(Control *p_close_button) {
Button *close_button = Object::cast_to<Button>(p_close_button);
if (close_button) {
- close_button->set_icon(get_theme_icon("Close", "EditorIcons"));
+ close_button->set_icon(get_theme_icon(SNAME("Close"), SNAME("EditorIcons")));
}
}
diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp
index a038da4c18..c91351022f 100644
--- a/editor/filesystem_dock.cpp
+++ b/editor/filesystem_dock.cpp
@@ -338,30 +338,28 @@ void FileSystemDock::_notification(int p_what) {
EditorFileSystem::get_singleton()->connect("filesystem_changed", callable_mp(this, &FileSystemDock::_fs_changed));
EditorResourcePreview::get_singleton()->connect("preview_invalidated", callable_mp(this, &FileSystemDock::_preview_invalidated));
- String ei = "EditorIcons";
-
- button_reload->set_icon(get_theme_icon(SNAME("Reload"), ei));
- button_toggle_display_mode->set_icon(get_theme_icon(SNAME("Panels2"), ei));
+ button_reload->set_icon(get_theme_icon(SNAME("Reload"), SNAME("EditorIcons")));
+ button_toggle_display_mode->set_icon(get_theme_icon(SNAME("Panels2"), SNAME("EditorIcons")));
button_file_list_display_mode->connect("pressed", callable_mp(this, &FileSystemDock::_toggle_file_display));
files->connect("item_activated", callable_mp(this, &FileSystemDock::_file_list_activate_file));
button_hist_next->connect("pressed", callable_mp(this, &FileSystemDock::_fw_history));
button_hist_prev->connect("pressed", callable_mp(this, &FileSystemDock::_bw_history));
- tree_search_box->set_right_icon(get_theme_icon(SNAME("Search"), ei));
+ tree_search_box->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
tree_search_box->set_clear_button_enabled(true);
- tree_button_sort->set_icon(get_theme_icon(SNAME("Sort"), ei));
+ tree_button_sort->set_icon(get_theme_icon(SNAME("Sort"), SNAME("EditorIcons")));
- file_list_search_box->set_right_icon(get_theme_icon(SNAME("Search"), ei));
+ file_list_search_box->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
file_list_search_box->set_clear_button_enabled(true);
- file_list_button_sort->set_icon(get_theme_icon(SNAME("Sort"), ei));
+ file_list_button_sort->set_icon(get_theme_icon(SNAME("Sort"), SNAME("EditorIcons")));
if (is_layout_rtl()) {
- button_hist_next->set_icon(get_theme_icon(SNAME("Back"), ei));
- button_hist_prev->set_icon(get_theme_icon(SNAME("Forward"), ei));
+ button_hist_next->set_icon(get_theme_icon(SNAME("Back"), SNAME("EditorIcons")));
+ button_hist_prev->set_icon(get_theme_icon(SNAME("Forward"), SNAME("EditorIcons")));
} else {
- button_hist_next->set_icon(get_theme_icon(SNAME("Forward"), ei));
- button_hist_prev->set_icon(get_theme_icon(SNAME("Back"), ei));
+ button_hist_next->set_icon(get_theme_icon(SNAME("Forward"), SNAME("EditorIcons")));
+ button_hist_prev->set_icon(get_theme_icon(SNAME("Back"), SNAME("EditorIcons")));
}
file_list_popup->connect("id_pressed", callable_mp(this, &FileSystemDock::_file_list_rmb_option));
tree_popup->connect("id_pressed", callable_mp(this, &FileSystemDock::_tree_rmb_option));
@@ -412,15 +410,14 @@ void FileSystemDock::_notification(int p_what) {
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
// Update icons.
- String ei = "EditorIcons";
- button_reload->set_icon(get_theme_icon(SNAME("Reload"), ei));
- button_toggle_display_mode->set_icon(get_theme_icon(SNAME("Panels2"), ei));
+ button_reload->set_icon(get_theme_icon(SNAME("Reload"), SNAME("EditorIcons")));
+ button_toggle_display_mode->set_icon(get_theme_icon(SNAME("Panels2"), SNAME("EditorIcons")));
if (is_layout_rtl()) {
- button_hist_next->set_icon(get_theme_icon(SNAME("Back"), ei));
- button_hist_prev->set_icon(get_theme_icon(SNAME("Forward"), ei));
+ button_hist_next->set_icon(get_theme_icon(SNAME("Back"), SNAME("EditorIcons")));
+ button_hist_prev->set_icon(get_theme_icon(SNAME("Forward"), SNAME("EditorIcons")));
} else {
- button_hist_next->set_icon(get_theme_icon(SNAME("Forward"), ei));
- button_hist_prev->set_icon(get_theme_icon(SNAME("Back"), ei));
+ button_hist_next->set_icon(get_theme_icon(SNAME("Forward"), SNAME("EditorIcons")));
+ button_hist_prev->set_icon(get_theme_icon(SNAME("Back"), SNAME("EditorIcons")));
}
if (file_list_display_mode == FILE_LIST_DISPLAY_LIST) {
button_file_list_display_mode->set_icon(get_theme_icon(SNAME("FileThumbnail"), SNAME("EditorIcons")));
@@ -428,13 +425,13 @@ void FileSystemDock::_notification(int p_what) {
button_file_list_display_mode->set_icon(get_theme_icon(SNAME("FileList"), SNAME("EditorIcons")));
}
- tree_search_box->set_right_icon(get_theme_icon(SNAME("Search"), ei));
+ tree_search_box->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
tree_search_box->set_clear_button_enabled(true);
- tree_button_sort->set_icon(get_theme_icon(SNAME("Sort"), ei));
+ tree_button_sort->set_icon(get_theme_icon(SNAME("Sort"), SNAME("EditorIcons")));
- file_list_search_box->set_right_icon(get_theme_icon(SNAME("Search"), ei));
+ file_list_search_box->set_right_icon(get_theme_icon(SNAME("Search"), SNAME("EditorIcons")));
file_list_search_box->set_clear_button_enabled(true);
- file_list_button_sort->set_icon(get_theme_icon(SNAME("Sort"), ei));
+ file_list_button_sort->set_icon(get_theme_icon(SNAME("Sort"), SNAME("EditorIcons")));
// Update always show folders.
bool new_always_show_folders = bool(EditorSettings::get_singleton()->get("docks/filesystem/always_show_folders"));
@@ -718,7 +715,6 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
String directory = path;
String file = "";
- String ei = "EditorIcons";
int thumbnail_size = EditorSettings::get_singleton()->get("docks/filesystem/thumbnail_size");
thumbnail_size *= EDSCALE;
Ref<Texture2D> folder_thumbnail;
@@ -736,13 +732,13 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
files->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size));
if (thumbnail_size < 64) {
- folder_thumbnail = get_theme_icon(SNAME("FolderMediumThumb"), ei);
- file_thumbnail = get_theme_icon(SNAME("FileMediumThumb"), ei);
- file_thumbnail_broken = get_theme_icon(SNAME("FileDeadMediumThumb"), ei);
+ folder_thumbnail = get_theme_icon(SNAME("FolderMediumThumb"), SNAME("EditorIcons"));
+ file_thumbnail = get_theme_icon(SNAME("FileMediumThumb"), SNAME("EditorIcons"));
+ file_thumbnail_broken = get_theme_icon(SNAME("FileDeadMediumThumb"), SNAME("EditorIcons"));
} else {
- folder_thumbnail = get_theme_icon(SNAME("FolderBigThumb"), ei);
- file_thumbnail = get_theme_icon(SNAME("FileBigThumb"), ei);
- file_thumbnail_broken = get_theme_icon(SNAME("FileDeadBigThumb"), ei);
+ folder_thumbnail = get_theme_icon(SNAME("FolderBigThumb"), SNAME("EditorIcons"));
+ file_thumbnail = get_theme_icon(SNAME("FileBigThumb"), SNAME("EditorIcons"));
+ file_thumbnail_broken = get_theme_icon(SNAME("FileDeadBigThumb"), SNAME("EditorIcons"));
}
} else {
// No thumbnails.
@@ -871,7 +867,6 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
// Fills the ItemList control node from the FileInfos.
String main_scene = ProjectSettings::get_singleton()->get("application/run/main_scene");
- String oi = "Object";
for (FileInfo &E : file_list) {
FileInfo *finfo = &(E);
String fname = finfo->name;
@@ -885,10 +880,10 @@ void FileSystemDock::_update_file_list(bool p_keep_selection) {
// Select the icons.
if (!finfo->import_broken) {
- type_icon = (has_theme_icon(ftype, ei)) ? get_theme_icon(ftype, ei) : get_theme_icon(oi, ei);
+ type_icon = (has_theme_icon(ftype, SNAME("EditorIcons"))) ? get_theme_icon(ftype, SNAME("EditorIcons")) : get_theme_icon(SNAME("Object"), SNAME("EditorIcons"));
big_icon = file_thumbnail;
} else {
- type_icon = get_theme_icon(SNAME("ImportFail"), ei);
+ type_icon = get_theme_icon(SNAME("ImportFail"), SNAME("EditorIcons"));
big_icon = file_thumbnail_broken;
tooltip += "\n" + TTR("Status: Import of file failed. Please fix file and reimport manually.");
}
@@ -1230,6 +1225,30 @@ void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const Strin
if (err != OK) {
EditorNode::get_singleton()->add_io_error(TTR("Error duplicating:") + "\n" + old_path + ".import\n");
}
+
+ // Remove uid from .import file to avoid conflict.
+ Ref<ConfigFile> cfg;
+ cfg.instantiate();
+ cfg->load(new_path + ".import");
+ cfg->erase_section_key("remap", "uid");
+ cfg->save(new_path + ".import");
+ } else if (p_item.is_file && (old_path.get_extension() == "tscn" || old_path.get_extension() == "tres")) {
+ // FIXME: Quick hack to fix text resources. This should be fixed properly.
+ FileAccessRef file = FileAccess::open(old_path, FileAccess::READ, &err);
+ if (err == OK) {
+ PackedStringArray lines = file->get_as_utf8_string().split("\n");
+ String line = lines[0];
+
+ if (line.contains("uid")) {
+ line = line.substr(0, line.find(" uid")) + "]";
+ lines.write[0] = line;
+
+ FileAccessRef file2 = FileAccess::open(new_path, FileAccess::WRITE, &err);
+ if (err == OK) {
+ file2->store_string(String("\n").join(lines));
+ }
+ }
+ }
}
} else {
EditorNode::get_singleton()->add_io_error(TTR("Error duplicating:") + "\n" + old_path + "\n");
diff --git a/editor/import/dynamicfont_import_settings.cpp b/editor/import/dynamicfont_import_settings.cpp
index 81b98c1d45..244352fbb2 100644
--- a/editor/import/dynamicfont_import_settings.cpp
+++ b/editor/import/dynamicfont_import_settings.cpp
@@ -495,7 +495,7 @@ void DynamicFontImportSettings::_variation_add() {
vars_item->set_text(0, TTR("New configuration"));
vars_item->set_editable(0, true);
- vars_item->add_button(1, vars_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove Variation"));
+ vars_item->add_button(1, vars_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove Variation"));
vars_item->set_button_color(1, 0, Color(1, 1, 1, 0.75));
Ref<DynamicFontImportSettingsData> import_variation_data;
@@ -643,8 +643,8 @@ void DynamicFontImportSettings::_glyph_selected() {
TreeItem *item = glyph_table->get_selected();
ERR_FAIL_NULL(item);
- Color scol = glyph_table->get_theme_color("box_selection_fill_color", "Editor");
- Color fcol = glyph_table->get_theme_color("font_selected_color", "Editor");
+ Color scol = glyph_table->get_theme_color(SNAME("box_selection_fill_color"), SNAME("Editor"));
+ Color fcol = glyph_table->get_theme_color(SNAME("font_selected_color"), SNAME("Editor"));
scol.a = 1.f;
int32_t c = item->get_metadata(glyph_table->get_selected_column());
@@ -705,8 +705,8 @@ void DynamicFontImportSettings::_edit_range(int32_t p_start, int32_t p_end) {
TreeItem *root = glyph_table->create_item();
ERR_FAIL_NULL(root);
- Color scol = glyph_table->get_theme_color("box_selection_fill_color", "Editor");
- Color fcol = glyph_table->get_theme_color("font_selected_color", "Editor");
+ Color scol = glyph_table->get_theme_color(SNAME("box_selection_fill_color"), SNAME("Editor"));
+ Color fcol = glyph_table->get_theme_color(SNAME("font_selected_color"), SNAME("Editor"));
scol.a = 1.f;
TreeItem *item = nullptr;
@@ -719,12 +719,12 @@ void DynamicFontImportSettings::_edit_range(int32_t p_start, int32_t p_end) {
item->set_text(0, _pad_zeros(String::num_int64(c, 16)));
item->set_text_alignment(0, HORIZONTAL_ALIGNMENT_LEFT);
item->set_selectable(0, false);
- item->set_custom_bg_color(0, glyph_table->get_theme_color("dark_color_3", "Editor"));
+ item->set_custom_bg_color(0, glyph_table->get_theme_color(SNAME("dark_color_3"), SNAME("Editor")));
}
if (font_main->has_char(c)) {
item->set_text(col + 1, String::chr(c));
item->set_custom_color(col + 1, Color(1, 1, 1));
- if (selected_chars.has(c) || (font_main->get_data(0).is_valid() && selected_glyphs.has(font_main->get_data(0)->get_glyph_index(get_theme_font_size("font_size") * 2, c)))) {
+ if (selected_chars.has(c) || (font_main->get_data(0).is_valid() && selected_glyphs.has(font_main->get_data(0)->get_glyph_index(get_theme_font_size(SNAME("font_size")) * 2, c)))) {
item->set_custom_color(col + 1, fcol);
item->set_custom_bg_color(col + 1, scol);
} else {
@@ -732,13 +732,13 @@ void DynamicFontImportSettings::_edit_range(int32_t p_start, int32_t p_end) {
item->clear_custom_bg_color(col + 1);
}
} else {
- item->set_custom_bg_color(col + 1, glyph_table->get_theme_color("dark_color_2", "Editor"));
+ item->set_custom_bg_color(col + 1, glyph_table->get_theme_color(SNAME("dark_color_2"), SNAME("Editor")));
}
item->set_metadata(col + 1, c);
item->set_text_alignment(col + 1, HORIZONTAL_ALIGNMENT_CENTER);
item->set_selectable(col + 1, true);
item->set_custom_font(col + 1, font_main);
- item->set_custom_font_size(col + 1, get_theme_font_size("font_size") * 2);
+ item->set_custom_font_size(col + 1, get_theme_font_size(SNAME("font_size")) * 2);
col++;
if (col == 16) {
@@ -752,8 +752,8 @@ bool DynamicFontImportSettings::_char_update(int32_t p_char) {
if (selected_chars.has(p_char)) {
selected_chars.erase(p_char);
return false;
- } else if (font_main->get_data(0).is_valid() && selected_glyphs.has(font_main->get_data(0)->get_glyph_index(get_theme_font_size("font_size") * 2, p_char))) {
- selected_glyphs.erase(font_main->get_data(0)->get_glyph_index(get_theme_font_size("font_size") * 2, p_char));
+ } else if (font_main->get_data(0).is_valid() && selected_glyphs.has(font_main->get_data(0)->get_glyph_index(get_theme_font_size(SNAME("font_size")) * 2, p_char))) {
+ selected_glyphs.erase(font_main->get_data(0)->get_glyph_index(get_theme_font_size(SNAME("font_size")) * 2, p_char));
return false;
} else {
selected_chars.insert(p_char);
@@ -767,7 +767,7 @@ void DynamicFontImportSettings::_range_update(int32_t p_start, int32_t p_end) {
for (int32_t i = p_start; i <= p_end; i++) {
if (font_main->has_char(i)) {
if (font_main->get_data(0).is_valid()) {
- all_selected = all_selected && (selected_chars.has(i) || (font_main->get_data(0).is_valid() && selected_glyphs.has(font_main->get_data(0)->get_glyph_index(get_theme_font_size("font_size") * 2, i))));
+ all_selected = all_selected && (selected_chars.has(i) || (font_main->get_data(0).is_valid() && selected_glyphs.has(font_main->get_data(0)->get_glyph_index(get_theme_font_size(SNAME("font_size")) * 2, i))));
} else {
all_selected = all_selected && selected_chars.has(i);
}
@@ -780,7 +780,7 @@ void DynamicFontImportSettings::_range_update(int32_t p_start, int32_t p_end) {
} else {
selected_chars.erase(i);
if (font_main->get_data(0).is_valid()) {
- selected_glyphs.erase(font_main->get_data(0)->get_glyph_index(get_theme_font_size("font_size") * 2, i));
+ selected_glyphs.erase(font_main->get_data(0)->get_glyph_index(get_theme_font_size(SNAME("font_size")) * 2, i));
}
}
}
@@ -809,7 +809,7 @@ void DynamicFontImportSettings::_lang_add_item(const String &p_locale) {
lang_item->set_checked(0, false);
lang_item->set_text(1, p_locale);
lang_item->set_editable(1, true);
- lang_item->add_button(2, lang_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ lang_item->add_button(2, lang_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
lang_item->set_button_color(2, 0, Color(1, 1, 1, 0.75));
}
@@ -841,7 +841,7 @@ void DynamicFontImportSettings::_ot_add_item(int p_option) {
ot_item->set_editable(0, false);
ot_item->set_text(1, "1");
ot_item->set_editable(1, true);
- ot_item->add_button(2, ot_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ ot_item->add_button(2, ot_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
ot_item->set_button_color(2, 0, Color(1, 1, 1, 0.75));
}
@@ -868,7 +868,7 @@ void DynamicFontImportSettings::_script_add_item(int p_option) {
script_item->set_checked(0, false);
script_item->set_text(1, script_codes[p_option]);
script_item->set_editable(1, true);
- script_item->add_button(2, lang_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ script_item->add_button(2, lang_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
script_item->set_button_color(2, 0, Color(1, 1, 1, 0.75));
}
@@ -895,10 +895,10 @@ void DynamicFontImportSettings::_notification(int p_what) {
if (p_what == NOTIFICATION_READY) {
connect("confirmed", callable_mp(this, &DynamicFontImportSettings::_re_import));
} else if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
- add_lang->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
- add_script->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
- add_var->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
- add_ot->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
+ add_lang->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
+ add_script->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
+ add_var->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
+ add_ot->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
}
}
@@ -1043,7 +1043,7 @@ void DynamicFontImportSettings::open_settings(const String &p_path) {
inspector_vars->edit(nullptr);
inspector_general->edit(nullptr);
- int gww = get_theme_font("font")->get_string_size("00000", get_theme_font_size("font_size")).x + 50;
+ int gww = get_theme_font(SNAME("font"))->get_string_size("00000", get_theme_font_size(SNAME("font_size"))).x + 50;
glyph_table->set_column_custom_minimum_width(0, gww);
glyph_table->clear();
@@ -1146,7 +1146,7 @@ void DynamicFontImportSettings::open_settings(const String &p_path) {
vars_item->set_text(0, TTR("Configuration") + " " + itos(i));
vars_item->set_editable(0, true);
- vars_item->add_button(1, vars_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove Variation"));
+ vars_item->add_button(1, vars_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove Variation"));
vars_item->set_button_color(1, 0, Color(1, 1, 1, 0.75));
Ref<DynamicFontImportSettingsData> import_variation_data_custom;
@@ -1184,7 +1184,7 @@ void DynamicFontImportSettings::open_settings(const String &p_path) {
lang_item->set_checked(0, true);
lang_item->set_text(1, _langs[i]);
lang_item->set_editable(1, true);
- lang_item->add_button(2, lang_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ lang_item->add_button(2, lang_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
}
} else if (key == "support_overrides/language_disabled") {
PackedStringArray _langs = config->get_value("params", key);
@@ -1197,7 +1197,7 @@ void DynamicFontImportSettings::open_settings(const String &p_path) {
lang_item->set_checked(0, false);
lang_item->set_text(1, _langs[i]);
lang_item->set_editable(1, true);
- lang_item->add_button(2, lang_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ lang_item->add_button(2, lang_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
}
} else if (key == "support_overrides/script_enabled") {
PackedStringArray _scripts = config->get_value("params", key);
@@ -1210,7 +1210,7 @@ void DynamicFontImportSettings::open_settings(const String &p_path) {
script_item->set_checked(0, true);
script_item->set_text(1, _scripts[i]);
script_item->set_editable(1, true);
- script_item->add_button(2, lang_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ script_item->add_button(2, lang_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
}
} else if (key == "support_overrides/script_disabled") {
PackedStringArray _scripts = config->get_value("params", key);
@@ -1223,7 +1223,7 @@ void DynamicFontImportSettings::open_settings(const String &p_path) {
script_item->set_checked(0, false);
script_item->set_text(1, _scripts[i]);
script_item->set_editable(1, true);
- script_item->add_button(2, lang_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ script_item->add_button(2, lang_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
}
} else if (key == "opentype_feature_overrides") {
Dictionary features = config->get_value("params", key);
@@ -1239,7 +1239,7 @@ void DynamicFontImportSettings::open_settings(const String &p_path) {
ot_item->set_editable(0, false);
ot_item->set_text(1, itos(value));
ot_item->set_editable(1, true);
- ot_item->add_button(2, ot_list->get_theme_icon("Remove", "EditorIcons"), BUTTON_REMOVE_VAR, false, TTR("Remove"));
+ ot_item->add_button(2, ot_list->get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")), BUTTON_REMOVE_VAR, false, TTR("Remove"));
ot_item->set_button_color(2, 0, Color(1, 1, 1, 0.75));
}
} else {
@@ -1356,7 +1356,7 @@ DynamicFontImportSettings::DynamicFontImportSettings() {
menu_ot->add_child(menu_ot_cu);
menu_ot_cu->connect("id_pressed", callable_mp(this, &DynamicFontImportSettings::_ot_add_item));
- Color warn_color = (EditorNode::get_singleton()) ? EditorNode::get_singleton()->get_gui_base()->get_theme_color("warning_color", "Editor") : Color(1, 1, 0);
+ Color warn_color = (EditorNode::get_singleton()) ? EditorNode::get_singleton()->get_gui_base()->get_theme_color(SNAME("warning_color"), SNAME("Editor")) : Color(1, 1, 0);
// Root layout
@@ -1438,7 +1438,7 @@ DynamicFontImportSettings::DynamicFontImportSettings() {
add_var = memnew(Button);
page2_hb_vars->add_child(add_var);
add_var->set_tooltip(TTR("Add configuration"));
- add_var->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
+ add_var->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
add_var->connect("pressed", callable_mp(this, &DynamicFontImportSettings::_variation_add));
vars_list = memnew(Tree);
@@ -1545,8 +1545,8 @@ DynamicFontImportSettings::DynamicFontImportSettings() {
for (int i = 0; i < 16; i++) {
glyph_table->set_column_title(i + 1, String::num_int64(i, 16));
}
- glyph_table->add_theme_style_override("selected", glyph_table->get_theme_stylebox("bg"));
- glyph_table->add_theme_style_override("selected_focus", glyph_table->get_theme_stylebox("bg"));
+ glyph_table->add_theme_style_override("selected", glyph_table->get_theme_stylebox(SNAME("bg")));
+ glyph_table->add_theme_style_override("selected_focus", glyph_table->get_theme_stylebox(SNAME("bg")));
glyph_table->add_theme_constant_override("hseparation", 0);
glyph_table->set_h_size_flags(Control::SIZE_EXPAND_FILL);
glyph_table->set_v_size_flags(Control::SIZE_EXPAND_FILL);
@@ -1590,7 +1590,7 @@ DynamicFontImportSettings::DynamicFontImportSettings() {
add_lang = memnew(Button);
hb_lang->add_child(add_lang);
add_lang->set_tooltip(TTR("Add language override"));
- add_lang->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
+ add_lang->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
add_lang->connect("pressed", callable_mp(this, &DynamicFontImportSettings::_lang_add));
lang_list = memnew(Tree);
@@ -1618,7 +1618,7 @@ DynamicFontImportSettings::DynamicFontImportSettings() {
add_script = memnew(Button);
hb_script->add_child(add_script);
add_script->set_tooltip(TTR("Add script override"));
- add_script->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
+ add_script->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
add_script->connect("pressed", callable_mp(this, &DynamicFontImportSettings::_script_add));
script_list = memnew(Tree);
@@ -1646,7 +1646,7 @@ DynamicFontImportSettings::DynamicFontImportSettings() {
add_ot = memnew(Button);
hb_ot->add_child(add_ot);
add_ot->set_tooltip(TTR("Add feature override"));
- add_ot->set_icon(add_var->get_theme_icon("Add", "EditorIcons"));
+ add_ot->set_icon(add_var->get_theme_icon(SNAME("Add"), SNAME("EditorIcons")));
add_ot->connect("pressed", callable_mp(this, &DynamicFontImportSettings::_ot_add));
ot_list = memnew(Tree);
diff --git a/editor/plugins/animation_blend_tree_editor_plugin.cpp b/editor/plugins/animation_blend_tree_editor_plugin.cpp
index b000ff8eee..40d6bc48e7 100644
--- a/editor/plugins/animation_blend_tree_editor_plugin.cpp
+++ b/editor/plugins/animation_blend_tree_editor_plugin.cpp
@@ -300,7 +300,7 @@ void AnimationNodeBlendTreeEditor::_add_node(int p_idx) {
base_name = add_options[p_idx].name;
} else {
ERR_FAIL_COND(add_options[p_idx].script.is_null());
- String base_type = add_options[p_idx].script->get_instance_base_type();
+ StringName base_type = add_options[p_idx].script->get_instance_base_type();
AnimationNode *an = Object::cast_to<AnimationNode>(ClassDB::instantiate(base_type));
ERR_FAIL_COND(!an);
anode = Ref<AnimationNode>(an);
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index 8d2e6a13b4..aa8ad55ff3 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -5804,7 +5804,7 @@ void CanvasItemEditorViewport::_create_nodes(Node *parent, Node *child, String &
}
// make visible for certain node type
- if (ClassDB::is_parent_class(child->get_class(), "Control")) {
+ if (Object::cast_to<Control>(child)) {
Size2 texture_size = texture->get_size();
editor_data->get_undo_redo().add_do_property(child, "rect_size", texture_size);
} else if (Object::cast_to<Polygon2D>(child)) {
@@ -5935,29 +5935,32 @@ bool CanvasItemEditorViewport::can_drop_data(const Point2 &p_point, const Varian
if (String(d["type"]) == "files") {
Vector<String> files = d["files"];
bool can_instantiate = false;
- for (int i = 0; i < files.size(); i++) { // check if dragged files contain resource or scene can be created at least once
- RES res = ResourceLoader::load(files[i]);
- if (res.is_null()) {
- continue;
- }
- String type = res->get_class();
- if (type == "PackedScene") {
- Ref<PackedScene> sdata = Ref<PackedScene>(Object::cast_to<PackedScene>(*res));
- Node *instantiated_scene = sdata->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
- if (!instantiated_scene) {
+
+ List<String> scene_extensions;
+ ResourceLoader::get_recognized_extensions_for_type("PackedScene", &scene_extensions);
+ List<String> texture_extensions;
+ ResourceLoader::get_recognized_extensions_for_type("Texture2D", &texture_extensions);
+
+ for (int i = 0; i < files.size(); i++) {
+ // Check if dragged files with texture or scene extension can be created at least once.
+ if (texture_extensions.find(files[i].get_extension()) || scene_extensions.find(files[i].get_extension())) {
+ RES res = ResourceLoader::load(files[i]);
+ if (res.is_null()) {
continue;
}
- memdelete(instantiated_scene);
- } else if (ClassDB::is_parent_class(type, "Texture2D")) {
- Ref<Texture2D> texture = Ref<Texture2D>(Object::cast_to<Texture2D>(*res));
- if (!texture.is_valid()) {
+ Ref<PackedScene> scn = res;
+ if (scn.is_valid()) {
+ Node *instantiated_scene = scn->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
+ if (!instantiated_scene) {
+ continue;
+ }
+ memdelete(instantiated_scene);
+ } else {
continue;
}
- } else {
- continue;
+ can_instantiate = true;
+ break;
}
- can_instantiate = true;
- break;
}
if (can_instantiate) {
if (!preview_node->get_parent()) { // create preview only once
diff --git a/editor/plugins/editor_preview_plugins.cpp b/editor/plugins/editor_preview_plugins.cpp
index 7e0019faac..d23b52014e 100644
--- a/editor/plugins/editor_preview_plugins.cpp
+++ b/editor/plugins/editor_preview_plugins.cpp
@@ -188,7 +188,7 @@ bool EditorImagePreviewPlugin::generate_small_preview_automatically() const {
}
////////////////////////////////////////////////////////////////////////////
-/////////////////////////////////////////////////
+
bool EditorBitmapPreviewPlugin::handles(const String &p_type) const {
return ClassDB::is_parent_class(p_type, "BitMap");
}
@@ -308,7 +308,7 @@ void EditorMaterialPreviewPlugin::_preview_done() {
}
bool EditorMaterialPreviewPlugin::handles(const String &p_type) const {
- return ClassDB::is_parent_class(p_type, "Material"); //any material
+ return ClassDB::is_parent_class(p_type, "Material"); // Any material.
}
bool EditorMaterialPreviewPlugin::generate_small_preview_automatically() const {
@@ -699,7 +699,7 @@ void EditorMeshPreviewPlugin::_preview_done() {
}
bool EditorMeshPreviewPlugin::handles(const String &p_type) const {
- return ClassDB::is_parent_class(p_type, "Mesh"); //any Mesh
+ return ClassDB::is_parent_class(p_type, "Mesh"); // Any mesh.
}
Ref<Texture2D> EditorMeshPreviewPlugin::generate(const RES &p_from, const Size2 &p_size) const {
diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp
index 0c0188e8d1..f79b5027cb 100644
--- a/editor/plugins/node_3d_editor_plugin.cpp
+++ b/editor/plugins/node_3d_editor_plugin.cpp
@@ -384,6 +384,28 @@ int Node3DEditorViewport::get_selected_count() const {
return count;
}
+void Node3DEditorViewport::cancel_transform() {
+ _edit.mode = TRANSFORM_NONE;
+
+ List<Node *> &selection = editor_selection->get_selected_node_list();
+
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
+ Node3D *sp = Object::cast_to<Node3D>(E->get());
+ if (!sp) {
+ continue;
+ }
+
+ Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
+ if (!se) {
+ continue;
+ }
+
+ sp->set_global_transform(se->original);
+ }
+ surface->update();
+ set_message(TTR("Transform Aborted."), 3);
+}
+
float Node3DEditorViewport::get_znear() const {
return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
}
@@ -864,12 +886,15 @@ void Node3DEditorViewport::_update_name() {
view_menu->reset_size();
}
-void Node3DEditorViewport::_compute_edit(const Point2 &p_point) {
+void Node3DEditorViewport::_compute_edit(const Point2 &p_point, const bool p_auto_center) {
+ _edit.original_local = spatial_editor->are_local_coords_enabled();
_edit.click_ray = _get_ray(p_point);
_edit.click_ray_pos = _get_ray_pos(p_point);
_edit.plane = TRANSFORM_VIEW;
+ if (p_auto_center) {
+ _edit.center = spatial_editor->get_gizmo_transform().origin;
+ }
spatial_editor->update_transform_gizmo();
- _edit.center = spatial_editor->get_gizmo_transform().origin;
Node3D *selected = spatial_editor->get_single_selected_node();
Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
@@ -1018,24 +1043,40 @@ bool Node3DEditorViewport::_transform_gizmo_select(const Vector2 &p_screenpos, b
if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE) {
int col_axis = -1;
- float col_d = 1e20;
- for (int i = 0; i < 3; i++) {
- Plane plane(gt.basis.get_axis(i).normalized(), gt.origin);
- Vector3 r;
- if (!plane.intersects_ray(ray_pos, ray, &r)) {
- continue;
+ Vector3 hit_position;
+ Vector3 hit_normal;
+ real_t ray_length = gt.origin.distance_to(ray_pos) + (GIZMO_CIRCLE_SIZE * gizmo_scale) * 4.0f;
+ if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * ray_length, gt.origin, gizmo_scale * (GIZMO_CIRCLE_SIZE), &hit_position, &hit_normal)) {
+ if (hit_normal.dot(_get_camera_normal()) < 0.05) {
+ hit_position = gt.xform_inv(hit_position).abs();
+ int min_axis = hit_position.min_axis_index();
+ if (hit_position[min_axis] < gizmo_scale * GIZMO_RING_HALF_WIDTH) {
+ col_axis = min_axis;
+ }
}
+ }
+
+ if (col_axis == -1) {
+ float col_d = 1e20;
- const real_t dist = r.distance_to(gt.origin);
- const Vector3 r_dir = (r - gt.origin).normalized();
+ for (int i = 0; i < 3; i++) {
+ Plane plane(gt.basis.get_axis(i).normalized(), gt.origin);
+ Vector3 r;
+ if (!plane.intersects_ray(ray_pos, ray, &r)) {
+ continue;
+ }
+
+ const real_t dist = r.distance_to(gt.origin);
+ const Vector3 r_dir = (r - gt.origin).normalized();
- if (_get_camera_normal().dot(r_dir) <= 0.005) {
- if (dist > gizmo_scale * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gizmo_scale * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
- const real_t d = ray_pos.distance_to(r);
- if (d < col_d) {
- col_d = d;
- col_axis = i;
+ if (_get_camera_normal().dot(r_dir) <= 0.005) {
+ if (dist > gizmo_scale * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gizmo_scale * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
+ const real_t d = ray_pos.distance_to(r);
+ if (d < col_d) {
+ col_d = d;
+ col_axis = i;
+ }
}
}
}
@@ -1325,6 +1366,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
}
}
+ _edit.center = spatial_editor->get_gizmo_target_center();
Ref<InputEventMouseButton> b = p_event;
if (b.is_valid()) {
@@ -1375,39 +1417,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
}
if (_edit.mode != TRANSFORM_NONE && b->is_pressed()) {
- //cancel motion
- _edit.mode = TRANSFORM_NONE;
-
- List<Node *> &selection = editor_selection->get_selected_node_list();
-
- for (Node *E : selection) {
- Node3D *sp = Object::cast_to<Node3D>(E);
- if (!sp) {
- continue;
- }
-
- Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
- if (!se) {
- continue;
- }
-
- if (se->gizmo.is_valid()) {
- Vector<int> ids;
- Vector<Transform3D> restore;
-
- for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
- ids.push_back(GE.key);
- restore.push_back(GE.value);
- }
-
- se->gizmo->commit_subgizmos(ids, restore, true);
- spatial_editor->update_transform_gizmo();
- } else {
- sp->set_global_transform(se->original);
- }
- }
- surface->update();
- set_message(TTR("Transform Aborted."), 3);
+ cancel_transform();
}
if (b->is_pressed()) {
@@ -1461,6 +1471,10 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
} break;
case MouseButton::LEFT: {
if (b->is_pressed()) {
+ if (_edit.mode != TRANSFORM_NONE && _edit.instant) {
+ commit_transform();
+ break; // just commit the edit, stop processing the event so we don't deselect the object
+ }
NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation/navigation_scheme").operator int();
if ((nav_scheme == NAVIGATION_MAYA || nav_scheme == NAVIGATION_MODO) && b->is_alt_pressed()) {
break;
@@ -1567,33 +1581,17 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
clicked = ObjectID();
if ((spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT && b->is_command_pressed()) || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE) {
- /* HANDLE ROTATION */
- if (get_selected_count() == 0) {
- break; //bye
- }
- //handle rotate
- _edit.mode = TRANSFORM_ROTATE;
- _compute_edit(b->get_position());
+ begin_transform(TRANSFORM_ROTATE, false);
break;
}
if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
- if (get_selected_count() == 0) {
- break; //bye
- }
- //handle translate
- _edit.mode = TRANSFORM_TRANSLATE;
- _compute_edit(b->get_position());
+ begin_transform(TRANSFORM_TRANSLATE, false);
break;
}
if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
- if (get_selected_count() == 0) {
- break; //bye
- }
- //handle scale
- _edit.mode = TRANSFORM_SCALE;
- _compute_edit(b->get_position());
+ begin_transform(TRANSFORM_SCALE, false);
break;
}
@@ -1648,32 +1646,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
se->gizmo->commit_subgizmos(ids, restore, false);
spatial_editor->update_transform_gizmo();
} else {
- static const char *_transform_name[4] = {
- TTRC("None"),
- TTRC("Rotate"),
- // TRANSLATORS: This refers to the movement that changes the position of an object.
- TTRC("Translate"),
- TTRC("Scale"),
- };
- undo_redo->create_action(TTRGET(_transform_name[_edit.mode]));
-
- List<Node *> &selection = editor_selection->get_selected_node_list();
-
- for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
- Node3D *sp = Object::cast_to<Node3D>(E->get());
- if (!sp) {
- continue;
- }
-
- Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
- if (!sel_item) {
- continue;
- }
-
- undo_redo->add_do_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
- undo_redo->add_undo_method(sp, "set_global_transform", sel_item->original);
- }
- undo_redo->commit_action();
+ commit_transform();
}
_edit.mode = TRANSFORM_NONE;
set_message("");
@@ -1739,7 +1712,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
set_message(n + ": " + String(v));
- } else if ((m->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE) {
+ } else if ((m->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE || _edit.instant) {
if (nav_scheme == NAVIGATION_MAYA && m->is_alt_pressed()) {
nav_mode = NAVIGATION_ORBIT;
} else if (nav_scheme == NAVIGATION_MODO && m->is_alt_pressed() && m->is_shift_pressed()) {
@@ -1767,324 +1740,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
return;
}
- Vector3 ray_pos = _get_ray_pos(m->get_position());
- Vector3 ray = _get_ray(m->get_position());
- double snap = EDITOR_GET("interface/inspector/default_float_step");
- int snap_step_decimals = Math::range_step_decimals(snap);
-
- switch (_edit.mode) {
- case TRANSFORM_SCALE: {
- Vector3 motion_mask;
- Plane plane;
- bool plane_mv = false;
-
- switch (_edit.plane) {
- case TRANSFORM_VIEW:
- motion_mask = Vector3(0, 0, 0);
- plane = Plane(_get_camera_normal(), _edit.center);
- break;
- case TRANSFORM_X_AXIS:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized();
- plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
- break;
- case TRANSFORM_Y_AXIS:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
- plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
- break;
- case TRANSFORM_Z_AXIS:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized();
- plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
- break;
- case TRANSFORM_YZ:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized(), _edit.center);
- plane_mv = true;
- break;
- case TRANSFORM_XZ:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized();
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized(), _edit.center);
- plane_mv = true;
- break;
- case TRANSFORM_XY:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized() + spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized(), _edit.center);
- plane_mv = true;
- break;
- }
-
- Vector3 intersection;
- if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
- break;
- }
-
- Vector3 click;
- if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
- break;
- }
-
- Vector3 motion = intersection - click;
- if (_edit.plane != TRANSFORM_VIEW) {
- if (!plane_mv) {
- motion = motion_mask.dot(motion) * motion_mask;
-
- } else {
- // Alternative planar scaling mode
- if (_get_key_modifier(m) != Key::SHIFT) {
- motion = motion_mask.dot(motion) * motion_mask;
- }
- }
-
- } else {
- const real_t center_click_dist = click.distance_to(_edit.center);
- const real_t center_inters_dist = intersection.distance_to(_edit.center);
- if (center_click_dist == 0) {
- break;
- }
-
- const real_t scale = center_inters_dist - center_click_dist;
- motion = Vector3(scale, scale, scale);
- }
-
- motion /= click.distance_to(_edit.center);
-
- // Disable local transformation for TRANSFORM_VIEW
- bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
-
- if (_edit.snap || spatial_editor->is_snap_enabled()) {
- snap = spatial_editor->get_scale_snap() / 100;
- }
- Vector3 motion_snapped = motion;
- motion_snapped.snap(Vector3(snap, snap, snap));
- // This might not be necessary anymore after issue #288 is solved (in 4.0?).
- set_message(TTR("Scaling: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
- String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
- motion = _edit.original.basis.inverse().xform(motion);
-
- List<Node *> &selection = editor_selection->get_selected_node_list();
- for (Node *E : selection) {
- Node3D *sp = Object::cast_to<Node3D>(E);
- if (!sp) {
- continue;
- }
-
- Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
- if (!se) {
- continue;
- }
-
- if (sp->has_meta("_edit_lock_")) {
- continue;
- }
-
- if (se->gizmo.is_valid()) {
- for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
- Transform3D xform = GE.value;
- Transform3D new_xform = _compute_transform(TRANSFORM_SCALE, se->original * xform, xform, motion, snap, local_coords, true); // Force orthogonal with subgizmo.
- if (!local_coords) {
- new_xform = se->original.affine_inverse() * new_xform;
- }
- se->gizmo->set_subgizmo_transform(GE.key, new_xform);
- }
- } else {
- Transform3D new_xform = _compute_transform(TRANSFORM_SCALE, se->original, se->original_local, motion, snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS);
- _transform_gizmo_apply(se->sp, new_xform, local_coords);
- }
- }
-
- spatial_editor->update_transform_gizmo();
- surface->update();
-
- } break;
-
- case TRANSFORM_TRANSLATE: {
- Vector3 motion_mask;
- Plane plane;
- bool plane_mv = false;
-
- switch (_edit.plane) {
- case TRANSFORM_VIEW:
- plane = Plane(_get_camera_normal(), _edit.center);
- break;
- case TRANSFORM_X_AXIS:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized();
- plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
- break;
- case TRANSFORM_Y_AXIS:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
- plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
- break;
- case TRANSFORM_Z_AXIS:
- motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized();
- plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
- break;
- case TRANSFORM_YZ:
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized(), _edit.center);
- plane_mv = true;
- break;
- case TRANSFORM_XZ:
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized(), _edit.center);
- plane_mv = true;
- break;
- case TRANSFORM_XY:
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized(), _edit.center);
- plane_mv = true;
- break;
- }
-
- Vector3 intersection;
- if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
- break;
- }
-
- Vector3 click;
- if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
- break;
- }
-
- Vector3 motion = intersection - click;
- if (_edit.plane != TRANSFORM_VIEW) {
- if (!plane_mv) {
- motion = motion_mask.dot(motion) * motion_mask;
- }
- }
-
- // Disable local transformation for TRANSFORM_VIEW
- bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
-
- if (_edit.snap || spatial_editor->is_snap_enabled()) {
- snap = spatial_editor->get_translate_snap();
- }
- Vector3 motion_snapped = motion;
- motion_snapped.snap(Vector3(snap, snap, snap));
- set_message(TTR("Translating: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
- String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
- motion = spatial_editor->get_gizmo_transform().basis.inverse().xform(motion);
-
- List<Node *> &selection = editor_selection->get_selected_node_list();
- for (Node *E : selection) {
- Node3D *sp = Object::cast_to<Node3D>(E);
- if (!sp) {
- continue;
- }
-
- Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
- if (!se) {
- continue;
- }
-
- if (sp->has_meta("_edit_lock_")) {
- continue;
- }
-
- if (se->gizmo.is_valid()) {
- for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
- Transform3D xform = GE.value;
- Transform3D new_xform = _compute_transform(TRANSFORM_TRANSLATE, se->original * xform, xform, motion, snap, local_coords, true); // Force orthogonal with subgizmo.
- new_xform = se->original.affine_inverse() * new_xform;
- se->gizmo->set_subgizmo_transform(GE.key, new_xform);
- }
- } else {
- Transform3D new_xform = _compute_transform(TRANSFORM_TRANSLATE, se->original, se->original_local, motion, snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS);
- _transform_gizmo_apply(se->sp, new_xform, false);
- }
- }
-
- spatial_editor->update_transform_gizmo();
- surface->update();
-
- } break;
-
- case TRANSFORM_ROTATE: {
- Plane plane;
- Vector3 axis;
-
- switch (_edit.plane) {
- case TRANSFORM_VIEW:
- plane = Plane(_get_camera_normal(), _edit.center);
- break;
- case TRANSFORM_X_AXIS:
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized(), _edit.center);
- axis = Vector3(1, 0, 0);
- break;
- case TRANSFORM_Y_AXIS:
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized(), _edit.center);
- axis = Vector3(0, 1, 0);
- break;
- case TRANSFORM_Z_AXIS:
- plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized(), _edit.center);
- axis = Vector3(0, 0, 1);
- break;
- case TRANSFORM_YZ:
- case TRANSFORM_XZ:
- case TRANSFORM_XY:
- break;
- }
-
- Vector3 intersection;
- if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
- break;
- }
-
- Vector3 click;
- if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
- break;
- }
-
- Vector3 y_axis = (click - _edit.center).normalized();
- Vector3 x_axis = plane.normal.cross(y_axis).normalized();
-
- double angle = Math::atan2(x_axis.dot(intersection - _edit.center), y_axis.dot(intersection - _edit.center));
-
- if (_edit.snap || spatial_editor->is_snap_enabled()) {
- snap = spatial_editor->get_rotate_snap();
- }
- angle = Math::rad2deg(angle) + snap * 0.5; //else it won't reach +180
- angle -= Math::fmod(angle, snap);
- set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
- angle = Math::deg2rad(angle);
-
- bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
-
- List<Node *> &selection = editor_selection->get_selected_node_list();
- for (Node *E : selection) {
- Node3D *sp = Object::cast_to<Node3D>(E);
- if (!sp) {
- continue;
- }
-
- Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
- if (!se) {
- continue;
- }
-
- if (sp->has_meta("_edit_lock_")) {
- continue;
- }
-
- Vector3 compute_axis = local_coords ? axis : plane.normal;
- if (se->gizmo.is_valid()) {
- for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
- Transform3D xform = GE.value;
-
- Transform3D new_xform = _compute_transform(TRANSFORM_ROTATE, se->original * xform, xform, compute_axis, angle, local_coords, true); // Force orthogonal with subgizmo.
- if (!local_coords) {
- new_xform = se->original.affine_inverse() * new_xform;
- }
- se->gizmo->set_subgizmo_transform(GE.key, new_xform);
- }
- } else {
- Transform3D new_xform = _compute_transform(TRANSFORM_ROTATE, se->original, se->original_local, compute_axis, angle, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS);
- _transform_gizmo_apply(se->sp, new_xform, local_coords);
- }
- }
-
- spatial_editor->update_transform_gizmo();
- surface->update();
-
- } break;
- default: {
- }
- }
+ update_transform(m->get_position(), _get_key_modifier(m) == Key::SHIFT);
}
} else if ((m->get_button_mask() & MouseButton::MASK_RIGHT) != MouseButton::NONE || freelook_active) {
if (nav_scheme == NAVIGATION_MAYA && m->is_alt_pressed()) {
@@ -2225,6 +1881,51 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
}
}
+ if (_edit.mode != TRANSFORM_NONE) {
+ // We're actively transforming, handle keys specially
+ TransformPlane new_plane = TRANSFORM_VIEW;
+ String new_message;
+ if (ED_IS_SHORTCUT("spatial_editor/lock_transform_x", p_event)) {
+ new_plane = TRANSFORM_X_AXIS;
+ new_message = TTR("X-Axis Transform.");
+ } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_y", p_event)) {
+ new_plane = TRANSFORM_Y_AXIS;
+ new_message = TTR("Y-Axis Transform.");
+ } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_z", p_event)) {
+ new_plane = TRANSFORM_Z_AXIS;
+ new_message = TTR("Z-Axis Transform.");
+ } else if (_edit.mode != TRANSFORM_ROTATE) { // rotating on a plane doesn't make sense
+ if (ED_IS_SHORTCUT("spatial_editor/lock_transform_yz", p_event)) {
+ new_plane = TRANSFORM_YZ;
+ new_message = TTR("YZ-Plane Transform.");
+ } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xz", p_event)) {
+ new_plane = TRANSFORM_XZ;
+ new_message = TTR("XZ-Plane Transform.");
+ } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xy", p_event)) {
+ new_plane = TRANSFORM_XY;
+ new_message = TTR("XY-Plane Transform.");
+ }
+ }
+
+ if (new_plane != TRANSFORM_VIEW) {
+ if (new_plane != _edit.plane) {
+ // lock me once and get a global constraint
+ _edit.plane = new_plane;
+ spatial_editor->set_local_coords_enabled(false);
+ } else if (!spatial_editor->are_local_coords_enabled()) {
+ // lock me twice and get a local constraint
+ spatial_editor->set_local_coords_enabled(true);
+ } else {
+ // lock me thrice and we're back where we started
+ _edit.plane = TRANSFORM_VIEW;
+ spatial_editor->set_local_coords_enabled(false);
+ }
+ update_transform(_edit.mouse_pos, Input::get_singleton()->is_key_pressed(Key::SHIFT));
+ set_message(new_message, 2);
+ accept_event();
+ return;
+ }
+ }
if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
if (_edit.mode != TRANSFORM_NONE) {
_edit.snap = !_edit.snap;
@@ -2315,6 +2016,18 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
set_message(TTR("Animation Key Inserted."));
}
+ if (ED_IS_SHORTCUT("spatial_editor/cancel_transform", p_event) && _edit.mode != TRANSFORM_NONE) {
+ cancel_transform();
+ }
+ if (ED_IS_SHORTCUT("spatial_editor/instant_translate", p_event)) {
+ begin_transform(TRANSFORM_TRANSLATE, true);
+ }
+ if (ED_IS_SHORTCUT("spatial_editor/instant_rotate", p_event)) {
+ begin_transform(TRANSFORM_ROTATE, true);
+ }
+ if (ED_IS_SHORTCUT("spatial_editor/instant_scale", p_event)) {
+ begin_transform(TRANSFORM_SCALE, true);
+ }
// Freelook doesn't work in orthogonal mode.
if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", p_event)) {
@@ -3036,7 +2749,7 @@ void Node3DEditorViewport::_draw() {
font->draw_string(ci, msgpos, message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(1, 1, 1, 1));
}
- if (_edit.mode == TRANSFORM_ROTATE) {
+ if (_edit.mode == TRANSFORM_ROTATE && _edit.show_rotation_line) {
Point2 center = _point_to_screen(_edit.center);
Color handle_color;
@@ -3544,6 +3257,13 @@ void Node3DEditorViewport::_init_gizmo_instance(int p_idx) {
RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
RS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
+
+ axis_gizmo_instance[i] = RS::get_singleton()->instance_create();
+ RS::get_singleton()->instance_set_base(axis_gizmo_instance[i], spatial_editor->get_axis_gizmo(i)->get_rid());
+ RS::get_singleton()->instance_set_scenario(axis_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_visible(axis_gizmo_instance[i], true);
+ RS::get_singleton()->instance_geometry_set_cast_shadows_setting(axis_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
+ RS::get_singleton()->instance_set_layer_mask(axis_gizmo_instance[i], layer);
}
// Rotation white outline
@@ -3563,6 +3283,7 @@ void Node3DEditorViewport::_finish_gizmo_instances() {
RS::get_singleton()->free(rotate_gizmo_instance[i]);
RS::get_singleton()->free(scale_gizmo_instance[i]);
RS::get_singleton()->free(scale_plane_gizmo_instance[i]);
+ RS::get_singleton()->free(axis_gizmo_instance[i]);
}
// Rotation white outline
RS::get_singleton()->free(rotate_gizmo_instance[3]);
@@ -3646,7 +3367,7 @@ void Node3DEditorViewport::update_transform_gizmo_view() {
Transform3D xform = spatial_editor->get_gizmo_transform();
- Transform3D camera_xform = camera->get_transform();
+ const Transform3D camera_xform = camera->get_transform();
if (xform.origin.is_equal_approx(camera_xform.origin)) {
for (int i = 0; i < 3; i++) {
@@ -3655,6 +3376,7 @@ void Node3DEditorViewport::update_transform_gizmo_view() {
RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
+ RenderingServer::get_singleton()->instance_set_visible(axis_gizmo_instance[i], false);
}
// Rotation white outline
RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
@@ -3664,11 +3386,63 @@ void Node3DEditorViewport::update_transform_gizmo_view() {
const Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized();
const Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized();
const Plane p = Plane(camz, camera_xform.origin);
- const real_t gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON);
+ const real_t gizmo_d = CLAMP(Math::abs(p.distance_to(xform.origin)), camera->get_near() * 2, camera->get_far() / 2);
const real_t d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
const real_t d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
const real_t dd = MAX(Math::abs(d0 - d1), CMP_EPSILON);
+ // This code ensures the gizmo stays on the screen. This includes if
+ // the gizmo would otherwise be behind the camera, to the sides of
+ // the camera, too close to the edge of the screen, too close to
+ // the camera, or too far away from the camera. First we calculate
+ // where the gizmo would go on screen, then we put it there.
+ const Vector3 object_position = spatial_editor->get_gizmo_target_center();
+ Vector2 gizmo_screen_position = camera->unproject_position(object_position);
+ const Vector2 viewport_size = viewport->get_size();
+ // We would use "camera.is_position_behind(parent_translation)" instead of dot,
+ // except that it also accounts for the near clip plane, which we don't want.
+ const bool is_in_front = camera_xform.basis.get_column(2).dot(object_position - camera_xform.origin) < 0;
+ const bool is_in_viewport = is_in_front && Rect2(Vector2(0, 0), viewport_size).has_point(gizmo_screen_position);
+ if (spatial_editor->is_keep_gizmo_onscreen_enabled()) {
+ if (!spatial_editor->is_gizmo_visible() || is_in_viewport) {
+ // In this case, the gizmo is either not visible, or in the viewport
+ // already, so we should hide the offscreen line.
+ gizmo_offscreen_line->hide();
+ } else {
+ // In this case, the point is not "normally" on screen, and
+ // it should be placed in the center.
+ const Vector2 half_viewport_size = viewport_size / 2;
+ gizmo_screen_position = half_viewport_size;
+ // The rest of this is for drawing the offscreen line.
+ // One point goes in the center of the viewport.
+ // Calculate where to put the other point of the line.
+ Vector2 unprojected_position = camera->unproject_position(object_position);
+ if (!is_in_front) {
+ // When the object is behind, we need to flip and grow the line.
+ unprojected_position -= half_viewport_size;
+ unprojected_position = unprojected_position.normalized() * -half_viewport_size.length_squared();
+ unprojected_position += half_viewport_size;
+ }
+ gizmo_offscreen_line->point1 = half_viewport_size;
+ gizmo_offscreen_line->point2 = unprojected_position;
+ gizmo_offscreen_line->update();
+ gizmo_offscreen_line->show();
+ }
+ // Update the gizmo's position using what we calculated.
+ xform.origin = camera->project_position(gizmo_screen_position, gizmo_d);
+ } else {
+ // In this case, the user does not want the gizmo to be
+ // kept on screen, so we should hide the offscreen line,
+ // and just use the gizmo's unmodified position.
+ gizmo_offscreen_line->hide();
+ if (is_in_viewport) {
+ xform.origin = camera->project_position(gizmo_screen_position, gizmo_d);
+ } else {
+ xform.origin = object_position;
+ }
+ }
+ spatial_editor->set_gizmo_transform(xform);
+
const real_t gizmo_size = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_size");
// At low viewport heights, multiply the gizmo scale based on the viewport height.
// This prevents the gizmo from growing very large and going outside the viewport.
@@ -3677,7 +3451,6 @@ void Node3DEditorViewport::update_transform_gizmo_view() {
(gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
MIN(viewport_base_height, subviewport_container->get_size().height) / viewport_base_height /
subviewport_container->get_stretch_shrink();
- Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
// if the determinant is zero, we should disable the gizmo from being rendered
// this prevents supplying bad values to the renderer and then having to filter it out again
@@ -3699,7 +3472,7 @@ void Node3DEditorViewport::update_transform_gizmo_view() {
if (xform.basis.get_axis(i).normalized().dot(xform.basis.get_axis((i + 1) % 3).normalized()) < 1.0) {
axis_angle = axis_angle.looking_at(xform.basis.get_axis(i).normalized(), xform.basis.get_axis((i + 1) % 3).normalized());
}
- axis_angle.basis.scale(scale);
+ axis_angle.basis *= gizmo_scale;
axis_angle.origin = xform.origin;
RenderingServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], axis_angle);
RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
@@ -3711,10 +3484,18 @@ void Node3DEditorViewport::update_transform_gizmo_view() {
RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
RenderingServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], axis_angle);
RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
+ RenderingServer::get_singleton()->instance_set_transform(axis_gizmo_instance[i], xform);
}
+
+ bool show_axes = spatial_editor->is_gizmo_visible() && _edit.mode != TRANSFORM_NONE;
+ RenderingServer *rs = RenderingServer::get_singleton();
+ rs->instance_set_visible(axis_gizmo_instance[0], show_axes && (_edit.plane == TRANSFORM_X_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_XZ));
+ rs->instance_set_visible(axis_gizmo_instance[1], show_axes && (_edit.plane == TRANSFORM_Y_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_YZ));
+ rs->instance_set_visible(axis_gizmo_instance[2], show_axes && (_edit.plane == TRANSFORM_Z_AXIS || _edit.plane == TRANSFORM_XZ || _edit.plane == TRANSFORM_YZ));
+
// Rotation white outline
xform.orthonormalize();
- xform.basis.scale(scale);
+ xform.basis *= gizmo_scale;
RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], xform);
RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE));
}
@@ -3978,7 +3759,7 @@ AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, boo
if (child) {
AABB child_bounds = _calculate_spatial_bounds(child, false);
- if (bounds.size == Vector3() && p_parent->get_class_name() == StringName("Node3D")) {
+ if (bounds.size == Vector3() && Object::cast_to<Node3D>(p_parent)) {
bounds = child_bounds;
} else {
bounds.merge_with(child_bounds);
@@ -3986,7 +3767,7 @@ AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, boo
}
}
- if (bounds.size == Vector3() && p_parent->get_class_name() != StringName("Node3D")) {
+ if (bounds.size == Vector3() && !Object::cast_to<Node3D>(p_parent)) {
bounds = AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
}
@@ -4213,25 +3994,19 @@ bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant
ResourceLoader::get_recognized_extensions_for_type("Mesh", &mesh_extensions);
for (int i = 0; i < files.size(); i++) {
+ // Check if dragged files with mesh or scene extension can be created at least once.
if (mesh_extensions.find(files[i].get_extension()) || scene_extensions.find(files[i].get_extension())) {
RES res = ResourceLoader::load(files[i]);
if (res.is_null()) {
continue;
}
-
- String type = res->get_class();
- if (type == "PackedScene") {
- Ref<PackedScene> sdata = ResourceLoader::load(files[i]);
- Node *instantiated_scene = sdata->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
+ Ref<PackedScene> scn = res;
+ if (scn.is_valid()) {
+ Node *instantiated_scene = scn->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
if (!instantiated_scene) {
continue;
}
memdelete(instantiated_scene);
- } else if (ClassDB::is_parent_class(type, "Mesh")) {
- Ref<Mesh> mesh = ResourceLoader::load(files[i]);
- if (!mesh.is_valid()) {
- continue;
- }
} else {
continue;
}
@@ -4299,6 +4074,387 @@ void Node3DEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_
_perform_drop_data();
}
+void Node3DEditorViewport::begin_transform(TransformMode p_mode, bool instant) {
+ if (get_selected_count() > 0) {
+ _edit.mode = p_mode;
+ _compute_edit(_edit.mouse_pos, false);
+ _edit.instant = instant;
+ _edit.snap = spatial_editor->is_snap_enabled();
+ }
+}
+
+void Node3DEditorViewport::commit_transform() {
+ ERR_FAIL_COND(_edit.mode == TRANSFORM_NONE);
+ static const char *_transform_name[4] = {
+ TTRC("None"),
+ TTRC("Rotate"),
+ // TRANSLATORS: This refers to the movement that changes the position of an object.
+ TTRC("Translate"),
+ TTRC("Scale"),
+ };
+ undo_redo->create_action(_transform_name[_edit.mode]);
+
+ List<Node *> &selection = editor_selection->get_selected_node_list();
+
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
+ Node3D *sp = Object::cast_to<Node3D>(E->get());
+ if (!sp) {
+ continue;
+ }
+
+ Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
+ if (!se) {
+ continue;
+ }
+
+ undo_redo->add_do_method(sp, "set_global_transform", sp->get_global_gizmo_transform());
+ undo_redo->add_undo_method(sp, "set_global_transform", se->original);
+ }
+ undo_redo->commit_action();
+ _edit.mode = TRANSFORM_NONE;
+ _edit.instant = false;
+ spatial_editor->set_local_coords_enabled(_edit.original_local);
+ set_message("");
+ spatial_editor->update_transform_gizmo();
+ surface->update();
+}
+
+void Node3DEditorViewport::update_transform(Point2 p_mousepos, bool p_shift) {
+ Vector3 ray_pos = _get_ray_pos(p_mousepos);
+ Vector3 ray = _get_ray(p_mousepos);
+ double snap = EDITOR_GET("interface/inspector/default_float_step");
+ int snap_step_decimals = Math::range_step_decimals(snap);
+
+ switch (_edit.mode) {
+ case TRANSFORM_SCALE: {
+ Vector3 motion_mask;
+ Plane plane;
+ bool plane_mv = false;
+
+ switch (_edit.plane) {
+ case TRANSFORM_VIEW:
+ motion_mask = Vector3(0, 0, 0);
+ plane = Plane(_get_camera_normal(), _edit.center);
+ break;
+ case TRANSFORM_X_AXIS:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized();
+ plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
+ break;
+ case TRANSFORM_Y_AXIS:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
+ plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
+ break;
+ case TRANSFORM_Z_AXIS:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized();
+ plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
+ break;
+ case TRANSFORM_YZ:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
+ plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized(), _edit.center);
+ plane_mv = true;
+ break;
+ case TRANSFORM_XZ:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized();
+ plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized(), _edit.center);
+ plane_mv = true;
+ break;
+ case TRANSFORM_XY:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized() + spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
+ plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized(), _edit.center);
+ plane_mv = true;
+ break;
+ }
+
+ Vector3 intersection;
+ if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
+ break;
+ }
+
+ Vector3 click;
+ if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
+ break;
+ }
+
+ Vector3 motion = intersection - click;
+ if (_edit.plane != TRANSFORM_VIEW) {
+ if (!plane_mv) {
+ motion = motion_mask.dot(motion) * motion_mask;
+
+ } else {
+ // Alternative planar scaling mode
+ if (p_shift) {
+ motion = motion_mask.dot(motion) * motion_mask;
+ }
+ }
+
+ } else {
+ const real_t center_click_dist = click.distance_to(_edit.center);
+ const real_t center_inters_dist = intersection.distance_to(_edit.center);
+ if (center_click_dist == 0) {
+ break;
+ }
+
+ const real_t scale = center_inters_dist - center_click_dist;
+ motion = Vector3(scale, scale, scale);
+ }
+
+ motion /= click.distance_to(_edit.center);
+
+ // Disable local transformation for TRANSFORM_VIEW
+ bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
+
+ if (_edit.snap || spatial_editor->is_snap_enabled()) {
+ snap = spatial_editor->get_scale_snap() / 100;
+ }
+ Vector3 motion_snapped = motion;
+ motion_snapped.snap(Vector3(snap, snap, snap));
+ // This might not be necessary anymore after issue #288 is solved (in 4.0?).
+ set_message(TTR("Scaling: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
+ String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
+ motion = _edit.original.basis.inverse().xform(motion);
+
+ List<Node *> &selection = editor_selection->get_selected_node_list();
+ for (Node *E : selection) {
+ Node3D *sp = Object::cast_to<Node3D>(E);
+ if (!sp) {
+ continue;
+ }
+
+ Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
+ if (!se) {
+ continue;
+ }
+
+ if (sp->has_meta("_edit_lock_")) {
+ continue;
+ }
+
+ if (se->gizmo.is_valid()) {
+ for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
+ Transform3D xform = GE.value;
+ Transform3D new_xform = _compute_transform(TRANSFORM_SCALE, se->original * xform, xform, motion, snap, local_coords, true); // Force orthogonal with subgizmo.
+ if (!local_coords) {
+ new_xform = se->original.affine_inverse() * new_xform;
+ }
+ se->gizmo->set_subgizmo_transform(GE.key, new_xform);
+ }
+ } else {
+ Transform3D new_xform = _compute_transform(TRANSFORM_SCALE, se->original, se->original_local, motion, snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS);
+ _transform_gizmo_apply(se->sp, new_xform, local_coords);
+ }
+ }
+
+ spatial_editor->update_transform_gizmo();
+ surface->update();
+
+ } break;
+
+ case TRANSFORM_TRANSLATE: {
+ Vector3 motion_mask;
+ Plane plane;
+ bool plane_mv = false;
+
+ switch (_edit.plane) {
+ case TRANSFORM_VIEW:
+ plane = Plane(_get_camera_normal(), _edit.center);
+ break;
+ case TRANSFORM_X_AXIS:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized();
+ plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
+ break;
+ case TRANSFORM_Y_AXIS:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized();
+ plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
+ break;
+ case TRANSFORM_Z_AXIS:
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized();
+ plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
+ break;
+ case TRANSFORM_YZ:
+ plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(0).normalized(), _edit.center);
+ plane_mv = true;
+ break;
+ case TRANSFORM_XZ:
+ plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(1).normalized(), _edit.center);
+ plane_mv = true;
+ break;
+ case TRANSFORM_XY:
+ plane = Plane(spatial_editor->get_gizmo_transform().basis.get_axis(2).normalized(), _edit.center);
+ plane_mv = true;
+ break;
+ }
+
+ Vector3 intersection;
+ if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
+ break;
+ }
+
+ Vector3 click;
+ if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
+ break;
+ }
+
+ Vector3 motion = intersection - click;
+ if (_edit.plane != TRANSFORM_VIEW) {
+ if (!plane_mv) {
+ motion = motion_mask.dot(motion) * motion_mask;
+ }
+ }
+
+ // Disable local transformation for TRANSFORM_VIEW
+ bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW);
+
+ if (_edit.snap || spatial_editor->is_snap_enabled()) {
+ snap = spatial_editor->get_translate_snap();
+ }
+ Vector3 motion_snapped = motion;
+ motion_snapped.snap(Vector3(snap, snap, snap));
+ set_message(TTR("Translating: ") + "(" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
+ String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
+ motion = spatial_editor->get_gizmo_transform().basis.inverse().xform(motion);
+
+ List<Node *> &selection = editor_selection->get_selected_node_list();
+ for (Node *E : selection) {
+ Node3D *sp = Object::cast_to<Node3D>(E);
+ if (!sp) {
+ continue;
+ }
+
+ Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
+ if (!se) {
+ continue;
+ }
+
+ if (sp->has_meta("_edit_lock_")) {
+ continue;
+ }
+
+ if (se->gizmo.is_valid()) {
+ for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
+ Transform3D xform = GE.value;
+ Transform3D new_xform = _compute_transform(TRANSFORM_TRANSLATE, se->original * xform, xform, motion, snap, local_coords, true); // Force orthogonal with subgizmo.
+ new_xform = se->original.affine_inverse() * new_xform;
+ se->gizmo->set_subgizmo_transform(GE.key, new_xform);
+ }
+ } else {
+ Transform3D new_xform = _compute_transform(TRANSFORM_TRANSLATE, se->original, se->original_local, motion, snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS);
+ _transform_gizmo_apply(se->sp, new_xform, false);
+ }
+ }
+
+ spatial_editor->update_transform_gizmo();
+ surface->update();
+
+ } break;
+
+ case TRANSFORM_ROTATE: {
+ Plane plane = Plane(_get_camera_normal(), _edit.center);
+
+ Vector3 local_axis;
+ Vector3 global_axis;
+ switch (_edit.plane) {
+ case TRANSFORM_VIEW:
+ // local_axis unused
+ global_axis = _get_camera_normal();
+ break;
+ case TRANSFORM_X_AXIS:
+ local_axis = Vector3(1, 0, 0);
+ break;
+ case TRANSFORM_Y_AXIS:
+ local_axis = Vector3(0, 1, 0);
+ break;
+ case TRANSFORM_Z_AXIS:
+ local_axis = Vector3(0, 0, 1);
+ break;
+ case TRANSFORM_YZ:
+ case TRANSFORM_XZ:
+ case TRANSFORM_XY:
+ break;
+ }
+
+ if (_edit.plane != TRANSFORM_VIEW) {
+ global_axis = spatial_editor->get_gizmo_transform().basis.xform(local_axis).normalized();
+ }
+
+ Vector3 intersection;
+ if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
+ break;
+ }
+
+ Vector3 click;
+ if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
+ break;
+ }
+
+ static const float orthogonal_threshold = Math::cos(Math::deg2rad(87.0f));
+ bool axis_is_orthogonal = ABS(plane.normal.dot(global_axis)) < orthogonal_threshold;
+
+ double angle = 0.0f;
+ if (axis_is_orthogonal) {
+ _edit.show_rotation_line = false;
+ Vector3 projection_axis = plane.normal.cross(global_axis);
+ Vector3 delta = intersection - click;
+ float projection = delta.dot(projection_axis);
+ angle = (projection * (Math_PI / 2.0f)) / (gizmo_scale * GIZMO_CIRCLE_SIZE);
+ } else {
+ _edit.show_rotation_line = true;
+ Vector3 click_axis = (click - _edit.center).normalized();
+ Vector3 current_axis = (intersection - _edit.center).normalized();
+ angle = click_axis.signed_angle_to(current_axis, global_axis);
+ }
+
+ if (_edit.snap || spatial_editor->is_snap_enabled()) {
+ snap = spatial_editor->get_rotate_snap();
+ }
+ angle = Math::rad2deg(angle) + snap * 0.5; //else it won't reach +180
+ angle -= Math::fmod(angle, snap);
+ set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
+ angle = Math::deg2rad(angle);
+
+ bool local_coords = (spatial_editor->are_local_coords_enabled() && _edit.plane != TRANSFORM_VIEW); // Disable local transformation for TRANSFORM_VIEW
+
+ List<Node *> &selection = editor_selection->get_selected_node_list();
+ for (Node *E : selection) {
+ Node3D *sp = Object::cast_to<Node3D>(E);
+ if (!sp) {
+ continue;
+ }
+
+ Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
+ if (!se) {
+ continue;
+ }
+
+ if (sp->has_meta("_edit_lock_")) {
+ continue;
+ }
+
+ Vector3 compute_axis = local_coords ? local_axis : global_axis;
+ if (se->gizmo.is_valid()) {
+ for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
+ Transform3D xform = GE.value;
+
+ Transform3D new_xform = _compute_transform(TRANSFORM_ROTATE, se->original * xform, xform, compute_axis, angle, local_coords, true); // Force orthogonal with subgizmo.
+ if (!local_coords) {
+ new_xform = se->original.affine_inverse() * new_xform;
+ }
+ se->gizmo->set_subgizmo_transform(GE.key, new_xform);
+ }
+ } else {
+ Transform3D new_xform = _compute_transform(TRANSFORM_ROTATE, se->original, se->original_local, compute_axis, angle, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS);
+ _transform_gizmo_apply(se->sp, new_xform, local_coords);
+ }
+ }
+
+ spatial_editor->update_transform_gizmo();
+ surface->update();
+
+ } break;
+ default: {
+ }
+ }
+}
+
Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, EditorNode *p_editor, int p_index) {
cpu_time_history_index = 0;
gpu_time_history_index = 0;
@@ -4306,6 +4462,8 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito
_edit.mode = TRANSFORM_NONE;
_edit.plane = TRANSFORM_VIEW;
_edit.snap = true;
+ _edit.show_rotation_line = true;
+ _edit.instant = false;
_edit.gizmo_handle = -1;
_edit.gizmo_handle_secondary = false;
@@ -4322,15 +4480,14 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito
zoom_indicator_delay = 0.0;
spatial_editor = p_spatial_editor;
- SubViewportContainer *c = memnew(SubViewportContainer);
- subviewport_container = c;
- c->set_stretch(true);
- add_child(c);
- c->set_anchors_and_offsets_preset(Control::PRESET_WIDE);
+ subviewport_container = memnew(SubViewportContainer);
+ subviewport_container->set_stretch(true);
+ add_child(subviewport_container);
+ subviewport_container->set_anchors_and_offsets_preset(Control::PRESET_WIDE);
viewport = memnew(SubViewport);
viewport->set_disable_input(true);
- c->add_child(viewport);
+ subviewport_container->add_child(viewport);
surface = memnew(Control);
surface->set_drag_forwarding(this);
add_child(surface);
@@ -4343,6 +4500,9 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito
camera->make_current();
surface->set_focus_mode(FOCUS_ALL);
+ gizmo_offscreen_line = memnew(GizmoOffScreenLine);
+ subviewport_container->add_child(gizmo_offscreen_line);
+
VBoxContainer *vbox = memnew(VBoxContainer);
surface->add_child(vbox);
vbox->set_offset(SIDE_LEFT, 10 * EDSCALE);
@@ -4383,7 +4543,7 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito
display_submenu->add_radio_check_item(TTR("Normal Buffer"), VIEW_DISPLAY_NORMAL_BUFFER);
display_submenu->add_separator();
display_submenu->add_radio_check_item(TTR("Shadow Atlas"), VIEW_DISPLAY_DEBUG_SHADOW_ATLAS);
- display_submenu->add_radio_check_item(TTR("Directional Shadow"), VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS);
+ display_submenu->add_radio_check_item(TTR("Directional Shadow Map"), VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS);
display_submenu->add_separator();
display_submenu->add_radio_check_item(TTR("Decal Atlas"), VIEW_DISPLAY_DEBUG_DECAL_ATLAS);
display_submenu->add_separator();
@@ -4399,14 +4559,14 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito
display_submenu->add_radio_check_item(TTR("SSAO"), VIEW_DISPLAY_DEBUG_SSAO);
display_submenu->add_radio_check_item(TTR("SSIL"), VIEW_DISPLAY_DEBUG_SSIL);
display_submenu->add_separator();
- display_submenu->add_radio_check_item(TTR("GI Buffer"), VIEW_DISPLAY_DEBUG_GI_BUFFER);
+ display_submenu->add_radio_check_item(TTR("VoxelGI/SDFGI Buffer"), VIEW_DISPLAY_DEBUG_GI_BUFFER);
display_submenu->add_separator();
- display_submenu->add_radio_check_item(TTR("Disable LOD"), VIEW_DISPLAY_DEBUG_DISABLE_LOD);
+ display_submenu->add_radio_check_item(TTR("Disable Mesh LOD"), VIEW_DISPLAY_DEBUG_DISABLE_LOD);
display_submenu->add_separator();
- display_submenu->add_radio_check_item(TTR("Omni Light Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS);
- display_submenu->add_radio_check_item(TTR("Spot Light Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS);
+ display_submenu->add_radio_check_item(TTR("OmniLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS);
+ display_submenu->add_radio_check_item(TTR("SpotLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS);
display_submenu->add_radio_check_item(TTR("Decal Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_DECALS);
- display_submenu->add_radio_check_item(TTR("Reflection Probe Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES);
+ display_submenu->add_radio_check_item(TTR("ReflectionProbe Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES);
display_submenu->add_radio_check_item(TTR("Occlusion Culling Buffer"), VIEW_DISPLAY_DEBUG_OCCLUDERS);
display_submenu->set_name("display_advanced");
@@ -4465,6 +4625,16 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito
ED_SHORTCUT("spatial_editor/freelook_down", TTR("Freelook Down"), Key::Q);
ED_SHORTCUT("spatial_editor/freelook_speed_modifier", TTR("Freelook Speed Modifier"), Key::SHIFT);
ED_SHORTCUT("spatial_editor/freelook_slow_modifier", TTR("Freelook Slow Modifier"), Key::ALT);
+ ED_SHORTCUT("spatial_editor/lock_transform_x", TTR("Lock Transformation to X axis"), Key::X);
+ ED_SHORTCUT("spatial_editor/lock_transform_y", TTR("Lock Transformation to Y axis"), Key::Y);
+ ED_SHORTCUT("spatial_editor/lock_transform_z", TTR("Lock Transformation to Z axis"), Key::Z);
+ ED_SHORTCUT("spatial_editor/lock_transform_yz", TTR("Lock Transformation to YZ plane"), KeyModifierMask::SHIFT | Key::X);
+ ED_SHORTCUT("spatial_editor/lock_transform_xz", TTR("Lock Transformation to XZ plane"), KeyModifierMask::SHIFT | Key::Y);
+ ED_SHORTCUT("spatial_editor/lock_transform_xy", TTR("Lock Transformation to XY plane"), KeyModifierMask::SHIFT | Key::Z);
+ ED_SHORTCUT("spatial_editor/cancel_transform", TTR("Cancel Transformation"), Key::ESCAPE);
+ ED_SHORTCUT("spatial_editor/instant_translate", TTR("Begin Translate Transformation"));
+ ED_SHORTCUT("spatial_editor/instant_rotate", TTR("Begin Rotate Transformation"));
+ ED_SHORTCUT("spatial_editor/instant_scale", TTR("Begin Scale Transformation"));
preview_camera = memnew(CheckBox);
preview_camera->set_text(TTR("Preview"));
@@ -4957,6 +5127,7 @@ void Node3DEditor::update_transform_gizmo() {
gizmo.visible = count > 0;
gizmo.transform.origin = (count > 0) ? gizmo_center / count : Vector3();
gizmo.transform.basis = (count == 1) ? gizmo_basis : Basis();
+ gizmo.target_center = gizmo_center / count;
for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
viewports[i]->update_transform_gizmo_view();
@@ -5109,6 +5280,7 @@ Dictionary Node3DEditor::get_state() const {
d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
+ d["keep_gizmo_onscreen"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_KEEP_GIZMO_ONSCREEN));
d["fov"] = get_fov();
d["znear"] = get_znear();
d["zfar"] = get_zfar();
@@ -5233,6 +5405,13 @@ void Node3DEditor::set_state(const Dictionary &p_state) {
RenderingServer::get_singleton()->instance_set_visible(origin_instance, use);
}
}
+ if (d.has("keep_gizmo_onscreen")) {
+ bool use = d["keep_gizmo_onscreen"];
+
+ if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_KEEP_GIZMO_ONSCREEN))) {
+ _menu_item_pressed(MENU_KEEP_GIZMO_ONSCREEN);
+ }
+ }
if (d.has("gizmos_status")) {
Dictionary gizmos_status = d["gizmos_status"];
@@ -5586,7 +5765,13 @@ void Node3DEditor::_menu_item_pressed(int p_option) {
_init_grid();
view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
-
+ } break;
+ case MENU_KEEP_GIZMO_ONSCREEN: {
+ keep_gizmo_onscreen = !view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
+ for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
+ get_editor_viewport(i)->update_transform_gizmo_view();
+ }
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), keep_gizmo_onscreen);
} break;
case MENU_VIEW_CAMERA_SETTINGS: {
settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
@@ -5854,6 +6039,7 @@ void fragment() {
rotate_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
scale_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
scale_plane_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
+ axis_gizmo[i] = Ref<ArrayMesh>(memnew(ArrayMesh));
Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D);
mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
@@ -6175,6 +6361,21 @@ void fragment() {
plane_mat_hl->set_albedo(col.from_hsv(col.get_h(), 0.25, 1.0, 1));
plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides
}
+
+ // Lines to visualize transforms locked to an axis/plane
+ {
+ Ref<SurfaceTool> surftool = memnew(SurfaceTool);
+ surftool->begin(Mesh::PRIMITIVE_LINES);
+
+ Vector3 vec;
+ vec[i] = 1;
+
+ // line extending through infinity(ish)
+ surftool->add_vertex(vec * -99999);
+ surftool->add_vertex(vec * 99999);
+ surftool->set_material(mat_hl);
+ surftool->commit(axis_gizmo[i]);
+ }
}
}
@@ -7555,12 +7756,14 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) {
p->add_separator();
p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTR("View Origin")), MENU_VIEW_ORIGIN);
p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTR("View Grid"), Key::NUMBERSIGN), MENU_VIEW_GRID);
+ p->add_check_shortcut(ED_SHORTCUT("spatial_editor/keep_gizmo_onscreen", TTR("Keep Gizmo On Screen"), KeyModifierMask::CMD + KeyModifierMask::ALT + Key::G), MENU_KEEP_GIZMO_ONSCREEN);
p->add_separator();
p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
+ p->set_item_checked(p->get_item_index(MENU_KEEP_GIZMO_ONSCREEN), true);
p->connect("id_pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed));
diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h
index 20a782c8a8..f14f8b90b9 100644
--- a/editor/plugins/node_3d_editor_plugin.h
+++ b/editor/plugins/node_3d_editor_plugin.h
@@ -87,6 +87,19 @@ public:
void set_viewport(Node3DEditorViewport *p_viewport);
};
+class GizmoOffScreenLine : public Control {
+ GDCLASS(GizmoOffScreenLine, Control);
+
+public:
+ Vector2 point1;
+ Vector2 point2;
+ void _notification(int p_what) {
+ if (p_what == NOTIFICATION_DRAW && is_visible()) {
+ draw_line(point1, point2, Color(0.0f, 0.75f, 0.75f), 2);
+ }
+ }
+};
+
class Node3DEditorViewport : public Control {
GDCLASS(Node3DEditorViewport, Control);
friend class Node3DEditor;
@@ -201,6 +214,7 @@ private:
CheckBox *preview_camera;
SubViewportContainer *subviewport_container;
+ GizmoOffScreenLine *gizmo_offscreen_line;
MenuButton *view_menu;
PopupMenu *display_submenu;
@@ -237,7 +251,7 @@ private:
};
void _update_name();
- void _compute_edit(const Point2 &p_point);
+ void _compute_edit(const Point2 &p_point, const bool p_auto_center = true);
void _clear_selected();
void _select_clicked(bool p_allow_locked);
ObjectID _select_ray(const Point2 &p_pos);
@@ -247,6 +261,7 @@ private:
Point2 _point_to_screen(const Vector3 &p_point);
Transform3D _get_camera_transform() const;
int get_selected_count() const;
+ void cancel_transform();
Vector3 _get_camera_position() const;
Vector3 _get_camera_normal() const;
@@ -310,10 +325,13 @@ private:
Point2 mouse_pos;
Point2 original_mouse_pos;
bool snap = false;
+ bool show_rotation_line = false;
Ref<EditorNode3DGizmo> gizmo;
int gizmo_handle = 0;
bool gizmo_handle_secondary = false;
Variant gizmo_initial_value;
+ bool original_local;
+ bool instant;
} _edit;
struct Cursor {
@@ -347,7 +365,7 @@ private:
real_t zoom_indicator_delay;
int zoom_failed_attempts_count = 0;
- RID move_gizmo_instance[3], move_plane_gizmo_instance[3], rotate_gizmo_instance[4], scale_gizmo_instance[3], scale_plane_gizmo_instance[3];
+ RID move_gizmo_instance[3], move_plane_gizmo_instance[3], rotate_gizmo_instance[4], scale_gizmo_instance[3], scale_plane_gizmo_instance[3], axis_gizmo_instance[3];
String last_message;
String message;
@@ -402,6 +420,10 @@ private:
Transform3D _compute_transform(TransformMode p_mode, const Transform3D &p_original, const Transform3D &p_original_local, Vector3 p_motion, double p_extra, bool p_local, bool p_orthogonal);
+ void begin_transform(TransformMode p_mode, bool instant);
+ void commit_transform();
+ void update_transform(Point2 p_mousepos, bool p_shift);
+
protected:
void _notification(int p_what);
static void _bind_methods();
@@ -499,6 +521,35 @@ class Node3DEditor : public VBoxContainer {
public:
static const unsigned int VIEWPORTS_COUNT = 4;
+ enum MenuOption {
+ MENU_GROUP_SELECTED,
+ MENU_KEEP_GIZMO_ONSCREEN,
+ MENU_LOCK_SELECTED,
+ MENU_SNAP_TO_FLOOR,
+ MENU_TOOL_LIST_SELECT,
+ MENU_TOOL_LOCAL_COORDS,
+ MENU_TOOL_MOVE,
+ MENU_TOOL_OVERRIDE_CAMERA,
+ MENU_TOOL_ROTATE,
+ MENU_TOOL_SCALE,
+ MENU_TOOL_SELECT,
+ MENU_TOOL_USE_SNAP,
+ MENU_TRANSFORM_CONFIGURE_SNAP,
+ MENU_TRANSFORM_DIALOG,
+ MENU_UNGROUP_SELECTED,
+ MENU_UNLOCK_SELECTED,
+ MENU_VIEW_CAMERA_SETTINGS,
+ MENU_VIEW_GIZMOS_3D_ICONS,
+ MENU_VIEW_GRID,
+ MENU_VIEW_ORIGIN,
+ MENU_VIEW_USE_1_VIEWPORT,
+ MENU_VIEW_USE_2_VIEWPORTS,
+ MENU_VIEW_USE_2_VIEWPORTS_ALT,
+ MENU_VIEW_USE_3_VIEWPORTS,
+ MENU_VIEW_USE_3_VIEWPORTS_ALT,
+ MENU_VIEW_USE_4_VIEWPORTS,
+ };
+
enum ToolMode {
TOOL_MODE_SELECT,
TOOL_MODE_MOVE,
@@ -517,7 +568,6 @@ public:
TOOL_OPT_USE_SNAP,
TOOL_OPT_OVERRIDE_CAMERA,
TOOL_OPT_MAX
-
};
private:
@@ -546,7 +596,8 @@ private:
Camera3D::Projection grid_camera_last_update_perspective = Camera3D::PROJECTION_PERSPECTIVE;
Vector3 grid_camera_last_update_position = Vector3();
- Ref<ArrayMesh> move_gizmo[3], move_plane_gizmo[3], rotate_gizmo[4], scale_gizmo[3], scale_plane_gizmo[3];
+ bool keep_gizmo_onscreen = true;
+ Ref<ArrayMesh> move_gizmo[3], move_plane_gizmo[3], rotate_gizmo[4], scale_gizmo[3], scale_plane_gizmo[3], axis_gizmo[3];
Ref<StandardMaterial3D> gizmo_color[3];
Ref<StandardMaterial3D> plane_gizmo_color[3];
Ref<ShaderMaterial> rotate_gizmo_color[3];
@@ -579,37 +630,10 @@ private:
struct Gizmo {
bool visible = false;
real_t scale = 0;
+ Vector3 target_center;
Transform3D transform;
} gizmo;
- enum MenuOption {
- MENU_TOOL_SELECT,
- MENU_TOOL_MOVE,
- MENU_TOOL_ROTATE,
- MENU_TOOL_SCALE,
- MENU_TOOL_LIST_SELECT,
- MENU_TOOL_LOCAL_COORDS,
- MENU_TOOL_USE_SNAP,
- MENU_TOOL_OVERRIDE_CAMERA,
- MENU_TRANSFORM_CONFIGURE_SNAP,
- MENU_TRANSFORM_DIALOG,
- MENU_VIEW_USE_1_VIEWPORT,
- MENU_VIEW_USE_2_VIEWPORTS,
- MENU_VIEW_USE_2_VIEWPORTS_ALT,
- MENU_VIEW_USE_3_VIEWPORTS,
- MENU_VIEW_USE_3_VIEWPORTS_ALT,
- MENU_VIEW_USE_4_VIEWPORTS,
- MENU_VIEW_ORIGIN,
- MENU_VIEW_GRID,
- MENU_VIEW_GIZMOS_3D_ICONS,
- MENU_VIEW_CAMERA_SETTINGS,
- MENU_LOCK_SELECTED,
- MENU_UNLOCK_SELECTED,
- MENU_GROUP_SELECTED,
- MENU_UNGROUP_SELECTED,
- MENU_SNAP_TO_FLOOR
- };
-
Button *tool_button[TOOL_MAX];
Button *tool_option_button[TOOL_OPT_MAX];
@@ -768,17 +792,22 @@ public:
float get_zfar() const { return settings_zfar->get_value(); }
float get_fov() const { return settings_fov->get_value(); }
+ Vector3 get_gizmo_target_center() const { return gizmo.target_center; }
Transform3D get_gizmo_transform() const { return gizmo.transform; }
+ void set_gizmo_transform(const Transform3D &p_transform) { gizmo.transform = p_transform; }
+ bool is_keep_gizmo_onscreen_enabled() const { return keep_gizmo_onscreen; }
bool is_gizmo_visible() const;
ToolMode get_tool_mode() const { return tool_mode; }
bool are_local_coords_enabled() const { return tool_option_button[Node3DEditor::TOOL_OPT_LOCAL_COORDS]->is_pressed(); }
+ void set_local_coords_enabled(bool on) const { tool_option_button[Node3DEditor::TOOL_OPT_LOCAL_COORDS]->set_pressed(on); }
bool is_snap_enabled() const { return snap_enabled ^ snap_key_enabled; }
double get_translate_snap() const;
double get_rotate_snap() const;
double get_scale_snap() const;
Ref<ArrayMesh> get_move_gizmo(int idx) const { return move_gizmo[idx]; }
+ Ref<ArrayMesh> get_axis_gizmo(int idx) const { return axis_gizmo[idx]; }
Ref<ArrayMesh> get_move_plane_gizmo(int idx) const { return move_plane_gizmo[idx]; }
Ref<ArrayMesh> get_rotate_gizmo(int idx) const { return rotate_gizmo[idx]; }
Ref<ArrayMesh> get_scale_gizmo(int idx) const { return scale_gizmo[idx]; }
diff --git a/editor/plugins/packed_scene_translation_parser_plugin.cpp b/editor/plugins/packed_scene_translation_parser_plugin.cpp
index b492c27f41..9a8584f4a2 100644
--- a/editor/plugins/packed_scene_translation_parser_plugin.cpp
+++ b/editor/plugins/packed_scene_translation_parser_plugin.cpp
@@ -132,10 +132,7 @@ PackedSceneEditorTranslationParserPlugin::PackedSceneEditorTranslationParserPlug
lookup_properties.insert("script");
// Exception list (to prevent false positives).
- exception_list.insert("LineEdit", Vector<StringName>());
- exception_list["LineEdit"].append("text");
- exception_list.insert("TextEdit", Vector<StringName>());
- exception_list["TextEdit"].append("text");
- exception_list.insert("CodeEdit", Vector<StringName>());
- exception_list["CodeEdit"].append("text");
+ exception_list.insert("LineEdit", { "text" });
+ exception_list.insert("TextEdit", { "text" });
+ exception_list.insert("CodeEdit", { "text" });
}
diff --git a/editor/plugins/packed_scene_translation_parser_plugin.h b/editor/plugins/packed_scene_translation_parser_plugin.h
index fc19496eb6..ecd090b31b 100644
--- a/editor/plugins/packed_scene_translation_parser_plugin.h
+++ b/editor/plugins/packed_scene_translation_parser_plugin.h
@@ -37,9 +37,9 @@ class PackedSceneEditorTranslationParserPlugin : public EditorTranslationParserP
GDCLASS(PackedSceneEditorTranslationParserPlugin, EditorTranslationParserPlugin);
// Scene Node's properties that contain translation strings.
- Set<StringName> lookup_properties;
+ Set<String> lookup_properties;
// Properties from specific Nodes that should be ignored.
- Map<StringName, Vector<StringName>> exception_list;
+ Map<String, Vector<String>> exception_list;
public:
virtual Error parse_file(const String &p_path, Vector<String> *r_ids, Vector<Vector<String>> *r_ids_ctx_plural) override;
diff --git a/editor/plugins/replication_editor_plugin.cpp b/editor/plugins/replication_editor_plugin.cpp
index 93f4a853f3..fd4fc8f59c 100644
--- a/editor/plugins/replication_editor_plugin.cpp
+++ b/editor/plugins/replication_editor_plugin.cpp
@@ -258,7 +258,7 @@ void ReplicationEditor::edit(MultiplayerSynchronizer *p_sync) {
Ref<Texture2D> ReplicationEditor::_get_class_icon(const Node *p_node) {
if (!p_node || !has_theme_icon(p_node->get_class(), "EditorIcons")) {
- return get_theme_icon("ImportFail", "EditorIcons");
+ return get_theme_icon(SNAME("ImportFail"), SNAME("EditorIcons"));
}
return get_theme_icon(p_node->get_class(), "EditorIcons");
}
@@ -285,7 +285,7 @@ void ReplicationEditor::_add_property(const NodePath &p_property, bool p_spawn,
icon = _get_class_icon(node);
}
item->set_icon(0, icon);
- item->add_button(3, get_theme_icon("Remove", "EditorIcons"));
+ item->add_button(3, get_theme_icon(SNAME("Remove"), SNAME("EditorIcons")));
item->set_text_alignment(1, HORIZONTAL_ALIGNMENT_CENTER);
item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK);
item->set_checked(1, p_spawn);
diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp
index 26227fa5bb..17de3ba026 100644
--- a/editor/plugins/script_editor_plugin.cpp
+++ b/editor/plugins/script_editor_plugin.cpp
@@ -2265,7 +2265,7 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra
if (use_external_editor &&
(EditorDebuggerNode::get_singleton()->get_dump_stack_script() != p_resource || EditorDebuggerNode::get_singleton()->get_debug_with_external_editor()) &&
p_resource->get_path().is_resource_file() &&
- p_resource->get_class_name() != StringName("VisualScript")) {
+ !Ref<VisualScript>(p_resource).is_valid()) {
String path = EditorSettings::get_singleton()->get("text_editor/external/exec_path");
String flags = EditorSettings::get_singleton()->get("text_editor/external/exec_flags");
@@ -2364,7 +2364,7 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra
se->set_edited_resource(p_resource);
- if (p_resource->get_class_name() != StringName("VisualScript")) {
+ if (!Ref<VisualScript>(p_resource).is_valid()) {
bool highlighter_set = false;
for (int i = 0; i < syntax_highlighters.size(); i++) {
Ref<EditorSyntaxHighlighter> highlighter = syntax_highlighters[i]->_create();
diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp
index 7b4ebbc6d8..c3d61dfd58 100644
--- a/editor/plugins/script_text_editor.cpp
+++ b/editor/plugins/script_text_editor.cpp
@@ -930,21 +930,22 @@ void ScriptTextEditor::_update_connected_methods() {
continue;
}
- if (methods_found.has(connection.callable.get_method())) {
+ const StringName method = connection.callable.get_method();
+ if (methods_found.has(method)) {
continue;
}
- if (!ClassDB::has_method(script->get_instance_base_type(), connection.callable.get_method())) {
+ if (!ClassDB::has_method(script->get_instance_base_type(), method)) {
int line = -1;
for (int j = 0; j < functions.size(); j++) {
String name = functions[j].get_slice(":", 0);
- if (name == connection.callable.get_method()) {
+ if (name == method) {
line = functions[j].get_slice(":", 1).to_int() - 1;
- text_edit->set_line_gutter_metadata(line, connection_gutter, connection.callable.get_method());
+ text_edit->set_line_gutter_metadata(line, connection_gutter, method);
text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_theme_icon(SNAME("Slot"), SNAME("EditorIcons")));
text_edit->set_line_gutter_clickable(line, connection_gutter, true);
- methods_found.insert(connection.callable.get_method());
+ methods_found.insert(method);
break;
}
}
@@ -957,7 +958,7 @@ void ScriptTextEditor::_update_connected_methods() {
bool found_inherited_function = false;
Ref<Script> inherited_script = script->get_base_script();
while (!inherited_script.is_null()) {
- if (inherited_script->has_method(connection.callable.get_method())) {
+ if (inherited_script->has_method(method)) {
found_inherited_function = true;
break;
}
@@ -1373,7 +1374,7 @@ void ScriptTextEditor::reload(bool p_soft) {
return;
}
scr->set_source_code(te->get_text());
- bool soft = p_soft || scr->get_instance_base_type() == "EditorPlugin"; //always soft-reload editor plugins
+ bool soft = p_soft || scr->get_instance_base_type() == "EditorPlugin"; // Always soft-reload editor plugins.
scr->get_language()->reload_tool_script(scr, soft);
}
diff --git a/editor/plugins/text_control_editor_plugin.cpp b/editor/plugins/text_control_editor_plugin.cpp
index 87eff9c3e9..4ce94176e5 100644
--- a/editor/plugins/text_control_editor_plugin.cpp
+++ b/editor/plugins/text_control_editor_plugin.cpp
@@ -110,7 +110,7 @@ void TextControlEditor::_update_styles_menu() {
for (Map<String, String>::Element *E = fonts[name].front(); E; E = E->next()) {
font_style_list->add_item(E->key());
}
- } else {
+ } else if (font_list->get_selected() >= 0) {
font_style_list->add_item("Default");
}
@@ -123,9 +123,9 @@ void TextControlEditor::_update_styles_menu() {
void TextControlEditor::_update_control() {
if (!edited_controls.is_empty()) {
- int font_selected = 0;
+ String font_selected;
bool same_font = true;
- int style_selected = 0;
+ String style_selected;
bool same_style = true;
int font_size = 0;
bool same_font_size = true;
@@ -136,26 +136,23 @@ void TextControlEditor::_update_control() {
Color outline_color = Color{ 1.0f, 1.0f, 1.0f };
bool same_outline_color = true;
- _update_fonts_menu();
- _update_styles_menu();
-
int count = edited_controls.size();
for (int i = 0; i < count; ++i) {
Control *edited_control = edited_controls[i];
- String edited_color;
- String edited_font;
- String edited_font_size;
+ StringName edited_color;
+ StringName edited_font;
+ StringName edited_font_size;
// Get override names.
- if (edited_control->is_class("RichTextLabel")) {
- edited_color = "default_color";
- edited_font = "normal_font";
- edited_font_size = "normal_font_size";
+ if (Object::cast_to<RichTextLabel>(edited_control)) {
+ edited_color = SNAME("default_color");
+ edited_font = SNAME("normal_font");
+ edited_font_size = SNAME("normal_font_size");
} else {
- edited_color = "font_color";
- edited_font = "font";
- edited_font_size = "font_size";
+ edited_color = SNAME("font_color");
+ edited_font = SNAME("font");
+ edited_font_size = SNAME("font_size");
}
// Get font override.
@@ -166,63 +163,46 @@ void TextControlEditor::_update_control() {
if (font.is_valid()) {
if (font->get_data_count() != 1) {
- custom_font = font;
if (i > 0) {
- same_font = same_font && (font_selected == FONT_INFO_USER_CUSTOM);
- same_style = same_style && (style_selected == 0);
+ same_font = same_font && (custom_font == font);
}
+ custom_font = font;
- font_selected = FONT_INFO_USER_CUSTOM;
- style_selected = 0;
+ font_selected = TTR("[Custom Font]");
+ same_style = false;
} else {
String name = font->get_data(0)->get_font_name();
String style = font->get_data(0)->get_font_style_name();
if (fonts.has(name) && fonts[name].has(style)) {
- for (int j = 0; j < font_list->get_item_count(); j++) {
- if (font_list->get_item_text(j) == name) {
- if (i > 0) {
- same_font = same_font && (j == font_selected);
- }
-
- font_selected = j;
- break;
- }
- }
- for (int j = 0; j < font_style_list->get_item_count(); j++) {
- if (font_style_list->get_item_text(j) == style) {
- if (i > 0) {
- same_style = same_style && (j == style_selected);
- }
-
- style_selected = j;
- break;
- }
+ if (i > 0) {
+ same_font = same_font && (name == font_selected);
+ same_style = same_style && (style == style_selected);
}
+ font_selected = name;
+ style_selected = style;
} else {
- custom_font = font;
if (i > 0) {
- same_font = same_font && (font_selected == FONT_INFO_USER_CUSTOM);
- same_style = same_style && (style_selected == 0);
+ same_font = same_font && (custom_font == font);
}
+ custom_font = font;
- font_selected = FONT_INFO_USER_CUSTOM;
- style_selected = 0;
+ font_selected = TTR("[Custom Font]");
+ same_style = false;
}
}
} else {
if (i > 0) {
- same_font = same_font && (font_selected == FONT_INFO_THEME_DEFAULT);
- same_style = same_style && (style_selected == 0);
+ same_font = same_font && (font_selected == TTR("[Theme Default]"));
}
- font_selected = FONT_INFO_THEME_DEFAULT;
- style_selected = 0;
+ font_selected = TTR("[Theme Default]");
+ same_style = false;
}
int current_font_size = edited_control->get_theme_font_size(edited_font_size);
- int current_outline_size = edited_control->get_theme_constant("outline_size");
+ int current_outline_size = edited_control->get_theme_constant(SNAME("outline_size"));
Color current_font_color = edited_control->get_theme_color(edited_color);
- Color current_outline_color = edited_control->get_theme_color("font_outline_color");
+ Color current_outline_color = edited_control->get_theme_color(SNAME("font_outline_color"));
if (i > 0) {
same_font_size = same_font_size && (font_size == current_font_size);
same_outline_size = same_outline_size && (outline_size == current_outline_size);
@@ -235,19 +215,29 @@ void TextControlEditor::_update_control() {
font_color = current_font_color;
outline_color = current_outline_color;
}
-
_update_fonts_menu();
if (same_font) {
- font_list->select(font_selected);
+ for (int j = 0; j < font_list->get_item_count(); j++) {
+ if (font_list->get_item_text(j) == font_selected) {
+ font_list->select(j);
+ break;
+ }
+ }
} else {
+ custom_font = Ref<Font>();
font_list->select(-1);
}
_update_styles_menu();
if (same_style) {
- font_style_list->select(style_selected);
+ for (int j = 0; j < font_style_list->get_item_count(); j++) {
+ if (font_style_list->get_item_text(j) == style_selected) {
+ font_style_list->select(j);
+ break;
+ }
+ }
} else {
- font_list->select(-1);
+ font_style_list->select(-1);
}
// Get other theme overrides.
@@ -282,6 +272,7 @@ void TextControlEditor::_update_control() {
}
void TextControlEditor::_font_selected(int p_id) {
+ _update_styles_menu();
_set_font();
}
@@ -301,11 +292,11 @@ void TextControlEditor::_set_font() {
for (int i = 0; i < count; ++i) {
Control *edited_control = edited_controls[i];
- String edited_font;
- if (edited_control->is_class("RichTextLabel")) {
- edited_font = "normal_font";
+ StringName edited_font;
+ if (Object::cast_to<RichTextLabel>(edited_control)) {
+ edited_font = SNAME("normal_font");
} else {
- edited_font = "font";
+ edited_font = SNAME("font");
}
if (font_list->get_selected_id() == FONT_INFO_THEME_DEFAULT) {
@@ -314,14 +305,13 @@ void TextControlEditor::_set_font() {
} else if (font_list->get_selected_id() == FONT_INFO_USER_CUSTOM) {
// Restore "custom_font".
ur->add_do_method(edited_control, "add_theme_font_override", edited_font, custom_font);
- } else {
+ } else if (font_list->get_selected() >= 0) {
// Load new font resource using selected name and style.
String name = font_list->get_item_text(font_list->get_selected());
String style = font_style_list->get_item_text(font_style_list->get_selected());
if (style.is_empty()) {
style = "Default";
}
-
if (fonts.has(name)) {
Ref<FontData> fd = ResourceLoader::load(fonts[name][style]);
if (fd.is_valid()) {
@@ -358,11 +348,11 @@ void TextControlEditor::_font_size_selected(double p_size) {
for (int i = 0; i < count; ++i) {
Control *edited_control = edited_controls[i];
- String edited_font_size;
- if (edited_control->is_class("RichTextLabel")) {
- edited_font_size = "normal_font_size";
+ StringName edited_font_size;
+ if (Object::cast_to<RichTextLabel>(edited_control)) {
+ edited_font_size = SNAME("normal_font_size");
} else {
- edited_font_size = "font_size";
+ edited_font_size = SNAME("font_size");
}
ur->add_do_method(edited_control, "add_theme_font_size_override", edited_font_size, p_size);
@@ -393,7 +383,7 @@ void TextControlEditor::_outline_size_selected(double p_size) {
ur->add_do_method(edited_control, "add_theme_constant_override", "outline_size", p_size);
if (edited_control->has_theme_constant_override("outline_size")) {
- ur->add_undo_method(edited_control, "add_theme_constant_override", "outline_size", edited_control->get_theme_constant("outline_size"));
+ ur->add_undo_method(edited_control, "add_theme_constant_override", "outline_size", edited_control->get_theme_constant(SNAME("outline_size")));
} else {
ur->add_undo_method(edited_control, "remove_theme_constant_override", "outline_size");
}
@@ -417,11 +407,11 @@ void TextControlEditor::_font_color_changed(const Color &p_color) {
for (int i = 0; i < count; ++i) {
Control *edited_control = edited_controls[i];
- String edited_color;
- if (edited_control->is_class("RichTextLabel")) {
- edited_color = "default_color";
+ StringName edited_color;
+ if (Object::cast_to<RichTextLabel>(edited_control)) {
+ edited_color = SNAME("default_color");
} else {
- edited_color = "font_color";
+ edited_color = SNAME("font_color");
}
ur->add_do_method(edited_control, "add_theme_color_override", edited_color, p_color);
@@ -452,7 +442,7 @@ void TextControlEditor::_outline_color_changed(const Color &p_color) {
ur->add_do_method(edited_control, "add_theme_color_override", "font_outline_color", p_color);
if (edited_control->has_theme_color_override("font_outline_color")) {
- ur->add_undo_method(edited_control, "add_theme_color_override", "font_outline_color", edited_control->get_theme_color("font_outline_color"));
+ ur->add_undo_method(edited_control, "add_theme_color_override", "font_outline_color", edited_control->get_theme_color(SNAME("font_outline_color")));
} else {
ur->add_undo_method(edited_control, "remove_theme_color_override", "font_outline_color");
}
@@ -476,19 +466,19 @@ void TextControlEditor::_clear_formatting() {
for (int i = 0; i < count; ++i) {
Control *edited_control = edited_controls[i];
- String edited_color;
- String edited_font;
- String edited_font_size;
+ StringName edited_color;
+ StringName edited_font;
+ StringName edited_font_size;
// Get override names.
- if (edited_control->is_class("RichTextLabel")) {
- edited_color = "default_color";
- edited_font = "normal_font";
- edited_font_size = "normal_font_size";
+ if (Object::cast_to<RichTextLabel>(edited_control)) {
+ edited_color = SNAME("default_color");
+ edited_font = SNAME("normal_font");
+ edited_font_size = SNAME("normal_font_size");
} else {
- edited_color = "font_color";
- edited_font = "font";
- edited_font_size = "font_size";
+ edited_color = SNAME("font_color");
+ edited_font = SNAME("font");
+ edited_font_size = SNAME("font_size");
}
ur->add_do_method(edited_control, "begin_bulk_theme_override");
@@ -511,12 +501,12 @@ void TextControlEditor::_clear_formatting() {
ur->add_do_method(edited_control, "remove_theme_color_override", "font_outline_color");
if (edited_control->has_theme_color_override("font_outline_color")) {
- ur->add_undo_method(edited_control, "add_theme_color_override", "font_outline_color", edited_control->get_theme_color("font_outline_color"));
+ ur->add_undo_method(edited_control, "add_theme_color_override", "font_outline_color", edited_control->get_theme_color(SNAME("font_outline_color")));
}
ur->add_do_method(edited_control, "remove_theme_constant_override", "outline_size");
if (edited_control->has_theme_constant_override("outline_size")) {
- ur->add_undo_method(edited_control, "add_theme_constant_override", "outline_size", edited_control->get_theme_constant("outline_size"));
+ ur->add_undo_method(edited_control, "add_theme_constant_override", "outline_size", edited_control->get_theme_constant(SNAME("outline_size")));
}
ur->add_do_method(edited_control, "end_bulk_theme_override");
diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp
index d1797e7400..dd19f3d781 100644
--- a/editor/plugins/visual_shader_editor_plugin.cpp
+++ b/editor/plugins/visual_shader_editor_plugin.cpp
@@ -2584,7 +2584,7 @@ void VisualShaderEditor::_add_node(int p_idx, const Vector<Variant> &p_ops, Stri
vsnode = Ref<VisualShaderNode>(vsn);
} else {
ERR_FAIL_COND(add_options[p_idx].script.is_null());
- String base_type = add_options[p_idx].script->get_instance_base_type();
+ StringName base_type = add_options[p_idx].script->get_instance_base_type();
VisualShaderNode *vsn = Object::cast_to<VisualShaderNode>(ClassDB::instantiate(base_type));
ERR_FAIL_COND(!vsn);
vsnode = Ref<VisualShaderNode>(vsn);
@@ -4783,11 +4783,11 @@ VisualShaderEditor::VisualShaderEditor() {
// SDF
{
- add_options.push_back(AddOption("ScreenUVToSDF", "SDF", "", "VisualShaderNodeScreenUVToSDF", TTR("Converts screen UV to a SDF."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
+ add_options.push_back(AddOption("ScreenUVToSDF", "SDF", "", "VisualShaderNodeScreenUVToSDF", TTR("Converts screen UV to a SDF."), {}, VisualShaderNode::PORT_TYPE_VECTOR_2D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
add_options.push_back(AddOption("SDFRaymarch", "SDF", "", "VisualShaderNodeSDFRaymarch", TTR("Casts a ray against the screen SDF and returns the distance travelled."), {}, -1, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
- add_options.push_back(AddOption("SDFToScreenUV", "SDF", "", "VisualShaderNodeSDFToScreenUV", TTR("Converts a SDF to screen UV."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
+ add_options.push_back(AddOption("SDFToScreenUV", "SDF", "", "VisualShaderNodeSDFToScreenUV", TTR("Converts a SDF to screen UV."), {}, VisualShaderNode::PORT_TYPE_VECTOR_2D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
add_options.push_back(AddOption("TextureSDF", "SDF", "", "VisualShaderNodeTextureSDF", TTR("Performs a SDF texture lookup."), {}, VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
- add_options.push_back(AddOption("TextureSDFNormal", "SDF", "", "VisualShaderNodeTextureSDFNormal", TTR("Performs a SDF normal texture lookup."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
+ add_options.push_back(AddOption("TextureSDFNormal", "SDF", "", "VisualShaderNodeTextureSDFNormal", TTR("Performs a SDF normal texture lookup."), {}, VisualShaderNode::PORT_TYPE_VECTOR_2D, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM));
}
// TEXTURES
@@ -4971,8 +4971,8 @@ VisualShaderEditor::VisualShaderEditor() {
add_options.push_back(AddOption("Subtract", "Vector", "Operators", "VisualShaderNodeVectorOp", TTR("Subtracts 3D vector from 3D vector."), { VisualShaderNodeVectorOp::OP_SUB, VisualShaderNodeVectorOp::OP_TYPE_VECTOR_3D }, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Vector2Constant", "Vector", "Variables", "VisualShaderNodeVec2Constant", TTR("2D vector constant."), {}, VisualShaderNode::PORT_TYPE_VECTOR_2D));
- add_options.push_back(AddOption("Vector3Constant", "Vector", "Variables", "VisualShaderNodeVec3Constant", TTR("3D vector constant."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Vector2Uniform", "Vector", "Variables", "VisualShaderNodeVec2Uniform", TTR("2D vector uniform."), {}, VisualShaderNode::PORT_TYPE_VECTOR_2D));
+ add_options.push_back(AddOption("Vector3Constant", "Vector", "Variables", "VisualShaderNodeVec3Constant", TTR("3D vector constant."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D));
add_options.push_back(AddOption("Vector3Uniform", "Vector", "Variables", "VisualShaderNodeVec3Uniform", TTR("3D vector uniform."), {}, VisualShaderNode::PORT_TYPE_VECTOR_3D));
// SPECIAL
diff --git a/editor/project_export.cpp b/editor/project_export.cpp
index f39a494df8..b8775cd3ed 100644
--- a/editor/project_export.cpp
+++ b/editor/project_export.cpp
@@ -1275,8 +1275,6 @@ ProjectExportDialog::ProjectExportDialog() {
set_hide_on_ok(false);
- editor_icons = "EditorIcons";
-
default_filename = EditorSettings::get_singleton()->get_project_metadata("export_options", "default_filename", "");
// If no default set, use project name
if (default_filename.is_empty()) {
diff --git a/editor/project_export.h b/editor/project_export.h
index 3d90a0d3ff..09e402c67f 100644
--- a/editor/project_export.h
+++ b/editor/project_export.h
@@ -85,8 +85,6 @@ private:
Label *include_label;
MarginContainer *include_margin;
- StringName editor_icons;
-
Button *export_button;
Button *export_all_button;
AcceptDialog *export_all_dialog;
diff --git a/editor/property_editor.cpp b/editor/property_editor.cpp
index 27fe696cc3..405e263a62 100644
--- a/editor/property_editor.cpp
+++ b/editor/property_editor.cpp
@@ -269,7 +269,9 @@ void CustomPropertyEditor::_menu_option(int p_which) {
res->call("set_instance_base_type", owner->get_class());
}
+ EditorNode::get_editor_data().instantiate_object_properties(obj);
v = obj;
+
emit_signal(SNAME("variant_changed"));
} break;
@@ -1092,7 +1094,9 @@ void CustomPropertyEditor::_type_create_selected(int p_idx) {
ERR_FAIL_COND(!obj);
ERR_FAIL_COND(!Object::cast_to<Resource>(obj));
+ EditorNode::get_editor_data().instantiate_object_properties(obj);
v = obj;
+
emit_signal(SNAME("variant_changed"));
hide();
}
@@ -1283,7 +1287,9 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
ERR_BREAK(!obj);
ERR_BREAK(!Object::cast_to<Resource>(obj));
+ EditorNode::get_editor_data().instantiate_object_properties(obj);
v = obj;
+
emit_signal(SNAME("variant_changed"));
hide();
}
diff --git a/editor/property_selector.cpp b/editor/property_selector.cpp
index 406bcbe342..0862efb4ee 100644
--- a/editor/property_selector.cpp
+++ b/editor/property_selector.cpp
@@ -214,10 +214,13 @@ void PropertySelector::_update_search() {
Variant::construct(type, v, nullptr, 0, ce);
v.get_method_list(&methods);
} else {
- Object *obj = ObjectDB::get_instance(script);
- if (Object::cast_to<Script>(obj)) {
+ Ref<Script> script_ref = Object::cast_to<Script>(ObjectDB::get_instance(script));
+ if (script_ref.is_valid()) {
methods.push_back(MethodInfo("*Script Methods"));
- Object::cast_to<Script>(obj)->get_script_method_list(&methods);
+ if (script_ref->is_built_in()) {
+ script_ref->reload(true);
+ }
+ script_ref->get_script_method_list(&methods);
}
StringName base = base_type;
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index 9b18d3a491..0e362b13c6 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -1206,8 +1206,16 @@ void SceneTreeDock::_notification(int p_what) {
create_root_dialog->add_child(top_row);
+ ScrollContainer *scroll_container = memnew(ScrollContainer);
+ scroll_container->set_name("NodeShortcutsScrollContainer");
+ create_root_dialog->add_child(scroll_container);
+ scroll_container->set_v_size_flags(SIZE_EXPAND_FILL);
+ scroll_container->set_horizontal_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED);
+
VBoxContainer *node_shortcuts = memnew(VBoxContainer);
node_shortcuts->set_name("NodeShortcuts");
+ scroll_container->add_child(node_shortcuts);
+ node_shortcuts->set_h_size_flags(SIZE_EXPAND_FILL);
VBoxContainer *beginner_node_shortcuts = memnew(VBoxContainer);
beginner_node_shortcuts->set_name("BeginnerNodeShortcuts");
@@ -1247,8 +1255,6 @@ void SceneTreeDock::_notification(int p_what) {
button_clipboard->set_icon(get_theme_icon(SNAME("ActionPaste"), SNAME("EditorIcons")));
button_clipboard->connect("pressed", callable_bind(callable_mp(this, &SceneTreeDock::_tool_selected), TOOL_PASTE, false));
- node_shortcuts->add_spacer();
- create_root_dialog->add_child(node_shortcuts);
_update_create_root_dialog();
} break;
@@ -3112,7 +3118,7 @@ void SceneTreeDock::_local_tree_selected() {
void SceneTreeDock::_update_create_root_dialog() {
BaseButton *toggle = Object::cast_to<BaseButton>(create_root_dialog->get_node(String("NodeShortcutsTopRow/NodeShortcutsToggle")));
- Node *node_shortcuts = create_root_dialog->get_node(String("NodeShortcuts"));
+ Node *node_shortcuts = create_root_dialog->get_node(String("NodeShortcutsScrollContainer/NodeShortcuts"));
if (!toggle || !node_shortcuts) {
return;
@@ -3142,6 +3148,7 @@ void SceneTreeDock::_update_create_root_dialog() {
Button *button = memnew(Button);
favorite_nodes->add_child(button);
button->set_text(l);
+ button->set_clip_text(true);
String name = l.get_slicec(' ', 0);
if (ScriptServer::is_global_class(name)) {
name = ScriptServer::get_global_class_native_base(name);
@@ -3403,6 +3410,7 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSel
create_root_dialog = memnew(VBoxContainer);
vbc->add_child(create_root_dialog);
+ create_root_dialog->set_v_size_flags(SIZE_EXPAND_FILL);
create_root_dialog->hide();
scene_tree = memnew(SceneTreeEditor(false, true, true));
diff --git a/main/main.cpp b/main/main.cpp
index f8088cba1c..216d0a446a 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -2250,9 +2250,8 @@ bool Main::start() {
}
}
- if (main_loop->is_class("SceneTree")) {
- SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
-
+ SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
+ if (sml) {
#ifdef DEBUG_ENABLED
if (debug_collisions) {
sml->set_debug_collisions_hint(true);
@@ -2294,20 +2293,18 @@ bool Main::start() {
RES res = ResourceLoader::load(info.path);
ERR_CONTINUE_MSG(res.is_null(), "Can't autoload: " + info.path);
Node *n = nullptr;
- if (res->is_class("PackedScene")) {
- Ref<PackedScene> ps = res;
- n = ps->instantiate();
- } else if (res->is_class("Script")) {
- Ref<Script> script_res = res;
+ Ref<PackedScene> scn = res;
+ Ref<Script> script_res = res;
+ if (scn.is_valid()) {
+ n = scn->instantiate();
+ } else if (script_res.is_valid()) {
StringName ibt = script_res->get_instance_base_type();
bool valid_type = ClassDB::is_parent_class(ibt, "Node");
ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path);
Object *obj = ClassDB::instantiate(ibt);
- ERR_CONTINUE_MSG(obj == nullptr,
- "Cannot instance script for autoload, expected 'Node' inheritance, got: " +
- String(ibt));
+ ERR_CONTINUE_MSG(!obj, "Cannot instance script for autoload, expected 'Node' inheritance, got: " + String(ibt) + ".");
n = Object::cast_to<Node>(obj);
n->set_script(script_res);
diff --git a/misc/dist/html/editor.html b/misc/dist/html/editor.html
index a681a2a1c3..9e03f50c37 100644
--- a/misc/dist/html/editor.html
+++ b/misc/dist/html/editor.html
@@ -265,6 +265,7 @@
<button id="btn-close-editor" class="btn close-btn" disabled="disabled" onclick="closeEditor()">×</button>
<button id="btn-tab-game" class="btn tab-btn" disabled="disabled" onclick="showTab('game')">Game</button>
<button id="btn-close-game" class="btn close-btn" disabled="disabled" onclick="closeGame()">×</button>
+ <button id="btn-tab-update" class="btn tab-btn" style="display: none;">Update</button>
</div>
<div id="tabs">
<div id="tab-loader">
@@ -324,10 +325,39 @@
<div id="status-notice" class="godot" style="display: none;"></div>
</div>
</div>
- <script>
+ <script>//<![CDATA[
window.addEventListener("load", () => {
+ function notifyUpdate(sw) {
+ const btn = document.getElementById("btn-tab-update");
+ btn.onclick = function () {
+ if (!window.confirm("Are you sure you want to update?\nClicking \"OK\" will reload all active instances!")) {
+ return;
+ }
+ sw.postMessage("update");
+ btn.innerHTML = "Updating...";
+ btn.disabled = true;
+ };
+ btn.style.display = "";
+ }
if ("serviceWorker" in navigator) {
- navigator.serviceWorker.register("service.worker.js");
+ navigator.serviceWorker.register("service.worker.js").then(function (reg) {
+ if (reg.waiting) {
+ notifyUpdate(reg.waiting);
+ }
+ reg.addEventListener("updatefound", function () {
+ const update = reg.installing;
+ update.addEventListener("statechange", function () {
+ if (update.state === "installed") {
+ // It's a new install, claim and perform aggressive caching.
+ if (!reg.active) {
+ update.postMessage("claim");
+ } else {
+ notifyUpdate(update);
+ }
+ }
+ });
+ });
+ });
}
if (localStorage.getItem("welcomeModalDismissed") !== 'true') {
@@ -342,7 +372,7 @@
localStorage.setItem("welcomeModalDismissed", 'true');
}
}
- </script>
+ //]]></script>
<script src="godot.tools.js"></script>
<script>//<![CDATA[
diff --git a/misc/dist/html/service-worker.js b/misc/dist/html/service-worker.js
index 063e40a6cb..310574f21d 100644
--- a/misc/dist/html/service-worker.js
+++ b/misc/dist/html/service-worker.js
@@ -4,7 +4,8 @@
// Incrementing CACHE_VERSION will kick off the install event and force
// previously cached resources to be updated from the network.
const CACHE_VERSION = "@GODOT_VERSION@";
-const CACHE_NAME = "@GODOT_NAME@-cache";
+const CACHE_PREFIX = "@GODOT_NAME@-sw-cache-";
+const CACHE_NAME = CACHE_PREFIX + CACHE_VERSION;
const OFFLINE_URL = "@GODOT_OFFLINE_PAGE@";
// Files that will be cached on load.
const CACHED_FILES = @GODOT_CACHE@;
@@ -13,26 +14,35 @@ const CACHABLE_FILES = @GODOT_OPT_CACHE@;
const FULL_CACHE = CACHED_FILES.concat(CACHABLE_FILES);
self.addEventListener("install", (event) => {
- event.waitUntil(async function () {
- const cache = await caches.open(CACHE_NAME);
- // Clear old cache (including optionals).
- await Promise.all(FULL_CACHE.map(path => cache.delete(path)));
- // Insert new one.
- const done = await cache.addAll(CACHED_FILES);
- return done;
- }());
+ event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(CACHED_FILES)));
});
self.addEventListener("activate", (event) => {
- event.waitUntil(async function () {
- if ("navigationPreload" in self.registration) {
- await self.registration.navigationPreload.enable();
- }
- }());
- // Tell the active service worker to take control of the page immediately.
- self.clients.claim();
+ event.waitUntil(caches.keys().then(
+ function (keys) {
+ // Remove old caches.
+ return Promise.all(keys.filter(key => key.startsWith(CACHE_PREFIX) && key != CACHE_NAME).map(key => caches.delete(key)));
+ }).then(function() {
+ // Enable navigation preload if available.
+ return ("navigationPreload" in self.registration) ? self.registration.navigationPreload.enable() : Promise.resolve();
+ })
+ );
});
+async function fetchAndCache(event, cache, isCachable) {
+ // Use the preloaded response, if it's there
+ let response = await event.preloadResponse;
+ if (!response) {
+ // Or, go over network.
+ response = await self.fetch(event.request);
+ }
+ if (isCachable) {
+ // And update the cache
+ cache.put(event.request, response.clone());
+ }
+ return response;
+}
+
self.addEventListener("fetch", (event) => {
const isNavigate = event.request.mode === "navigate";
const url = event.request.url || "";
@@ -42,32 +52,54 @@ self.addEventListener("fetch", (event) => {
const isCachable = FULL_CACHE.some(v => v === local) || (base === referrer && base.endsWith(CACHED_FILES[0]));
if (isNavigate || isCachable) {
event.respondWith(async function () {
- try {
- // Use the preloaded response, if it's there
- let request = event.request.clone();
- let response = await event.preloadResponse;
- if (!response) {
- // Or, go over network.
- response = await fetch(event.request);
- }
- if (isCachable) {
- // Update the cache
- const cache = await caches.open(CACHE_NAME);
- cache.put(request, response.clone());
- }
- return response;
- } catch (error) {
- const cache = await caches.open(CACHE_NAME);
- if (event.request.mode === "navigate") {
- // Check if we have full cache.
- const cached = await Promise.all(FULL_CACHE.map(name => cache.match(name)));
- const missing = cached.some(v => v === undefined);
- const cachedResponse = missing ? await caches.match(OFFLINE_URL) : await caches.match(CACHED_FILES[0]);
- return cachedResponse;
+ // Try to use cache first
+ const cache = await caches.open(CACHE_NAME);
+ if (event.request.mode === "navigate") {
+ // Check if we have full cache during HTML page request.
+ const fullCache = await Promise.all(FULL_CACHE.map(name => cache.match(name)));
+ const missing = fullCache.some(v => v === undefined);
+ if (missing) {
+ try {
+ // Try network if some cached file is missing (so we can display offline page in case).
+ return await fetchAndCache(event, cache, isCachable);
+ } catch (e) {
+ // And return the hopefully always cached offline page in case of network failure.
+ console.error("Network error: ", e);
+ return await caches.match(OFFLINE_URL);
+ }
}
- const cachedResponse = await caches.match(event.request);
- return cachedResponse;
+ }
+ const cached = await cache.match(event.request);
+ if (cached) {
+ return cached;
+ } else {
+ // Try network if don't have it in cache.
+ return await fetchAndCache(event, cache, isCachable);
}
}());
}
});
+
+self.addEventListener("message", (event) => {
+ // No cross origin
+ if (event.origin != self.origin) {
+ return;
+ }
+ const id = event.source.id || "";
+ const msg = event.data || "";
+ // Ensure it's one of our clients.
+ self.clients.get(id).then(function (client) {
+ if (!client) {
+ return; // Not a valid client.
+ }
+ if (msg === "claim") {
+ self.skipWaiting().then(() => self.clients.claim());
+ } else if (msg === "clear") {
+ caches.delete(CACHE_NAME);
+ } else if (msg === "update") {
+ self.skipWaiting().then(() => self.clients.claim()).then(() => self.clients.matchAll()).then(all => all.forEach(c => c.navigate(c.url)));
+ } else {
+ onClientMessage(event);
+ }
+ });
+});
diff --git a/modules/SCsub b/modules/SCsub
index 5ff4623743..fcc01e2c1b 100644
--- a/modules/SCsub
+++ b/modules/SCsub
@@ -22,36 +22,45 @@ env.CommandNoCache(
),
)
-# Header to be included in `tests/test_main.cpp` to run module-specific tests.
-if env["tests"]:
- env.Depends("modules_tests.gen.h", Value(env.module_list))
- env.CommandNoCache(
- "modules_tests.gen.h",
- Value(env.module_list),
- env.Run(
- modules_builders.generate_modules_tests,
- "Generating modules tests header.",
- # NOTE: No need to run in subprocess since this is still executed serially.
- subprocess=False,
- ),
- )
- env.AlwaysBuild("modules_tests.gen.h")
vs_sources = []
+test_headers = []
# libmodule_<name>.a for each active module.
for name, path in env.module_list.items():
env.modules_sources = []
- if not os.path.isabs(path):
- SConscript(name + "/SCsub") # Built-in.
- else:
- SConscript(path + "/SCsub") # Custom.
+ # Name for built-in modules, (absolute) path for custom ones.
+ base_path = path if os.path.isabs(path) else name
+ SConscript(base_path + "/SCsub")
lib = env_modules.add_library("module_%s" % name, env.modules_sources)
env.Prepend(LIBS=[lib])
if env["vsproj"]:
vs_sources += env.modules_sources
+ if env["tests"]:
+ # Lookup potential headers in `tests` subfolder.
+ import glob
+
+ module_tests = sorted(glob.glob(os.path.join(base_path, "tests", "*.h")))
+ if module_tests != []:
+ test_headers += module_tests
+
+
+# Generate header to be included in `tests/test_main.cpp` to run module-specific tests.
+if env["tests"]:
+ env.Depends("modules_tests.gen.h", test_headers)
+ env.CommandNoCache(
+ "modules_tests.gen.h",
+ test_headers,
+ env.Run(
+ modules_builders.generate_modules_tests,
+ "Generating modules tests header.",
+ # NOTE: No need to run in subprocess since this is still executed serially.
+ subprocess=False,
+ ),
+ )
+
# libmodules.a with only register_module_types.
# Must be last so that all libmodule_<name>.a libraries are on the right side
# in the linker command.
diff --git a/modules/camera/camera_osx.h b/modules/camera/camera_osx.h
index 9d67235839..b0db844599 100644
--- a/modules/camera/camera_osx.h
+++ b/modules/camera/camera_osx.h
@@ -39,7 +39,6 @@
class CameraOSX : public CameraServer {
public:
CameraOSX();
- ~CameraOSX();
void update_feeds();
};
diff --git a/modules/camera/camera_osx.mm b/modules/camera/camera_osx.mm
index 391006bfc2..d199c31b2f 100644
--- a/modules/camera/camera_osx.mm
+++ b/modules/camera/camera_osx.mm
@@ -114,18 +114,12 @@
if (output) {
[self removeOutput:output];
[output setSampleBufferDelegate:nil queue:nullptr];
- [output release];
output = nullptr;
}
[self commitConfiguration];
}
-- (void)dealloc {
- // bye bye
- [super dealloc];
-}
-
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
// This gets called every time our camera has a new image for us to process.
// May need to investigate in a way to throttle this if we get more images then we're rendering frames..
@@ -208,7 +202,6 @@ public:
AVCaptureDevice *get_device() const;
CameraFeedOSX();
- ~CameraFeedOSX();
void set_device(AVCaptureDevice *p_device);
@@ -227,7 +220,6 @@ CameraFeedOSX::CameraFeedOSX() {
void CameraFeedOSX::set_device(AVCaptureDevice *p_device) {
device = p_device;
- [device retain];
// get some info
NSString *device_name = p_device.localizedName;
@@ -240,18 +232,6 @@ void CameraFeedOSX::set_device(AVCaptureDevice *p_device) {
};
};
-CameraFeedOSX::~CameraFeedOSX() {
- if (capture_session != nullptr) {
- [capture_session release];
- capture_session = nullptr;
- };
-
- if (device != nullptr) {
- [device release];
- device = nullptr;
- };
-};
-
bool CameraFeedOSX::activate_feed() {
if (capture_session) {
// Already recording!
@@ -282,7 +262,6 @@ void CameraFeedOSX::deactivate_feed() {
// end camera capture if we have one
if (capture_session) {
[capture_session cleanup];
- [capture_session release];
capture_session = nullptr;
};
};
@@ -317,8 +296,6 @@ void CameraFeedOSX::deactivate_feed() {
// remove notifications
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasConnectedNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceWasDisconnectedNotification object:nil];
-
- [super dealloc];
}
@end
@@ -376,7 +353,3 @@ CameraOSX::CameraOSX() {
// should only have one of these....
device_notifications = [[MyDeviceNotifications alloc] initForServer:this];
};
-
-CameraOSX::~CameraOSX() {
- [device_notifications release];
-};
diff --git a/modules/csg/doc_classes/CSGBox3D.xml b/modules/csg/doc_classes/CSGBox3D.xml
index 4b479ed42e..64b07a6cbb 100644
--- a/modules/csg/doc_classes/CSGBox3D.xml
+++ b/modules/csg/doc_classes/CSGBox3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
This node allows you to create a box for use with the CSG system.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<members>
<member name="material" type="Material" setter="set_material" getter="get_material">
diff --git a/modules/csg/doc_classes/CSGCombiner3D.xml b/modules/csg/doc_classes/CSGCombiner3D.xml
index 422c5d35b7..16903141de 100644
--- a/modules/csg/doc_classes/CSGCombiner3D.xml
+++ b/modules/csg/doc_classes/CSGCombiner3D.xml
@@ -5,7 +5,9 @@
</brief_description>
<description>
For complex arrangements of shapes, it is sometimes needed to add structure to your CSG nodes. The CSGCombiner3D node allows you to create this structure. The node encapsulates the result of the CSG operations of its children. In this way, it is possible to do operations on one set of shapes that are children of one CSGCombiner3D node, and a set of separate operations on a second set of shapes that are children of a second CSGCombiner3D node, and then do an operation that takes the two end results as its input to create the final shape.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
</class>
diff --git a/modules/csg/doc_classes/CSGCylinder3D.xml b/modules/csg/doc_classes/CSGCylinder3D.xml
index 1fe2025bab..fa61957c84 100644
--- a/modules/csg/doc_classes/CSGCylinder3D.xml
+++ b/modules/csg/doc_classes/CSGCylinder3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
This node allows you to create a cylinder (or cone) for use with the CSG system.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<members>
<member name="cone" type="bool" setter="set_cone" getter="is_cone" default="false">
diff --git a/modules/csg/doc_classes/CSGMesh3D.xml b/modules/csg/doc_classes/CSGMesh3D.xml
index 42fcb7bd2b..660659a98b 100644
--- a/modules/csg/doc_classes/CSGMesh3D.xml
+++ b/modules/csg/doc_classes/CSGMesh3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
This CSG node allows you to use any mesh resource as a CSG shape, provided it is closed, does not self-intersect, does not contain internal faces and has no edges that connect to more than two faces. See also [CSGPolygon3D] for drawing 2D extruded polygons to be used as CSG nodes.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<members>
<member name="material" type="Material" setter="set_material" getter="get_material">
diff --git a/modules/csg/doc_classes/CSGPolygon3D.xml b/modules/csg/doc_classes/CSGPolygon3D.xml
index 5a49eebc7b..e8ef79a9e5 100644
--- a/modules/csg/doc_classes/CSGPolygon3D.xml
+++ b/modules/csg/doc_classes/CSGPolygon3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
An array of 2D points is extruded to quickly and easily create a variety of 3D meshes. See also [CSGMesh3D] for using 3D meshes as CSG nodes.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<members>
<member name="depth" type="float" setter="set_depth" getter="get_depth" default="1.0">
diff --git a/modules/csg/doc_classes/CSGPrimitive3D.xml b/modules/csg/doc_classes/CSGPrimitive3D.xml
index 8f4c8b9451..7eac85368e 100644
--- a/modules/csg/doc_classes/CSGPrimitive3D.xml
+++ b/modules/csg/doc_classes/CSGPrimitive3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
Parent class for various CSG primitives. It contains code and functionality that is common between them. It cannot be used directly. Instead use one of the various classes that inherit from it.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<members>
<member name="invert_faces" type="bool" setter="set_invert_faces" getter="is_inverting_faces" default="false">
diff --git a/modules/csg/doc_classes/CSGShape3D.xml b/modules/csg/doc_classes/CSGShape3D.xml
index f5031064d6..b2513703c0 100644
--- a/modules/csg/doc_classes/CSGShape3D.xml
+++ b/modules/csg/doc_classes/CSGShape3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
This is the CSG base class that provides CSG operation support to the various CSG nodes in Godot.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<methods>
<method name="get_collision_layer_value" qualifiers="const">
diff --git a/modules/csg/doc_classes/CSGSphere3D.xml b/modules/csg/doc_classes/CSGSphere3D.xml
index b8dfb4cf5f..1ef20bc7ca 100644
--- a/modules/csg/doc_classes/CSGSphere3D.xml
+++ b/modules/csg/doc_classes/CSGSphere3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
This node allows you to create a sphere for use with the CSG system.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<members>
<member name="material" type="Material" setter="set_material" getter="get_material">
diff --git a/modules/csg/doc_classes/CSGTorus3D.xml b/modules/csg/doc_classes/CSGTorus3D.xml
index 2c0eef8f09..09256af109 100644
--- a/modules/csg/doc_classes/CSGTorus3D.xml
+++ b/modules/csg/doc_classes/CSGTorus3D.xml
@@ -5,8 +5,10 @@
</brief_description>
<description>
This node allows you to create a torus for use with the CSG system.
+ [b]Note:[/b] CSG nodes are intended to be used for level prototyping. Creating CSG nodes has a significant CPU cost compared to creating a [MeshInstance3D] with a [PrimitiveMesh]. Moving a CSG node within another CSG node also has a significant CPU cost, so it should be avoided during gameplay.
</description>
<tutorials>
+ <link title="Prototyping levels with CSG">$DOCS_URL/tutorials/3d/csg_tools.html</link>
</tutorials>
<members>
<member name="inner_radius" type="float" setter="set_inner_radius" getter="get_inner_radius" default="0.5">
diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp
index be304a43f0..5d5414c694 100644
--- a/modules/gdnative/nativescript/nativescript.cpp
+++ b/modules/gdnative/nativescript/nativescript.cpp
@@ -766,7 +766,7 @@ Variant NativeScriptInstance::call(const StringName &p_method, const Variant **p
void NativeScriptInstance::notification(int p_notification) {
#ifdef DEBUG_ENABLED
if (p_notification == MainLoop::NOTIFICATION_CRASH) {
- if (current_method_call != StringName("")) {
+ if (current_method_call != StringName()) {
ERR_PRINT("NativeScriptInstance detected crash on method: " + current_method_call);
current_method_call = "";
}
diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp
index 71ab8ef0a2..ec3c9eb4ff 100644
--- a/modules/gdnative/pluginscript/pluginscript_script.cpp
+++ b/modules/gdnative/pluginscript/pluginscript_script.cpp
@@ -93,7 +93,7 @@ Variant PluginScript::_new(const Variant **p_args, int p_argcount, Callable::Cal
REF ref;
Object *owner = nullptr;
- if (get_instance_base_type() == "") {
+ if (get_instance_base_type() == StringName()) {
owner = memnew(RefCounted);
} else {
owner = ClassDB::instantiate(get_instance_base_type());
diff --git a/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd b/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd
index 0824d894c5..edaccae018 100644
--- a/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd
+++ b/modules/gdscript/editor_templates/CharacterBody2D/basic_movement.gd
@@ -3,7 +3,7 @@
extends _BASE_
const SPEED: float = 300.0
-const JUMP_FORCE: float = -400.0
+const JUMP_VELOCITY: float = -400.0
# Get the gravity from the project settings to be synced with RigidDynamicBody nodes.
var gravity: int = ProjectSettings.get_setting("physics/2d/default_gravity")
@@ -16,7 +16,7 @@ func _physics_process(delta: float) -> void:
# Handle Jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
- motion_velocity.y = JUMP_FORCE
+ motion_velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
diff --git a/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd b/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd
index ce6d67ae84..e191e5451a 100644
--- a/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd
+++ b/modules/gdscript/editor_templates/CharacterBody3D/basic_movement.gd
@@ -3,7 +3,7 @@
extends _BASE_
const SPEED: float = 5.0
-const JUMP_FORCE: float = 4.5
+const JUMP_VELOCITY: float = 4.5
# Get the gravity from the project settings to be synced with RigidDynamicBody nodes.
var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity")
@@ -16,7 +16,7 @@ func _physics_process(delta: float) -> void:
# Handle Jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
- motion_velocity.y = JUMP_FORCE
+ motion_velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
diff --git a/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd b/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd
index 27383b878d..d71f2592fe 100644
--- a/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd
+++ b/modules/gdscript/editor_templates/VisualShaderNodeCustom/basic.gd
@@ -34,8 +34,5 @@ func _get_output_port_name(port: int) -> String:
func _get_output_port_type(port: int) -> int:
return PORT_TYPE_SCALAR
-func _get_global_code(mode: Shader.Mode) -> String:
- return ""
-
func _get_code(input_vars: Array[String], output_vars: Array[String], mode: Shader.Mode, type: VisualShader.Type) -> String:
return output_vars[0] + " = 0.0;"
diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp
index a80874d785..58a788e255 100644
--- a/modules/gdscript/gdscript.cpp
+++ b/modules/gdscript/gdscript.cpp
@@ -43,6 +43,7 @@
#include "gdscript_cache.h"
#include "gdscript_compiler.h"
#include "gdscript_parser.h"
+#include "gdscript_rpc_callable.h"
#include "gdscript_warning.h"
#ifdef TESTS_ENABLED
@@ -1375,7 +1376,13 @@ bool GDScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
while (sl) {
const Map<StringName, GDScriptFunction *>::Element *E = sl->member_functions.find(p_name);
if (E) {
- r_ret = Callable(this->owner, E->key());
+ Multiplayer::RPCConfig config;
+ config.name = p_name;
+ if (sptr->rpc_functions.find(config) != -1) {
+ r_ret = Callable(memnew(GDScriptRPCCallable(this->owner, E->key())));
+ } else {
+ r_ret = Callable(this->owner, E->key());
+ }
return true; //index found
}
sl = sl->_base;
diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp
index 9ff52347e9..94daba4bf6 100644
--- a/modules/gdscript/gdscript_analyzer.cpp
+++ b/modules/gdscript/gdscript_analyzer.cpp
@@ -196,7 +196,7 @@ Error GDScriptAnalyzer::check_class_member_name_conflict(const GDScriptParser::C
}
if (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::NATIVE) {
- if (current_data_type->native_type != StringName("")) {
+ if (current_data_type->native_type != StringName()) {
return check_native_member_name_conflict(
p_member_name,
p_member_node,
@@ -250,7 +250,7 @@ Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class,
if (!p_class->extends_used) {
result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
result.kind = GDScriptParser::DataType::NATIVE;
- result.native_type = "RefCounted";
+ result.native_type = SNAME("RefCounted");
} else {
result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
@@ -438,7 +438,7 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type
StringName first = p_type->type_chain[0]->name;
- if (first == "Variant") {
+ if (first == SNAME("Variant")) {
result.kind = GDScriptParser::DataType::VARIANT;
if (p_type->type_chain.size() > 1) {
push_error(R"("Variant" type don't contain nested types.)", p_type->type_chain[1]);
@@ -447,9 +447,9 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type
return result;
}
- if (first == "Object") {
+ if (first == SNAME("Object")) {
result.kind = GDScriptParser::DataType::NATIVE;
- result.native_type = "Object";
+ result.native_type = SNAME("Object");
if (p_type->type_chain.size() > 1) {
push_error(R"("Object" type don't contain nested types.)", p_type->type_chain[1]);
return GDScriptParser::DataType();
@@ -2552,7 +2552,7 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node)
GDScriptParser::DataType result;
result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
result.kind = GDScriptParser::DataType::NATIVE;
- result.native_type = "Node";
+ result.native_type = SNAME("Node");
result.builtin_type = Variant::OBJECT;
if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, result.native_type)) {
@@ -3524,7 +3524,7 @@ GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo
result.builtin_type = p_property.type;
if (p_property.type == Variant::OBJECT) {
result.kind = GDScriptParser::DataType::NATIVE;
- result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
+ result.native_type = p_property.class_name == StringName() ? SNAME("Object") : p_property.class_name;
} else {
result.kind = GDScriptParser::DataType::BUILTIN;
result.builtin_type = p_property.type;
diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp
index 33a88dd2dd..f0dc830ed8 100644
--- a/modules/gdscript/gdscript_editor.cpp
+++ b/modules/gdscript/gdscript_editor.cpp
@@ -652,7 +652,7 @@ static void _get_directory_contents(EditorFileSystemDirectory *p_dir, Map<String
}
static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_annotation, int p_argument, const String p_quote_style, Map<String, ScriptCodeCompletionOption> &r_result) {
- if (p_annotation->name == "@export_range") {
+ if (p_annotation->name == SNAME("@export_range")) {
if (p_argument == 3 || p_argument == 4) {
// Slider hint.
ScriptCodeCompletionOption slider1("or_greater", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
@@ -662,7 +662,7 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a
slider2.insert_text = slider2.display.quote(p_quote_style);
r_result.insert(slider2.display, slider2);
}
- } else if (p_annotation->name == "@export_exp_easing") {
+ } else if (p_annotation->name == SNAME("@export_exp_easing")) {
if (p_argument == 0 || p_argument == 1) {
// Easing hint.
ScriptCodeCompletionOption hint1("attenuation", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
@@ -672,7 +672,7 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a
hint2.insert_text = hint2.display.quote(p_quote_style);
r_result.insert(hint2.display, hint2);
}
- } else if (p_annotation->name == "@export_node_path") {
+ } else if (p_annotation->name == SNAME("@export_node_path")) {
ScriptCodeCompletionOption node("Node", ScriptCodeCompletionOption::KIND_CLASS);
r_result.insert(node.display, node);
List<StringName> node_types;
@@ -684,7 +684,7 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a
ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CLASS);
r_result.insert(option.display, option);
}
- } else if (p_annotation->name == "@warning_ignore") {
+ } else if (p_annotation->name == SNAME("@warning_ignore")) {
for (int warning_code = 0; warning_code < GDScriptWarning::WARNING_MAX; warning_code++) {
ScriptCodeCompletionOption warning(GDScriptWarning::get_name_from_code((GDScriptWarning::Code)warning_code).to_lower(), ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
r_result.insert(warning.display, warning);
@@ -1384,7 +1384,7 @@ static bool _guess_expression_type(GDScriptParser::CompletionContext &p_context,
Object *baseptr = base.value;
- if (all_is_const && String(call->function_name) == "get_node" && ClassDB::is_parent_class(native_type.native_type, "Node") && args.size()) {
+ if (all_is_const && call->function_name == SNAME("get_node") && ClassDB::is_parent_class(native_type.native_type, SNAME("Node")) && args.size()) {
String arg1 = args[0];
if (arg1.begins_with("/root/")) {
String which = arg1.get_slice("/", 2);
@@ -2085,7 +2085,7 @@ static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContex
GDScriptParser::DataType base_type = p_base.type;
bool is_static = base_type.is_meta_type;
- if (is_static && p_method == "new") {
+ if (is_static && p_method == SNAME("new")) {
r_type.type = base_type;
r_type.type.is_meta_type = false;
r_type.type.is_constant = false;
@@ -2274,7 +2274,7 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c
r_arghint = _make_arguments_hint(info, p_argidx);
}
- if (p_argidx == 0 && ClassDB::is_parent_class(class_name, "Node") && (p_method == "get_node" || p_method == "has_node")) {
+ if (p_argidx == 0 && ClassDB::is_parent_class(class_name, SNAME("Node")) && (p_method == SNAME("get_node") || p_method == SNAME("has_node"))) {
// Get autoloads
List<PropertyInfo> props;
ProjectSettings::get_singleton()->get_property_list(&props);
@@ -2291,7 +2291,7 @@ static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, c
}
}
- if (p_argidx == 0 && method_args > 0 && ClassDB::is_parent_class(class_name, "InputEvent") && p_method.operator String().contains("action")) {
+ if (p_argidx == 0 && method_args > 0 && ClassDB::is_parent_class(class_name, SNAME("InputEvent")) && p_method.operator String().contains("action")) {
// Get input actions
List<PropertyInfo> props;
ProjectSettings::get_singleton()->get_property_list(&props);
diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp
index cfad832a6c..8e4e457ec1 100644
--- a/modules/gdscript/gdscript_parser.cpp
+++ b/modules/gdscript/gdscript_parser.cpp
@@ -519,7 +519,7 @@ void GDScriptParser::parse_program() {
// Check for @tool annotation.
AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL);
if (annotation != nullptr) {
- if (annotation->name == "@tool") {
+ if (annotation->name == SNAME("@tool")) {
// TODO: don't allow @tool anywhere else. (Should all script annotations be the first thing?).
_is_tool = true;
if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
@@ -573,7 +573,7 @@ void GDScriptParser::parse_program() {
// Check for @icon annotation.
AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::CLASS_LEVEL);
if (annotation != nullptr) {
- if (annotation->name == "@icon") {
+ if (annotation->name == SNAME("@icon")) {
if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
push_error(R"(Expected newline after "@icon" annotation.)");
}
@@ -3503,7 +3503,7 @@ bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node
// This is called after the analyzer is done finding the type, so this should be set here.
DataType export_type = variable->get_datatype();
- if (p_annotation->name == "@export") {
+ if (p_annotation->name == SNAME("@export")) {
if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
return false;
@@ -3528,7 +3528,7 @@ bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node
variable->export_info.hint_string = Variant::get_type_name(export_type.builtin_type);
break;
case GDScriptParser::DataType::NATIVE:
- if (ClassDB::is_parent_class(export_type.native_type, "Resource")) {
+ if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
variable->export_info.type = Variant::OBJECT;
variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
variable->export_info.hint_string = export_type.native_type;
diff --git a/modules/gdscript/gdscript_rpc_callable.cpp b/modules/gdscript/gdscript_rpc_callable.cpp
new file mode 100644
index 0000000000..07e5ed4171
--- /dev/null
+++ b/modules/gdscript/gdscript_rpc_callable.cpp
@@ -0,0 +1,86 @@
+/*************************************************************************/
+/* gdscript_rpc_callable.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 "gdscript_rpc_callable.h"
+
+#include "core/templates/hashfuncs.h"
+#include "scene/main/node.h"
+
+bool GDScriptRPCCallable::compare_equal(const CallableCustom *p_a, const CallableCustom *p_b) {
+ return p_a->hash() == p_b->hash();
+}
+
+bool GDScriptRPCCallable::compare_less(const CallableCustom *p_a, const CallableCustom *p_b) {
+ return p_a->hash() < p_b->hash();
+}
+
+uint32_t GDScriptRPCCallable::hash() const {
+ return h;
+}
+
+String GDScriptRPCCallable::get_as_text() const {
+ String class_name = object->get_class();
+ Ref<Script> script = object->get_script();
+ return class_name + "(" + script->get_path().get_file() + ")::" + String(method) + " (rpc)";
+}
+
+CallableCustom::CompareEqualFunc GDScriptRPCCallable::get_compare_equal_func() const {
+ return compare_equal;
+}
+
+CallableCustom::CompareLessFunc GDScriptRPCCallable::get_compare_less_func() const {
+ return compare_less;
+}
+
+ObjectID GDScriptRPCCallable::get_object() const {
+ return object->get_instance_id();
+}
+
+void GDScriptRPCCallable::call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const {
+ r_return_value = object->call(method, p_arguments, p_argcount, r_call_error);
+}
+
+GDScriptRPCCallable::GDScriptRPCCallable(Object *p_object, const StringName &p_method) {
+ object = p_object;
+ method = p_method;
+ h = method.hash();
+ h = hash_djb2_one_64(object->get_instance_id(), h);
+ node = Object::cast_to<Node>(object);
+ ERR_FAIL_COND_MSG(!node, "RPC can only be defined on class that extends Node.");
+}
+
+void GDScriptRPCCallable::rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const {
+ if (unlikely(!node)) {
+ r_call_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
+ return;
+ }
+ r_call_error.error = Callable::CallError::CALL_OK;
+ node->rpcp(p_peer_id, method, p_arguments, p_argcount);
+}
diff --git a/modules/gdscript/gdscript_rpc_callable.h b/modules/gdscript/gdscript_rpc_callable.h
new file mode 100644
index 0000000000..2c8734a74b
--- /dev/null
+++ b/modules/gdscript/gdscript_rpc_callable.h
@@ -0,0 +1,61 @@
+/*************************************************************************/
+/* gdscript_rpc_callable.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 GDSCRIPT_RPC_CALLABLE
+#define GDSCRIPT_RPC_CALLABLE
+
+#include "core/variant/callable.h"
+#include "core/variant/variant.h"
+
+class Node;
+
+class GDScriptRPCCallable : public CallableCustom {
+ Object *object = nullptr;
+ Node *node = nullptr;
+ StringName method;
+ uint32_t h = 0;
+
+ static bool compare_equal(const CallableCustom *p_a, const CallableCustom *p_b);
+ static bool compare_less(const CallableCustom *p_a, const CallableCustom *p_b);
+
+public:
+ uint32_t hash() const override;
+ String get_as_text() const override;
+ CompareEqualFunc get_compare_equal_func() const override;
+ CompareLessFunc get_compare_less_func() const override;
+ ObjectID get_object() const override;
+ void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override;
+ void rpc(int p_peer_id, const Variant **p_arguments, int p_argcount, Callable::CallError &r_call_error) const override;
+
+ GDScriptRPCCallable(Object *p_object, const StringName &p_method);
+ virtual ~GDScriptRPCCallable() = default;
+};
+
+#endif // GDSCRIPT_RPC_CALLABLE
diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp
index 73a424dae4..c2bb2caa29 100644
--- a/modules/gdscript/tests/gdscript_test_runner.cpp
+++ b/modules/gdscript/tests/gdscript_test_runner.cpp
@@ -73,23 +73,21 @@ void init_autoloads() {
RES res = ResourceLoader::load(info.path);
ERR_CONTINUE_MSG(res.is_null(), "Can't autoload: " + info.path);
Node *n = nullptr;
- if (res->is_class("PackedScene")) {
- Ref<PackedScene> ps = res;
- n = ps->instantiate();
- } else if (res->is_class("Script")) {
- Ref<Script> script_res = res;
- StringName ibt = script_res->get_instance_base_type();
+ Ref<PackedScene> scn = res;
+ Ref<Script> script = res;
+ if (scn.is_valid()) {
+ n = scn->instantiate();
+ } else if (script.is_valid()) {
+ StringName ibt = script->get_instance_base_type();
bool valid_type = ClassDB::is_parent_class(ibt, "Node");
ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path);
Object *obj = ClassDB::instantiate(ibt);
- ERR_CONTINUE_MSG(obj == nullptr,
- "Cannot instance script for autoload, expected 'Node' inheritance, got: " +
- String(ibt));
+ ERR_CONTINUE_MSG(!obj, "Cannot instance script for autoload, expected 'Node' inheritance, got: " + String(ibt) + ".");
n = Object::cast_to<Node>(obj);
- n->set_script(script_res);
+ n->set_script(script);
}
ERR_CONTINUE_MSG(!n, "Path in autoload not a node or script: " + info.path);
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index 67deedf839..6df7835855 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -813,6 +813,7 @@ void GridMap::_update_octants_callback() {
}
while (to_delete.front()) {
+ memdelete(octant_map[to_delete.front()->get()]);
octant_map.erase(to_delete.front()->get());
to_delete.pop_front();
}
diff --git a/modules/modules_builders.py b/modules/modules_builders.py
index 2243162555..13d5a2075a 100644
--- a/modules/modules_builders.py
+++ b/modules/modules_builders.py
@@ -14,13 +14,10 @@ def generate_modules_enabled(target, source, env):
def generate_modules_tests(target, source, env):
import os
- import glob
with open(target[0].path, "w") as f:
- for name, path in env.module_list.items():
- headers = glob.glob(os.path.join(path, "tests", "*.h"))
- for h in headers:
- f.write('#include "%s"\n' % (os.path.normpath(h)))
+ for header in source:
+ f.write('#include "%s"\n' % (os.path.normpath(header.path)))
if __name__ == "__main__":
diff --git a/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs b/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs
index 6e9547ce9b..b0ded3133f 100644
--- a/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs
+++ b/modules/mono/editor_templates/CharacterBody2D/basic_movement.cs
@@ -6,7 +6,7 @@ using System;
public partial class _CLASS_ : _BASE_
{
public const float Speed = 300.0f;
- public const float JumpForce = -400.0f;
+ public const float JumpVelocity = -400.0f;
// Get the gravity from the project settings to be synced with RigidDynamicBody nodes.
public float gravity = (float)ProjectSettings.GetSetting("physics/2d/default_gravity");
@@ -21,7 +21,7 @@ public partial class _CLASS_ : _BASE_
// Handle Jump.
if (Input.IsActionJustPressed("ui_accept") && IsOnFloor())
- motionVelocity.y = JumpForce;
+ motionVelocity.y = JumpVelocity;
// Get the input direction and handle the movement/deceleration.
// As good practice, you should replace UI actions with custom gameplay actions.
diff --git a/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs b/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs
index 13be4bbcb1..d8c2f67ac8 100644
--- a/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs
+++ b/modules/mono/editor_templates/CharacterBody3D/basic_movement.cs
@@ -6,7 +6,7 @@ using System;
public partial class _CLASS_ : _BASE_
{
public const float Speed = 5.0f;
- public const float JumpForce = 4.5f;
+ public const float JumpVelocity = 4.5f;
// Get the gravity from the project settings to be synced with RigidDynamicBody nodes.
public float gravity = (float)ProjectSettings.GetSetting("physics/3d/default_gravity");
@@ -21,7 +21,7 @@ public partial class _CLASS_ : _BASE_
// Handle Jump.
if (Input.IsActionJustPressed("ui_accept") && IsOnFloor())
- motionVelocity.y = JumpForce;
+ motionVelocity.y = JumpVelocity;
// Get the input direction and handle the movement/deceleration.
// As good practice, you should replace UI actions with custom gameplay actions.
diff --git a/modules/mono/editor_templates/VisualShaderNodeCustom/basic.cs b/modules/mono/editor_templates/VisualShaderNodeCustom/basic.cs
index 00fdc9968e..a1b93e7daa 100644
--- a/modules/mono/editor_templates/VisualShaderNodeCustom/basic.cs
+++ b/modules/mono/editor_templates/VisualShaderNodeCustom/basic.cs
@@ -55,11 +55,6 @@ public partial class VisualShaderNode_CLASS_ : _BASE_
return 0;
}
- public override string _GetGlobalCode(Shader.Mode mode)
- {
- return "";
- }
-
public override string _GetCode(Godot.Collections.Array inputVars, Godot.Collections.Array outputVars, Shader.Mode mode, VisualShader.Type type)
{
return "";
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
index eba0ea9a79..a1f058ffe5 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs
@@ -266,7 +266,7 @@ namespace Godot
/// <returns>The capitalized string.</returns>
public static string Capitalize(this string instance)
{
- string aux = instance.Replace("_", " ").ToLower();
+ string aux = instance.CamelcaseToUnderscore(true).Replace("_", " ").Trim();
string cap = string.Empty;
for (int i = 0; i < aux.GetSliceCount(" "); i++)
@@ -284,6 +284,51 @@ namespace Godot
return cap;
}
+ private static string CamelcaseToUnderscore(this string instance, bool lowerCase)
+ {
+ string newString = string.Empty;
+ int startIndex = 0;
+
+ for (int i = 1; i < instance.Length; i++)
+ {
+ bool isUpper = char.IsUpper(instance[i]);
+ bool isNumber = char.IsDigit(instance[i]);
+
+ bool areNext2Lower = false;
+ bool isNextLower = false;
+ bool isNextNumber = false;
+ bool wasPrecedentUpper = char.IsUpper(instance[i - 1]);
+ bool wasPrecedentNumber = char.IsDigit(instance[i - 1]);
+
+ if (i + 2 < instance.Length)
+ {
+ areNext2Lower = char.IsLower(instance[i + 1]) && char.IsLower(instance[i + 2]);
+ }
+
+ if (i + 1 < instance.Length)
+ {
+ isNextLower = char.IsLower(instance[i + 1]);
+ isNextNumber = char.IsDigit(instance[i + 1]);
+ }
+
+ bool condA = isUpper && !wasPrecedentUpper && !wasPrecedentNumber;
+ bool condB = wasPrecedentUpper && isUpper && areNext2Lower;
+ bool condC = isNumber && !wasPrecedentNumber;
+ bool canBreakNumberLetter = isNumber && !wasPrecedentNumber && isNextLower;
+ bool canBreakLetterNumber = !isNumber && wasPrecedentNumber && (isNextLower || isNextNumber);
+
+ bool shouldSplit = condA || condB || condC || canBreakNumberLetter || canBreakLetterNumber;
+ if (shouldSplit)
+ {
+ newString += instance.Substring(startIndex, i - startIndex) + "_";
+ startIndex = i;
+ }
+ }
+
+ newString += instance.Substring(startIndex, instance.Length - startIndex);
+ return lowerCase ? newString.ToLower() : newString;
+ }
+
/// <summary>
/// Performs a case-sensitive comparison to another string, return -1 if less, 0 if equal and +1 if greater.
/// </summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
index 1f5282e88f..fa7838633c 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs
@@ -512,24 +512,24 @@ namespace Godot
/// Returns the result of the spherical linear interpolation between
/// this vector and <paramref name="to"/> by amount <paramref name="weight"/>.
///
- /// Note: Both vectors must be normalized.
+ /// This method also handles interpolating the lengths if the input vectors have different lengths.
+ /// For the special case of one or both input vectors having zero length, this method behaves like [method lerp].
/// </summary>
- /// <param name="to">The destination vector for interpolation. Must be normalized.</param>
+ /// <param name="to">The destination vector for interpolation.</param>
/// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The resulting vector of the interpolation.</returns>
public Vector2 Slerp(Vector2 to, real_t weight)
{
-#if DEBUG
- if (!IsNormalized())
- {
- throw new InvalidOperationException("Vector2.Slerp: From vector is not normalized.");
+ real_t startLengthSquared = LengthSquared();
+ real_t endLengthSquared = to.LengthSquared();
+ if (startLengthSquared == 0.0 || endLengthSquared == 0.0) {
+ // Zero length vectors have no angle, so the best we can do is either lerp or throw an error.
+ return Lerp(to, weight);
}
- if (!to.IsNormalized())
- {
- throw new InvalidOperationException($"Vector2.Slerp: `{nameof(to)}` is not normalized.");
- }
-#endif
- return Rotated(AngleTo(to) * weight);
+ real_t startLength = Mathf.Sqrt(startLengthSquared);
+ real_t resultLength = Mathf.Lerp(startLength, Mathf.Sqrt(endLengthSquared), weight);
+ real_t angle = AngleTo(to);
+ return Rotated(angle * weight) * (resultLength / startLength);
}
/// <summary>
diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
index 433a5d9dc9..0faf13f8b7 100644
--- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
+++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs
@@ -549,25 +549,24 @@ namespace Godot
/// Returns the result of the spherical linear interpolation between
/// this vector and <paramref name="to"/> by amount <paramref name="weight"/>.
///
- /// Note: Both vectors must be normalized.
+ /// This method also handles interpolating the lengths if the input vectors have different lengths.
+ /// For the special case of one or both input vectors having zero length, this method behaves like [method lerp].
/// </summary>
- /// <param name="to">The destination vector for interpolation. Must be normalized.</param>
+ /// <param name="to">The destination vector for interpolation.</param>
/// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The resulting vector of the interpolation.</returns>
public Vector3 Slerp(Vector3 to, real_t weight)
{
-#if DEBUG
- if (!IsNormalized())
- {
- throw new InvalidOperationException("Vector3.Slerp: From vector is not normalized.");
+ real_t startLengthSquared = LengthSquared();
+ real_t endLengthSquared = to.LengthSquared();
+ if (startLengthSquared == 0.0 || endLengthSquared == 0.0) {
+ // Zero length vectors have no angle, so the best we can do is either lerp or throw an error.
+ return Lerp(to, weight);
}
- if (!to.IsNormalized())
- {
- throw new InvalidOperationException($"Vector3.Slerp: `{nameof(to)}` is not normalized.");
- }
-#endif
- real_t theta = AngleTo(to);
- return Rotated(Cross(to), theta * weight);
+ real_t startLength = Mathf.Sqrt(startLengthSquared);
+ real_t resultLength = Mathf.Lerp(startLength, Mathf.Sqrt(endLengthSquared), weight);
+ real_t angle = AngleTo(to);
+ return Rotated(Cross(to).Normalized(), angle * weight) * (resultLength / startLength);
}
/// <summary>
diff --git a/modules/visual_script/editor/visual_script_editor.cpp b/modules/visual_script/editor/visual_script_editor.cpp
index 1a7d473bd4..5ea8eaff00 100644
--- a/modules/visual_script/editor/visual_script_editor.cpp
+++ b/modules/visual_script/editor/visual_script_editor.cpp
@@ -653,7 +653,6 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
List<int> ids;
script->get_node_list(&ids);
- StringName editor_icons = "EditorIcons";
for (int &E : ids) {
if (p_only_id >= 0 && p_only_id != E) {
diff --git a/modules/visual_script/editor/visual_script_property_selector.cpp b/modules/visual_script/editor/visual_script_property_selector.cpp
index 4072dcebe5..bba5410629 100644
--- a/modules/visual_script/editor/visual_script_property_selector.cpp
+++ b/modules/visual_script/editor/visual_script_property_selector.cpp
@@ -1114,14 +1114,14 @@ TreeItem *VisualScriptPropertySelector::SearchRunner::_create_class_item(TreeIte
String details = p_doc->name;
if (p_doc->category.begins_with("VisualScriptCustomNode/")) {
Vector<String> path = p_doc->name.split("/");
- icon = ui_service->get_theme_icon("VisualScript", "EditorIcons");
+ icon = ui_service->get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons"));
text_0 = path[path.size() - 1];
text_1 = "VisualScriptCustomNode";
what = "VisualScriptCustomNode";
details = "CustomNode";
} else if (p_doc->category.begins_with("VisualScriptNode/")) {
Vector<String> path = p_doc->name.split("/");
- icon = ui_service->get_theme_icon("VisualScript", "EditorIcons");
+ icon = ui_service->get_theme_icon(SNAME("VisualScript"), SNAME("EditorIcons"));
text_0 = path[path.size() - 1];
if (p_doc->category.begins_with("VisualScriptNode/deconstruct")) {
text_0 = "deconstruct " + text_0;
diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp
index fbdf3a654b..88445f2f98 100644
--- a/modules/visual_script/visual_script.cpp
+++ b/modules/visual_script/visual_script.cpp
@@ -1164,9 +1164,6 @@ void VisualScript::_bind_methods() {
ClassDB::bind_method(D_METHOD("remove_custom_signal", "name"), &VisualScript::remove_custom_signal);
ClassDB::bind_method(D_METHOD("rename_custom_signal", "name", "new_name"), &VisualScript::rename_custom_signal);
- //ClassDB::bind_method(D_METHOD("set_variable_info","name","info"),&VScript::set_variable_info);
- //ClassDB::bind_method(D_METHOD("get_variable_info","name"),&VScript::set_variable_info);
-
ClassDB::bind_method(D_METHOD("set_instance_base_type", "type"), &VisualScript::set_instance_base_type);
ClassDB::bind_method(D_METHOD("_set_data", "data"), &VisualScript::_set_data);
diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp
index f3594e5164..e7f4e542c1 100644
--- a/modules/visual_script/visual_script_nodes.cpp
+++ b/modules/visual_script/visual_script_nodes.cpp
@@ -2495,7 +2495,7 @@ static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const
VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
VisualScriptSceneNode::TypeGuess tg;
tg.type = Variant::OBJECT;
- tg.gdclass = "Node";
+ tg.gdclass = SNAME("Node");
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
@@ -2649,7 +2649,7 @@ VisualScriptNodeInstance *VisualScriptSceneTree::instantiate(VisualScriptInstanc
VisualScriptSceneTree::TypeGuess VisualScriptSceneTree::guess_output_type(TypeGuess *p_inputs, int p_output) const {
TypeGuess tg;
tg.type = Variant::OBJECT;
- tg.gdclass = "SceneTree";
+ tg.gdclass = SNAME("SceneTree");
return tg;
}
@@ -2766,11 +2766,11 @@ PropertyInfo VisualScriptSelf::get_input_value_port_info(int p_idx) const {
}
PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const {
- String type_name;
+ StringName type_name;
if (get_visual_script().is_valid()) {
type_name = get_visual_script()->get_instance_base_type();
} else {
- type_name = "instance";
+ type_name = SNAME("instance");
}
return PropertyInfo(Variant::OBJECT, type_name);
@@ -2801,7 +2801,7 @@ VisualScriptNodeInstance *VisualScriptSelf::instantiate(VisualScriptInstance *p_
VisualScriptSelf::TypeGuess VisualScriptSelf::guess_output_type(TypeGuess *p_inputs, int p_output) const {
VisualScriptSceneNode::TypeGuess tg;
tg.type = Variant::OBJECT;
- tg.gdclass = "Object";
+ tg.gdclass = SNAME("Object");
Ref<Script> script = get_visual_script();
if (!script.is_valid()) {
diff --git a/platform/javascript/api/api.cpp b/platform/javascript/api/api.cpp
index 0c4accccc3..4190b24b8e 100644
--- a/platform/javascript/api/api.cpp
+++ b/platform/javascript/api/api.cpp
@@ -71,6 +71,9 @@ void JavaScript::_bind_methods() {
ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "create_object", &JavaScript::_create_object_bind, mi);
}
ClassDB::bind_method(D_METHOD("download_buffer", "buffer", "name", "mime"), &JavaScript::download_buffer, DEFVAL("application/octet-stream"));
+ ClassDB::bind_method(D_METHOD("pwa_needs_update"), &JavaScript::pwa_needs_update);
+ ClassDB::bind_method(D_METHOD("pwa_update"), &JavaScript::pwa_update);
+ ADD_SIGNAL(MethodInfo("pwa_update_available"));
}
#if !defined(JAVASCRIPT_ENABLED) || !defined(JAVASCRIPT_EVAL_ENABLED)
@@ -102,6 +105,12 @@ Variant JavaScript::_create_object_bind(const Variant **p_args, int p_argcount,
}
#endif
#if !defined(JAVASCRIPT_ENABLED)
+bool JavaScript::pwa_needs_update() const {
+ return false;
+}
+Error JavaScript::pwa_update() {
+ return ERR_UNAVAILABLE;
+}
void JavaScript::download_buffer(Vector<uint8_t> p_arr, const String &p_name, const String &p_mime) {
}
#endif
diff --git a/platform/javascript/api/javascript_singleton.h b/platform/javascript/api/javascript_singleton.h
index 63f1aec624..e93b0a18a1 100644
--- a/platform/javascript/api/javascript_singleton.h
+++ b/platform/javascript/api/javascript_singleton.h
@@ -59,6 +59,8 @@ public:
Ref<JavaScriptObject> create_callback(const Callable &p_callable);
Variant _create_object_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error);
void download_buffer(Vector<uint8_t> p_arr, const String &p_name, const String &p_mime = "application/octet-stream");
+ bool pwa_needs_update() const;
+ Error pwa_update();
static JavaScript *get_singleton();
JavaScript();
diff --git a/platform/javascript/export/export_plugin.cpp b/platform/javascript/export/export_plugin.cpp
index 92826630b4..d4c198d631 100644
--- a/platform/javascript/export/export_plugin.cpp
+++ b/platform/javascript/export/export_plugin.cpp
@@ -139,8 +139,7 @@ void EditorExportPlatformJavaScript::_fix_html(Vector<uint8_t> &p_html, const Re
}
if (p_preset->get("progressive_web_app/enabled")) {
head_include += "<link rel='manifest' href='" + p_name + ".manifest.json'>\n";
- head_include += "<script type='application/javascript'>window.addEventListener('load', () => {if ('serviceWorker' in navigator) {navigator.serviceWorker.register('" +
- p_name + ".service.worker.js');}});</script>\n";
+ config["serviceWorker"] = p_name + ".service.worker.js";
}
// Replaces HTML string
@@ -188,35 +187,46 @@ Error EditorExportPlatformJavaScript::_add_manifest_icon(const String &p_path, c
}
Error EditorExportPlatformJavaScript::_build_pwa(const Ref<EditorExportPreset> &p_preset, const String p_path, const Vector<SharedObject> &p_shared_objects) {
+ String proj_name = ProjectSettings::get_singleton()->get_setting("application/config/name");
+ if (proj_name.is_empty()) {
+ proj_name = "Godot Game";
+ }
+
// Service worker
const String dir = p_path.get_base_dir();
const String name = p_path.get_file().get_basename();
const ExportMode mode = (ExportMode)(int)p_preset->get("variant/export_type");
Map<String, String> replaces;
- replaces["@GODOT_VERSION@"] = "1";
- replaces["@GODOT_NAME@"] = name;
+ replaces["@GODOT_VERSION@"] = String::num_int64(OS::get_singleton()->get_unix_time()) + "|" + String::num_int64(OS::get_singleton()->get_ticks_usec());
+ replaces["@GODOT_NAME@"] = proj_name.substr(0, 16);
replaces["@GODOT_OFFLINE_PAGE@"] = name + ".offline.html";
- Array files;
- replaces["@GODOT_OPT_CACHE@"] = Variant(files).to_json_string();
- files.push_back(name + ".html");
- files.push_back(name + ".js");
- files.push_back(name + ".wasm");
- files.push_back(name + ".pck");
- files.push_back(name + ".offline.html");
+
+ // Files cached during worker install.
+ Array cache_files;
+ cache_files.push_back(name + ".html");
+ cache_files.push_back(name + ".js");
+ cache_files.push_back(name + ".offline.html");
if (p_preset->get("html/export_icon")) {
- files.push_back(name + ".icon.png");
- files.push_back(name + ".apple-touch-icon.png");
+ cache_files.push_back(name + ".icon.png");
+ cache_files.push_back(name + ".apple-touch-icon.png");
}
if (mode == EXPORT_MODE_THREADS) {
- files.push_back(name + ".worker.js");
- files.push_back(name + ".audio.worklet.js");
- } else if (mode == EXPORT_MODE_GDNATIVE) {
- files.push_back(name + ".side.wasm");
+ cache_files.push_back(name + ".worker.js");
+ cache_files.push_back(name + ".audio.worklet.js");
+ }
+ replaces["@GODOT_CACHE@"] = Variant(cache_files).to_json_string();
+
+ // Heavy files that are cached on demand.
+ Array opt_cache_files;
+ opt_cache_files.push_back(name + ".wasm");
+ opt_cache_files.push_back(name + ".pck");
+ if (mode == EXPORT_MODE_GDNATIVE) {
+ opt_cache_files.push_back(name + ".side.wasm");
for (int i = 0; i < p_shared_objects.size(); i++) {
- files.push_back(p_shared_objects[i].path.get_file());
+ opt_cache_files.push_back(p_shared_objects[i].path.get_file());
}
}
- replaces["@GODOT_CACHE@"] = Variant(files).to_json_string();
+ replaces["@GODOT_OPT_CACHE@"] = Variant(opt_cache_files).to_json_string();
const String sw_path = dir.plus_file(name + ".service.worker.js");
Vector<uint8_t> sw;
@@ -256,10 +266,6 @@ Error EditorExportPlatformJavaScript::_build_pwa(const Ref<EditorExportPreset> &
const int orientation = CLAMP(int(p_preset->get("progressive_web_app/orientation")), 0, 3);
Dictionary manifest;
- String proj_name = ProjectSettings::get_singleton()->get_setting("application/config/name");
- if (proj_name.is_empty()) {
- proj_name = "Godot Game";
- }
manifest["name"] = proj_name;
manifest["start_url"] = "./" + name + ".html";
manifest["display"] = String::utf8(modes[display]);
diff --git a/platform/javascript/godot_js.h b/platform/javascript/godot_js.h
index 15de8b5dc7..2cb5c3025c 100644
--- a/platform/javascript/godot_js.h
+++ b/platform/javascript/godot_js.h
@@ -49,6 +49,8 @@ extern void godot_js_os_fs_sync(void (*p_callback)());
extern int godot_js_os_execute(const char *p_json);
extern void godot_js_os_shell_open(const char *p_uri);
extern int godot_js_os_hw_concurrency_get();
+extern int godot_js_pwa_cb(void (*p_callback)());
+extern int godot_js_pwa_update();
// Input
extern void godot_js_input_mouse_button_cb(int (*p_callback)(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers));
diff --git a/platform/javascript/javascript_singleton.cpp b/platform/javascript/javascript_singleton.cpp
index b10e8007c0..77858bff01 100644
--- a/platform/javascript/javascript_singleton.cpp
+++ b/platform/javascript/javascript_singleton.cpp
@@ -30,6 +30,7 @@
#include "api/javascript_singleton.h"
#include "emscripten.h"
+#include "os_javascript.h"
extern "C" {
extern void godot_js_os_download_buffer(const uint8_t *p_buf, int p_buf_size, const char *p_name, const char *p_mime);
@@ -355,3 +356,10 @@ Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) {
void JavaScript::download_buffer(Vector<uint8_t> p_arr, const String &p_name, const String &p_mime) {
godot_js_os_download_buffer(p_arr.ptr(), p_arr.size(), p_name.utf8().get_data(), p_mime.utf8().get_data());
}
+
+bool JavaScript::pwa_needs_update() const {
+ return OS_JavaScript::get_singleton()->pwa_needs_update();
+}
+Error JavaScript::pwa_update() {
+ return OS_JavaScript::get_singleton()->pwa_update();
+}
diff --git a/platform/javascript/js/engine/config.js b/platform/javascript/js/engine/config.js
index a6f9c4614c..2e5e1ed0d1 100644
--- a/platform/javascript/js/engine/config.js
+++ b/platform/javascript/js/engine/config.js
@@ -107,6 +107,13 @@ const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-
*/
experimentalVK: false,
/**
+ * The progressive web app service worker to install.
+ * @memberof EngineConfig
+ * @default
+ * @type {string}
+ */
+ serviceWorker: '',
+ /**
* @ignore
* @type {Array.<string>}
*/
@@ -249,6 +256,7 @@ const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-
this.persistentDrops = parse('persistentDrops', this.persistentDrops);
this.experimentalVK = parse('experimentalVK', this.experimentalVK);
this.focusCanvas = parse('focusCanvas', this.focusCanvas);
+ this.serviceWorker = parse('serviceWorker', this.serviceWorker);
this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs);
this.fileSizes = parse('fileSizes', this.fileSizes);
this.args = parse('args', this.args);
diff --git a/platform/javascript/js/engine/engine.js b/platform/javascript/js/engine/engine.js
index 17a8df9e29..d2ba595083 100644
--- a/platform/javascript/js/engine/engine.js
+++ b/platform/javascript/js/engine/engine.js
@@ -189,6 +189,9 @@ const Engine = (function () {
preloader.preloadedFiles.length = 0; // Clear memory
me.rtenv['callMain'](me.config.args);
initPromise = null;
+ if (me.config.serviceWorker && 'serviceWorker' in navigator) {
+ navigator.serviceWorker.register(me.config.serviceWorker);
+ }
resolve();
});
});
diff --git a/platform/javascript/js/libs/library_godot_os.js b/platform/javascript/js/libs/library_godot_os.js
index 662d215443..12d06a8d51 100644
--- a/platform/javascript/js/libs/library_godot_os.js
+++ b/platform/javascript/js/libs/library_godot_os.js
@@ -368,3 +368,58 @@ const GodotEventListeners = {
},
};
mergeInto(LibraryManager.library, GodotEventListeners);
+
+const GodotPWA = {
+
+ $GodotPWA__deps: ['$GodotRuntime', '$GodotEventListeners'],
+ $GodotPWA: {
+ hasUpdate: false,
+
+ updateState: function (cb, reg) {
+ if (!reg) {
+ return;
+ }
+ if (!reg.active) {
+ return;
+ }
+ if (reg.waiting) {
+ GodotPWA.hasUpdate = true;
+ cb();
+ }
+ GodotEventListeners.add(reg, 'updatefound', function () {
+ const installing = reg.installing;
+ GodotEventListeners.add(installing, 'statechange', function () {
+ if (installing.state === 'installed') {
+ GodotPWA.hasUpdate = true;
+ cb();
+ }
+ });
+ });
+ },
+ },
+
+ godot_js_pwa_cb__sig: 'vi',
+ godot_js_pwa_cb: function (p_update_cb) {
+ if ('serviceWorker' in navigator) {
+ const cb = GodotRuntime.get_func(p_update_cb);
+ navigator.serviceWorker.getRegistration().then(GodotPWA.updateState.bind(null, cb));
+ }
+ },
+
+ godot_js_pwa_update__sig: 'i',
+ godot_js_pwa_update: function () {
+ if ('serviceWorker' in navigator && GodotPWA.hasUpdate) {
+ navigator.serviceWorker.getRegistration().then(function (reg) {
+ if (!reg || !reg.waiting) {
+ return;
+ }
+ reg.waiting.postMessage('update');
+ });
+ return 0;
+ }
+ return 1;
+ },
+};
+
+autoAddDeps(GodotPWA, '$GodotPWA');
+mergeInto(LibraryManager.library, GodotPWA);
diff --git a/platform/javascript/os_javascript.cpp b/platform/javascript/os_javascript.cpp
index 39eea13ca1..de5ca44f9d 100644
--- a/platform/javascript/os_javascript.cpp
+++ b/platform/javascript/os_javascript.cpp
@@ -45,6 +45,7 @@
#include <emscripten.h>
#include <stdlib.h>
+#include "api/javascript_singleton.h"
#include "godot_js.h"
void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
@@ -203,6 +204,19 @@ void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags
}
}
+void OS_JavaScript::update_pwa_state_callback() {
+ if (OS_JavaScript::get_singleton()) {
+ OS_JavaScript::get_singleton()->pwa_is_waiting = true;
+ }
+ if (JavaScript::get_singleton()) {
+ JavaScript::get_singleton()->emit_signal("pwa_update_available");
+ }
+}
+
+Error OS_JavaScript::pwa_update() {
+ return godot_js_pwa_update() ? FAILED : OK;
+}
+
bool OS_JavaScript::is_userfs_persistent() const {
return idb_available;
}
@@ -226,6 +240,8 @@ OS_JavaScript::OS_JavaScript() {
godot_js_config_locale_get(locale_ptr, 16);
setenv("LANG", locale_ptr, true);
+ godot_js_pwa_cb(&OS_JavaScript::update_pwa_state_callback);
+
if (AudioDriverJavaScript::is_available()) {
#ifdef NO_THREADS
audio_drivers.push_back(memnew(AudioDriverScriptProcessor));
diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h
index 3404fe9dcf..9e272f9aa1 100644
--- a/platform/javascript/os_javascript.h
+++ b/platform/javascript/os_javascript.h
@@ -45,11 +45,13 @@ class OS_JavaScript : public OS_Unix {
bool idb_is_syncing = false;
bool idb_available = false;
bool idb_needs_sync = false;
+ bool pwa_is_waiting = false;
static void main_loop_callback();
static void file_access_close_callback(const String &p_file, int p_flags);
static void fs_sync_callback();
+ static void update_pwa_state_callback();
protected:
void initialize() override;
@@ -65,6 +67,9 @@ public:
// Override return type to make writing static callbacks less tedious.
static OS_JavaScript *get_singleton();
+ bool pwa_needs_update() const { return pwa_is_waiting; }
+ Error pwa_update();
+
void initialize_joypads() override;
MainLoop *get_main_loop() const override;
diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp
index c3b44f348c..bf9c9b1766 100644
--- a/platform/linuxbsd/display_server_x11.cpp
+++ b/platform/linuxbsd/display_server_x11.cpp
@@ -1835,7 +1835,7 @@ void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled) {
Hints hints;
Atom property;
hints.flags = 2;
- hints.decorations = window_get_flag(WINDOW_FLAG_BORDERLESS, p_window) ? 0 : 1;
+ hints.decorations = wd.borderless ? 0 : 1;
property = XInternAtom(x11_display, "_MOTIF_WM_HINTS", True);
if (property != None) {
XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5);
diff --git a/platform/linuxbsd/joypad_linux.cpp b/platform/linuxbsd/joypad_linux.cpp
index 5eda42fea6..8e963238e3 100644
--- a/platform/linuxbsd/joypad_linux.cpp
+++ b/platform/linuxbsd/joypad_linux.cpp
@@ -333,8 +333,9 @@ void JoypadLinux::open_joypad(const char *p_path) {
}
// Check if the device supports basic gamepad events
- if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
- test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit))) {
+ bool has_abs_left = (test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit));
+ bool has_abs_right = (test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit));
+ if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && (has_abs_left || has_abs_right))) {
close(fd);
return;
}
diff --git a/platform/osx/SCsub b/platform/osx/SCsub
index 8ba106d1c2..d72a75af04 100644
--- a/platform/osx/SCsub
+++ b/platform/osx/SCsub
@@ -6,14 +6,21 @@ from platform_methods import run_in_subprocess
import platform_osx_builders
files = [
- "crash_handler_osx.mm",
"os_osx.mm",
+ "godot_application.mm",
+ "godot_application_delegate.mm",
+ "crash_handler_osx.mm",
+ "osx_terminal_logger.mm",
"display_server_osx.mm",
+ "godot_content_view.mm",
+ "godot_window_delegate.mm",
+ "godot_window.mm",
+ "key_mapping_osx.mm",
"godot_main_osx.mm",
"dir_access_osx.mm",
"joypad_osx.cpp",
"vulkan_context_osx.mm",
- "gl_manager_osx.mm",
+ "gl_manager_osx_legacy.mm",
]
prog = env.add_program("#bin/godot", files)
diff --git a/platform/osx/detect.py b/platform/osx/detect.py
index c67791b340..0ff93bedb4 100644
--- a/platform/osx/detect.py
+++ b/platform/osx/detect.py
@@ -78,14 +78,16 @@ def configure(env):
env["osxcross"] = True
if env["arch"] == "arm64":
- print("Building for macOS 10.15+, platform arm64.")
- env.Append(CCFLAGS=["-arch", "arm64", "-mmacosx-version-min=10.15"])
- env.Append(LINKFLAGS=["-arch", "arm64", "-mmacosx-version-min=10.15"])
+ print("Building for macOS 11.0+, platform arm64.")
+ env.Append(CCFLAGS=["-arch", "arm64", "-mmacosx-version-min=11.0"])
+ env.Append(LINKFLAGS=["-arch", "arm64", "-mmacosx-version-min=11.0"])
else:
print("Building for macOS 10.12+, platform x86_64.")
env.Append(CCFLAGS=["-arch", "x86_64", "-mmacosx-version-min=10.12"])
env.Append(LINKFLAGS=["-arch", "x86_64", "-mmacosx-version-min=10.12"])
+ env.Append(CCFLAGS=["-fobjc-arc"])
+
if not "osxcross" in env: # regular native build
if env["macports_clang"] != "no":
mpprefix = os.environ.get("MACPORTS_PREFIX", "/opt/local")
@@ -188,6 +190,8 @@ def configure(env):
env.Append(CCFLAGS=["-Wno-deprecated-declarations"]) # Disable deprecation warnings
env.Append(LINKFLAGS=["-framework", "OpenGL"])
+ env.Append(LINKFLAGS=["-rpath", "@executable_path/../Frameworks", "-rpath", "@executable_path"])
+
if env["vulkan"]:
env.Append(CPPDEFINES=["VULKAN_ENABLED"])
env.Append(LINKFLAGS=["-framework", "Metal", "-framework", "QuartzCore", "-framework", "IOSurface"])
diff --git a/platform/osx/display_server_osx.h b/platform/osx/display_server_osx.h
index 4fc733fe2c..eaf03d298e 100644
--- a/platform/osx/display_server_osx.h
+++ b/platform/osx/display_server_osx.h
@@ -37,13 +37,13 @@
#include "servers/display_server.h"
#if defined(GLES3_ENABLED)
-#include "gl_manager_osx.h"
-#endif
+#include "gl_manager_osx_legacy.h"
+#endif // GLES3_ENABLED
#if defined(VULKAN_ENABLED)
#include "drivers/vulkan/rendering_device_vulkan.h"
#include "platform/osx/vulkan_context_osx.h"
-#endif
+#endif // VULKAN_ENABLED
#include <AppKit/AppKit.h>
#include <AppKit/NSCursor.h>
@@ -59,27 +59,8 @@ class DisplayServerOSX : public DisplayServer {
_THREAD_SAFE_CLASS_
public:
- void _send_event(NSEvent *p_event);
- NSMenu *_get_dock_menu() const;
- void _menu_callback(id p_sender);
-
-#if defined(GLES3_ENABLED)
- GLManager_OSX *gl_manager = nullptr;
-#endif
-#if defined(VULKAN_ENABLED)
- VulkanContextOSX *context_vulkan = nullptr;
- RenderingDeviceVulkan *rendering_device_vulkan = nullptr;
-#endif
-
- const NSMenu *_get_menu_root(const String &p_menu_root) const;
- NSMenu *_get_menu_root(const String &p_menu_root);
-
- NSMenu *apple_menu = nullptr;
- NSMenu *dock_menu = nullptr;
- Map<String, NSMenu *> submenu;
-
struct KeyEvent {
- WindowID window_id;
+ WindowID window_id = INVALID_WINDOW_ID;
unsigned int osx_state = false;
bool pressed = false;
bool echo = false;
@@ -89,20 +70,6 @@ public:
uint32_t unicode = 0;
};
- struct WarpEvent {
- NSTimeInterval timestamp;
- NSPoint delta;
- };
-
- List<WarpEvent> warp_events;
- NSTimeInterval last_warp = 0;
- bool ignore_warp = false;
-
- float display_max_scale = 1.f;
-
- Vector<KeyEvent> key_event_buffer;
- int key_event_pos;
-
struct WindowData {
id window_delegate;
id window_object;
@@ -116,8 +83,6 @@ public:
Size2i max_size;
Size2i size;
- bool mouse_down_control = false;
-
bool im_active = false;
Size2i im_position;
@@ -140,49 +105,102 @@ public:
bool no_focus = false;
};
+private:
+#if defined(GLES3_ENABLED)
+ GLManager_OSX *gl_manager = nullptr;
+#endif
+#if defined(VULKAN_ENABLED)
+ VulkanContextOSX *context_vulkan = nullptr;
+ RenderingDeviceVulkan *rendering_device_vulkan = nullptr;
+#endif
+ String rendering_driver;
+
+ NSMenu *apple_menu = nullptr;
+ NSMenu *dock_menu = nullptr;
+ Map<String, NSMenu *> submenu;
+
+ struct WarpEvent {
+ NSTimeInterval timestamp;
+ NSPoint delta;
+ };
+ List<WarpEvent> warp_events;
+ NSTimeInterval last_warp = 0;
+ bool ignore_warp = false;
+
+ Vector<KeyEvent> key_event_buffer;
+ int key_event_pos = 0;
+
Point2i im_selection;
String im_text;
- Map<WindowID, WindowData> windows;
+ CGEventSourceRef event_source;
+ MouseMode mouse_mode = MOUSE_MODE_VISIBLE;
+ MouseButton last_button_state = MouseButton::NONE;
- WindowID last_focused_window = INVALID_WINDOW_ID;
+ bool drop_events = false;
+ bool in_dispatch_input_event = false;
+
+ struct LayoutInfo {
+ String name;
+ String code;
+ };
+ Vector<LayoutInfo> kbd_layouts;
+ int current_layout = 0;
+ bool keyboard_layout_dirty = true;
+ WindowID last_focused_window = INVALID_WINDOW_ID;
WindowID window_id_counter = MAIN_WINDOW_ID;
+ float display_max_scale = 1.f;
+ Point2i origin;
+ bool displays_arrangement_dirty = true;
- WindowID _create_window(WindowMode p_mode, VSyncMode p_vsync_mode, const Rect2i &p_rect);
- void _update_window(WindowData p_wd);
- void _send_window_event(const WindowData &wd, WindowEvent p_event);
- static void _dispatch_input_events(const Ref<InputEvent> &p_event);
- void _dispatch_input_event(const Ref<InputEvent> &p_event);
- WindowID _find_window_id(id p_window);
+ CursorShape cursor_shape = CURSOR_ARROW;
+ NSCursor *cursors[CURSOR_MAX];
+ Map<CursorShape, Vector<Variant>> cursors_cache;
+
+ Map<WindowID, WindowData> windows;
+
+ const NSMenu *_get_menu_root(const String &p_menu_root) const;
+ NSMenu *_get_menu_root(const String &p_menu_root);
+ WindowID _create_window(WindowMode p_mode, VSyncMode p_vsync_mode, const Rect2i &p_rect);
+ void _update_window_style(WindowData p_wd);
void _set_window_per_pixel_transparency_enabled(bool p_enabled, WindowID p_window);
+ void _update_displays_arrangement();
Point2i _get_screens_origin() const;
Point2i _get_native_screen_position(int p_screen) const;
+ static void _displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info);
+ static void _dispatch_input_events(const Ref<InputEvent> &p_event);
+ void _dispatch_input_event(const Ref<InputEvent> &p_event);
void _push_input(const Ref<InputEvent> &p_event);
void _process_key_events();
- void _release_pressed_events();
+ void _update_keyboard_layouts();
+ static void _keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info);
- String rendering_driver;
+ static NSCursor *_cursor_from_selector(SEL p_selector, SEL p_fallback = nil);
- id autoreleasePool;
- CGEventSourceRef eventSource;
+public:
+ NSMenu *get_dock_menu() const;
+ void menu_callback(id p_sender);
- CursorShape cursor_shape;
- NSCursor *cursors[CURSOR_MAX];
- Map<CursorShape, Vector<Variant>> cursors_cache;
+ bool has_window(WindowID p_window) const;
+ WindowData &get_window(WindowID p_window);
- MouseMode mouse_mode;
- Point2i last_mouse_pos;
- MouseButton last_button_state = MouseButton::NONE;
+ void send_event(NSEvent *p_event);
+ void send_window_event(const WindowData &p_wd, WindowEvent p_event);
+ void release_pressed_events();
+ void get_key_modifier_state(unsigned int p_osx_state, Ref<InputEventWithModifiers> r_state) const;
+ void update_mouse_pos(WindowData &p_wd, NSPoint p_location_in_window);
+ void push_to_key_event_buffer(const KeyEvent &p_event);
+ void update_im_text(const Point2i &p_selection, const String &p_text);
+ void set_last_focused_window(WindowID p_window);
- bool window_focused;
- bool drop_events;
- bool in_dispatch_input_event = false;
+ void window_update(WindowID p_window);
+ void window_destroy(WindowID p_window);
+ void window_resize(WindowID p_window, int p_width, int p_height);
-public:
virtual bool has_feature(Feature p_feature) const override;
virtual String get_name() const override;
@@ -216,8 +234,10 @@ public:
virtual void mouse_set_mode(MouseMode p_mode) override;
virtual MouseMode mouse_get_mode() const override;
+ bool update_mouse_wrap(WindowData &p_wd, NSPoint &r_delta, NSPoint &r_mpos, NSTimeInterval p_timestamp);
virtual void mouse_warp_to_position(const Point2i &p_to) override;
virtual Point2i mouse_get_position() const override;
+ void mouse_set_button_state(MouseButton p_state);
virtual MouseButton mouse_get_button_state() const override;
virtual void clipboard_set(const String &p_text) override;
@@ -297,6 +317,7 @@ public:
virtual Point2i ime_get_selection() const override;
virtual String ime_get_text() const override;
+ void cursor_update_shape();
virtual void cursor_set_shape(CursorShape p_shape) override;
virtual CursorShape cursor_get_shape() const override;
virtual void cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape = CURSOR_ARROW, const Vector2 &p_hotspot = Vector2()) override;
diff --git a/platform/osx/display_server_osx.mm b/platform/osx/display_server_osx.mm
index 000be79852..2691664b96 100644
--- a/platform/osx/display_server_osx.mm
+++ b/platform/osx/display_server_osx.mm
@@ -30,6 +30,11 @@
#include "display_server_osx.h"
+#include "godot_content_view.h"
+#include "godot_menu_item.h"
+#include "godot_window.h"
+#include "godot_window_delegate.h"
+#include "key_mapping_osx.h"
#include "os_osx.h"
#include "core/io/marshalls.h"
@@ -47,217 +52,122 @@
#if defined(GLES3_ENABLED)
#include "drivers/gles3/rasterizer_gles3.h"
-
-#import <AppKit/NSOpenGLView.h>
#endif
#if defined(VULKAN_ENABLED)
#include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
-
-#include <QuartzCore/CAMetalLayer.h>
-#endif
-
-#ifndef NSAppKitVersionNumber10_14
-#define NSAppKitVersionNumber10_14 1671
#endif
-#define DS_OSX ((DisplayServerOSX *)(DisplayServerOSX::get_singleton()))
-
-static bool ignore_momentum_scroll = false;
-
-static void _get_key_modifier_state(unsigned int p_osx_state, Ref<InputEventWithModifiers> r_state) {
- r_state->set_shift_pressed((p_osx_state & NSEventModifierFlagShift));
- r_state->set_ctrl_pressed((p_osx_state & NSEventModifierFlagControl));
- r_state->set_alt_pressed((p_osx_state & NSEventModifierFlagOption));
- r_state->set_meta_pressed((p_osx_state & NSEventModifierFlagCommand));
-}
-
-static Vector2i _get_mouse_pos(DisplayServerOSX::WindowData &p_wd, NSPoint p_locationInWindow) {
- const NSRect contentRect = [p_wd.window_view frame];
- const float scale = DS_OSX->screen_get_max_scale();
- p_wd.mouse_pos.x = p_locationInWindow.x * scale;
- p_wd.mouse_pos.y = (contentRect.size.height - p_locationInWindow.y) * scale;
- DS_OSX->last_mouse_pos = p_wd.mouse_pos;
- Input::get_singleton()->set_mouse_position(p_wd.mouse_pos);
- return p_wd.mouse_pos;
-}
-
-static void _push_to_key_event_buffer(const DisplayServerOSX::KeyEvent &p_event) {
- Vector<DisplayServerOSX::KeyEvent> &buffer = DS_OSX->key_event_buffer;
- if (DS_OSX->key_event_pos >= buffer.size()) {
- buffer.resize(1 + DS_OSX->key_event_pos);
- }
- buffer.write[DS_OSX->key_event_pos++] = p_event;
-}
-
-static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) {
- if ([NSCursor respondsToSelector:selector]) {
- id object = [NSCursor performSelector:selector];
- if ([object isKindOfClass:[NSCursor class]]) {
- return object;
+const NSMenu *DisplayServerOSX::_get_menu_root(const String &p_menu_root) const {
+ const NSMenu *menu = nullptr;
+ if (p_menu_root == "") {
+ // Main menu.
+ menu = [NSApp mainMenu];
+ } else if (p_menu_root.to_lower() == "_dock") {
+ // macOS dock menu.
+ menu = dock_menu;
+ } else {
+ // Submenu.
+ if (submenu.has(p_menu_root)) {
+ menu = submenu[p_menu_root];
}
}
- if (fallback) {
- // Fallback should be a reasonable default, no need to check.
- return [NSCursor performSelector:fallback];
- }
- return [NSCursor arrowCursor];
-}
-
-/*************************************************************************/
-/* GlobalMenuItem */
-/*************************************************************************/
-
-@interface GlobalMenuItem : NSObject {
-@public
- Callable callback;
- Variant meta;
- bool checkable;
-}
-
-@end
-
-@implementation GlobalMenuItem
-@end
-
-/*************************************************************************/
-/* GodotWindowDelegate */
-/*************************************************************************/
-
-@interface GodotWindowDelegate : NSObject {
- DisplayServerOSX::WindowID window_id;
-}
-
-- (void)windowWillClose:(NSNotification *)notification;
-- (void)setWindowID:(DisplayServerOSX::WindowID)wid;
-
-@end
-
-@implementation GodotWindowDelegate
-
-- (void)setWindowID:(DisplayServerOSX::WindowID)wid {
- window_id = wid;
-}
-
-- (BOOL)windowShouldClose:(id)sender {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return YES;
+ if (menu == apple_menu) {
+ // Do not allow to change Apple menu.
+ return nullptr;
}
- DS_OSX->_send_window_event(DS_OSX->windows[window_id], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST);
- return NO;
+ return menu;
}
-- (void)windowWillClose:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
- }
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- while (wd.transient_children.size()) {
- DS_OSX->window_set_transient(wd.transient_children.front()->get(), DisplayServerOSX::INVALID_WINDOW_ID);
- }
-
- if (wd.transient_parent != DisplayServerOSX::INVALID_WINDOW_ID) {
- DS_OSX->window_set_transient(window_id, DisplayServerOSX::INVALID_WINDOW_ID);
- }
-
-#if defined(GLES3_ENABLED)
- if (DS_OSX->gl_manager) {
- DS_OSX->gl_manager->window_destroy(window_id);
- }
-#endif
-#ifdef VULKAN_ENABLED
- if (DS_OSX->context_vulkan) {
- DS_OSX->context_vulkan->window_destroy(window_id);
+NSMenu *DisplayServerOSX::_get_menu_root(const String &p_menu_root) {
+ NSMenu *menu = nullptr;
+ if (p_menu_root == "") {
+ // Main menu.
+ menu = [NSApp mainMenu];
+ } else if (p_menu_root.to_lower() == "_dock") {
+ // macOS dock menu.
+ menu = dock_menu;
+ } else {
+ // Submenu.
+ if (!submenu.has(p_menu_root)) {
+ NSMenu *n_menu = [[NSMenu alloc] initWithTitle:[NSString stringWithUTF8String:p_menu_root.utf8().get_data()]];
+ submenu[p_menu_root] = n_menu;
+ }
+ menu = submenu[p_menu_root];
}
-#endif
-
- DS_OSX->windows.erase(window_id);
-}
-
-- (void)windowDidEnterFullScreen:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
+ if (menu == apple_menu) {
+ // Do not allow to change Apple menu.
+ return nullptr;
}
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- wd.fullscreen = true;
-
- [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
- [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
- // Force window resize event.
- [self windowDidResize:notification];
+ return menu;
}
-- (void)windowDidExitFullScreen:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
- }
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- wd.fullscreen = false;
-
- const float scale = DS_OSX->screen_get_max_scale();
- if (wd.min_size != Size2i()) {
- Size2i size = wd.min_size / scale;
- [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
- }
- if (wd.max_size != Size2i()) {
- Size2i size = wd.max_size / scale;
- [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
- }
-
- if (wd.resize_disabled) {
- [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
- }
-
- if (wd.on_top) {
- [wd.window_object setLevel:NSFloatingWindowLevel];
- }
- // Force window resize event.
- [self windowDidResize:notification];
-}
+DisplayServerOSX::WindowID DisplayServerOSX::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, const Rect2i &p_rect) {
+ WindowID id;
+ const float scale = screen_get_max_scale();
+ {
+ WindowData wd;
-- (void)windowDidChangeBackingProperties:(NSNotification *)notification {
- if (!DisplayServerOSX::get_singleton()) {
- return;
- }
+ wd.window_delegate = [[GodotWindowDelegate alloc] init];
+ ERR_FAIL_COND_V_MSG(wd.window_delegate == nil, INVALID_WINDOW_ID, "Can't create a window delegate");
+ [wd.window_delegate setWindowID:window_id_counter];
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
+ Point2i position = p_rect.position;
+ // OS X native y-coordinate relative to _get_screens_origin() is negative,
+ // Godot passes a positive value.
+ position.y *= -1;
+ position += _get_screens_origin();
- CGFloat newBackingScaleFactor = [wd.window_object backingScaleFactor];
- CGFloat oldBackingScaleFactor = [[[notification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
+ // initWithContentRect uses bottom-left corner of the window’s frame as origin.
+ wd.window_object = [[GodotWindow alloc]
+ initWithContentRect:NSMakeRect(position.x / scale, (position.y - p_rect.size.height) / scale, p_rect.size.width / scale, p_rect.size.height / scale)
+ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
+ backing:NSBackingStoreBuffered
+ defer:NO];
+ ERR_FAIL_COND_V_MSG(wd.window_object == nil, INVALID_WINDOW_ID, "Can't create a window");
+ [wd.window_object setWindowID:window_id_counter];
- if (newBackingScaleFactor != oldBackingScaleFactor) {
- //Set new display scale and window size
- const float scale = DS_OSX->screen_get_max_scale();
- const NSRect contentRect = [wd.window_view frame];
+ wd.window_view = [[GodotContentView alloc] init];
+ ERR_FAIL_COND_V_MSG(wd.window_view == nil, INVALID_WINDOW_ID, "Can't create a window view");
+ [wd.window_view setWindowID:window_id_counter];
+ [wd.window_view setWantsLayer:TRUE];
- wd.size.width = contentRect.size.width * scale;
- wd.size.height = contentRect.size.height * scale;
+ [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
+ [wd.window_object setContentView:wd.window_view];
+ [wd.window_object setDelegate:wd.window_delegate];
+ [wd.window_object setAcceptsMouseMovedEvents:YES];
+ [wd.window_object setRestorable:NO];
+ [wd.window_object setColorSpace:[NSColorSpace sRGBColorSpace]];
- DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_DPI_CHANGE);
+ if ([wd.window_object respondsToSelector:@selector(setTabbingMode:)]) {
+ [wd.window_object setTabbingMode:NSWindowTabbingModeDisallowed];
+ }
CALayer *layer = [wd.window_view layer];
if (layer) {
layer.contentsScale = scale;
}
- //Force window resize event
- [self windowDidResize:notification];
+#if defined(VULKAN_ENABLED)
+ if (context_vulkan) {
+ Error err = context_vulkan->window_create(window_id_counter, p_vsync_mode, wd.window_view, p_rect.size.width, p_rect.size.height);
+ ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan context");
+ }
+#endif
+#if defined(GLES3_ENABLED)
+ if (gl_manager) {
+ Error err = gl_manager->window_create(window_id_counter, wd.window_view, p_rect.size.width, p_rect.size.height);
+ ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context");
+ }
+#endif
+ id = window_id_counter++;
+ windows[id] = wd;
}
-}
-- (void)windowDidResize:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
- }
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
+ WindowData &wd = windows[id];
+ window_set_mode(p_mode, id);
const NSRect contentRect = [wd.window_view frame];
-
- const float scale = DS_OSX->screen_get_max_scale();
wd.size.width = contentRect.size.width * scale;
wd.size.height = contentRect.size.height * scale;
@@ -267,1204 +177,448 @@ static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) {
}
#if defined(GLES3_ENABLED)
- if (DS_OSX->gl_manager) {
- DS_OSX->gl_manager->window_resize(window_id, wd.size.width, wd.size.height);
+ if (gl_manager) {
+ gl_manager->window_resize(id, wd.size.width, wd.size.height);
}
#endif
#if defined(VULKAN_ENABLED)
- if (DS_OSX->context_vulkan) {
- DS_OSX->context_vulkan->window_resize(window_id, wd.size.width, wd.size.height);
+ if (context_vulkan) {
+ context_vulkan->window_resize(id, wd.size.width, wd.size.height);
}
#endif
- if (!wd.rect_changed_callback.is_null()) {
- Variant size = Rect2i(DS_OSX->window_get_position(window_id), DS_OSX->window_get_size(window_id));
- Variant *sizep = &size;
- Variant ret;
- Callable::CallError ce;
- wd.rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
- }
+ return id;
}
-- (void)windowDidMove:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
- }
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- DS_OSX->_release_pressed_events();
+void DisplayServerOSX::_update_window_style(WindowData p_wd) {
+ bool borderless_full = false;
- if (!wd.rect_changed_callback.is_null()) {
- Variant size = Rect2i(DS_OSX->window_get_position(window_id), DS_OSX->window_get_size(window_id));
- Variant *sizep = &size;
- Variant ret;
- Callable::CallError ce;
- wd.rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
- }
-}
+ if (p_wd.borderless) {
+ NSRect frameRect = [p_wd.window_object frame];
+ NSRect screenRect = [[p_wd.window_object screen] frame];
-- (void)windowDidBecomeKey:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
+ // Check if our window covers up the screen.
+ if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
+ frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
+ borderless_full = true;
+ }
}
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
- if (DS_OSX->mouse_mode == DisplayServer::MOUSE_MODE_CAPTURED) {
- const NSRect contentRect = [wd.window_view frame];
- NSRect pointInWindowRect = NSMakeRect(contentRect.size.width / 2, contentRect.size.height / 2, 0, 0);
- NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
- CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
- CGWarpMouseCursorPosition(lMouseWarpPos);
+ if (borderless_full) {
+ // If the window covers up the screen set the level to above the main menu and hide on deactivate.
+ [p_wd.window_object setLevel:NSMainMenuWindowLevel + 1];
+ [p_wd.window_object setHidesOnDeactivate:YES];
} else {
- _ALLOW_DISCARD_ _get_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
- Input::get_singleton()->set_mouse_position(wd.mouse_pos);
- }
-
- DS_OSX->window_focused = true;
- DS_OSX->last_focused_window = window_id;
- DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_IN);
-}
-
-- (void)windowDidResignKey:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
+ // Reset these when our window is not a borderless window that covers up the screen.
+ if (p_wd.on_top && !p_wd.fullscreen) {
+ [p_wd.window_object setLevel:NSFloatingWindowLevel];
+ } else {
+ [p_wd.window_object setLevel:NSNormalWindowLevel];
+ }
+ [p_wd.window_object setHidesOnDeactivate:NO];
}
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- DS_OSX->window_focused = false;
-
- DS_OSX->_release_pressed_events();
- DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT);
}
-- (void)windowDidMiniaturize:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
- return;
- }
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- DS_OSX->window_focused = false;
-
- DS_OSX->_release_pressed_events();
- DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT);
-}
+void DisplayServerOSX::_set_window_per_pixel_transparency_enabled(bool p_enabled, WindowID p_window) {
+ ERR_FAIL_COND(!windows.has(p_window));
+ WindowData &wd = windows[p_window];
-- (void)windowDidDeminiaturize:(NSNotification *)notification {
- if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
+ if (!OS::get_singleton()->is_layered_allowed()) {
return;
}
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- DS_OSX->window_focused = true;
- DS_OSX->last_focused_window = window_id;
- DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_IN);
-}
-
-@end
-
-/*************************************************************************/
-/* GodotContentView */
-/*************************************************************************/
-
+ if (wd.layered_window != p_enabled) {
+ if (p_enabled) {
+ [wd.window_object setBackgroundColor:[NSColor clearColor]];
+ [wd.window_object setOpaque:NO];
+ [wd.window_object setHasShadow:NO];
+ CALayer *layer = [wd.window_view layer];
+ if (layer) {
+ [layer setBackgroundColor:[NSColor clearColor].CGColor];
+ [layer setOpaque:NO];
+ }
#if defined(GLES3_ENABLED)
-@interface GodotContentView : NSOpenGLView <NSTextInputClient> {
-#else
-@interface GodotContentView : NSView <NSTextInputClient> {
-#endif
-
- DisplayServerOSX::WindowID window_id;
- NSTrackingArea *trackingArea;
- NSMutableAttributedString *markedText;
- bool imeInputEventInProgress;
-}
-
-- (void)cancelComposition;
-- (CALayer *)makeBackingLayer;
-- (BOOL)wantsUpdateLayer;
-- (void)updateLayer;
-- (void)setWindowID:(DisplayServerOSX::WindowID)wid;
-
-@end
-
-@implementation GodotContentView
-
-- (void)setWindowID:(DisplayServerOSX::WindowID)wid {
- window_id = wid;
-}
-
-+ (void)initialize {
- if (self == [GodotContentView class]) {
- // nothing left to do here at the moment..
- }
-}
-
-- (CALayer *)makeBackingLayer {
-#if defined(VULKAN_ENABLED)
- if (DS_OSX->context_vulkan) {
- CALayer *layer = [[CAMetalLayer class] layer];
- return layer;
- }
+ if (gl_manager) {
+ gl_manager->window_set_per_pixel_transparency_enabled(p_window, true);
+ }
#endif
- return [super makeBackingLayer];
-}
-
-- (void)updateLayer {
+ wd.layered_window = true;
+ } else {
+ [wd.window_object setBackgroundColor:[NSColor colorWithCalibratedWhite:1 alpha:1]];
+ [wd.window_object setOpaque:YES];
+ [wd.window_object setHasShadow:YES];
+ CALayer *layer = [wd.window_view layer];
+ if (layer) {
+ [layer setBackgroundColor:[NSColor colorWithCalibratedWhite:1 alpha:1].CGColor];
+ [layer setOpaque:YES];
+ }
#if defined(GLES3_ENABLED)
- if (DS_OSX->gl_manager) {
- DS_OSX->gl_manager->window_update(window_id);
- }
+ if (gl_manager) {
+ gl_manager->window_set_per_pixel_transparency_enabled(p_window, false);
+ }
#endif
-#if defined(VULKAN_ENABLED)
- if (DS_OSX->context_vulkan) {
- [super updateLayer];
+ wd.layered_window = false;
+ }
+ NSRect frameRect = [wd.window_object frame];
+ [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:YES];
+ [wd.window_object setFrame:frameRect display:YES];
}
-#endif
-}
-
-- (BOOL)wantsUpdateLayer {
- return YES;
}
-- (id)init {
- self = [super init];
- trackingArea = nil;
- imeInputEventInProgress = false;
- [self updateTrackingAreas];
-#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
- [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
-#else
- [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
-#endif
- markedText = [[NSMutableAttributedString alloc] init];
- return self;
-}
+void DisplayServerOSX::_update_displays_arrangement() {
+ origin = Point2i();
-- (void)dealloc {
- [trackingArea release];
- [markedText release];
- [super dealloc];
+ for (int i = 0; i < get_screen_count(); i++) {
+ Point2i position = _get_native_screen_position(i);
+ if (position.x < origin.x) {
+ origin.x = position.x;
+ }
+ if (position.y > origin.y) {
+ origin.y = position.y;
+ }
+ }
+ displays_arrangement_dirty = false;
}
-static const NSRange kEmptyRange = { NSNotFound, 0 };
-
-- (BOOL)hasMarkedText {
- return (markedText.length > 0);
-}
+Point2i DisplayServerOSX::_get_screens_origin() const {
+ // Returns the native top-left screen coordinate of the smallest rectangle
+ // that encompasses all screens. Needed in get_screen_position(),
+ // window_get_position, and window_set_position()
+ // to convert between OS X native screen coordinates and the ones expected by Godot.
-- (NSRange)markedRange {
- return NSMakeRange(0, markedText.length);
-}
+ if (displays_arrangement_dirty) {
+ const_cast<DisplayServerOSX *>(this)->_update_displays_arrangement();
+ }
-- (NSRange)selectedRange {
- return kEmptyRange;
+ return origin;
}
-- (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
- if ([aString isKindOfClass:[NSAttributedString class]]) {
- [markedText initWithAttributedString:aString];
- } else {
- [markedText initWithString:aString];
- }
- if (markedText.length == 0) {
- [self unmarkText];
- return;
+Point2i DisplayServerOSX::_get_native_screen_position(int p_screen) const {
+ NSArray *screenArray = [NSScreen screens];
+ if ((NSUInteger)p_screen < [screenArray count]) {
+ NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
+ // Return the top-left corner of the screen, for OS X the y starts at the bottom.
+ return Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * screen_get_max_scale();
}
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- if (wd.im_active) {
- imeInputEventInProgress = true;
- DS_OSX->im_text.parse_utf8([[markedText mutableString] UTF8String]);
- DS_OSX->im_selection = Point2i(selectedRange.location, selectedRange.length);
+ return Point2i();
+}
- OS_OSX::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
+void DisplayServerOSX::_displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (ds) {
+ ds->displays_arrangement_dirty = true;
}
}
-- (void)doCommandBySelector:(SEL)aSelector {
- if ([self respondsToSelector:aSelector]) {
- [self performSelector:aSelector];
- }
+void DisplayServerOSX::_dispatch_input_events(const Ref<InputEvent> &p_event) {
+ ((DisplayServerOSX *)(get_singleton()))->_dispatch_input_event(p_event);
}
-- (void)unmarkText {
- imeInputEventInProgress = false;
- [[markedText mutableString] setString:@""];
+void DisplayServerOSX::_dispatch_input_event(const Ref<InputEvent> &p_event) {
+ _THREAD_SAFE_METHOD_
+ if (!in_dispatch_input_event) {
+ in_dispatch_input_event = true;
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
+ Variant ev = p_event;
+ Variant *evp = &ev;
+ Variant ret;
+ Callable::CallError ce;
- if (wd.im_active) {
- DS_OSX->im_text = String();
- DS_OSX->im_selection = Point2i();
+ Ref<InputEventFromWindow> event_from_window = p_event;
+ if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
+ // Send to a window.
+ if (windows.has(event_from_window->get_window_id())) {
+ Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
+ if (callable.is_null()) {
+ return;
+ }
+ callable.call((const Variant **)&evp, 1, ret, ce);
+ }
+ } else {
+ // Send to all windows.
+ for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
+ Callable callable = E->get().input_event_callback;
+ if (callable.is_null()) {
+ continue;
+ }
+ callable.call((const Variant **)&evp, 1, ret, ce);
+ }
+ }
- OS_OSX::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
+ in_dispatch_input_event = false;
}
}
-- (NSArray *)validAttributesForMarkedText {
- return [NSArray array];
-}
-
-- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
- return nil;
-}
-
-- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
- return 0;
-}
-
-- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
- ERR_FAIL_COND_V(!DS_OSX->windows.has(window_id), NSMakeRect(0, 0, 0, 0));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- const NSRect contentRect = [wd.window_view frame];
- const float scale = DS_OSX->screen_get_max_scale();
- NSRect pointInWindowRect = NSMakeRect(wd.im_position.x / scale, contentRect.size.height - (wd.im_position.y / scale) - 1, 0, 0);
- NSPoint pointOnScreen = [wd.window_object convertRectToScreen:pointInWindowRect].origin;
-
- return NSMakeRect(pointOnScreen.x, pointOnScreen.y, 0, 0);
+void DisplayServerOSX::_push_input(const Ref<InputEvent> &p_event) {
+ Ref<InputEvent> ev = p_event;
+ Input::get_singleton()->parse_input_event(ev);
}
-- (void)cancelComposition {
- [self unmarkText];
- NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
- [currentInputContext discardMarkedText];
-}
+void DisplayServerOSX::_process_key_events() {
+ Ref<InputEventKey> k;
+ for (int i = 0; i < key_event_pos; i++) {
+ const KeyEvent &ke = key_event_buffer[i];
+ if (ke.raw) {
+ // Non IME input - no composite characters, pass events as is.
+ k.instantiate();
-- (void)insertText:(id)aString {
- [self insertText:aString replacementRange:NSMakeRange(0, 0)];
-}
+ k->set_window_id(ke.window_id);
+ get_key_modifier_state(ke.osx_state, k);
+ k->set_pressed(ke.pressed);
+ k->set_echo(ke.echo);
+ k->set_keycode(ke.keycode);
+ k->set_physical_keycode((Key)ke.physical_keycode);
+ k->set_unicode(ke.unicode);
-- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
- NSEvent *event = [NSApp currentEvent];
+ _push_input(k);
+ } else {
+ // IME input.
+ if ((i == 0 && ke.keycode == Key::NONE) || (i > 0 && key_event_buffer[i - 1].keycode == Key::NONE)) {
+ k.instantiate();
- NSString *characters;
- if ([aString isKindOfClass:[NSAttributedString class]]) {
- characters = [aString string];
- } else {
- characters = (NSString *)aString;
- }
+ k->set_window_id(ke.window_id);
+ get_key_modifier_state(ke.osx_state, k);
+ k->set_pressed(ke.pressed);
+ k->set_echo(ke.echo);
+ k->set_keycode(Key::NONE);
+ k->set_physical_keycode(Key::NONE);
+ k->set_unicode(ke.unicode);
- NSCharacterSet *ctrlChars = [NSCharacterSet controlCharacterSet];
- NSCharacterSet *wsnlChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
- if ([characters rangeOfCharacterFromSet:ctrlChars].length && [characters rangeOfCharacterFromSet:wsnlChars].length == 0) {
- NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
- [currentInputContext discardMarkedText];
- [self cancelComposition];
- return;
- }
+ _push_input(k);
+ }
+ if (ke.keycode != Key::NONE) {
+ k.instantiate();
- Char16String text;
- text.resize([characters length] + 1);
- [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
+ k->set_window_id(ke.window_id);
+ get_key_modifier_state(ke.osx_state, k);
+ k->set_pressed(ke.pressed);
+ k->set_echo(ke.echo);
+ k->set_keycode(ke.keycode);
+ k->set_physical_keycode((Key)ke.physical_keycode);
- String u32text;
- u32text.parse_utf16(text.ptr(), text.length());
+ if (i + 1 < key_event_pos && key_event_buffer[i + 1].keycode == Key::NONE) {
+ k->set_unicode(key_event_buffer[i + 1].unicode);
+ }
- for (int i = 0; i < u32text.length(); i++) {
- const char32_t codepoint = u32text[i];
- if ((codepoint & 0xFF00) == 0xF700) {
- continue;
+ _push_input(k);
+ }
}
-
- DisplayServerOSX::KeyEvent ke;
-
- ke.window_id = window_id;
- ke.osx_state = [event modifierFlags];
- ke.pressed = true;
- ke.echo = false;
- ke.raw = false; // IME input event
- ke.keycode = Key::NONE;
- ke.physical_keycode = Key::NONE;
- ke.unicode = codepoint;
-
- _push_to_key_event_buffer(ke);
}
- [self cancelComposition];
-}
-- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
- return NSDragOperationCopy;
+ key_event_pos = 0;
}
-- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
- return NSDragOperationCopy;
-}
+void DisplayServerOSX::_update_keyboard_layouts() {
+ kbd_layouts.clear();
+ current_layout = 0;
-- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
- ERR_FAIL_COND_V(!DS_OSX->windows.has(window_id), NO);
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
+ TISInputSourceRef cur_source = TISCopyCurrentKeyboardInputSource();
+ NSString *cur_name = (__bridge NSString *)TISGetInputSourceProperty(cur_source, kTISPropertyLocalizedName);
+ CFRelease(cur_source);
- if (!wd.drop_files_callback.is_null()) {
- Vector<String> files;
- NSPasteboard *pboard = [sender draggingPasteboard];
+ // Enum IME layouts.
+ NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
+ NSArray *list_ime = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_ime, false);
+ for (NSUInteger i = 0; i < [list_ime count]; i++) {
+ LayoutInfo ly;
+ NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
+ ly.name.parse_utf8([name UTF8String]);
-#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
- NSArray *items = pboard.pasteboardItems;
- for (NSPasteboardItem *item in items) {
- NSString *path = [item stringForType:NSPasteboardTypeFileURL];
- NSString *ns = [NSURL URLWithString:path].path;
- char *utfs = strdup([ns UTF8String]);
- String ret;
- ret.parse_utf8(utfs);
- free(utfs);
- files.push_back(ret);
- }
-#else
- NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
- for (NSString *ns in filenames) {
- char *utfs = strdup([ns UTF8String]);
- String ret;
- ret.parse_utf8(utfs);
- free(utfs);
- files.push_back(ret);
- }
-#endif
+ NSArray *langs = (__bridge NSArray *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyInputSourceLanguages);
+ ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
+ kbd_layouts.push_back(ly);
- Variant v = files;
- Variant *vp = &v;
- Variant ret;
- Callable::CallError ce;
- wd.drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
+ if ([name isEqualToString:cur_name]) {
+ current_layout = kbd_layouts.size() - 1;
+ }
}
- return NO;
-}
+ // Enum plain keyboard layouts.
+ NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
+ NSArray *list_kbd = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_kbd, false);
+ for (NSUInteger i = 0; i < [list_kbd count]; i++) {
+ LayoutInfo ly;
+ NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
+ ly.name.parse_utf8([name UTF8String]);
-- (BOOL)isOpaque {
- return YES;
-}
+ NSArray *langs = (__bridge NSArray *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyInputSourceLanguages);
+ ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
+ kbd_layouts.push_back(ly);
-- (BOOL)canBecomeKeyView {
- if (DS_OSX->windows.has(window_id)) {
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
- if (wd.no_focus) {
- return NO;
+ if ([name isEqualToString:cur_name]) {
+ current_layout = kbd_layouts.size() - 1;
}
}
- return YES;
-}
-
-- (BOOL)acceptsFirstResponder {
- return YES;
-}
-- (void)cursorUpdate:(NSEvent *)event {
- DisplayServer::CursorShape p_shape = DS_OSX->cursor_shape;
- DS_OSX->cursor_shape = DisplayServer::CURSOR_MAX;
- DS_OSX->cursor_set_shape(p_shape);
+ keyboard_layout_dirty = false;
}
-static void _mouseDownEvent(DisplayServer::WindowID window_id, NSEvent *event, MouseButton index, MouseButton mask, bool pressed) {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- if (pressed) {
- DS_OSX->last_button_state |= mask;
- } else {
- DS_OSX->last_button_state &= (MouseButton)~mask;
- }
-
- Ref<InputEventMouseButton> mb;
- mb.instantiate();
- mb->set_window_id(window_id);
- const Vector2 pos = _get_mouse_pos(wd, [event locationInWindow]);
- _get_key_modifier_state([event modifierFlags], mb);
- mb->set_button_index(index);
- mb->set_pressed(pressed);
- mb->set_position(pos);
- mb->set_global_position(pos);
- mb->set_button_mask(DS_OSX->last_button_state);
- if (index == MouseButton::LEFT && pressed) {
- mb->set_double_click([event clickCount] == 2);
+void DisplayServerOSX::_keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (ds) {
+ ds->keyboard_layout_dirty = true;
}
-
- Input::get_singleton()->parse_input_event(mb);
}
-- (void)mouseDown:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- if (([event modifierFlags] & NSEventModifierFlagControl)) {
- wd.mouse_down_control = true;
- _mouseDownEvent(window_id, event, MouseButton::RIGHT, MouseButton::MASK_RIGHT, true);
- } else {
- wd.mouse_down_control = false;
- _mouseDownEvent(window_id, event, MouseButton::LEFT, MouseButton::MASK_LEFT, true);
+NSCursor *DisplayServerOSX::_cursor_from_selector(SEL p_selector, SEL p_fallback) {
+ if ([NSCursor respondsToSelector:p_selector]) {
+ id object = [NSCursor performSelector:p_selector];
+ if ([object isKindOfClass:[NSCursor class]]) {
+ return object;
+ }
}
-}
-
-- (void)mouseDragged:(NSEvent *)event {
- [self mouseMoved:event];
-}
-
-- (void)mouseUp:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- if (wd.mouse_down_control) {
- _mouseDownEvent(window_id, event, MouseButton::RIGHT, MouseButton::MASK_RIGHT, false);
- } else {
- _mouseDownEvent(window_id, event, MouseButton::LEFT, MouseButton::MASK_LEFT, false);
+ if (p_fallback) {
+ // Fallback should be a reasonable default, no need to check.
+ return [NSCursor performSelector:p_fallback];
}
+ return [NSCursor arrowCursor];
}
-- (void)mouseMoved:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- NSPoint delta = NSMakePoint([event deltaX], [event deltaY]);
- NSPoint mpos = [event locationInWindow];
+NSMenu *DisplayServerOSX::get_dock_menu() const {
+ return dock_menu;
+}
- if (DS_OSX->ignore_warp) {
- // Discard late events, before warp
- if (([event timestamp]) < DS_OSX->last_warp) {
- return;
- }
- DS_OSX->ignore_warp = false;
+void DisplayServerOSX::menu_callback(id p_sender) {
+ if (![p_sender representedObject]) {
return;
}
- if (DS_OSX->mouse_mode == DisplayServer::MOUSE_MODE_CONFINED || DS_OSX->mouse_mode == DisplayServer::MOUSE_MODE_CONFINED_HIDDEN) {
- // Discard late events
- if (([event timestamp]) < DS_OSX->last_warp) {
- return;
- }
+ GodotMenuItem *value = [p_sender representedObject];
- // Warp affects next event delta, subtract previous warp deltas
- List<DisplayServerOSX::WarpEvent>::Element *F = DS_OSX->warp_events.front();
- while (F) {
- if (F->get().timestamp < [event timestamp]) {
- List<DisplayServerOSX::WarpEvent>::Element *E = F;
- delta.x -= E->get().delta.x;
- delta.y -= E->get().delta.y;
- F = F->next();
- DS_OSX->warp_events.erase(E);
+ if (value) {
+ if (value->checkable) {
+ if ([p_sender state] == NSControlStateValueOff) {
+ [p_sender setState:NSControlStateValueOn];
} else {
- F = F->next();
+ [p_sender setState:NSControlStateValueOff];
}
}
- // Confine mouse position to the window, and update delta
- NSRect frame = [wd.window_object frame];
- NSPoint conf_pos = mpos;
- conf_pos.x = CLAMP(conf_pos.x + delta.x, 0.f, frame.size.width);
- conf_pos.y = CLAMP(conf_pos.y - delta.y, 0.f, frame.size.height);
- delta.x = conf_pos.x - mpos.x;
- delta.y = mpos.y - conf_pos.y;
- mpos = conf_pos;
-
- // Move mouse cursor
- NSRect pointInWindowRect = NSMakeRect(conf_pos.x, conf_pos.y, 0, 0);
- conf_pos = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
- conf_pos.y = CGDisplayBounds(CGMainDisplayID()).size.height - conf_pos.y;
- CGWarpMouseCursorPosition(conf_pos);
-
- // Save warp data
- DS_OSX->last_warp = [[NSProcessInfo processInfo] systemUptime];
- DisplayServerOSX::WarpEvent ev;
- ev.timestamp = DS_OSX->last_warp;
- ev.delta = delta;
- DS_OSX->warp_events.push_back(ev);
- }
-
- Ref<InputEventMouseMotion> mm;
- mm.instantiate();
-
- mm->set_window_id(window_id);
- mm->set_button_mask(DS_OSX->last_button_state);
- const Vector2i pos = _get_mouse_pos(wd, mpos);
- mm->set_position(pos);
- mm->set_pressure([event pressure]);
- if ([event subtype] == NSEventSubtypeTabletPoint) {
- const NSPoint p = [event tilt];
- mm->set_tilt(Vector2(p.x, p.y));
+ if (value->callback != Callable()) {
+ Variant tag = value->meta;
+ Variant *tagp = &tag;
+ Variant ret;
+ Callable::CallError ce;
+ value->callback.call((const Variant **)&tagp, 1, ret, ce);
+ }
}
- mm->set_global_position(pos);
- mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
- const Vector2i relativeMotion = Vector2i(delta.x, delta.y) * DS_OSX->screen_get_max_scale();
- mm->set_relative(relativeMotion);
- _get_key_modifier_state([event modifierFlags], mm);
-
- Input::get_singleton()->parse_input_event(mm);
-}
-
-- (void)rightMouseDown:(NSEvent *)event {
- _mouseDownEvent(window_id, event, MouseButton::RIGHT, MouseButton::MASK_RIGHT, true);
-}
-
-- (void)rightMouseDragged:(NSEvent *)event {
- [self mouseMoved:event];
-}
-
-- (void)rightMouseUp:(NSEvent *)event {
- _mouseDownEvent(window_id, event, MouseButton::RIGHT, MouseButton::MASK_RIGHT, false);
}
-- (void)otherMouseDown:(NSEvent *)event {
- if ((int)[event buttonNumber] == 2) {
- _mouseDownEvent(window_id, event, MouseButton::MIDDLE, MouseButton::MASK_MIDDLE, true);
- } else if ((int)[event buttonNumber] == 3) {
- _mouseDownEvent(window_id, event, MouseButton::MB_XBUTTON1, MouseButton::MASK_XBUTTON1, true);
- } else if ((int)[event buttonNumber] == 4) {
- _mouseDownEvent(window_id, event, MouseButton::MB_XBUTTON2, MouseButton::MASK_XBUTTON2, true);
- } else {
- return;
- }
+bool DisplayServerOSX::has_window(WindowID p_window) const {
+ return windows.has(p_window);
}
-- (void)otherMouseDragged:(NSEvent *)event {
- [self mouseMoved:event];
+DisplayServerOSX::WindowData &DisplayServerOSX::get_window(WindowID p_window) {
+ return windows[p_window];
}
-- (void)otherMouseUp:(NSEvent *)event {
- if ((int)[event buttonNumber] == 2) {
- _mouseDownEvent(window_id, event, MouseButton::MIDDLE, MouseButton::MASK_MIDDLE, false);
- } else if ((int)[event buttonNumber] == 3) {
- _mouseDownEvent(window_id, event, MouseButton::MB_XBUTTON1, MouseButton::MASK_XBUTTON1, false);
- } else if ((int)[event buttonNumber] == 4) {
- _mouseDownEvent(window_id, event, MouseButton::MB_XBUTTON2, MouseButton::MASK_XBUTTON2, false);
- } else {
- return;
- }
-}
+void DisplayServerOSX::send_event(NSEvent *p_event) {
+ // Special case handling of command-period, which is traditionally a special
+ // shortcut in macOS and doesn't arrive at our regular keyDown handler.
+ if ([p_event type] == NSEventTypeKeyDown) {
+ if (([p_event modifierFlags] & NSEventModifierFlagCommand) && [p_event keyCode] == 0x2f) {
+ Ref<InputEventKey> k;
+ k.instantiate();
-- (void)mouseExited:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
+ get_key_modifier_state([p_event modifierFlags], k);
+ k->set_window_id(DisplayServerOSX::INVALID_WINDOW_ID);
+ k->set_pressed(true);
+ k->set_keycode(Key::PERIOD);
+ k->set_physical_keycode(Key::PERIOD);
+ k->set_echo([p_event isARepeat]);
- if (DS_OSX->mouse_mode != DisplayServer::MOUSE_MODE_CAPTURED) {
- DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_MOUSE_EXIT);
+ Input::get_singleton()->parse_input_event(k);
+ }
}
}
-- (void)mouseEntered:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
+void DisplayServerOSX::send_window_event(const WindowData &wd, WindowEvent p_event) {
+ _THREAD_SAFE_METHOD_
- if (DS_OSX->mouse_mode != DisplayServer::MOUSE_MODE_CAPTURED) {
- DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_MOUSE_ENTER);
+ if (!wd.event_callback.is_null()) {
+ Variant event = int(p_event);
+ Variant *eventp = &event;
+ Variant ret;
+ Callable::CallError ce;
+ wd.event_callback.call((const Variant **)&eventp, 1, ret, ce);
}
-
- DisplayServer::CursorShape p_shape = DS_OSX->cursor_shape;
- DS_OSX->cursor_shape = DisplayServer::CURSOR_MAX;
- DS_OSX->cursor_set_shape(p_shape);
-}
-
-- (void)magnifyWithEvent:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- Ref<InputEventMagnifyGesture> ev;
- ev.instantiate();
- ev->set_window_id(window_id);
- _get_key_modifier_state([event modifierFlags], ev);
- ev->set_position(_get_mouse_pos(wd, [event locationInWindow]));
- ev->set_factor([event magnification] + 1.0);
-
- Input::get_singleton()->parse_input_event(ev);
}
-- (void)viewDidChangeBackingProperties {
- // nothing left to do here
-}
-
-- (void)updateTrackingAreas {
- if (trackingArea != nil) {
- [self removeTrackingArea:trackingArea];
- [trackingArea release];
- }
-
- NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingCursorUpdate | NSTrackingInVisibleRect;
- trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
-
- [self addTrackingArea:trackingArea];
- [super updateTrackingAreas];
-}
-
-static bool isNumpadKey(unsigned int key) {
- static const unsigned int table[] = {
- 0x41, /* kVK_ANSI_KeypadDecimal */
- 0x43, /* kVK_ANSI_KeypadMultiply */
- 0x45, /* kVK_ANSI_KeypadPlus */
- 0x47, /* kVK_ANSI_KeypadClear */
- 0x4b, /* kVK_ANSI_KeypadDivide */
- 0x4c, /* kVK_ANSI_KeypadEnter */
- 0x4e, /* kVK_ANSI_KeypadMinus */
- 0x51, /* kVK_ANSI_KeypadEquals */
- 0x52, /* kVK_ANSI_Keypad0 */
- 0x53, /* kVK_ANSI_Keypad1 */
- 0x54, /* kVK_ANSI_Keypad2 */
- 0x55, /* kVK_ANSI_Keypad3 */
- 0x56, /* kVK_ANSI_Keypad4 */
- 0x57, /* kVK_ANSI_Keypad5 */
- 0x58, /* kVK_ANSI_Keypad6 */
- 0x59, /* kVK_ANSI_Keypad7 */
- 0x5b, /* kVK_ANSI_Keypad8 */
- 0x5c, /* kVK_ANSI_Keypad9 */
- 0x5f, /* kVK_JIS_KeypadComma */
- 0x00
- };
- for (int i = 0; table[i] != 0; i++) {
- if (key == table[i]) {
- return true;
- }
+void DisplayServerOSX::release_pressed_events() {
+ _THREAD_SAFE_METHOD_
+ if (Input::get_singleton()) {
+ Input::get_singleton()->release_pressed_events();
}
- return false;
}
-// Keyboard symbol translation table
-static const Key _osx_to_godot_table[128] = {
- /* 00 */ Key::A,
- /* 01 */ Key::S,
- /* 02 */ Key::D,
- /* 03 */ Key::F,
- /* 04 */ Key::H,
- /* 05 */ Key::G,
- /* 06 */ Key::Z,
- /* 07 */ Key::X,
- /* 08 */ Key::C,
- /* 09 */ Key::V,
- /* 0a */ Key::SECTION, /* ISO Section */
- /* 0b */ Key::B,
- /* 0c */ Key::Q,
- /* 0d */ Key::W,
- /* 0e */ Key::E,
- /* 0f */ Key::R,
- /* 10 */ Key::Y,
- /* 11 */ Key::T,
- /* 12 */ Key::KEY_1,
- /* 13 */ Key::KEY_2,
- /* 14 */ Key::KEY_3,
- /* 15 */ Key::KEY_4,
- /* 16 */ Key::KEY_6,
- /* 17 */ Key::KEY_5,
- /* 18 */ Key::EQUAL,
- /* 19 */ Key::KEY_9,
- /* 1a */ Key::KEY_7,
- /* 1b */ Key::MINUS,
- /* 1c */ Key::KEY_8,
- /* 1d */ Key::KEY_0,
- /* 1e */ Key::BRACERIGHT,
- /* 1f */ Key::O,
- /* 20 */ Key::U,
- /* 21 */ Key::BRACELEFT,
- /* 22 */ Key::I,
- /* 23 */ Key::P,
- /* 24 */ Key::ENTER,
- /* 25 */ Key::L,
- /* 26 */ Key::J,
- /* 27 */ Key::APOSTROPHE,
- /* 28 */ Key::K,
- /* 29 */ Key::SEMICOLON,
- /* 2a */ Key::BACKSLASH,
- /* 2b */ Key::COMMA,
- /* 2c */ Key::SLASH,
- /* 2d */ Key::N,
- /* 2e */ Key::M,
- /* 2f */ Key::PERIOD,
- /* 30 */ Key::TAB,
- /* 31 */ Key::SPACE,
- /* 32 */ Key::QUOTELEFT,
- /* 33 */ Key::BACKSPACE,
- /* 34 */ Key::UNKNOWN,
- /* 35 */ Key::ESCAPE,
- /* 36 */ Key::META,
- /* 37 */ Key::META,
- /* 38 */ Key::SHIFT,
- /* 39 */ Key::CAPSLOCK,
- /* 3a */ Key::ALT,
- /* 3b */ Key::CTRL,
- /* 3c */ Key::SHIFT,
- /* 3d */ Key::ALT,
- /* 3e */ Key::CTRL,
- /* 3f */ Key::UNKNOWN, /* Function */
- /* 40 */ Key::UNKNOWN, /* F17 */
- /* 41 */ Key::KP_PERIOD,
- /* 42 */ Key::UNKNOWN,
- /* 43 */ Key::KP_MULTIPLY,
- /* 44 */ Key::UNKNOWN,
- /* 45 */ Key::KP_ADD,
- /* 46 */ Key::UNKNOWN,
- /* 47 */ Key::NUMLOCK, /* Really KeypadClear... */
- /* 48 */ Key::VOLUMEUP, /* VolumeUp */
- /* 49 */ Key::VOLUMEDOWN, /* VolumeDown */
- /* 4a */ Key::VOLUMEMUTE, /* Mute */
- /* 4b */ Key::KP_DIVIDE,
- /* 4c */ Key::KP_ENTER,
- /* 4d */ Key::UNKNOWN,
- /* 4e */ Key::KP_SUBTRACT,
- /* 4f */ Key::UNKNOWN, /* F18 */
- /* 50 */ Key::UNKNOWN, /* F19 */
- /* 51 */ Key::EQUAL, /* KeypadEqual */
- /* 52 */ Key::KP_0,
- /* 53 */ Key::KP_1,
- /* 54 */ Key::KP_2,
- /* 55 */ Key::KP_3,
- /* 56 */ Key::KP_4,
- /* 57 */ Key::KP_5,
- /* 58 */ Key::KP_6,
- /* 59 */ Key::KP_7,
- /* 5a */ Key::UNKNOWN, /* F20 */
- /* 5b */ Key::KP_8,
- /* 5c */ Key::KP_9,
- /* 5d */ Key::YEN, /* JIS Yen */
- /* 5e */ Key::UNDERSCORE, /* JIS Underscore */
- /* 5f */ Key::COMMA, /* JIS KeypadComma */
- /* 60 */ Key::F5,
- /* 61 */ Key::F6,
- /* 62 */ Key::F7,
- /* 63 */ Key::F3,
- /* 64 */ Key::F8,
- /* 65 */ Key::F9,
- /* 66 */ Key::UNKNOWN, /* JIS Eisu */
- /* 67 */ Key::F11,
- /* 68 */ Key::UNKNOWN, /* JIS Kana */
- /* 69 */ Key::F13,
- /* 6a */ Key::F16,
- /* 6b */ Key::F14,
- /* 6c */ Key::UNKNOWN,
- /* 6d */ Key::F10,
- /* 6e */ Key::MENU,
- /* 6f */ Key::F12,
- /* 70 */ Key::UNKNOWN,
- /* 71 */ Key::F15,
- /* 72 */ Key::INSERT, /* Really Help... */
- /* 73 */ Key::HOME,
- /* 74 */ Key::PAGEUP,
- /* 75 */ Key::KEY_DELETE,
- /* 76 */ Key::F4,
- /* 77 */ Key::END,
- /* 78 */ Key::F2,
- /* 79 */ Key::PAGEDOWN,
- /* 7a */ Key::F1,
- /* 7b */ Key::LEFT,
- /* 7c */ Key::RIGHT,
- /* 7d */ Key::DOWN,
- /* 7e */ Key::UP,
- /* 7f */ Key::UNKNOWN,
-};
-
-// Translates a OS X keycode to a Godot keycode
-static Key translateKey(unsigned int key) {
- if (key >= 128) {
- return Key::UNKNOWN;
- }
-
- return _osx_to_godot_table[key];
-}
-
-// Translates a Godot keycode back to a OSX keycode
-static unsigned int unmapKey(Key key) {
- for (int i = 0; i <= 126; i++) {
- if (_osx_to_godot_table[i] == key) {
- return i;
- }
- }
- return 127;
-}
-
-struct _KeyCodeMap {
- UniChar kchar;
- Key kcode;
-};
-
-static const _KeyCodeMap _keycodes[55] = {
- { '`', Key::QUOTELEFT },
- { '~', Key::ASCIITILDE },
- { '0', Key::KEY_0 },
- { '1', Key::KEY_1 },
- { '2', Key::KEY_2 },
- { '3', Key::KEY_3 },
- { '4', Key::KEY_4 },
- { '5', Key::KEY_5 },
- { '6', Key::KEY_6 },
- { '7', Key::KEY_7 },
- { '8', Key::KEY_8 },
- { '9', Key::KEY_9 },
- { '-', Key::MINUS },
- { '_', Key::UNDERSCORE },
- { '=', Key::EQUAL },
- { '+', Key::PLUS },
- { 'q', Key::Q },
- { 'w', Key::W },
- { 'e', Key::E },
- { 'r', Key::R },
- { 't', Key::T },
- { 'y', Key::Y },
- { 'u', Key::U },
- { 'i', Key::I },
- { 'o', Key::O },
- { 'p', Key::P },
- { '[', Key::BRACELEFT },
- { ']', Key::BRACERIGHT },
- { '{', Key::BRACELEFT },
- { '}', Key::BRACERIGHT },
- { 'a', Key::A },
- { 's', Key::S },
- { 'd', Key::D },
- { 'f', Key::F },
- { 'g', Key::G },
- { 'h', Key::H },
- { 'j', Key::J },
- { 'k', Key::K },
- { 'l', Key::L },
- { ';', Key::SEMICOLON },
- { ':', Key::COLON },
- { '\'', Key::APOSTROPHE },
- { '\"', Key::QUOTEDBL },
- { '\\', Key::BACKSLASH },
- { '#', Key::NUMBERSIGN },
- { 'z', Key::Z },
- { 'x', Key::X },
- { 'c', Key::C },
- { 'v', Key::V },
- { 'b', Key::B },
- { 'n', Key::N },
- { 'm', Key::M },
- { ',', Key::COMMA },
- { '.', Key::PERIOD },
- { '/', Key::SLASH }
-};
-
-static Key remapKey(unsigned int key, unsigned int state) {
- if (isNumpadKey(key)) {
- return translateKey(key);
- }
-
- TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
- if (!currentKeyboard) {
- return translateKey(key);
- }
-
- CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
- if (!layoutData) {
- return translateKey(key);
- }
-
- const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
-
- UInt32 keysDown = 0;
- UniChar chars[4];
- UniCharCount realLength;
-
- OSStatus err = UCKeyTranslate(keyboardLayout,
- key,
- kUCKeyActionDisplay,
- (state >> 8) & 0xFF,
- LMGetKbdType(),
- kUCKeyTranslateNoDeadKeysBit,
- &keysDown,
- sizeof(chars) / sizeof(chars[0]),
- &realLength,
- chars);
-
- if (err != noErr) {
- return translateKey(key);
- }
-
- for (unsigned int i = 0; i < 55; i++) {
- if (_keycodes[i].kchar == chars[0]) {
- return _keycodes[i].kcode;
- }
- }
- return translateKey(key);
-}
-
-- (void)keyDown:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- ignore_momentum_scroll = true;
-
- // Ignore all input if IME input is in progress
- if (!imeInputEventInProgress) {
- NSString *characters = [event characters];
- NSUInteger length = [characters length];
-
- if (!wd.im_active && length > 0 && keycode_has_unicode(remapKey([event keyCode], [event modifierFlags]))) {
- // Fallback unicode character handler used if IME is not active
- Char16String text;
- text.resize([characters length] + 1);
- [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
-
- String u32text;
- u32text.parse_utf16(text.ptr(), text.length());
-
- for (int i = 0; i < u32text.length(); i++) {
- const char32_t codepoint = u32text[i];
-
- DisplayServerOSX::KeyEvent ke;
-
- ke.window_id = window_id;
- ke.osx_state = [event modifierFlags];
- ke.pressed = true;
- ke.echo = [event isARepeat];
- ke.keycode = remapKey([event keyCode], [event modifierFlags]);
- ke.physical_keycode = translateKey([event keyCode]);
- ke.raw = true;
- ke.unicode = codepoint;
-
- _push_to_key_event_buffer(ke);
- }
- } else {
- DisplayServerOSX::KeyEvent ke;
-
- ke.window_id = window_id;
- ke.osx_state = [event modifierFlags];
- ke.pressed = true;
- ke.echo = [event isARepeat];
- ke.keycode = remapKey([event keyCode], [event modifierFlags]);
- ke.physical_keycode = translateKey([event keyCode]);
- ke.raw = false;
- ke.unicode = 0;
-
- _push_to_key_event_buffer(ke);
- }
- }
-
- // Pass events to IME handler
- if (wd.im_active) {
- [self interpretKeyEvents:[NSArray arrayWithObject:event]];
- }
+void DisplayServerOSX::get_key_modifier_state(unsigned int p_osx_state, Ref<InputEventWithModifiers> r_state) const {
+ r_state->set_shift_pressed((p_osx_state & NSEventModifierFlagShift));
+ r_state->set_ctrl_pressed((p_osx_state & NSEventModifierFlagControl));
+ r_state->set_alt_pressed((p_osx_state & NSEventModifierFlagOption));
+ r_state->set_meta_pressed((p_osx_state & NSEventModifierFlagCommand));
}
-- (void)flagsChanged:(NSEvent *)event {
- ignore_momentum_scroll = true;
-
- // Ignore all input if IME input is in progress
- if (!imeInputEventInProgress) {
- DisplayServerOSX::KeyEvent ke;
-
- ke.window_id = window_id;
- ke.echo = false;
- ke.raw = true;
-
- int key = [event keyCode];
- int mod = [event modifierFlags];
-
- if (key == 0x36 || key == 0x37) {
- if (mod & NSEventModifierFlagCommand) {
- mod &= ~NSEventModifierFlagCommand;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else if (key == 0x38 || key == 0x3c) {
- if (mod & NSEventModifierFlagShift) {
- mod &= ~NSEventModifierFlagShift;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else if (key == 0x3a || key == 0x3d) {
- if (mod & NSEventModifierFlagOption) {
- mod &= ~NSEventModifierFlagOption;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else if (key == 0x3b || key == 0x3e) {
- if (mod & NSEventModifierFlagControl) {
- mod &= ~NSEventModifierFlagControl;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else {
- return;
- }
-
- ke.osx_state = mod;
- ke.keycode = remapKey(key, mod);
- ke.physical_keycode = translateKey(key);
- ke.unicode = 0;
-
- _push_to_key_event_buffer(ke);
- }
+void DisplayServerOSX::update_mouse_pos(DisplayServerOSX::WindowData &p_wd, NSPoint p_location_in_window) {
+ const NSRect content_rect = [p_wd.window_view frame];
+ const float scale = screen_get_max_scale();
+ p_wd.mouse_pos.x = p_location_in_window.x * scale;
+ p_wd.mouse_pos.y = (content_rect.size.height - p_location_in_window.y) * scale;
+ Input::get_singleton()->set_mouse_position(p_wd.mouse_pos);
}
-- (void)keyUp:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- // Ignore all input if IME input is in progress
- if (!imeInputEventInProgress) {
- NSString *characters = [event characters];
- NSUInteger length = [characters length];
-
- // Fallback unicode character handler used if IME is not active
- if (!wd.im_active && length > 0 && keycode_has_unicode(remapKey([event keyCode], [event modifierFlags]))) {
- Char16String text;
- text.resize([characters length] + 1);
- [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
-
- String u32text;
- u32text.parse_utf16(text.ptr(), text.length());
-
- for (int i = 0; i < u32text.length(); i++) {
- const char32_t codepoint = u32text[i];
- DisplayServerOSX::KeyEvent ke;
-
- ke.window_id = window_id;
- ke.osx_state = [event modifierFlags];
- ke.pressed = false;
- ke.echo = [event isARepeat];
- ke.keycode = remapKey([event keyCode], [event modifierFlags]);
- ke.physical_keycode = translateKey([event keyCode]);
- ke.raw = true;
- ke.unicode = codepoint;
-
- _push_to_key_event_buffer(ke);
- }
- } else {
- DisplayServerOSX::KeyEvent ke;
-
- ke.window_id = window_id;
- ke.osx_state = [event modifierFlags];
- ke.pressed = false;
- ke.echo = [event isARepeat];
- ke.keycode = remapKey([event keyCode], [event modifierFlags]);
- ke.physical_keycode = translateKey([event keyCode]);
- ke.raw = true;
- ke.unicode = 0;
-
- _push_to_key_event_buffer(ke);
- }
+void DisplayServerOSX::push_to_key_event_buffer(const DisplayServerOSX::KeyEvent &p_event) {
+ if (key_event_pos >= key_event_buffer.size()) {
+ key_event_buffer.resize(1 + key_event_pos);
}
+ key_event_buffer.write[key_event_pos++] = p_event;
}
-inline void sendScrollEvent(DisplayServer::WindowID window_id, MouseButton button, double factor, int modifierFlags) {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- MouseButton mask = mouse_button_to_mask(button);
-
- Ref<InputEventMouseButton> sc;
- sc.instantiate();
-
- sc->set_window_id(window_id);
- _get_key_modifier_state(modifierFlags, sc);
- sc->set_button_index(button);
- sc->set_factor(factor);
- sc->set_pressed(true);
- sc->set_position(wd.mouse_pos);
- sc->set_global_position(wd.mouse_pos);
- DS_OSX->last_button_state |= (MouseButton)mask;
- sc->set_button_mask(DS_OSX->last_button_state);
+void DisplayServerOSX::update_im_text(const Point2i &p_selection, const String &p_text) {
+ im_selection = p_selection;
+ im_text = p_text;
- Input::get_singleton()->parse_input_event(sc);
-
- sc.instantiate();
- sc->set_window_id(window_id);
- sc->set_button_index(button);
- sc->set_factor(factor);
- sc->set_pressed(false);
- sc->set_position(wd.mouse_pos);
- sc->set_global_position(wd.mouse_pos);
- DS_OSX->last_button_state &= (MouseButton)~mask;
- sc->set_button_mask(DS_OSX->last_button_state);
-
- Input::get_singleton()->parse_input_event(sc);
+ OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
}
-inline void sendPanEvent(DisplayServer::WindowID window_id, double dx, double dy, int modifierFlags) {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- Ref<InputEventPanGesture> pg;
- pg.instantiate();
-
- pg->set_window_id(window_id);
- _get_key_modifier_state(modifierFlags, pg);
- pg->set_position(wd.mouse_pos);
- pg->set_delta(Vector2(-dx, -dy));
-
- Input::get_singleton()->parse_input_event(pg);
+void DisplayServerOSX::set_last_focused_window(WindowID p_window) {
+ last_focused_window = p_window;
}
-- (void)scrollWheel:(NSEvent *)event {
- ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
- DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
-
- double deltaX, deltaY;
-
- _ALLOW_DISCARD_ _get_mouse_pos(wd, [event locationInWindow]);
-
- deltaX = [event scrollingDeltaX];
- deltaY = [event scrollingDeltaY];
-
- if ([event hasPreciseScrollingDeltas]) {
- deltaX *= 0.03;
- deltaY *= 0.03;
+void DisplayServerOSX::window_update(WindowID p_window) {
+#if defined(GLES3_ENABLED)
+ if (gl_manager) {
+ gl_manager->window_update(p_window);
}
+#endif
+}
- if ([event momentumPhase] != NSEventPhaseNone) {
- if (ignore_momentum_scroll) {
- return;
- }
- } else {
- ignore_momentum_scroll = false;
+void DisplayServerOSX::window_destroy(WindowID p_window) {
+#if defined(GLES3_ENABLED)
+ if (gl_manager) {
+ gl_manager->window_destroy(p_window);
}
-
- if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
- sendPanEvent(window_id, deltaX, deltaY, [event modifierFlags]);
- } else {
- if (fabs(deltaX)) {
- sendScrollEvent(window_id, 0 > deltaX ? MouseButton::WHEEL_RIGHT : MouseButton::WHEEL_LEFT, fabs(deltaX * 0.3), [event modifierFlags]);
- }
- if (fabs(deltaY)) {
- sendScrollEvent(window_id, 0 < deltaY ? MouseButton::WHEEL_UP : MouseButton::WHEEL_DOWN, fabs(deltaY * 0.3), [event modifierFlags]);
- }
+#endif
+#ifdef VULKAN_ENABLED
+ if (context_vulkan) {
+ context_vulkan->window_destroy(p_window);
}
+#endif
+ windows.erase(p_window);
}
-@end
-
-/*************************************************************************/
-/* GodotWindow */
-/*************************************************************************/
-
-@interface GodotWindow : NSWindow {
-}
-
-@end
-
-@implementation GodotWindow
-
-- (BOOL)canBecomeKeyWindow {
- // Required for NSBorderlessWindowMask windows
- for (Map<DisplayServer::WindowID, DisplayServerOSX::WindowData>::Element *E = DS_OSX->windows.front(); E; E = E->next()) {
- if (E->get().window_object == self) {
- if (E->get().no_focus) {
- return NO;
- }
- }
+void DisplayServerOSX::window_resize(WindowID p_window, int p_width, int p_height) {
+#if defined(GLES3_ENABLED)
+ if (gl_manager) {
+ gl_manager->window_resize(p_window, p_width, p_height);
}
- return YES;
-}
-
-- (BOOL)canBecomeMainWindow {
- // Required for NSBorderlessWindowMask windows
- for (Map<DisplayServer::WindowID, DisplayServerOSX::WindowData>::Element *E = DS_OSX->windows.front(); E; E = E->next()) {
- if (E->get().window_object == self) {
- if (E->get().no_focus) {
- return NO;
- }
- }
+#endif
+#if defined(VULKAN_ENABLED)
+ if (context_vulkan) {
+ context_vulkan->window_resize(p_window, p_width, p_height);
}
- return YES;
+#endif
}
-@end
-
-/*************************************************************************/
-/* DisplayServerOSX */
-/*************************************************************************/
-
bool DisplayServerOSX::has_feature(Feature p_feature) const {
switch (p_feature) {
case FEATURE_GLOBAL_MENU:
@@ -1494,57 +648,13 @@ String DisplayServerOSX::get_name() const {
return "OSX";
}
-const NSMenu *DisplayServerOSX::_get_menu_root(const String &p_menu_root) const {
- const NSMenu *menu = nullptr;
- if (p_menu_root == "") {
- // Main menu.x
- menu = [NSApp mainMenu];
- } else if (p_menu_root.to_lower() == "_dock") {
- // macOS dock menu.
- menu = dock_menu;
- } else {
- // Submenu.
- if (submenu.has(p_menu_root)) {
- menu = submenu[p_menu_root];
- }
- }
- if (menu == apple_menu) {
- // Do not allow to change Apple menu.
- return nullptr;
- }
- return menu;
-}
-
-NSMenu *DisplayServerOSX::_get_menu_root(const String &p_menu_root) {
- NSMenu *menu = nullptr;
- if (p_menu_root == "") {
- // Main menu.
- menu = [NSApp mainMenu];
- } else if (p_menu_root.to_lower() == "_dock") {
- // macOS dock menu.
- menu = dock_menu;
- } else {
- // Submenu.
- if (!submenu.has(p_menu_root)) {
- NSMenu *n_menu = [[NSMenu alloc] initWithTitle:[NSString stringWithUTF8String:p_menu_root.utf8().get_data()]];
- submenu[p_menu_root] = n_menu;
- }
- menu = submenu[p_menu_root];
- }
- if (menu == apple_menu) {
- // Do not allow to change Apple menu.
- return nullptr;
- }
- return menu;
-}
-
void DisplayServerOSX::global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag) {
_THREAD_SAFE_METHOD_
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
- GlobalMenuItem *obj = [[[GlobalMenuItem alloc] init] autorelease];
+ GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
obj->checkable = false;
@@ -1558,7 +668,7 @@ void DisplayServerOSX::global_menu_add_check_item(const String &p_menu_root, con
NSMenu *menu = _get_menu_root(p_menu_root);
if (menu) {
NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
- GlobalMenuItem *obj = [[[GlobalMenuItem alloc] init] autorelease];
+ GodotMenuItem *obj = [[GodotMenuItem alloc] init];
obj->callback = p_callback;
obj->meta = p_tag;
obj->checkable = true;
@@ -1614,7 +724,7 @@ bool DisplayServerOSX::global_menu_is_item_checkable(const String &p_menu_root,
if (menu) {
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
- GlobalMenuItem *obj = [menu_item representedObject];
+ GodotMenuItem *obj = [menu_item representedObject];
if (obj) {
return obj->checkable;
}
@@ -1630,7 +740,7 @@ Callable DisplayServerOSX::global_menu_get_item_callback(const String &p_menu_ro
if (menu) {
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
- GlobalMenuItem *obj = [menu_item representedObject];
+ GodotMenuItem *obj = [menu_item representedObject];
if (obj) {
return obj->callback;
}
@@ -1646,7 +756,7 @@ Variant DisplayServerOSX::global_menu_get_item_tag(const String &p_menu_root, in
if (menu) {
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
- GlobalMenuItem *obj = [menu_item representedObject];
+ GodotMenuItem *obj = [menu_item representedObject];
if (obj) {
return obj->meta;
}
@@ -1662,10 +772,8 @@ String DisplayServerOSX::global_menu_get_item_text(const String &p_menu_root, in
if (menu) {
const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
- char *utfs = strdup([[menu_item title] UTF8String]);
String ret;
- ret.parse_utf8(utfs);
- free(utfs);
+ ret.parse_utf8([[menu_item title] UTF8String]);
return ret;
}
}
@@ -1720,7 +828,7 @@ void DisplayServerOSX::global_menu_set_item_checkable(const String &p_menu_root,
}
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
- GlobalMenuItem *obj = [menu_item representedObject];
+ GodotMenuItem *obj = [menu_item representedObject];
obj->checkable = p_checkable;
}
}
@@ -1736,7 +844,7 @@ void DisplayServerOSX::global_menu_set_item_callback(const String &p_menu_root,
}
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
- GlobalMenuItem *obj = [menu_item representedObject];
+ GodotMenuItem *obj = [menu_item representedObject];
obj->callback = p_callback;
}
}
@@ -1752,7 +860,7 @@ void DisplayServerOSX::global_menu_set_item_tag(const String &p_menu_root, int p
}
NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
if (menu_item) {
- GlobalMenuItem *obj = [menu_item representedObject];
+ GodotMenuItem *obj = [menu_item representedObject];
obj->meta = p_tag;
}
}
@@ -1869,7 +977,6 @@ Error DisplayServerOSX::dialog_show(String p_title, String p_description, Vector
p_callback.call((const Variant **)&buttonp, 1, ret, ce);
}
- [window release];
return OK;
}
@@ -1891,10 +998,8 @@ Error DisplayServerOSX::dialog_input_text(String p_title, String p_description,
[window runModal];
- char *utfs = strdup([[input stringValue] UTF8String]);
String ret;
- ret.parse_utf8(utfs);
- free(utfs);
+ ret.parse_utf8([[input stringValue] UTF8String]);
if (!p_callback.is_null()) {
Variant text = ret;
@@ -1904,7 +1009,6 @@ Error DisplayServerOSX::dialog_input_text(String p_title, String p_description,
p_callback.call((const Variant **)&textp, 1, ret, ce);
}
- [window release];
return OK;
}
@@ -1959,9 +1063,7 @@ void DisplayServerOSX::mouse_set_mode(MouseMode p_mode) {
mouse_mode = p_mode;
if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
- CursorShape p_shape = cursor_shape;
- cursor_shape = DisplayServer::CURSOR_MAX;
- cursor_set_shape(p_shape);
+ cursor_update_shape();
}
}
@@ -1969,25 +1071,82 @@ DisplayServer::MouseMode DisplayServerOSX::mouse_get_mode() const {
return mouse_mode;
}
+bool DisplayServerOSX::update_mouse_wrap(WindowData &p_wd, NSPoint &r_delta, NSPoint &r_mpos, NSTimeInterval p_timestamp) {
+ _THREAD_SAFE_METHOD_
+
+ if (ignore_warp) {
+ // Discard late events, before warp.
+ if (p_timestamp < last_warp) {
+ return true;
+ }
+ ignore_warp = false;
+ return true;
+ }
+
+ if (mouse_mode == DisplayServer::MOUSE_MODE_CONFINED || mouse_mode == DisplayServer::MOUSE_MODE_CONFINED_HIDDEN) {
+ // Discard late events.
+ if (p_timestamp < last_warp) {
+ return true;
+ }
+
+ // Warp affects next event delta, subtract previous warp deltas.
+ List<WarpEvent>::Element *F = warp_events.front();
+ while (F) {
+ if (F->get().timestamp < p_timestamp) {
+ List<DisplayServerOSX::WarpEvent>::Element *E = F;
+ r_delta.x -= E->get().delta.x;
+ r_delta.y -= E->get().delta.y;
+ F = F->next();
+ warp_events.erase(E);
+ } else {
+ F = F->next();
+ }
+ }
+
+ // Confine mouse position to the window, and update delta.
+ NSRect frame = [p_wd.window_object frame];
+ NSPoint conf_pos = r_mpos;
+ conf_pos.x = CLAMP(conf_pos.x + r_delta.x, 0.f, frame.size.width);
+ conf_pos.y = CLAMP(conf_pos.y - r_delta.y, 0.f, frame.size.height);
+ r_delta.x = conf_pos.x - r_mpos.x;
+ r_delta.y = r_mpos.y - conf_pos.y;
+ r_mpos = conf_pos;
+
+ // Move mouse cursor.
+ NSRect point_in_window_rect = NSMakeRect(conf_pos.x, conf_pos.y, 0, 0);
+ conf_pos = [[p_wd.window_view window] convertRectToScreen:point_in_window_rect].origin;
+ conf_pos.y = CGDisplayBounds(CGMainDisplayID()).size.height - conf_pos.y;
+ CGWarpMouseCursorPosition(conf_pos);
+
+ // Save warp data.
+ last_warp = [[NSProcessInfo processInfo] systemUptime];
+
+ DisplayServerOSX::WarpEvent ev;
+ ev.timestamp = last_warp;
+ ev.delta = r_delta;
+ warp_events.push_back(ev);
+ }
+
+ return false;
+}
+
void DisplayServerOSX::mouse_warp_to_position(const Point2i &p_to) {
_THREAD_SAFE_METHOD_
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- last_mouse_pos = p_to;
- } else {
+ if (mouse_mode != MOUSE_MODE_CAPTURED) {
WindowID window_id = windows.has(last_focused_window) ? last_focused_window : MAIN_WINDOW_ID;
WindowData &wd = windows[window_id];
- //local point in window coords
+ // Local point in window coords.
const NSRect contentRect = [wd.window_view frame];
const float scale = screen_get_max_scale();
NSRect pointInWindowRect = NSMakeRect(p_to.x / scale, contentRect.size.height - (p_to.y / scale - 1), 0, 0);
NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
- //point in scren coords
+ // Point in scren coords.
CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
- //do the warping
+ // Do the warping.
CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
CGAssociateMouseAndMouseCursorPosition(false);
@@ -2013,6 +1172,10 @@ Point2i DisplayServerOSX::mouse_get_position() const {
return Vector2i();
}
+void DisplayServerOSX::mouse_set_button_state(MouseButton p_state) {
+ last_button_state = p_state;
+}
+
MouseButton DisplayServerOSX::mouse_get_button_state() const {
return last_button_state;
}
@@ -2044,11 +1207,8 @@ String DisplayServerOSX::clipboard_get() const {
NSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
NSString *string = [objectsToPaste objectAtIndex:0];
- char *utfs = strdup([string UTF8String]);
String ret;
- ret.parse_utf8(utfs);
- free(utfs);
-
+ ret.parse_utf8([string UTF8String]);
return ret;
}
@@ -2059,48 +1219,6 @@ int DisplayServerOSX::get_screen_count() const {
return [screenArray count];
}
-// Returns the native top-left screen coordinate of the smallest rectangle
-// that encompasses all screens. Needed in get_screen_position(),
-// window_get_position, and window_set_position()
-// to convert between OS X native screen coordinates and the ones expected by Godot
-
-static bool displays_arrangement_dirty = true;
-static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
- displays_arrangement_dirty = true;
-}
-
-Point2i DisplayServerOSX::_get_screens_origin() const {
- static Point2i origin;
-
- if (displays_arrangement_dirty) {
- origin = Point2i();
-
- for (int i = 0; i < get_screen_count(); i++) {
- Point2i position = _get_native_screen_position(i);
- if (position.x < origin.x) {
- origin.x = position.x;
- }
- if (position.y > origin.y) {
- origin.y = position.y;
- }
- }
- displays_arrangement_dirty = false;
- }
-
- return origin;
-}
-
-Point2i DisplayServerOSX::_get_native_screen_position(int p_screen) const {
- NSArray *screenArray = [NSScreen screens];
- if ((NSUInteger)p_screen < [screenArray count]) {
- NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
- // Return the top-left corner of the screen, for OS X the y starts at the bottom
- return Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * screen_get_max_scale();
- }
-
- return Point2i();
-}
-
Point2i DisplayServerOSX::screen_get_position(int p_screen) const {
_THREAD_SAFE_METHOD_
@@ -2110,7 +1228,7 @@ Point2i DisplayServerOSX::screen_get_position(int p_screen) const {
Point2i position = _get_native_screen_position(p_screen) - _get_screens_origin();
// OS X native y-coordinate relative to _get_screens_origin() is negative,
- // Godot expects a positive value
+ // Godot expects a positive value.
position.y *= -1;
return position;
}
@@ -2124,7 +1242,7 @@ Size2i DisplayServerOSX::screen_get_size(int p_screen) const {
NSArray *screenArray = [NSScreen screens];
if ((NSUInteger)p_screen < [screenArray count]) {
- // Note: Use frame to get the whole screen size
+ // Note: Use frame to get the whole screen size.
NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
return Size2i(nsrect.size.width, nsrect.size.height) * screen_get_max_scale();
}
@@ -2254,56 +1372,6 @@ void DisplayServerOSX::show_window(WindowID p_id) {
}
}
-void DisplayServerOSX::_send_window_event(const WindowData &wd, WindowEvent p_event) {
- _THREAD_SAFE_METHOD_
-
- if (!wd.event_callback.is_null()) {
- Variant event = int(p_event);
- Variant *eventp = &event;
- Variant ret;
- Callable::CallError ce;
- wd.event_callback.call((const Variant **)&eventp, 1, ret, ce);
- }
-}
-
-DisplayServerOSX::WindowID DisplayServerOSX::_find_window_id(id p_window) {
- for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
- if (E->get().window_object == p_window) {
- return E->key();
- }
- }
- return INVALID_WINDOW_ID;
-}
-
-void DisplayServerOSX::_update_window(WindowData p_wd) {
- bool borderless_full = false;
-
- if (p_wd.borderless) {
- NSRect frameRect = [p_wd.window_object frame];
- NSRect screenRect = [[p_wd.window_object screen] frame];
-
- // Check if our window covers up the screen
- if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
- frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
- borderless_full = true;
- }
- }
-
- if (borderless_full) {
- // If the window covers up the screen set the level to above the main menu and hide on deactivate
- [p_wd.window_object setLevel:NSMainMenuWindowLevel + 1];
- [p_wd.window_object setHidesOnDeactivate:YES];
- } else {
- // Reset these when our window is not a borderless window that covers up the screen
- if (p_wd.on_top && !p_wd.fullscreen) {
- [p_wd.window_object setLevel:NSFloatingWindowLevel];
- } else {
- [p_wd.window_object setLevel:NSNormalWindowLevel];
- }
- [p_wd.window_object setHidesOnDeactivate:NO];
- }
-}
-
void DisplayServerOSX::delete_sub_window(WindowID p_id) {
_THREAD_SAFE_METHOD_
@@ -2316,24 +1384,6 @@ void DisplayServerOSX::delete_sub_window(WindowID p_id) {
[wd.window_object close];
}
-void DisplayServerOSX::window_set_title(const String &p_title, WindowID p_window) {
- _THREAD_SAFE_METHOD_
-
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
-
- [wd.window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
-}
-
-void DisplayServerOSX::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
- _THREAD_SAFE_METHOD_
-
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
-
- wd.mpath = p_region;
-}
-
void DisplayServerOSX::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
_THREAD_SAFE_METHOD_
@@ -2372,6 +1422,24 @@ void DisplayServerOSX::window_set_drop_files_callback(const Callable &p_callable
wd.drop_files_callback = p_callable;
}
+void DisplayServerOSX::window_set_title(const String &p_title, WindowID p_window) {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND(!windows.has(p_window));
+ WindowData &wd = windows[p_window];
+
+ [wd.window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
+}
+
+void DisplayServerOSX::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND(!windows.has(p_window));
+ WindowData &wd = windows[p_window];
+
+ wd.mpath = p_region;
+}
+
int DisplayServerOSX::window_get_current_screen(WindowID p_window) const {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND_V(!windows.has(p_window), -1);
@@ -2403,39 +1471,6 @@ void DisplayServerOSX::window_set_current_screen(int p_screen, WindowID p_window
}
}
-void DisplayServerOSX::window_set_transient(WindowID p_window, WindowID p_parent) {
- _THREAD_SAFE_METHOD_
- ERR_FAIL_COND(p_window == p_parent);
-
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd_window = windows[p_window];
-
- ERR_FAIL_COND(wd_window.transient_parent == p_parent);
-
- ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
- if (p_parent == INVALID_WINDOW_ID) {
- //remove transient
- ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
- ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
-
- WindowData &wd_parent = windows[wd_window.transient_parent];
-
- wd_window.transient_parent = INVALID_WINDOW_ID;
- wd_parent.transient_children.erase(p_window);
-
- [wd_window.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
- } else {
- ERR_FAIL_COND(!windows.has(p_parent));
- ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
- WindowData &wd_parent = windows[p_parent];
-
- wd_window.transient_parent = p_parent;
- wd_parent.transient_children.insert(p_window);
-
- [wd_window.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
- }
-}
-
Point2i DisplayServerOSX::window_get_position(WindowID p_window) const {
_THREAD_SAFE_METHOD_
@@ -2447,14 +1482,14 @@ Point2i DisplayServerOSX::window_get_position(WindowID p_window) const {
const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
Point2i pos;
- // Return the position of the top-left corner, for OS X the y starts at the bottom
+ // Return the position of the top-left corner, for OS X the y starts at the bottom.
const float scale = screen_get_max_scale();
pos.x = nsrect.origin.x;
pos.y = (nsrect.origin.y + nsrect.size.height);
pos *= scale;
pos -= _get_screens_origin();
// OS X native y-coordinate relative to _get_screens_origin() is negative,
- // Godot expects a positive value
+ // Godot expects a positive value.
pos.y *= -1;
return pos;
}
@@ -2467,7 +1502,7 @@ void DisplayServerOSX::window_set_position(const Point2i &p_position, WindowID p
Point2i position = p_position;
// OS X native y-coordinate relative to _get_screens_origin() is negative,
- // Godot passes a positive value
+ // Godot passes a positive value.
position.y *= -1;
position += _get_screens_origin();
position /= screen_get_max_scale();
@@ -2483,8 +1518,41 @@ void DisplayServerOSX::window_set_position(const Point2i &p_position, WindowID p
[wd.window_object setFrameTopLeftPoint:NSMakePoint(position.x - offset.x, position.y - offset.y)];
- _update_window(wd);
- _ALLOW_DISCARD_ _get_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
+ _update_window_style(wd);
+ update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
+}
+
+void DisplayServerOSX::window_set_transient(WindowID p_window, WindowID p_parent) {
+ _THREAD_SAFE_METHOD_
+ ERR_FAIL_COND(p_window == p_parent);
+
+ ERR_FAIL_COND(!windows.has(p_window));
+ WindowData &wd_window = windows[p_window];
+
+ ERR_FAIL_COND(wd_window.transient_parent == p_parent);
+
+ ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
+ if (p_parent == INVALID_WINDOW_ID) {
+ // Remove transient.
+ ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
+ ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
+
+ WindowData &wd_parent = windows[wd_window.transient_parent];
+
+ wd_window.transient_parent = INVALID_WINDOW_ID;
+ wd_parent.transient_children.erase(p_window);
+
+ [wd_window.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
+ } else {
+ ERR_FAIL_COND(!windows.has(p_parent));
+ ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
+ WindowData &wd_parent = windows[p_parent];
+
+ wd_window.transient_parent = p_parent;
+ wd_parent.transient_children.insert(p_window);
+
+ [wd_window.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
+ }
}
void DisplayServerOSX::window_set_max_size(const Size2i p_size, WindowID p_window) {
@@ -2565,7 +1633,7 @@ void DisplayServerOSX::window_set_size(const Size2i p_size, WindowID p_window) {
[wd.window_object setFrame:new_frame display:YES];
- _update_window(wd);
+ _update_window_style(wd);
}
Size2i DisplayServerOSX::window_get_size(WindowID p_window) const {
@@ -2585,73 +1653,6 @@ Size2i DisplayServerOSX::window_get_real_size(WindowID p_window) const {
return Size2i(frame.size.width, frame.size.height) * screen_get_max_scale();
}
-bool DisplayServerOSX::window_is_maximize_allowed(WindowID p_window) const {
- return true;
-}
-
-void DisplayServerOSX::_set_window_per_pixel_transparency_enabled(bool p_enabled, WindowID p_window) {
- ERR_FAIL_COND(!windows.has(p_window));
- WindowData &wd = windows[p_window];
-
- if (!OS_OSX::get_singleton()->is_layered_allowed()) {
- return;
- }
- if (wd.layered_window != p_enabled) {
- if (p_enabled) {
- [wd.window_object setBackgroundColor:[NSColor clearColor]];
- [wd.window_object setOpaque:NO];
- [wd.window_object setHasShadow:NO];
- CALayer *layer = [wd.window_view layer];
- if (layer) {
- [layer setOpaque:NO];
- }
-#if defined(VULKAN_ENABLED)
- if (context_vulkan) {
- //TODO - implement transparency for Vulkan
- }
-#endif
-#if defined(GLES3_ENABLED)
- if (gl_manager) {
- //TODO - reimplement OpenGLES
- }
-#endif
- wd.layered_window = true;
- } else {
- [wd.window_object setBackgroundColor:[NSColor colorWithCalibratedWhite:1 alpha:1]];
- [wd.window_object setOpaque:YES];
- [wd.window_object setHasShadow:YES];
- CALayer *layer = [wd.window_view layer];
- if (layer) {
- [layer setOpaque:YES];
- }
-#if defined(VULKAN_ENABLED)
- if (context_vulkan) {
- //TODO - implement transparency for Vulkan
- }
-#endif
-#if defined(GLES3_ENABLED)
- if (gl_manager) {
- //TODO - reimplement OpenGLES
- }
-#endif
- wd.layered_window = false;
- }
-#if defined(GLES3_ENABLED)
- if (gl_manager) {
- //TODO - reimplement OpenGLES
- }
-#endif
-#if defined(VULKAN_ENABLED)
- if (context_vulkan) {
- //TODO - implement transparency for Vulkan
- }
-#endif
- NSRect frameRect = [wd.window_object frame];
- [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:YES];
- [wd.window_object setFrame:frameRect display:YES];
- }
-}
-
void DisplayServerOSX::window_set_mode(WindowMode p_mode, WindowID p_window) {
_THREAD_SAFE_METHOD_
@@ -2660,12 +1661,12 @@ void DisplayServerOSX::window_set_mode(WindowMode p_mode, WindowID p_window) {
WindowMode old_mode = window_get_mode(p_window);
if (old_mode == p_mode) {
- return; // do nothing
+ return; // Do nothing.
}
switch (old_mode) {
case WINDOW_MODE_WINDOWED: {
- //do nothing
+ // Do nothing.
} break;
case WINDOW_MODE_MINIMIZED: {
[wd.window_object deminiaturize:nil];
@@ -2673,10 +1674,8 @@ void DisplayServerOSX::window_set_mode(WindowMode p_mode, WindowID p_window) {
case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
case WINDOW_MODE_FULLSCREEN: {
[wd.window_object setLevel:NSNormalWindowLevel];
- if (wd.layered_window) {
- _set_window_per_pixel_transparency_enabled(true, p_window);
- }
- if (wd.resize_disabled) { //restore resize disabled
+ _set_window_per_pixel_transparency_enabled(true, p_window);
+ if (wd.resize_disabled) { // Restore resize disabled.
[wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
}
if (wd.min_size != Size2i()) {
@@ -2699,17 +1698,17 @@ void DisplayServerOSX::window_set_mode(WindowMode p_mode, WindowID p_window) {
switch (p_mode) {
case WINDOW_MODE_WINDOWED: {
- //do nothing
+ // Do nothing.
} break;
case WINDOW_MODE_MINIMIZED: {
[wd.window_object performMiniaturize:nil];
} break;
case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
case WINDOW_MODE_FULLSCREEN: {
- if (wd.layered_window)
- _set_window_per_pixel_transparency_enabled(false, p_window);
- if (wd.resize_disabled) //fullscreen window should be resizable to work
+ _set_window_per_pixel_transparency_enabled(false, p_window);
+ if (wd.resize_disabled) { // Fullscreen window should be resizable to work.
[wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
+ }
[wd.window_object setContentMinSize:NSMakeSize(0, 0)];
[wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
[wd.window_object toggleFullScreen:nil];
@@ -2729,7 +1728,7 @@ DisplayServer::WindowMode DisplayServerOSX::window_get_mode(WindowID p_window) c
ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
const WindowData &wd = windows[p_window];
- if (wd.fullscreen) { //if fullscreen, it's not in another mode
+ if (wd.fullscreen) { // If fullscreen, it's not in another mode.
return WINDOW_MODE_FULLSCREEN;
}
if ([wd.window_object isZoomed] && !wd.resize_disabled) {
@@ -2741,10 +1740,14 @@ DisplayServer::WindowMode DisplayServerOSX::window_get_mode(WindowID p_window) c
}
}
- // all other discarded, return windowed.
+ // All other discarded, return windowed.
return WINDOW_MODE_WINDOWED;
}
+bool DisplayServerOSX::window_is_maximize_allowed(WindowID p_window) const {
+ return true;
+}
+
void DisplayServerOSX::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
_THREAD_SAFE_METHOD_
@@ -2754,7 +1757,7 @@ void DisplayServerOSX::window_set_flag(WindowFlags p_flag, bool p_enabled, Windo
switch (p_flag) {
case WINDOW_FLAG_RESIZE_DISABLED: {
wd.resize_disabled = p_enabled;
- if (wd.fullscreen) { //fullscreen window should be resizable, style will be applied on exiting fs
+ if (wd.fullscreen) { // Fullscreen window should be resizable, style will be applied on exiting fullscreen.
return;
}
if (p_enabled) {
@@ -2764,7 +1767,7 @@ void DisplayServerOSX::window_set_flag(WindowFlags p_flag, bool p_enabled, Windo
}
} break;
case WINDOW_FLAG_BORDERLESS: {
- // OrderOut prevents a lose focus bug with the window
+ // OrderOut prevents a lose focus bug with the window.
if ([wd.window_object isVisible]) {
[wd.window_object orderOut:nil];
}
@@ -2772,15 +1775,14 @@ void DisplayServerOSX::window_set_flag(WindowFlags p_flag, bool p_enabled, Windo
if (p_enabled) {
[wd.window_object setStyleMask:NSWindowStyleMaskBorderless];
} else {
- if (wd.layered_window)
- _set_window_per_pixel_transparency_enabled(false, p_window);
+ _set_window_per_pixel_transparency_enabled(false, p_window);
[wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
- // Force update of the window styles
+ // Force update of the window styles.
NSRect frameRect = [wd.window_object frame];
[wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
[wd.window_object setFrame:frameRect display:NO];
}
- _update_window(wd);
+ _update_window_style(wd);
if ([wd.window_object isVisible]) {
if (wd.no_focus) {
[wd.window_object orderFront:nil];
@@ -2801,9 +1803,8 @@ void DisplayServerOSX::window_set_flag(WindowFlags p_flag, bool p_enabled, Windo
}
} break;
case WINDOW_FLAG_TRANSPARENT: {
- wd.layered_window = p_enabled;
if (p_enabled) {
- [wd.window_object setStyleMask:NSWindowStyleMaskBorderless]; // force borderless
+ [wd.window_object setStyleMask:NSWindowStyleMaskBorderless]; // Force borderless.
} else if (!wd.borderless) {
[wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
}
@@ -2906,28 +1907,103 @@ void DisplayServerOSX::window_set_ime_position(const Point2i &p_pos, WindowID p_
wd.im_position = p_pos;
}
-bool DisplayServerOSX::get_swap_cancel_ok() {
- return false;
+DisplayServer::WindowID DisplayServerOSX::get_window_at_screen_position(const Point2i &p_position) const {
+ Point2i position = p_position;
+ position.y *= -1;
+ position += _get_screens_origin();
+ position /= screen_get_max_scale();
+
+ NSInteger wnum = [NSWindow windowNumberAtPoint:NSMakePoint(position.x, position.y) belowWindowWithWindowNumber:0 /*topmost*/];
+ for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
+ if ([E->get().window_object windowNumber] == wnum) {
+ return E->key();
+ }
+ }
+ return INVALID_WINDOW_ID;
}
-void DisplayServerOSX::cursor_set_shape(CursorShape p_shape) {
+int64_t DisplayServerOSX::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
+ ERR_FAIL_COND_V(!windows.has(p_window), 0);
+ switch (p_handle_type) {
+ case DISPLAY_HANDLE: {
+ return 0; // Not supported.
+ }
+ case WINDOW_HANDLE: {
+ return (int64_t)windows[p_window].window_object;
+ }
+ case WINDOW_VIEW: {
+ return (int64_t)windows[p_window].window_view;
+ }
+ default: {
+ return 0;
+ }
+ }
+}
+
+void DisplayServerOSX::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
_THREAD_SAFE_METHOD_
- ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
+ ERR_FAIL_COND(!windows.has(p_window));
+ windows[p_window].instance_id = p_instance;
+}
- if (cursor_shape == p_shape) {
- return;
+ObjectID DisplayServerOSX::window_get_attached_instance_id(WindowID p_window) const {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
+ return windows[p_window].instance_id;
+}
+
+void DisplayServerOSX::gl_window_make_current(DisplayServer::WindowID p_window_id) {
+#if defined(GLES3_ENABLED)
+ gl_manager->window_make_current(p_window_id);
+#endif
+}
+
+void DisplayServerOSX::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
+ _THREAD_SAFE_METHOD_
+#if defined(GLES3_ENABLED)
+ if (gl_manager) {
+ gl_manager->set_use_vsync(p_vsync_mode);
}
+#endif
+#if defined(VULKAN_ENABLED)
+ if (context_vulkan) {
+ context_vulkan->set_vsync_mode(p_window, p_vsync_mode);
+ }
+#endif
+}
- if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
- cursor_shape = p_shape;
- return;
+DisplayServer::VSyncMode DisplayServerOSX::window_get_vsync_mode(WindowID p_window) const {
+ _THREAD_SAFE_METHOD_
+#if defined(GLES3_ENABLED)
+ if (gl_manager) {
+ return (gl_manager->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
+ }
+#endif
+#if defined(VULKAN_ENABLED)
+ if (context_vulkan) {
+ return context_vulkan->get_vsync_mode(p_window);
}
+#endif
+ return DisplayServer::VSYNC_ENABLED;
+}
+
+Point2i DisplayServerOSX::ime_get_selection() const {
+ return im_selection;
+}
+
+String DisplayServerOSX::ime_get_text() const {
+ return im_text;
+}
- if (cursors[p_shape] != nullptr) {
- [cursors[p_shape] set];
+void DisplayServerOSX::cursor_update_shape() {
+ _THREAD_SAFE_METHOD_
+
+ if (cursors[cursor_shape] != nullptr) {
+ [cursors[cursor_shape] set];
} else {
- switch (p_shape) {
+ switch (cursor_shape) {
case CURSOR_ARROW:
[[NSCursor arrowCursor] set];
break;
@@ -2956,16 +2032,16 @@ void DisplayServerOSX::cursor_set_shape(CursorShape p_shape) {
[[NSCursor operationNotAllowedCursor] set];
break;
case CURSOR_VSIZE:
- [_cursorFromSelector(@selector(_windowResizeNorthSouthCursor), @selector(resizeUpDownCursor)) set];
+ [_cursor_from_selector(@selector(_windowResizeNorthSouthCursor), @selector(resizeUpDownCursor)) set];
break;
case CURSOR_HSIZE:
- [_cursorFromSelector(@selector(_windowResizeEastWestCursor), @selector(resizeLeftRightCursor)) set];
+ [_cursor_from_selector(@selector(_windowResizeEastWestCursor), @selector(resizeLeftRightCursor)) set];
break;
case CURSOR_BDIAGSIZE:
- [_cursorFromSelector(@selector(_windowResizeNorthEastSouthWestCursor)) set];
+ [_cursor_from_selector(@selector(_windowResizeNorthEastSouthWestCursor)) set];
break;
case CURSOR_FDIAGSIZE:
- [_cursorFromSelector(@selector(_windowResizeNorthWestSouthEastCursor)) set];
+ [_cursor_from_selector(@selector(_windowResizeNorthWestSouthEastCursor)) set];
break;
case CURSOR_MOVE:
[[NSCursor arrowCursor] set];
@@ -2977,14 +2053,30 @@ void DisplayServerOSX::cursor_set_shape(CursorShape p_shape) {
[[NSCursor resizeLeftRightCursor] set];
break;
case CURSOR_HELP:
- [_cursorFromSelector(@selector(_helpCursor)) set];
+ [_cursor_from_selector(@selector(_helpCursor)) set];
break;
default: {
}
}
}
+}
+
+void DisplayServerOSX::cursor_set_shape(CursorShape p_shape) {
+ _THREAD_SAFE_METHOD_
+
+ ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
+
+ if (cursor_shape == p_shape) {
+ return;
+ }
cursor_shape = p_shape;
+
+ if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
+ return;
+ }
+
+ cursor_update_shape();
}
DisplayServerOSX::CursorShape DisplayServerOSX::cursor_get_shape() const {
@@ -3079,7 +2171,6 @@ void DisplayServerOSX::cursor_set_custom_image(const RES &p_cursor, CursorShape
NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
- [cursors[p_shape] release];
cursors[p_shape] = cursor;
Vector<Variant> params;
@@ -3092,94 +2183,32 @@ void DisplayServerOSX::cursor_set_custom_image(const RES &p_cursor, CursorShape
[cursor set];
}
}
-
- [imgrep release];
- [nsimage release];
} else {
- // Reset to default system cursor
+ // Reset to default system cursor.
if (cursors[p_shape] != nullptr) {
- [cursors[p_shape] release];
cursors[p_shape] = nullptr;
}
- CursorShape c = cursor_shape;
- cursor_shape = CURSOR_MAX;
- cursor_set_shape(c);
+ cursor_update_shape();
cursors_cache.erase(p_shape);
}
}
-struct LayoutInfo {
- String name;
- String code;
-};
-
-static Vector<LayoutInfo> kbd_layouts;
-static int current_layout = 0;
-static bool keyboard_layout_dirty = true;
-static void keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
- kbd_layouts.clear();
- current_layout = 0;
- keyboard_layout_dirty = true;
-}
-
-void _update_keyboard_layouts() {
- @autoreleasepool {
- TISInputSourceRef cur_source = TISCopyCurrentKeyboardInputSource();
- NSString *cur_name = (NSString *)TISGetInputSourceProperty(cur_source, kTISPropertyLocalizedName);
- CFRelease(cur_source);
-
- // Enum IME layouts
- NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
- NSArray *list_ime = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_ime, false);
- for (NSUInteger i = 0; i < [list_ime count]; i++) {
- LayoutInfo ly;
- NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
- ly.name.parse_utf8([name UTF8String]);
-
- NSArray *langs = (NSArray *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyInputSourceLanguages);
- ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
- kbd_layouts.push_back(ly);
-
- if ([name isEqualToString:cur_name]) {
- current_layout = kbd_layouts.size() - 1;
- }
- }
- [list_ime release];
-
- // Enum plain keyboard layouts
- NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
- NSArray *list_kbd = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_kbd, false);
- for (NSUInteger i = 0; i < [list_kbd count]; i++) {
- LayoutInfo ly;
- NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
- ly.name.parse_utf8([name UTF8String]);
-
- NSArray *langs = (NSArray *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyInputSourceLanguages);
- ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
- kbd_layouts.push_back(ly);
-
- if ([name isEqualToString:cur_name]) {
- current_layout = kbd_layouts.size() - 1;
- }
- }
- [list_kbd release];
- }
-
- keyboard_layout_dirty = false;
+bool DisplayServerOSX::get_swap_cancel_ok() {
+ return false;
}
int DisplayServerOSX::keyboard_get_layout_count() const {
if (keyboard_layout_dirty) {
- _update_keyboard_layouts();
+ const_cast<DisplayServerOSX *>(this)->_update_keyboard_layouts();
}
return kbd_layouts.size();
}
void DisplayServerOSX::keyboard_set_current_layout(int p_index) {
if (keyboard_layout_dirty) {
- _update_keyboard_layouts();
+ const_cast<DisplayServerOSX *>(this)->_update_keyboard_layouts();
}
ERR_FAIL_INDEX(p_index, kbd_layouts.size());
@@ -3187,31 +2216,29 @@ void DisplayServerOSX::keyboard_set_current_layout(int p_index) {
NSString *cur_name = [NSString stringWithUTF8String:kbd_layouts[p_index].name.utf8().get_data()];
NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
- NSArray *list_kbd = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_kbd, false);
+ NSArray *list_kbd = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_kbd, false);
for (NSUInteger i = 0; i < [list_kbd count]; i++) {
- NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
+ NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
if ([name isEqualToString:cur_name]) {
- TISSelectInputSource((TISInputSourceRef)[list_kbd objectAtIndex:i]);
+ TISSelectInputSource((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i]);
break;
}
}
- [list_kbd release];
NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
- NSArray *list_ime = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_ime, false);
+ NSArray *list_ime = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_ime, false);
for (NSUInteger i = 0; i < [list_ime count]; i++) {
- NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
+ NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
if ([name isEqualToString:cur_name]) {
- TISSelectInputSource((TISInputSourceRef)[list_ime objectAtIndex:i]);
+ TISSelectInputSource((__bridge TISInputSourceRef)[list_ime objectAtIndex:i]);
break;
}
}
- [list_ime release];
}
int DisplayServerOSX::keyboard_get_current_layout() const {
if (keyboard_layout_dirty) {
- _update_keyboard_layouts();
+ const_cast<DisplayServerOSX *>(this)->_update_keyboard_layouts();
}
return current_layout;
@@ -3219,7 +2246,7 @@ int DisplayServerOSX::keyboard_get_current_layout() const {
String DisplayServerOSX::keyboard_get_layout_language(int p_index) const {
if (keyboard_layout_dirty) {
- _update_keyboard_layouts();
+ const_cast<DisplayServerOSX *>(this)->_update_keyboard_layouts();
}
ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
@@ -3228,7 +2255,7 @@ String DisplayServerOSX::keyboard_get_layout_language(int p_index) const {
String DisplayServerOSX::keyboard_get_layout_name(int p_index) const {
if (keyboard_layout_dirty) {
- _update_keyboard_layouts();
+ const_cast<DisplayServerOSX *>(this)->_update_keyboard_layouts();
}
ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
@@ -3242,124 +2269,8 @@ Key DisplayServerOSX::keyboard_get_keycode_from_physical(Key p_keycode) const {
Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
- unsigned int osx_keycode = unmapKey((Key)keycode_no_mod);
- return (Key)(remapKey(osx_keycode, 0) | modifiers);
-}
-
-void DisplayServerOSX::_push_input(const Ref<InputEvent> &p_event) {
- Ref<InputEvent> ev = p_event;
- Input::get_singleton()->parse_input_event(ev);
-}
-
-void DisplayServerOSX::_release_pressed_events() {
- _THREAD_SAFE_METHOD_
- if (Input::get_singleton()) {
- Input::get_singleton()->release_pressed_events();
- }
-}
-
-NSMenu *DisplayServerOSX::_get_dock_menu() const {
- return dock_menu;
-}
-
-void DisplayServerOSX::_menu_callback(id p_sender) {
- if (![p_sender representedObject]) {
- return;
- }
-
- GlobalMenuItem *value = [p_sender representedObject];
-
- if (value) {
- if (value->checkable) {
- if ([p_sender state] == NSControlStateValueOff) {
- [p_sender setState:NSControlStateValueOn];
- } else {
- [p_sender setState:NSControlStateValueOff];
- }
- }
-
- if (value->callback != Callable()) {
- Variant tag = value->meta;
- Variant *tagp = &tag;
- Variant ret;
- Callable::CallError ce;
- value->callback.call((const Variant **)&tagp, 1, ret, ce);
- }
- }
-}
-
-void DisplayServerOSX::_send_event(NSEvent *p_event) {
- // special case handling of command-period, which is traditionally a special
- // shortcut in macOS and doesn't arrive at our regular keyDown handler.
- if ([p_event type] == NSEventTypeKeyDown) {
- if (([p_event modifierFlags] & NSEventModifierFlagCommand) && [p_event keyCode] == 0x2f) {
- Ref<InputEventKey> k;
- k.instantiate();
-
- _get_key_modifier_state([p_event modifierFlags], k);
- k->set_window_id(DisplayServerOSX::INVALID_WINDOW_ID);
- k->set_pressed(true);
- k->set_keycode(Key::PERIOD);
- k->set_physical_keycode(Key::PERIOD);
- k->set_echo([p_event isARepeat]);
-
- Input::get_singleton()->parse_input_event(k);
- }
- }
-}
-
-void DisplayServerOSX::_process_key_events() {
- Ref<InputEventKey> k;
- for (int i = 0; i < key_event_pos; i++) {
- const KeyEvent &ke = key_event_buffer[i];
- if (ke.raw) {
- // Non IME input - no composite characters, pass events as is
- k.instantiate();
-
- k->set_window_id(ke.window_id);
- _get_key_modifier_state(ke.osx_state, k);
- k->set_pressed(ke.pressed);
- k->set_echo(ke.echo);
- k->set_keycode(ke.keycode);
- k->set_physical_keycode((Key)ke.physical_keycode);
- k->set_unicode(ke.unicode);
-
- _push_input(k);
- } else {
- // IME input
- if ((i == 0 && ke.keycode == Key::NONE) || (i > 0 && key_event_buffer[i - 1].keycode == Key::NONE)) {
- k.instantiate();
-
- k->set_window_id(ke.window_id);
- _get_key_modifier_state(ke.osx_state, k);
- k->set_pressed(ke.pressed);
- k->set_echo(ke.echo);
- k->set_keycode(Key::NONE);
- k->set_physical_keycode(Key::NONE);
- k->set_unicode(ke.unicode);
-
- _push_input(k);
- }
- if (ke.keycode != Key::NONE) {
- k.instantiate();
-
- k->set_window_id(ke.window_id);
- _get_key_modifier_state(ke.osx_state, k);
- k->set_pressed(ke.pressed);
- k->set_echo(ke.echo);
- k->set_keycode(ke.keycode);
- k->set_physical_keycode((Key)ke.physical_keycode);
-
- if (i + 1 < key_event_pos && key_event_buffer[i + 1].keycode == Key::NONE) {
- k->set_unicode(key_event_buffer[i + 1].unicode);
- }
-
- _push_input(k);
- }
- }
- }
-
- key_event_pos = 0;
+ unsigned int osx_keycode = KeyMappingOSX::unmap_key((Key)keycode_no_mod);
+ return (Key)(KeyMappingOSX::remap_key(osx_keycode, 0) | modifiers);
}
void DisplayServerOSX::process_events() {
@@ -3387,8 +2298,8 @@ void DisplayServerOSX::process_events() {
for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
WindowData &wd = E->get();
if (wd.mpath.size() > 0) {
- const Vector2 mpos = _get_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
- if (Geometry2D::is_point_in_polygon(mpos, wd.mpath)) {
+ update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
+ if (Geometry2D::is_point_in_polygon(wd.mouse_pos, wd.mpath)) {
if ([wd.window_object ignoresMouseEvents]) {
[wd.window_object setIgnoresMouseEvents:NO];
}
@@ -3403,9 +2314,6 @@ void DisplayServerOSX::process_events() {
}
}
}
-
- [autoreleasePool drain];
- autoreleasePool = [[NSAutoreleasePool alloc] init];
}
void DisplayServerOSX::force_process_and_drop_events() {
@@ -3416,6 +2324,18 @@ void DisplayServerOSX::force_process_and_drop_events() {
drop_events = false;
}
+void DisplayServerOSX::release_rendering_thread() {
+}
+
+void DisplayServerOSX::make_rendering_thread() {
+}
+
+void DisplayServerOSX::swap_buffers() {
+#if defined(GLES3_ENABLED)
+ gl_manager->swap_buffers();
+#endif
+}
+
void DisplayServerOSX::set_native_icon(const String &p_filename) {
_THREAD_SAFE_METHOD_
@@ -3428,10 +2348,10 @@ void DisplayServerOSX::set_native_icon(const String &p_filename) {
f->get_buffer((uint8_t *)&data.write[0], len);
memdelete(f);
- NSData *icon_data = [[[NSData alloc] initWithBytes:&data.write[0] length:len] autorelease];
+ NSData *icon_data = [[NSData alloc] initWithBytes:&data.write[0] length:len];
ERR_FAIL_COND_MSG(!icon_data, "Error reading icon data.");
- NSImage *icon = [[[NSImage alloc] initWithData:icon_data] autorelease];
+ NSImage *icon = [[NSImage alloc] initWithData:icon_data];
ERR_FAIL_COND_MSG(!icon, "Error loading icon.");
[NSApp setApplicationIconImage:icon];
@@ -3474,112 +2394,6 @@ void DisplayServerOSX::set_icon(const Ref<Image> &p_icon) {
[nsimg addRepresentation:imgrep];
[NSApp setApplicationIconImage:nsimg];
-
- [imgrep release];
- [nsimg release];
-}
-
-void DisplayServerOSX::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
- _THREAD_SAFE_METHOD_
-#if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->swap_buffers();
- }
-#endif
-#if defined(VULKAN_ENABLED)
- if (context_vulkan) {
- context_vulkan->set_vsync_mode(p_window, p_vsync_mode);
- }
-#endif
-}
-
-DisplayServer::VSyncMode DisplayServerOSX::window_get_vsync_mode(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
-#if defined(GLES3_ENABLED)
- if (gl_manager) {
- return (gl_manager->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
- }
-#endif
-#if defined(VULKAN_ENABLED)
- if (context_vulkan) {
- return context_vulkan->get_vsync_mode(p_window);
- }
-#endif
- return DisplayServer::VSYNC_ENABLED;
-}
-
-Vector<String> DisplayServerOSX::get_rendering_drivers_func() {
- Vector<String> drivers;
-
-#if defined(VULKAN_ENABLED)
- drivers.push_back("vulkan");
-#endif
-#if defined(GLES3_ENABLED)
- drivers.push_back("opengl3");
-#endif
-
- return drivers;
-}
-
-void DisplayServerOSX::gl_window_make_current(DisplayServer::WindowID p_window_id) {
-#if defined(GLES3_ENABLED)
- gl_manager->window_make_current(p_window_id);
-#endif
-}
-
-Point2i DisplayServerOSX::ime_get_selection() const {
- return im_selection;
-}
-
-String DisplayServerOSX::ime_get_text() const {
- return im_text;
-}
-
-DisplayServer::WindowID DisplayServerOSX::get_window_at_screen_position(const Point2i &p_position) const {
- Point2i position = p_position;
- position.y *= -1;
- position += _get_screens_origin();
- position /= screen_get_max_scale();
-
- NSInteger wnum = [NSWindow windowNumberAtPoint:NSMakePoint(position.x, position.y) belowWindowWithWindowNumber:0 /*topmost*/];
- for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
- if ([E->get().window_object windowNumber] == wnum) {
- return E->key();
- }
- }
- return INVALID_WINDOW_ID;
-}
-
-int64_t DisplayServerOSX::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
- ERR_FAIL_COND_V(!windows.has(p_window), 0);
- switch (p_handle_type) {
- case DISPLAY_HANDLE: {
- return 0; // Not supported.
- }
- case WINDOW_HANDLE: {
- return (int64_t)windows[p_window].window_object;
- }
- case WINDOW_VIEW: {
- return (int64_t)windows[p_window].window_view;
- }
- default: {
- return 0;
- }
- }
-}
-
-void DisplayServerOSX::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
- _THREAD_SAFE_METHOD_
-
- ERR_FAIL_COND(!windows.has(p_window));
- windows[p_window].instance_id = p_instance;
-}
-
-ObjectID DisplayServerOSX::window_get_attached_instance_id(WindowID p_window) const {
- _THREAD_SAFE_METHOD_
-
- ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
- return windows[p_window].instance_id;
}
DisplayServer *DisplayServerOSX::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
@@ -3590,179 +2404,48 @@ DisplayServer *DisplayServerOSX::create_func(const String &p_rendering_driver, W
return ds;
}
-DisplayServerOSX::WindowID DisplayServerOSX::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, const Rect2i &p_rect) {
- WindowID id;
- const float scale = screen_get_max_scale();
- {
- WindowData wd;
-
- wd.window_delegate = [[GodotWindowDelegate alloc] init];
- ERR_FAIL_COND_V_MSG(wd.window_delegate == nil, INVALID_WINDOW_ID, "Can't create a window delegate");
- [wd.window_delegate setWindowID:window_id_counter];
-
- Point2i position = p_rect.position;
- // OS X native y-coordinate relative to _get_screens_origin() is negative,
- // Godot passes a positive value
- position.y *= -1;
- position += _get_screens_origin();
-
- // initWithContentRect uses bottom-left corner of the window’s frame as origin.
- wd.window_object = [[GodotWindow alloc]
- initWithContentRect:NSMakeRect(position.x / scale, (position.y - p_rect.size.height) / scale, p_rect.size.width / scale, p_rect.size.height / scale)
- styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
- backing:NSBackingStoreBuffered
- defer:NO];
- ERR_FAIL_COND_V_MSG(wd.window_object == nil, INVALID_WINDOW_ID, "Can't create a window");
-
- wd.window_view = [[GodotContentView alloc] init];
- ERR_FAIL_COND_V_MSG(wd.window_view == nil, INVALID_WINDOW_ID, "Can't create a window view");
- [wd.window_view setWindowID:window_id_counter];
- [wd.window_view setWantsLayer:TRUE];
-
- [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
- [wd.window_object setContentView:wd.window_view];
- [wd.window_object setDelegate:wd.window_delegate];
- [wd.window_object setAcceptsMouseMovedEvents:YES];
- [wd.window_object setRestorable:NO];
- [wd.window_object setColorSpace:[NSColorSpace sRGBColorSpace]];
-
- if ([wd.window_object respondsToSelector:@selector(setTabbingMode:)]) {
- [wd.window_object setTabbingMode:NSWindowTabbingModeDisallowed];
- }
-
- CALayer *layer = [wd.window_view layer];
- if (layer) {
- layer.contentsScale = scale;
- }
+Vector<String> DisplayServerOSX::get_rendering_drivers_func() {
+ Vector<String> drivers;
#if defined(VULKAN_ENABLED)
- if (context_vulkan) {
- Error err = context_vulkan->window_create(window_id_counter, p_vsync_mode, wd.window_view, p_rect.size.width, p_rect.size.height);
- ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan context");
- }
-#endif
-#if defined(GLES3_ENABLED)
- if (gl_manager) {
- Error err = gl_manager->window_create(window_id_counter, wd.window_view, p_rect.size.width, p_rect.size.height);
- ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context");
- }
+ drivers.push_back("vulkan");
#endif
- id = window_id_counter++;
- windows[id] = wd;
- }
-
- WindowData &wd = windows[id];
- window_set_mode(p_mode, id);
-
- const NSRect contentRect = [wd.window_view frame];
- wd.size.width = contentRect.size.width * scale;
- wd.size.height = contentRect.size.height * scale;
-
- CALayer *layer = [wd.window_view layer];
- if (layer) {
- layer.contentsScale = scale;
- }
-
#if defined(GLES3_ENABLED)
- if (gl_manager) {
- gl_manager->window_resize(id, wd.size.width, wd.size.height);
- }
-#endif
-#if defined(VULKAN_ENABLED)
- if (context_vulkan) {
- context_vulkan->window_resize(id, wd.size.width, wd.size.height);
- }
+ drivers.push_back("opengl3");
#endif
- return id;
-}
-
-void DisplayServerOSX::_dispatch_input_events(const Ref<InputEvent> &p_event) {
- ((DisplayServerOSX *)(get_singleton()))->_dispatch_input_event(p_event);
-}
-
-void DisplayServerOSX::_dispatch_input_event(const Ref<InputEvent> &p_event) {
- _THREAD_SAFE_METHOD_
- if (!in_dispatch_input_event) {
- in_dispatch_input_event = true;
-
- Variant ev = p_event;
- Variant *evp = &ev;
- Variant ret;
- Callable::CallError ce;
-
- Ref<InputEventFromWindow> event_from_window = p_event;
- if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
- //send to a window
- if (windows.has(event_from_window->get_window_id())) {
- Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
- if (callable.is_null()) {
- return;
- }
- callable.call((const Variant **)&evp, 1, ret, ce);
- }
- } else {
- //send to all windows
- for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
- Callable callable = E->get().input_event_callback;
- if (callable.is_null()) {
- continue;
- }
- callable.call((const Variant **)&evp, 1, ret, ce);
- }
- }
-
- in_dispatch_input_event = false;
- }
-}
-
-void DisplayServerOSX::release_rendering_thread() {
-}
-
-void DisplayServerOSX::make_rendering_thread() {
+ return drivers;
}
-void DisplayServerOSX::swap_buffers() {
-#if defined(GLES3_ENABLED)
- gl_manager->swap_buffers();
-#endif
+void DisplayServerOSX::register_osx_driver() {
+ register_create_function("osx", create_func, get_rendering_drivers_func);
}
DisplayServerOSX::DisplayServerOSX(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
r_error = OK;
- drop_events = false;
memset(cursors, 0, sizeof(cursors));
- cursor_shape = CURSOR_ARROW;
-
- key_event_pos = 0;
- mouse_mode = MOUSE_MODE_VISIBLE;
- autoreleasePool = [[NSAutoreleasePool alloc] init];
+ event_source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
+ ERR_FAIL_COND(!event_source);
- eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
- ERR_FAIL_COND(!eventSource);
-
- CGEventSourceSetLocalEventsSuppressionInterval(eventSource, 0.0);
-
- keyboard_layout_dirty = true;
- displays_arrangement_dirty = true;
+ CGEventSourceSetLocalEventsSuppressionInterval(event_source, 0.0);
int screen_count = get_screen_count();
for (int i = 0; i < screen_count; i++) {
display_max_scale = fmax(display_max_scale, screen_get_scale(i));
}
- // Register to be notified on keyboard layout changes
+ // Register to be notified on keyboard layout changes.
CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
- nullptr, keyboard_layout_changed,
+ nullptr, _keyboard_layout_changed,
kTISNotifySelectedKeyboardInputSourceChanged, nullptr,
CFNotificationSuspensionBehaviorDeliverImmediately);
- // Register to be notified on displays arrangement changes
- CGDisplayRegisterReconfigurationCallback(displays_arrangement_changed, nullptr);
+ // Register to be notified on displays arrangement changes.
+ CGDisplayRegisterReconfigurationCallback(_displays_arrangement_changed, nullptr);
NSMenuItem *menu_item;
NSString *title;
@@ -3772,11 +2455,11 @@ DisplayServerOSX::DisplayServerOSX(const String &p_rendering_driver, WindowMode
nsappname = [[NSProcessInfo processInfo] processName];
}
- // Setup Dock menu
+ // Setup Dock menu.
dock_menu = [[NSMenu alloc] initWithTitle:@"_dock"];
- // Setup Apple menu
- apple_menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
+ // Setup Apple menu.
+ apple_menu = [[NSMenu alloc] initWithTitle:@""];
title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
[apple_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
@@ -3786,7 +2469,6 @@ DisplayServerOSX::DisplayServerOSX(const String &p_rendering_driver, WindowMode
menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
[apple_menu setSubmenu:services forItem:menu_item];
[NSApp setServicesMenu:services];
- [services release];
[apple_menu addItem:[NSMenuItem separatorItem]];
@@ -3803,7 +2485,7 @@ DisplayServerOSX::DisplayServerOSX(const String &p_rendering_driver, WindowMode
title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
[apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
- // Add items to the menu bar
+ // Add items to the menu bar.
NSMenu *main_menu = [NSApp mainMenu];
menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
[main_menu setSubmenu:apple_menu forItem:menu_item];
@@ -3865,15 +2547,7 @@ DisplayServerOSX::DisplayServerOSX(const String &p_rendering_driver, WindowMode
}
DisplayServerOSX::~DisplayServerOSX() {
- if (dock_menu) {
- [dock_menu release];
- }
-
- for (Map<String, NSMenu *>::Element *E = submenu.front(); E; E = E->next()) {
- [E->get() release];
- }
-
- //destroy all windows
+ // Destroy all windows.
for (Map<WindowID, WindowData>::Element *E = windows.front(); E;) {
Map<WindowID, WindowData>::Element *F = E;
E = E->next();
@@ -3881,7 +2555,7 @@ DisplayServerOSX::~DisplayServerOSX() {
[F->get().window_object close];
}
- //destroy drivers
+ // Destroy drivers.
#if defined(GLES3_ENABLED)
if (gl_manager) {
memdelete(gl_manager);
@@ -3902,11 +2576,7 @@ DisplayServerOSX::~DisplayServerOSX() {
#endif
CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), nullptr, kTISNotifySelectedKeyboardInputSourceChanged, nullptr);
- CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, nullptr);
+ CGDisplayRemoveReconfigurationCallback(_displays_arrangement_changed, nullptr);
cursors_cache.clear();
}
-
-void DisplayServerOSX::register_osx_driver() {
- register_create_function("osx", create_func, get_rendering_drivers_func);
-}
diff --git a/platform/osx/gl_manager_osx.h b/platform/osx/gl_manager_osx_legacy.h
index 0229b672a2..b5a1b9dd98 100644
--- a/platform/osx/gl_manager_osx.h
+++ b/platform/osx/gl_manager_osx_legacy.h
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* gl_manager_osx.h */
+/* gl_manager_osx_legacy.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,8 +28,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef GL_MANAGER_OSX_H
-#define GL_MANAGER_OSX_H
+#ifndef GL_MANAGER_OSX_LEGACY_H
+#define GL_MANAGER_OSX_LEGACY_H
#if defined(OSX_ENABLED) && defined(GLES3_ENABLED)
@@ -50,29 +50,21 @@ public:
private:
struct GLWindow {
- GLWindow() { in_use = false; }
- bool in_use;
+ int width = 0;
+ int height = 0;
- DisplayServer::WindowID window_id;
- int width;
- int height;
-
- id window_view;
- NSOpenGLContext *context;
+ id window_view = nullptr;
+ NSOpenGLContext *context = nullptr;
};
- LocalVector<GLWindow> _windows;
-
- NSOpenGLContext *_shared_context = nullptr;
- GLWindow *_current_window;
+ Map<DisplayServer::WindowID, GLWindow> windows;
- Error _create_context(GLWindow &win);
- void _internal_set_current_window(GLWindow *p_win);
+ NSOpenGLContext *shared_context = nullptr;
+ DisplayServer::WindowID current_window = DisplayServer::INVALID_WINDOW_ID;
- GLWindow &get_window(unsigned int id) { return _windows[id]; }
- const GLWindow &get_window(unsigned int id) const { return _windows[id]; }
+ Error create_context(GLWindow &win);
- bool use_vsync;
+ bool use_vsync = false;
ContextType context_type;
public:
@@ -80,7 +72,6 @@ public:
void window_destroy(DisplayServer::WindowID p_window_id);
void window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height);
- // get directly from the cached GLWindow
int window_get_width(DisplayServer::WindowID p_window_id = 0);
int window_get_height(DisplayServer::WindowID p_window_id = 0);
@@ -91,6 +82,7 @@ public:
void window_make_current(DisplayServer::WindowID p_window_id);
void window_update(DisplayServer::WindowID p_window_id);
+ void window_set_per_pixel_transparency_enabled(DisplayServer::WindowID p_window_id, bool p_enabled);
Error initialize();
@@ -101,6 +93,5 @@ public:
~GLManager_OSX();
};
-#endif // defined(OSX_ENABLED) && defined(GLES3_ENABLED)
-
-#endif // GL_MANAGER_OSX_H
+#endif // OSX_ENABLED && GLES3_ENABLED
+#endif // GL_MANAGER_OSX_LEGACY_H
diff --git a/platform/osx/gl_manager_osx.mm b/platform/osx/gl_manager_osx_legacy.mm
index 3e70de8523..fbe64e32a3 100644
--- a/platform/osx/gl_manager_osx.mm
+++ b/platform/osx/gl_manager_osx_legacy.mm
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* gl_manager_osx.mm */
+/* gl_manager_osx_legacy.mm */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,7 +28,7 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "gl_manager_osx.h"
+#include "gl_manager_osx_legacy.h"
#ifdef OSX_ENABLED
#ifdef GLES3_ENABLED
@@ -36,7 +36,7 @@
#include <stdio.h>
#include <stdlib.h>
-Error GLManager_OSX::_create_context(GLWindow &win) {
+Error GLManager_OSX::create_context(GLWindow &win) {
NSOpenGLPixelFormatAttribute attributes[] = {
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAClosestPolicy,
@@ -50,10 +50,10 @@ Error GLManager_OSX::_create_context(GLWindow &win) {
NSOpenGLPixelFormat *pixel_format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
ERR_FAIL_COND_V(pixel_format == nil, ERR_CANT_CREATE);
- win.context = [[NSOpenGLContext alloc] initWithFormat:pixel_format shareContext:_shared_context];
+ win.context = [[NSOpenGLContext alloc] initWithFormat:pixel_format shareContext:shared_context];
ERR_FAIL_COND_V(win.context == nil, ERR_CANT_CREATE);
- if (_shared_context == nullptr) {
- _shared_context = win.context;
+ if (shared_context == nullptr) {
+ shared_context = win.context;
}
[win.context setView:win.window_view];
@@ -63,40 +63,27 @@ Error GLManager_OSX::_create_context(GLWindow &win) {
}
Error GLManager_OSX::window_create(DisplayServer::WindowID p_window_id, id p_view, int p_width, int p_height) {
- if (p_window_id >= (int)_windows.size()) {
- _windows.resize(p_window_id + 1);
- }
-
- GLWindow &win = _windows[p_window_id];
- win.in_use = true;
- win.window_id = p_window_id;
+ GLWindow win;
win.width = p_width;
win.height = p_height;
win.window_view = p_view;
- if (_create_context(win) != OK) {
- _windows.remove_at(_windows.size() - 1);
+ if (create_context(win) != OK) {
return FAILED;
}
- window_make_current(_windows.size() - 1);
+ windows[p_window_id] = win;
+ window_make_current(p_window_id);
return OK;
}
-void GLManager_OSX::_internal_set_current_window(GLWindow *p_win) {
- _current_window = p_win;
-}
-
void GLManager_OSX::window_resize(DisplayServer::WindowID p_window_id, int p_width, int p_height) {
- if (p_window_id == -1) {
+ if (!windows.has(p_window_id)) {
return;
}
- GLWindow &win = _windows[p_window_id];
- if (!win.in_use) {
- return;
- }
+ GLWindow &win = windows[p_window_id];
win.width = p_width;
win.height = p_height;
@@ -116,24 +103,37 @@ void GLManager_OSX::window_resize(DisplayServer::WindowID p_window_id, int p_wid
}
int GLManager_OSX::window_get_width(DisplayServer::WindowID p_window_id) {
- return get_window(p_window_id).width;
+ if (!windows.has(p_window_id)) {
+ return 0;
+ }
+
+ GLWindow &win = windows[p_window_id];
+ return win.width;
}
int GLManager_OSX::window_get_height(DisplayServer::WindowID p_window_id) {
- return get_window(p_window_id).height;
+ if (!windows.has(p_window_id)) {
+ return 0;
+ }
+
+ GLWindow &win = windows[p_window_id];
+ return win.height;
}
void GLManager_OSX::window_destroy(DisplayServer::WindowID p_window_id) {
- GLWindow &win = get_window(p_window_id);
- win.in_use = false;
+ if (!windows.has(p_window_id)) {
+ return;
+ }
- if (_current_window == &win) {
- _current_window = nullptr;
+ if (current_window == p_window_id) {
+ current_window = DisplayServer::INVALID_WINDOW_ID;
}
+
+ windows.erase(p_window_id);
}
void GLManager_OSX::release_current() {
- if (!_current_window) {
+ if (current_window == DisplayServer::INVALID_WINDOW_ID) {
return;
}
@@ -141,63 +141,59 @@ void GLManager_OSX::release_current() {
}
void GLManager_OSX::window_make_current(DisplayServer::WindowID p_window_id) {
- if (p_window_id == -1) {
- return;
- }
-
- GLWindow &win = _windows[p_window_id];
- if (!win.in_use) {
+ if (current_window == p_window_id) {
return;
}
-
- if (&win == _current_window) {
+ if (!windows.has(p_window_id)) {
return;
}
+ GLWindow &win = windows[p_window_id];
[win.context makeCurrentContext];
- _internal_set_current_window(&win);
+ current_window = p_window_id;
}
void GLManager_OSX::make_current() {
- if (!_current_window) {
+ if (current_window == DisplayServer::INVALID_WINDOW_ID) {
return;
}
- if (!_current_window->in_use) {
- WARN_PRINT("current window not in use!");
+ if (!windows.has(current_window)) {
return;
}
- [_current_window->context makeCurrentContext];
+
+ GLWindow &win = windows[current_window];
+ [win.context makeCurrentContext];
}
void GLManager_OSX::swap_buffers() {
- // NO NEED TO CALL SWAP BUFFERS for each window...
- // see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glXSwapBuffers.xml
-
- if (!_current_window) {
- return;
- }
- if (!_current_window->in_use) {
- WARN_PRINT("current window not in use!");
- return;
+ for (Map<DisplayServer::WindowID, GLWindow>::Element *E = windows.front(); E; E = E->next()) {
+ [E->get().context flushBuffer];
}
- [_current_window->context flushBuffer];
}
void GLManager_OSX::window_update(DisplayServer::WindowID p_window_id) {
- if (p_window_id == -1) {
+ if (!windows.has(p_window_id)) {
return;
}
- GLWindow &win = _windows[p_window_id];
- if (!win.in_use) {
- return;
- }
+ GLWindow &win = windows[p_window_id];
+ [win.context update];
+}
- if (&win == _current_window) {
+void GLManager_OSX::window_set_per_pixel_transparency_enabled(DisplayServer::WindowID p_window_id, bool p_enabled) {
+ if (!windows.has(p_window_id)) {
return;
}
+ GLWindow &win = windows[p_window_id];
+ if (p_enabled) {
+ GLint opacity = 0;
+ [win.context setValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity];
+ } else {
+ GLint opacity = 1;
+ [win.context setValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity];
+ }
[win.context update];
}
@@ -207,6 +203,7 @@ Error GLManager_OSX::initialize() {
void GLManager_OSX::set_use_vsync(bool p_use) {
use_vsync = p_use;
+
CGLContextObj ctx = CGLGetCurrentContext();
if (ctx) {
GLint swapInterval = p_use ? 1 : 0;
@@ -221,8 +218,6 @@ bool GLManager_OSX::is_using_vsync() const {
GLManager_OSX::GLManager_OSX(ContextType p_context_type) {
context_type = p_context_type;
- use_vsync = false;
- _current_window = nullptr;
}
GLManager_OSX::~GLManager_OSX() {
diff --git a/platform/osx/godot_application.h b/platform/osx/godot_application.h
new file mode 100644
index 0000000000..8d48a659f3
--- /dev/null
+++ b/platform/osx/godot_application.h
@@ -0,0 +1,42 @@
+/*************************************************************************/
+/* godot_application.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 GODOT_APPLICATION_H
+#define GODOT_APPLICATION_H
+
+#include "core/os/os.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+
+@interface GodotApplication : NSApplication
+@end
+
+#endif // GODOT_APPLICATION_H
diff --git a/platform/osx/godot_application.mm b/platform/osx/godot_application.mm
new file mode 100644
index 0000000000..00a58700e8
--- /dev/null
+++ b/platform/osx/godot_application.mm
@@ -0,0 +1,53 @@
+/*************************************************************************/
+/* godot_application.mm */
+/*************************************************************************/
+/* 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 "godot_application.h"
+
+#include "display_server_osx.h"
+
+@implementation GodotApplication
+
+- (void)sendEvent:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (ds) {
+ ds->send_event(event);
+ }
+
+ // From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
+ // This works around an AppKit bug, where key up events while holding
+ // down the command key don't get sent to the key window.
+ if ([event type] == NSEventTypeKeyUp && ([event modifierFlags] & NSEventModifierFlagCommand)) {
+ [[self keyWindow] sendEvent:event];
+ } else {
+ [super sendEvent:event];
+ }
+}
+
+@end
diff --git a/platform/osx/godot_application_delegate.h b/platform/osx/godot_application_delegate.h
new file mode 100644
index 0000000000..8eec762d8f
--- /dev/null
+++ b/platform/osx/godot_application_delegate.h
@@ -0,0 +1,45 @@
+/*************************************************************************/
+/* godot_application_delegate.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 GODOT_APPLICATION_DELEGATE_H
+#define GODOT_APPLICATION_DELEGATE_H
+
+#include "core/os/os.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+
+@interface GodotApplicationDelegate : NSObject
+- (void)forceUnbundledWindowActivationHackStep1;
+- (void)forceUnbundledWindowActivationHackStep2;
+- (void)forceUnbundledWindowActivationHackStep3;
+@end
+
+#endif // GODOT_APPLICATION_DELEGATE_H
diff --git a/platform/osx/godot_application_delegate.mm b/platform/osx/godot_application_delegate.mm
new file mode 100644
index 0000000000..be284ba543
--- /dev/null
+++ b/platform/osx/godot_application_delegate.mm
@@ -0,0 +1,132 @@
+/*************************************************************************/
+/* godot_application_delegate.mm */
+/*************************************************************************/
+/* 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 "godot_application_delegate.h"
+
+#include "display_server_osx.h"
+#include "os_osx.h"
+
+@implementation GodotApplicationDelegate
+
+- (void)forceUnbundledWindowActivationHackStep1 {
+ // Step 1: Switch focus to macOS SystemUIServer process.
+ // Required to perform step 2, TransformProcessType will fail if app is already the in focus.
+ for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.systemuiserver"]) {
+ [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
+ break;
+ }
+ [self performSelector:@selector(forceUnbundledWindowActivationHackStep2)
+ withObject:nil
+ afterDelay:0.02];
+}
+
+- (void)forceUnbundledWindowActivationHackStep2 {
+ // Step 2: Register app as foreground process.
+ ProcessSerialNumber psn = { 0, kCurrentProcess };
+ (void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
+ [self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
+}
+
+- (void)forceUnbundledWindowActivationHackStep3 {
+ // Step 3: Switch focus back to app window.
+ [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
+}
+
+- (void)applicationDidFinishLaunching:(NSNotification *)notice {
+ NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
+ if (nsappname == nil || isatty(STDOUT_FILENO) || isatty(STDIN_FILENO) || isatty(STDERR_FILENO)) {
+ // If the executable is started from terminal or is not bundled, macOS WindowServer won't register and activate app window correctly (menu and title bar are grayed out and input ignored).
+ [self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
+ }
+}
+
+- (void)applicationDidResignActive:(NSNotification *)notification {
+ if (OS::get_singleton()->get_main_loop()) {
+ OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
+ }
+}
+
+- (void)applicationDidBecomeActive:(NSNotification *)notification {
+ if (OS::get_singleton()->get_main_loop()) {
+ OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
+ }
+}
+
+- (void)globalMenuCallback:(id)sender {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (ds) {
+ return ds->menu_callback(sender);
+ }
+}
+
+- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (ds) {
+ return ds->get_dock_menu();
+ } else {
+ return nullptr;
+ }
+}
+
+- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
+ // Note: may be called called before main loop init!
+ OS_OSX *os = (OS_OSX *)OS::get_singleton();
+ if (os) {
+ os->set_open_with_filename(String::utf8([filename UTF8String]));
+ }
+
+#ifdef TOOLS_ENABLED
+ // Open new instance.
+ if (os && os->get_main_loop()) {
+ List<String> args;
+ args.push_back(os->get_open_with_filename());
+ String exec = os->get_executable_path();
+ os->create_process(exec, args);
+ }
+#endif
+ return YES;
+}
+
+- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (ds) {
+ ds->send_window_event(ds->get_window(DisplayServerOSX::MAIN_WINDOW_ID), DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST);
+ }
+ return NSTerminateCancel;
+}
+
+- (void)showAbout:(id)sender {
+ OS_OSX *os = (OS_OSX *)OS::get_singleton();
+ if (os && os->get_main_loop()) {
+ os->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_ABOUT);
+ }
+}
+
+@end
diff --git a/platform/osx/godot_content_view.h b/platform/osx/godot_content_view.h
new file mode 100644
index 0000000000..7942d716dc
--- /dev/null
+++ b/platform/osx/godot_content_view.h
@@ -0,0 +1,65 @@
+/*************************************************************************/
+/* godot_content_view.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 GODOT_CONTENT_VIEW_H
+#define GODOT_CONTENT_VIEW_H
+
+#include "servers/display_server.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+
+#if defined(GLES3_ENABLED)
+#import <AppKit/NSOpenGLView.h>
+#define RootView NSOpenGLView
+#else
+#define RootView NSView
+#endif
+
+#import <QuartzCore/CAMetalLayer.h>
+
+@interface GodotContentView : RootView <NSTextInputClient> {
+ DisplayServer::WindowID window_id;
+ NSTrackingArea *tracking_area;
+ NSMutableAttributedString *marked_text;
+ bool ime_input_event_in_progress;
+ bool mouse_down_control;
+ bool ignore_momentum_scroll;
+}
+
+- (void)processScrollEvent:(NSEvent *)event button:(MouseButton)button factor:(double)factor;
+- (void)processPanEvent:(NSEvent *)event dx:(double)dx dy:(double)dy;
+- (void)processMouseEvent:(NSEvent *)event index:(MouseButton)index mask:(MouseButton)mask pressed:(bool)pressed;
+- (void)setWindowID:(DisplayServer::WindowID)wid;
+- (void)cancelComposition;
+
+@end
+
+#endif // GODOT_CONTENT_VIEW_H
diff --git a/platform/osx/godot_content_view.mm b/platform/osx/godot_content_view.mm
new file mode 100644
index 0000000000..4e831e1ccc
--- /dev/null
+++ b/platform/osx/godot_content_view.mm
@@ -0,0 +1,760 @@
+/*************************************************************************/
+/* godot_content_view.mm */
+/*************************************************************************/
+/* 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 "godot_content_view.h"
+
+#include "display_server_osx.h"
+#include "key_mapping_osx.h"
+
+@implementation GodotContentView
+
+- (id)init {
+ self = [super init];
+ window_id = DisplayServer::INVALID_WINDOW_ID;
+ tracking_area = nil;
+ ime_input_event_in_progress = false;
+ mouse_down_control = false;
+ ignore_momentum_scroll = false;
+ [self updateTrackingAreas];
+
+ if (@available(macOS 10.13, *)) {
+ [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
+#if !defined(__aarch64__) // Do not build deprectead 10.13 code on ARM.
+ } else {
+ [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
+#endif
+ }
+ marked_text = [[NSMutableAttributedString alloc] init];
+ return self;
+}
+
+- (void)setWindowID:(DisplayServerOSX::WindowID)wid {
+ window_id = wid;
+}
+
+// MARK: Backing Layer
+
+- (CALayer *)makeBackingLayer {
+ return [[CAMetalLayer class] layer];
+}
+
+- (void)updateLayer {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ ds->window_update(window_id);
+ [super updateLayer];
+}
+
+- (BOOL)wantsUpdateLayer {
+ return YES;
+}
+
+- (BOOL)isOpaque {
+ return YES;
+}
+
+// MARK: IME
+
+- (BOOL)hasMarkedText {
+ return (marked_text.length > 0);
+}
+
+- (NSRange)markedRange {
+ return NSMakeRange(0, marked_text.length);
+}
+
+- (NSRange)selectedRange {
+ static const NSRange kEmptyRange = { NSNotFound, 0 };
+ return kEmptyRange;
+}
+
+- (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
+ if ([aString isKindOfClass:[NSAttributedString class]]) {
+ marked_text = [[NSMutableAttributedString alloc] initWithAttributedString:aString];
+ } else {
+ marked_text = [[NSMutableAttributedString alloc] initWithString:aString];
+ }
+ if (marked_text.length == 0) {
+ [self unmarkText];
+ return;
+ }
+
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ if (wd.im_active) {
+ ime_input_event_in_progress = true;
+ ds->update_im_text(Point2i(selectedRange.location, selectedRange.length), String::utf8([[marked_text mutableString] UTF8String]));
+ }
+}
+
+- (void)unmarkText {
+ ime_input_event_in_progress = false;
+ [[marked_text mutableString] setString:@""];
+
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ if (wd.im_active) {
+ ds->update_im_text(Point2i(), String());
+ }
+}
+
+- (NSArray *)validAttributesForMarkedText {
+ return [NSArray array];
+}
+
+- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
+ return nil;
+}
+
+- (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
+ return 0;
+}
+
+- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return NSMakeRect(0, 0, 0, 0);
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ const NSRect content_rect = [wd.window_view frame];
+ const float scale = ds->screen_get_max_scale();
+ NSRect point_in_window_rect = NSMakeRect(wd.im_position.x / scale, content_rect.size.height - (wd.im_position.y / scale) - 1, 0, 0);
+ NSPoint point_on_screen = [wd.window_object convertRectToScreen:point_in_window_rect].origin;
+
+ return NSMakeRect(point_on_screen.x, point_on_screen.y, 0, 0);
+}
+
+- (void)cancelComposition {
+ [self unmarkText];
+ [[NSTextInputContext currentInputContext] discardMarkedText];
+}
+
+- (void)insertText:(id)aString {
+ [self insertText:aString replacementRange:NSMakeRange(0, 0)];
+}
+
+- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
+ NSEvent *event = [NSApp currentEvent];
+
+ NSString *characters;
+ if ([aString isKindOfClass:[NSAttributedString class]]) {
+ characters = [aString string];
+ } else {
+ characters = (NSString *)aString;
+ }
+
+ NSCharacterSet *ctrl_chars = [NSCharacterSet controlCharacterSet];
+ NSCharacterSet *wsnl_chars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
+ if ([characters rangeOfCharacterFromSet:ctrl_chars].length && [characters rangeOfCharacterFromSet:wsnl_chars].length == 0) {
+ [[NSTextInputContext currentInputContext] discardMarkedText];
+ [self cancelComposition];
+ return;
+ }
+
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ [self cancelComposition];
+ return;
+ }
+
+ Char16String text;
+ text.resize([characters length] + 1);
+ [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
+
+ String u32text;
+ u32text.parse_utf16(text.ptr(), text.length());
+
+ for (int i = 0; i < u32text.length(); i++) {
+ const char32_t codepoint = u32text[i];
+ if ((codepoint & 0xFF00) == 0xF700) {
+ continue;
+ }
+
+ DisplayServerOSX::KeyEvent ke;
+
+ ke.window_id = window_id;
+ ke.osx_state = [event modifierFlags];
+ ke.pressed = true;
+ ke.echo = false;
+ ke.raw = false; // IME input event.
+ ke.keycode = Key::NONE;
+ ke.physical_keycode = Key::NONE;
+ ke.unicode = codepoint;
+
+ ds->push_to_key_event_buffer(ke);
+ }
+ [self cancelComposition];
+}
+
+// MARK: Drag and drop
+
+- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
+ return NSDragOperationCopy;
+}
+
+- (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
+ return NSDragOperationCopy;
+}
+
+- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return NO;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ if (!wd.drop_files_callback.is_null()) {
+ Vector<String> files;
+ NSPasteboard *pboard = [sender draggingPasteboard];
+
+ if (@available(macOS 10.13, *)) {
+ NSArray *items = pboard.pasteboardItems;
+ for (NSPasteboardItem *item in items) {
+ NSString *url = [item stringForType:NSPasteboardTypeFileURL];
+ NSString *file = [NSURL URLWithString:url].path;
+ files.push_back(String::utf8([file UTF8String]));
+ }
+#if !defined(__aarch64__) // Do not build deprectead 10.13 code on ARM.
+ } else {
+ NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
+ for (NSString *file in filenames) {
+ files.push_back(String::utf8([file UTF8String]));
+ }
+#endif
+ }
+
+ Variant v = files;
+ Variant *vp = &v;
+ Variant ret;
+ Callable::CallError ce;
+ wd.drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
+ }
+
+ return NO;
+}
+
+// MARK: Focus
+
+- (BOOL)canBecomeKeyView {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return YES;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ return !wd.no_focus;
+}
+
+- (BOOL)acceptsFirstResponder {
+ return YES;
+}
+
+// MARK: Mouse
+
+- (void)cursorUpdate:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds) {
+ return;
+ }
+
+ ds->cursor_update_shape();
+}
+
+- (void)processMouseEvent:(NSEvent *)event index:(MouseButton)index mask:(MouseButton)mask pressed:(bool)pressed {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ MouseButton last_button_state = ds->mouse_get_button_state();
+
+ if (pressed) {
+ last_button_state |= mask;
+ } else {
+ last_button_state &= (MouseButton)~mask;
+ }
+ ds->mouse_set_button_state(last_button_state);
+
+ Ref<InputEventMouseButton> mb;
+ mb.instantiate();
+ mb->set_window_id(window_id);
+ ds->update_mouse_pos(wd, [event locationInWindow]);
+ ds->get_key_modifier_state([event modifierFlags], mb);
+ mb->set_button_index(index);
+ mb->set_pressed(pressed);
+ mb->set_position(wd.mouse_pos);
+ mb->set_global_position(wd.mouse_pos);
+ mb->set_button_mask(last_button_state);
+ if (index == MouseButton::LEFT && pressed) {
+ mb->set_double_click([event clickCount] == 2);
+ }
+
+ Input::get_singleton()->parse_input_event(mb);
+}
+
+- (void)mouseDown:(NSEvent *)event {
+ if (([event modifierFlags] & NSEventModifierFlagControl)) {
+ mouse_down_control = true;
+ [self processMouseEvent:event index:MouseButton::RIGHT mask:MouseButton::MASK_RIGHT pressed:true];
+ } else {
+ mouse_down_control = false;
+ [self processMouseEvent:event index:MouseButton::LEFT mask:MouseButton::MASK_LEFT pressed:true];
+ }
+}
+
+- (void)mouseDragged:(NSEvent *)event {
+ [self mouseMoved:event];
+}
+
+- (void)mouseUp:(NSEvent *)event {
+ if (mouse_down_control) {
+ [self processMouseEvent:event index:MouseButton::RIGHT mask:MouseButton::MASK_RIGHT pressed:false];
+ } else {
+ [self processMouseEvent:event index:MouseButton::LEFT mask:MouseButton::MASK_LEFT pressed:false];
+ }
+}
+
+- (void)mouseMoved:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ NSPoint delta = NSMakePoint([event deltaX], [event deltaY]);
+ NSPoint mpos = [event locationInWindow];
+
+ if (ds->update_mouse_wrap(wd, delta, mpos, [event timestamp])) {
+ return;
+ }
+
+ Ref<InputEventMouseMotion> mm;
+ mm.instantiate();
+
+ mm->set_window_id(window_id);
+ mm->set_button_mask(ds->mouse_get_button_state());
+ ds->update_mouse_pos(wd, mpos);
+ mm->set_position(wd.mouse_pos);
+ mm->set_pressure([event pressure]);
+ if ([event subtype] == NSEventSubtypeTabletPoint) {
+ const NSPoint p = [event tilt];
+ mm->set_tilt(Vector2(p.x, p.y));
+ }
+ mm->set_global_position(wd.mouse_pos);
+ mm->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
+ const Vector2i relativeMotion = Vector2i(delta.x, delta.y) * ds->screen_get_max_scale();
+ mm->set_relative(relativeMotion);
+ ds->get_key_modifier_state([event modifierFlags], mm);
+
+ Input::get_singleton()->parse_input_event(mm);
+}
+
+- (void)rightMouseDown:(NSEvent *)event {
+ [self processMouseEvent:event index:MouseButton::RIGHT mask:MouseButton::MASK_RIGHT pressed:true];
+}
+
+- (void)rightMouseDragged:(NSEvent *)event {
+ [self mouseMoved:event];
+}
+
+- (void)rightMouseUp:(NSEvent *)event {
+ [self processMouseEvent:event index:MouseButton::RIGHT mask:MouseButton::MASK_RIGHT pressed:false];
+}
+
+- (void)otherMouseDown:(NSEvent *)event {
+ if ((int)[event buttonNumber] == 2) {
+ [self processMouseEvent:event index:MouseButton::MIDDLE mask:MouseButton::MASK_MIDDLE pressed:true];
+ } else if ((int)[event buttonNumber] == 3) {
+ [self processMouseEvent:event index:MouseButton::MB_XBUTTON1 mask:MouseButton::MASK_XBUTTON1 pressed:true];
+ } else if ((int)[event buttonNumber] == 4) {
+ [self processMouseEvent:event index:MouseButton::MB_XBUTTON2 mask:MouseButton::MASK_XBUTTON2 pressed:true];
+ } else {
+ return;
+ }
+}
+
+- (void)otherMouseDragged:(NSEvent *)event {
+ [self mouseMoved:event];
+}
+
+- (void)otherMouseUp:(NSEvent *)event {
+ if ((int)[event buttonNumber] == 2) {
+ [self processMouseEvent:event index:MouseButton::MIDDLE mask:MouseButton::MASK_MIDDLE pressed:false];
+ } else if ((int)[event buttonNumber] == 3) {
+ [self processMouseEvent:event index:MouseButton::MB_XBUTTON1 mask:MouseButton::MASK_XBUTTON1 pressed:false];
+ } else if ((int)[event buttonNumber] == 4) {
+ [self processMouseEvent:event index:MouseButton::MB_XBUTTON2 mask:MouseButton::MASK_XBUTTON2 pressed:false];
+ } else {
+ return;
+ }
+}
+
+- (void)mouseExited:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ if (ds->mouse_get_mode() != DisplayServer::MOUSE_MODE_CAPTURED) {
+ ds->send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_MOUSE_EXIT);
+ }
+}
+
+- (void)mouseEntered:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ if (ds->mouse_get_mode() != DisplayServer::MOUSE_MODE_CAPTURED) {
+ ds->send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_MOUSE_ENTER);
+ }
+
+ ds->cursor_update_shape();
+}
+
+- (void)magnifyWithEvent:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ Ref<InputEventMagnifyGesture> ev;
+ ev.instantiate();
+ ev->set_window_id(window_id);
+ ds->get_key_modifier_state([event modifierFlags], ev);
+ ds->update_mouse_pos(wd, [event locationInWindow]);
+ ev->set_position(wd.mouse_pos);
+ ev->set_factor([event magnification] + 1.0);
+
+ Input::get_singleton()->parse_input_event(ev);
+}
+
+- (void)updateTrackingAreas {
+ if (tracking_area != nil) {
+ [self removeTrackingArea:tracking_area];
+ }
+
+ NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingCursorUpdate | NSTrackingInVisibleRect;
+ tracking_area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
+
+ [self addTrackingArea:tracking_area];
+ [super updateTrackingAreas];
+}
+
+// MARK: Keyboard
+
+- (void)keyDown:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ ignore_momentum_scroll = true;
+
+ // Ignore all input if IME input is in progress.
+ if (!ime_input_event_in_progress) {
+ NSString *characters = [event characters];
+ NSUInteger length = [characters length];
+
+ if (!wd.im_active && length > 0 && keycode_has_unicode(KeyMappingOSX::remap_key([event keyCode], [event modifierFlags]))) {
+ // Fallback unicode character handler used if IME is not active.
+ Char16String text;
+ text.resize([characters length] + 1);
+ [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
+
+ String u32text;
+ u32text.parse_utf16(text.ptr(), text.length());
+
+ for (int i = 0; i < u32text.length(); i++) {
+ const char32_t codepoint = u32text[i];
+
+ DisplayServerOSX::KeyEvent ke;
+
+ ke.window_id = window_id;
+ ke.osx_state = [event modifierFlags];
+ ke.pressed = true;
+ ke.echo = [event isARepeat];
+ ke.keycode = KeyMappingOSX::remap_key([event keyCode], [event modifierFlags]);
+ ke.physical_keycode = KeyMappingOSX::translate_key([event keyCode]);
+ ke.raw = true;
+ ke.unicode = codepoint;
+
+ ds->push_to_key_event_buffer(ke);
+ }
+ } else {
+ DisplayServerOSX::KeyEvent ke;
+
+ ke.window_id = window_id;
+ ke.osx_state = [event modifierFlags];
+ ke.pressed = true;
+ ke.echo = [event isARepeat];
+ ke.keycode = KeyMappingOSX::remap_key([event keyCode], [event modifierFlags]);
+ ke.physical_keycode = KeyMappingOSX::translate_key([event keyCode]);
+ ke.raw = false;
+ ke.unicode = 0;
+
+ ds->push_to_key_event_buffer(ke);
+ }
+ }
+
+ // Pass events to IME handler
+ if (wd.im_active) {
+ [self interpretKeyEvents:[NSArray arrayWithObject:event]];
+ }
+}
+
+- (void)flagsChanged:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+ ignore_momentum_scroll = true;
+
+ // Ignore all input if IME input is in progress
+ if (!ime_input_event_in_progress) {
+ DisplayServerOSX::KeyEvent ke;
+
+ ke.window_id = window_id;
+ ke.echo = false;
+ ke.raw = true;
+
+ int key = [event keyCode];
+ int mod = [event modifierFlags];
+
+ if (key == 0x36 || key == 0x37) {
+ if (mod & NSEventModifierFlagCommand) {
+ mod &= ~NSEventModifierFlagCommand;
+ ke.pressed = true;
+ } else {
+ ke.pressed = false;
+ }
+ } else if (key == 0x38 || key == 0x3c) {
+ if (mod & NSEventModifierFlagShift) {
+ mod &= ~NSEventModifierFlagShift;
+ ke.pressed = true;
+ } else {
+ ke.pressed = false;
+ }
+ } else if (key == 0x3a || key == 0x3d) {
+ if (mod & NSEventModifierFlagOption) {
+ mod &= ~NSEventModifierFlagOption;
+ ke.pressed = true;
+ } else {
+ ke.pressed = false;
+ }
+ } else if (key == 0x3b || key == 0x3e) {
+ if (mod & NSEventModifierFlagControl) {
+ mod &= ~NSEventModifierFlagControl;
+ ke.pressed = true;
+ } else {
+ ke.pressed = false;
+ }
+ } else {
+ return;
+ }
+
+ ke.osx_state = mod;
+ ke.keycode = KeyMappingOSX::remap_key(key, mod);
+ ke.physical_keycode = KeyMappingOSX::translate_key(key);
+ ke.unicode = 0;
+
+ ds->push_to_key_event_buffer(ke);
+ }
+}
+
+- (void)keyUp:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ // Ignore all input if IME input is in progress.
+ if (!ime_input_event_in_progress) {
+ NSString *characters = [event characters];
+ NSUInteger length = [characters length];
+
+ // Fallback unicode character handler used if IME is not active.
+ if (!wd.im_active && length > 0 && keycode_has_unicode(KeyMappingOSX::remap_key([event keyCode], [event modifierFlags]))) {
+ Char16String text;
+ text.resize([characters length] + 1);
+ [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
+
+ String u32text;
+ u32text.parse_utf16(text.ptr(), text.length());
+
+ for (int i = 0; i < u32text.length(); i++) {
+ const char32_t codepoint = u32text[i];
+ DisplayServerOSX::KeyEvent ke;
+
+ ke.window_id = window_id;
+ ke.osx_state = [event modifierFlags];
+ ke.pressed = false;
+ ke.echo = [event isARepeat];
+ ke.keycode = KeyMappingOSX::remap_key([event keyCode], [event modifierFlags]);
+ ke.physical_keycode = KeyMappingOSX::translate_key([event keyCode]);
+ ke.raw = true;
+ ke.unicode = codepoint;
+
+ ds->push_to_key_event_buffer(ke);
+ }
+ } else {
+ DisplayServerOSX::KeyEvent ke;
+
+ ke.window_id = window_id;
+ ke.osx_state = [event modifierFlags];
+ ke.pressed = false;
+ ke.echo = [event isARepeat];
+ ke.keycode = KeyMappingOSX::remap_key([event keyCode], [event modifierFlags]);
+ ke.physical_keycode = KeyMappingOSX::translate_key([event keyCode]);
+ ke.raw = true;
+ ke.unicode = 0;
+
+ ds->push_to_key_event_buffer(ke);
+ }
+ }
+}
+
+// MARK: Scroll and pan
+
+- (void)processScrollEvent:(NSEvent *)event button:(MouseButton)button factor:(double)factor {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ MouseButton mask = mouse_button_to_mask(button);
+
+ Ref<InputEventMouseButton> sc;
+ sc.instantiate();
+
+ sc->set_window_id(window_id);
+ ds->get_key_modifier_state([event modifierFlags], sc);
+ sc->set_button_index(button);
+ sc->set_factor(factor);
+ sc->set_pressed(true);
+ sc->set_position(wd.mouse_pos);
+ sc->set_global_position(wd.mouse_pos);
+ MouseButton last_button_state = ds->mouse_get_button_state() | (MouseButton)mask;
+ sc->set_button_mask(last_button_state);
+ ds->mouse_set_button_state(last_button_state);
+
+ Input::get_singleton()->parse_input_event(sc);
+
+ sc.instantiate();
+ sc->set_window_id(window_id);
+ sc->set_button_index(button);
+ sc->set_factor(factor);
+ sc->set_pressed(false);
+ sc->set_position(wd.mouse_pos);
+ sc->set_global_position(wd.mouse_pos);
+ last_button_state &= (MouseButton)~mask;
+ sc->set_button_mask(last_button_state);
+ ds->mouse_set_button_state(last_button_state);
+
+ Input::get_singleton()->parse_input_event(sc);
+}
+
+- (void)processPanEvent:(NSEvent *)event dx:(double)dx dy:(double)dy {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ Ref<InputEventPanGesture> pg;
+ pg.instantiate();
+
+ pg->set_window_id(window_id);
+ ds->get_key_modifier_state([event modifierFlags], pg);
+ pg->set_position(wd.mouse_pos);
+ pg->set_delta(Vector2(-dx, -dy));
+
+ Input::get_singleton()->parse_input_event(pg);
+}
+
+- (void)scrollWheel:(NSEvent *)event {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ ds->update_mouse_pos(wd, [event locationInWindow]);
+
+ double delta_x = [event scrollingDeltaX];
+ double delta_y = [event scrollingDeltaY];
+
+ if ([event hasPreciseScrollingDeltas]) {
+ delta_x *= 0.03;
+ delta_y *= 0.03;
+ }
+
+ if ([event momentumPhase] != NSEventPhaseNone) {
+ if (ignore_momentum_scroll) {
+ return;
+ }
+ } else {
+ ignore_momentum_scroll = false;
+ }
+
+ if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
+ [self processPanEvent:event dx:delta_x dy:delta_y];
+ } else {
+ if (fabs(delta_x)) {
+ [self processScrollEvent:event button:(0 > delta_x ? MouseButton::WHEEL_RIGHT : MouseButton::WHEEL_LEFT) factor:fabs(delta_x * 0.3)];
+ }
+ if (fabs(delta_y)) {
+ [self processScrollEvent:event button:(0 < delta_y ? MouseButton::WHEEL_UP : MouseButton::WHEEL_DOWN) factor:fabs(delta_y * 0.3)];
+ }
+ }
+}
+
+@end
diff --git a/platform/osx/godot_main_osx.mm b/platform/osx/godot_main_osx.mm
index 64a93f7292..7fabfaa1b7 100644
--- a/platform/osx/godot_main_osx.mm
+++ b/platform/osx/godot_main_osx.mm
@@ -37,7 +37,7 @@
int main(int argc, char **argv) {
#if defined(VULKAN_ENABLED)
- // MoltenVK - enable full component swizzling support
+ // MoltenVK - enable full component swizzling support.
setenv("MVK_CONFIG_FULL_IMAGE_VIEW_SWIZZLE", "1", 1);
#endif
@@ -45,13 +45,14 @@ int main(int argc, char **argv) {
const char *dbg_arg = "-NSDocumentRevisionsDebugMode";
printf("arguments\n");
for (int i = 0; i < argc; i++) {
- if (strcmp(dbg_arg, argv[i]) == 0)
+ if (strcmp(dbg_arg, argv[i]) == 0) {
first_arg = i + 2;
+ }
printf("%i: %s\n", i, argv[i]);
};
#ifdef DEBUG_ENABLED
- // lets report the path we made current after all that
+ // Lets report the path we made current after all that.
char cwd[4096];
getcwd(cwd, 4096);
printf("Current path: %s\n", cwd);
@@ -60,23 +61,25 @@ int main(int argc, char **argv) {
OS_OSX os;
Error err;
- // We must override main when testing is enabled
+ // We must override main when testing is enabled.
TEST_MAIN_OVERRIDE
- if (os.open_with_filename != "") {
- char *argv_c = (char *)malloc(os.open_with_filename.utf8().size());
- memcpy(argv_c, os.open_with_filename.utf8().get_data(), os.open_with_filename.utf8().size());
+ if (os.get_open_with_filename() != "") {
+ char *argv_c = (char *)malloc(os.get_open_with_filename().utf8().size());
+ memcpy(argv_c, os.get_open_with_filename().utf8().get_data(), os.get_open_with_filename().utf8().size());
err = Main::setup(argv[0], 1, &argv_c);
free(argv_c);
} else {
err = Main::setup(argv[0], argc - first_arg, &argv[first_arg]);
}
- if (err != OK)
+ if (err != OK) {
return 255;
+ }
- if (Main::start())
- os.run(); // it is actually the OS that decides how to run
+ if (Main::start()) {
+ os.run(); // It is actually the OS that decides how to run.
+ }
Main::cleanup();
diff --git a/platform/osx/godot_menu_item.h b/platform/osx/godot_menu_item.h
new file mode 100644
index 0000000000..50c4709c18
--- /dev/null
+++ b/platform/osx/godot_menu_item.h
@@ -0,0 +1,52 @@
+/*************************************************************************/
+/* godot_menu_item.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 GODOT_MENU_ITEM_H
+#define GODOT_MENU_ITEM_H
+
+#include "servers/display_server.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+
+@interface GodotMenuItem : NSObject {
+@public
+ Callable callback;
+ Variant meta;
+ int id;
+ bool checkable;
+}
+
+@end
+
+@implementation GodotMenuItem
+@end
+
+#endif // GODOT_MENU_ITEM_H
diff --git a/platform/osx/godot_window.h b/platform/osx/godot_window.h
new file mode 100644
index 0000000000..16ff101142
--- /dev/null
+++ b/platform/osx/godot_window.h
@@ -0,0 +1,47 @@
+/*************************************************************************/
+/* godot_window.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 GODOT_WINDOW_H
+#define GODOT_WINDOW_H
+
+#include "servers/display_server.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+
+@interface GodotWindow : NSWindow {
+ DisplayServer::WindowID window_id;
+}
+
+- (void)setWindowID:(DisplayServer::WindowID)wid;
+
+@end
+
+#endif //GODOT_WINDOW_H
diff --git a/platform/osx/godot_window.mm b/platform/osx/godot_window.mm
new file mode 100644
index 0000000000..772a2ddb9f
--- /dev/null
+++ b/platform/osx/godot_window.mm
@@ -0,0 +1,69 @@
+/*************************************************************************/
+/* godot_window.mm */
+/*************************************************************************/
+/* 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 "godot_window.h"
+
+#include "display_server_osx.h"
+
+@implementation GodotWindow
+
+- (id)init {
+ self = [super init];
+ window_id = DisplayServer::INVALID_WINDOW_ID;
+ return self;
+}
+
+- (void)setWindowID:(DisplayServerOSX::WindowID)wid {
+ window_id = wid;
+}
+
+- (BOOL)canBecomeKeyWindow {
+ // Required for NSWindowStyleMaskBorderless windows.
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return YES;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ return !wd.no_focus;
+}
+
+- (BOOL)canBecomeMainWindow {
+ // Required for NSWindowStyleMaskBorderless windows.
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return YES;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ return !wd.no_focus;
+}
+
+@end
diff --git a/platform/osx/godot_window_delegate.h b/platform/osx/godot_window_delegate.h
new file mode 100644
index 0000000000..8a1f681fcd
--- /dev/null
+++ b/platform/osx/godot_window_delegate.h
@@ -0,0 +1,47 @@
+/*************************************************************************/
+/* godot_window_delegate.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 GODOT_WINDOW_DELEGATE_H
+#define GODOT_WINDOW_DELEGATE_H
+
+#include "servers/display_server.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+
+@interface GodotWindowDelegate : NSObject <NSWindowDelegate> {
+ DisplayServer::WindowID window_id;
+}
+
+- (void)setWindowID:(DisplayServer::WindowID)wid;
+
+@end
+
+#endif //GODOT_WINDOW_DELEGATE_H
diff --git a/platform/osx/godot_window_delegate.mm b/platform/osx/godot_window_delegate.mm
new file mode 100644
index 0000000000..1742be987d
--- /dev/null
+++ b/platform/osx/godot_window_delegate.mm
@@ -0,0 +1,254 @@
+/*************************************************************************/
+/* godot_window_delegate.mm */
+/*************************************************************************/
+/* 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 "godot_window_delegate.h"
+
+#include "display_server_osx.h"
+
+@implementation GodotWindowDelegate
+
+- (void)setWindowID:(DisplayServer::WindowID)wid {
+ window_id = wid;
+}
+
+- (BOOL)windowShouldClose:(id)sender {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return YES;
+ }
+
+ ds->send_window_event(ds->get_window(window_id), DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST);
+ return NO;
+}
+
+- (void)windowWillClose:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ while (wd.transient_children.size()) {
+ ds->window_set_transient(wd.transient_children.front()->get(), DisplayServerOSX::INVALID_WINDOW_ID);
+ }
+
+ if (wd.transient_parent != DisplayServerOSX::INVALID_WINDOW_ID) {
+ ds->window_set_transient(window_id, DisplayServerOSX::INVALID_WINDOW_ID);
+ }
+
+ ds->window_destroy(window_id);
+}
+
+- (void)windowDidEnterFullScreen:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ wd.fullscreen = true;
+ // Reset window size limits.
+ [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
+ [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
+
+ // Force window resize event.
+ [self windowDidResize:notification];
+}
+
+- (void)windowDidExitFullScreen:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ wd.fullscreen = false;
+
+ // Set window size limits.
+ const float scale = ds->screen_get_max_scale();
+ if (wd.min_size != Size2i()) {
+ Size2i size = wd.min_size / scale;
+ [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
+ }
+ if (wd.max_size != Size2i()) {
+ Size2i size = wd.max_size / scale;
+ [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
+ }
+
+ // Restore resizability state.
+ if (wd.resize_disabled) {
+ [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
+ }
+
+ // Restore on-top state.
+ if (wd.on_top) {
+ [wd.window_object setLevel:NSFloatingWindowLevel];
+ }
+
+ // Force window resize event.
+ [self windowDidResize:notification];
+}
+
+- (void)windowDidChangeBackingProperties:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ CGFloat new_scale_factor = [wd.window_object backingScaleFactor];
+ CGFloat old_scale_factor = [[[notification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
+
+ if (new_scale_factor != old_scale_factor) {
+ // Set new display scale and window size.
+ const float scale = ds->screen_get_max_scale();
+ const NSRect content_rect = [wd.window_view frame];
+
+ wd.size.width = content_rect.size.width * scale;
+ wd.size.height = content_rect.size.height * scale;
+
+ ds->send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_DPI_CHANGE);
+
+ CALayer *layer = [wd.window_view layer];
+ if (layer) {
+ layer.contentsScale = scale;
+ }
+
+ //Force window resize event
+ [self windowDidResize:notification];
+ }
+}
+
+- (void)windowDidResize:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ const NSRect content_rect = [wd.window_view frame];
+ const float scale = ds->screen_get_max_scale();
+ wd.size.width = content_rect.size.width * scale;
+ wd.size.height = content_rect.size.height * scale;
+
+ CALayer *layer = [wd.window_view layer];
+ if (layer) {
+ layer.contentsScale = scale;
+ }
+
+ ds->window_resize(window_id, wd.size.width, wd.size.height);
+
+ if (!wd.rect_changed_callback.is_null()) {
+ Variant size = Rect2i(ds->window_get_position(window_id), ds->window_get_size(window_id));
+ Variant *sizep = &size;
+ Variant ret;
+ Callable::CallError ce;
+ wd.rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
+ }
+}
+
+- (void)windowDidMove:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+ ds->release_pressed_events();
+
+ if (!wd.rect_changed_callback.is_null()) {
+ Variant size = Rect2i(ds->window_get_position(window_id), ds->window_get_size(window_id));
+ Variant *sizep = &size;
+ Variant ret;
+ Callable::CallError ce;
+ wd.rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
+ }
+}
+
+- (void)windowDidBecomeKey:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ if (ds->mouse_get_mode() == DisplayServer::MOUSE_MODE_CAPTURED) {
+ const NSRect content_rect = [wd.window_view frame];
+ NSRect point_in_window_rect = NSMakeRect(content_rect.size.width / 2, content_rect.size.height / 2, 0, 0);
+ NSPoint point_on_screen = [[wd.window_view window] convertRectToScreen:point_in_window_rect].origin;
+ CGPoint mouse_warp_pos = { point_on_screen.x, CGDisplayBounds(CGMainDisplayID()).size.height - point_on_screen.y };
+ CGWarpMouseCursorPosition(mouse_warp_pos);
+ } else {
+ ds->update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
+ }
+
+ ds->set_last_focused_window(window_id);
+ ds->send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_IN);
+}
+
+- (void)windowDidResignKey:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ ds->release_pressed_events();
+ ds->send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT);
+}
+
+- (void)windowDidMiniaturize:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ ds->release_pressed_events();
+ ds->send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT);
+}
+
+- (void)windowDidDeminiaturize:(NSNotification *)notification {
+ DisplayServerOSX *ds = (DisplayServerOSX *)DisplayServer::get_singleton();
+ if (!ds || !ds->has_window(window_id)) {
+ return;
+ }
+
+ DisplayServerOSX::WindowData &wd = ds->get_window(window_id);
+
+ ds->set_last_focused_window(window_id);
+ ds->send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_IN);
+}
+
+@end
diff --git a/platform/osx/joypad_osx.cpp b/platform/osx/joypad_osx.cpp
index c2356f12cd..d518206f04 100644
--- a/platform/osx/joypad_osx.cpp
+++ b/platform/osx/joypad_osx.cpp
@@ -80,7 +80,7 @@ int joypad::get_hid_element_state(rec_element *p_element) const {
if (IOHIDDeviceGetValue(device_ref, p_element->ref, &valueRef) == kIOReturnSuccess) {
value = (SInt32)IOHIDValueGetIntegerValue(valueRef);
- /* record min and max for auto calibration */
+ // Record min and max for auto calibration.
if (value < p_element->min) {
p_element->min = value;
}
@@ -179,7 +179,7 @@ void joypad::add_hid_element(IOHIDElementRef p_element) {
break;
}
- if (list) { /* add to list */
+ if (list) { // Add to list.
rec_element element;
element.ref = p_element;
@@ -280,7 +280,7 @@ static String _hex_str(uint8_t p_byte) {
bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad *p_joy) {
p_joy->device_ref = p_device_ref;
- /* get device name */
+ // Get device name.
String name;
char c_name[256];
CFTypeRef refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDProductKey));
@@ -319,7 +319,7 @@ bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad *p_joy) {
sprintf(uid, "%08x%08x%08x%08x", OSSwapHostToBigInt32(3), OSSwapHostToBigInt32(vendor), OSSwapHostToBigInt32(product_id), OSSwapHostToBigInt32(version));
input->joy_connection_changed(id, true, name, uid);
} else {
- //bluetooth device
+ // Bluetooth device.
String guid = "05000000";
for (int i = 0; i < 12; i++) {
if (i < name.size())
@@ -445,7 +445,7 @@ static HatMask process_hat_value(int p_min, int p_max, int p_value, bool p_offse
void JoypadOSX::poll_joypads() const {
while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
- /* no-op. Pending callbacks will fire. */
+ // No-op. Pending callbacks will fire.
}
}
@@ -568,7 +568,7 @@ void JoypadOSX::config_hid_manager(CFArrayRef p_matching_array) const {
IOHIDManagerScheduleWithRunLoop(hid_manager, runloop, GODOT_JOY_LOOP_RUN_MODE);
while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
- /* no-op. Callback fires once per existing device. */
+ // No-op. Callback fires once per existing device.
}
}
diff --git a/platform/osx/joypad_osx.h b/platform/osx/joypad_osx.h
index 8ea1033a77..4ca7fb1698 100644
--- a/platform/osx/joypad_osx.h
+++ b/platform/osx/joypad_osx.h
@@ -66,7 +66,7 @@ struct joypad {
int id = 0;
bool offset_hat = false;
- io_service_t ffservice = 0; /* Interface for force feedback, 0 = no ff */
+ io_service_t ffservice = 0; // Interface for force feedback, 0 = no ff.
FFCONSTANTFORCE ff_constant_force;
FFDeviceObjectReference ff_device = nullptr;
FFEffectObjectReference ff_object = nullptr;
diff --git a/platform/osx/key_mapping_osx.h b/platform/osx/key_mapping_osx.h
new file mode 100644
index 0000000000..252cc907bb
--- /dev/null
+++ b/platform/osx/key_mapping_osx.h
@@ -0,0 +1,52 @@
+/*************************************************************************/
+/* key_mapping_osx.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 KEY_MAPPING_OSX_H
+#define KEY_MAPPING_OSX_H
+
+#include "core/os/keyboard.h"
+
+class KeyMappingOSX {
+ KeyMappingOSX() {}
+
+ static bool is_numpad_key(unsigned int key);
+
+public:
+ // Mappings input.
+ static Key translate_key(unsigned int key);
+ static unsigned int unmap_key(Key key);
+ static Key remap_key(unsigned int key, unsigned int state);
+
+ // Mapping for menu shortcuts.
+ static String keycode_get_native_string(Key p_keycode);
+ static unsigned int keycode_get_native_mask(Key p_keycode);
+};
+
+#endif // KEY_MAPPING_OSX_H
diff --git a/platform/osx/key_mapping_osx.mm b/platform/osx/key_mapping_osx.mm
new file mode 100644
index 0000000000..fde9206824
--- /dev/null
+++ b/platform/osx/key_mapping_osx.mm
@@ -0,0 +1,477 @@
+/*************************************************************************/
+/* key_mapping_osx.mm */
+/*************************************************************************/
+/* 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 "key_mapping_osx.h"
+
+#include <Carbon/Carbon.h>
+#include <Cocoa/Cocoa.h>
+
+bool KeyMappingOSX::is_numpad_key(unsigned int key) {
+ static const unsigned int table[] = {
+ 0x41, /* kVK_ANSI_KeypadDecimal */
+ 0x43, /* kVK_ANSI_KeypadMultiply */
+ 0x45, /* kVK_ANSI_KeypadPlus */
+ 0x47, /* kVK_ANSI_KeypadClear */
+ 0x4b, /* kVK_ANSI_KeypadDivide */
+ 0x4c, /* kVK_ANSI_KeypadEnter */
+ 0x4e, /* kVK_ANSI_KeypadMinus */
+ 0x51, /* kVK_ANSI_KeypadEquals */
+ 0x52, /* kVK_ANSI_Keypad0 */
+ 0x53, /* kVK_ANSI_Keypad1 */
+ 0x54, /* kVK_ANSI_Keypad2 */
+ 0x55, /* kVK_ANSI_Keypad3 */
+ 0x56, /* kVK_ANSI_Keypad4 */
+ 0x57, /* kVK_ANSI_Keypad5 */
+ 0x58, /* kVK_ANSI_Keypad6 */
+ 0x59, /* kVK_ANSI_Keypad7 */
+ 0x5b, /* kVK_ANSI_Keypad8 */
+ 0x5c, /* kVK_ANSI_Keypad9 */
+ 0x5f, /* kVK_JIS_KeypadComma */
+ 0x00
+ };
+ for (int i = 0; table[i] != 0; i++) {
+ if (key == table[i]) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// Keyboard symbol translation table.
+static const Key _osx_to_godot_table[128] = {
+ /* 00 */ Key::A,
+ /* 01 */ Key::S,
+ /* 02 */ Key::D,
+ /* 03 */ Key::F,
+ /* 04 */ Key::H,
+ /* 05 */ Key::G,
+ /* 06 */ Key::Z,
+ /* 07 */ Key::X,
+ /* 08 */ Key::C,
+ /* 09 */ Key::V,
+ /* 0a */ Key::SECTION, /* ISO Section */
+ /* 0b */ Key::B,
+ /* 0c */ Key::Q,
+ /* 0d */ Key::W,
+ /* 0e */ Key::E,
+ /* 0f */ Key::R,
+ /* 10 */ Key::Y,
+ /* 11 */ Key::T,
+ /* 12 */ Key::KEY_1,
+ /* 13 */ Key::KEY_2,
+ /* 14 */ Key::KEY_3,
+ /* 15 */ Key::KEY_4,
+ /* 16 */ Key::KEY_6,
+ /* 17 */ Key::KEY_5,
+ /* 18 */ Key::EQUAL,
+ /* 19 */ Key::KEY_9,
+ /* 1a */ Key::KEY_7,
+ /* 1b */ Key::MINUS,
+ /* 1c */ Key::KEY_8,
+ /* 1d */ Key::KEY_0,
+ /* 1e */ Key::BRACERIGHT,
+ /* 1f */ Key::O,
+ /* 20 */ Key::U,
+ /* 21 */ Key::BRACELEFT,
+ /* 22 */ Key::I,
+ /* 23 */ Key::P,
+ /* 24 */ Key::ENTER,
+ /* 25 */ Key::L,
+ /* 26 */ Key::J,
+ /* 27 */ Key::APOSTROPHE,
+ /* 28 */ Key::K,
+ /* 29 */ Key::SEMICOLON,
+ /* 2a */ Key::BACKSLASH,
+ /* 2b */ Key::COMMA,
+ /* 2c */ Key::SLASH,
+ /* 2d */ Key::N,
+ /* 2e */ Key::M,
+ /* 2f */ Key::PERIOD,
+ /* 30 */ Key::TAB,
+ /* 31 */ Key::SPACE,
+ /* 32 */ Key::QUOTELEFT,
+ /* 33 */ Key::BACKSPACE,
+ /* 34 */ Key::UNKNOWN,
+ /* 35 */ Key::ESCAPE,
+ /* 36 */ Key::META,
+ /* 37 */ Key::META,
+ /* 38 */ Key::SHIFT,
+ /* 39 */ Key::CAPSLOCK,
+ /* 3a */ Key::ALT,
+ /* 3b */ Key::CTRL,
+ /* 3c */ Key::SHIFT,
+ /* 3d */ Key::ALT,
+ /* 3e */ Key::CTRL,
+ /* 3f */ Key::UNKNOWN, /* Function */
+ /* 40 */ Key::UNKNOWN, /* F17 */
+ /* 41 */ Key::KP_PERIOD,
+ /* 42 */ Key::UNKNOWN,
+ /* 43 */ Key::KP_MULTIPLY,
+ /* 44 */ Key::UNKNOWN,
+ /* 45 */ Key::KP_ADD,
+ /* 46 */ Key::UNKNOWN,
+ /* 47 */ Key::NUMLOCK, /* Really KeypadClear... */
+ /* 48 */ Key::VOLUMEUP, /* VolumeUp */
+ /* 49 */ Key::VOLUMEDOWN, /* VolumeDown */
+ /* 4a */ Key::VOLUMEMUTE, /* Mute */
+ /* 4b */ Key::KP_DIVIDE,
+ /* 4c */ Key::KP_ENTER,
+ /* 4d */ Key::UNKNOWN,
+ /* 4e */ Key::KP_SUBTRACT,
+ /* 4f */ Key::UNKNOWN, /* F18 */
+ /* 50 */ Key::UNKNOWN, /* F19 */
+ /* 51 */ Key::EQUAL, /* KeypadEqual */
+ /* 52 */ Key::KP_0,
+ /* 53 */ Key::KP_1,
+ /* 54 */ Key::KP_2,
+ /* 55 */ Key::KP_3,
+ /* 56 */ Key::KP_4,
+ /* 57 */ Key::KP_5,
+ /* 58 */ Key::KP_6,
+ /* 59 */ Key::KP_7,
+ /* 5a */ Key::UNKNOWN, /* F20 */
+ /* 5b */ Key::KP_8,
+ /* 5c */ Key::KP_9,
+ /* 5d */ Key::YEN, /* JIS Yen */
+ /* 5e */ Key::UNDERSCORE, /* JIS Underscore */
+ /* 5f */ Key::COMMA, /* JIS KeypadComma */
+ /* 60 */ Key::F5,
+ /* 61 */ Key::F6,
+ /* 62 */ Key::F7,
+ /* 63 */ Key::F3,
+ /* 64 */ Key::F8,
+ /* 65 */ Key::F9,
+ /* 66 */ Key::UNKNOWN, /* JIS Eisu */
+ /* 67 */ Key::F11,
+ /* 68 */ Key::UNKNOWN, /* JIS Kana */
+ /* 69 */ Key::F13,
+ /* 6a */ Key::F16,
+ /* 6b */ Key::F14,
+ /* 6c */ Key::UNKNOWN,
+ /* 6d */ Key::F10,
+ /* 6e */ Key::MENU,
+ /* 6f */ Key::F12,
+ /* 70 */ Key::UNKNOWN,
+ /* 71 */ Key::F15,
+ /* 72 */ Key::INSERT, /* Really Help... */
+ /* 73 */ Key::HOME,
+ /* 74 */ Key::PAGEUP,
+ /* 75 */ Key::KEY_DELETE,
+ /* 76 */ Key::F4,
+ /* 77 */ Key::END,
+ /* 78 */ Key::F2,
+ /* 79 */ Key::PAGEDOWN,
+ /* 7a */ Key::F1,
+ /* 7b */ Key::LEFT,
+ /* 7c */ Key::RIGHT,
+ /* 7d */ Key::DOWN,
+ /* 7e */ Key::UP,
+ /* 7f */ Key::UNKNOWN,
+};
+
+// Translates a OS X keycode to a Godot keycode.
+Key KeyMappingOSX::translate_key(unsigned int key) {
+ if (key >= 128) {
+ return Key::UNKNOWN;
+ }
+
+ return _osx_to_godot_table[key];
+}
+
+// Translates a Godot keycode back to a OSX keycode.
+unsigned int KeyMappingOSX::unmap_key(Key key) {
+ for (int i = 0; i <= 126; i++) {
+ if (_osx_to_godot_table[i] == key) {
+ return i;
+ }
+ }
+ return 127;
+}
+
+struct _KeyCodeMap {
+ UniChar kchar;
+ Key kcode;
+};
+
+static const _KeyCodeMap _keycodes[55] = {
+ { '`', Key::QUOTELEFT },
+ { '~', Key::ASCIITILDE },
+ { '0', Key::KEY_0 },
+ { '1', Key::KEY_1 },
+ { '2', Key::KEY_2 },
+ { '3', Key::KEY_3 },
+ { '4', Key::KEY_4 },
+ { '5', Key::KEY_5 },
+ { '6', Key::KEY_6 },
+ { '7', Key::KEY_7 },
+ { '8', Key::KEY_8 },
+ { '9', Key::KEY_9 },
+ { '-', Key::MINUS },
+ { '_', Key::UNDERSCORE },
+ { '=', Key::EQUAL },
+ { '+', Key::PLUS },
+ { 'q', Key::Q },
+ { 'w', Key::W },
+ { 'e', Key::E },
+ { 'r', Key::R },
+ { 't', Key::T },
+ { 'y', Key::Y },
+ { 'u', Key::U },
+ { 'i', Key::I },
+ { 'o', Key::O },
+ { 'p', Key::P },
+ { '[', Key::BRACELEFT },
+ { ']', Key::BRACERIGHT },
+ { '{', Key::BRACELEFT },
+ { '}', Key::BRACERIGHT },
+ { 'a', Key::A },
+ { 's', Key::S },
+ { 'd', Key::D },
+ { 'f', Key::F },
+ { 'g', Key::G },
+ { 'h', Key::H },
+ { 'j', Key::J },
+ { 'k', Key::K },
+ { 'l', Key::L },
+ { ';', Key::SEMICOLON },
+ { ':', Key::COLON },
+ { '\'', Key::APOSTROPHE },
+ { '\"', Key::QUOTEDBL },
+ { '\\', Key::BACKSLASH },
+ { '#', Key::NUMBERSIGN },
+ { 'z', Key::Z },
+ { 'x', Key::X },
+ { 'c', Key::C },
+ { 'v', Key::V },
+ { 'b', Key::B },
+ { 'n', Key::N },
+ { 'm', Key::M },
+ { ',', Key::COMMA },
+ { '.', Key::PERIOD },
+ { '/', Key::SLASH }
+};
+
+// Remap key according to current keyboard layout.
+Key KeyMappingOSX::remap_key(unsigned int key, unsigned int state) {
+ if (is_numpad_key(key)) {
+ return translate_key(key);
+ }
+
+ TISInputSourceRef current_keyboard = TISCopyCurrentKeyboardInputSource();
+ if (!current_keyboard) {
+ return translate_key(key);
+ }
+
+ CFDataRef layout_data = (CFDataRef)TISGetInputSourceProperty(current_keyboard, kTISPropertyUnicodeKeyLayoutData);
+ if (!layout_data) {
+ return translate_key(key);
+ }
+
+ const UCKeyboardLayout *keyboard_layout = (const UCKeyboardLayout *)CFDataGetBytePtr(layout_data);
+
+ UInt32 keys_down = 0;
+ UniChar chars[4];
+ UniCharCount real_length;
+
+ OSStatus err = UCKeyTranslate(keyboard_layout,
+ key,
+ kUCKeyActionDisplay,
+ (state >> 8) & 0xFF,
+ LMGetKbdType(),
+ kUCKeyTranslateNoDeadKeysBit,
+ &keys_down,
+ sizeof(chars) / sizeof(chars[0]),
+ &real_length,
+ chars);
+
+ if (err != noErr) {
+ return translate_key(key);
+ }
+
+ for (unsigned int i = 0; i < 55; i++) {
+ if (_keycodes[i].kchar == chars[0]) {
+ return _keycodes[i].kcode;
+ }
+ }
+ return translate_key(key);
+}
+
+struct _KeyCodeText {
+ Key code;
+ char32_t text;
+};
+
+static const _KeyCodeText _native_keycodes[] = {
+ /* clang-format off */
+ {Key::ESCAPE ,0x001B},
+ {Key::TAB ,0x0009},
+ {Key::BACKTAB ,0x007F},
+ {Key::BACKSPACE ,0x0008},
+ {Key::ENTER ,0x000D},
+ {Key::INSERT ,NSInsertFunctionKey},
+ {Key::KEY_DELETE ,0x007F},
+ {Key::PAUSE ,NSPauseFunctionKey},
+ {Key::PRINT ,NSPrintScreenFunctionKey},
+ {Key::SYSREQ ,NSSysReqFunctionKey},
+ {Key::CLEAR ,NSClearLineFunctionKey},
+ {Key::HOME ,0x2196},
+ {Key::END ,0x2198},
+ {Key::LEFT ,0x001C},
+ {Key::UP ,0x001E},
+ {Key::RIGHT ,0x001D},
+ {Key::DOWN ,0x001F},
+ {Key::PAGEUP ,0x21DE},
+ {Key::PAGEDOWN ,0x21DF},
+ {Key::NUMLOCK ,NSClearLineFunctionKey},
+ {Key::SCROLLLOCK ,NSScrollLockFunctionKey},
+ {Key::F1 ,NSF1FunctionKey},
+ {Key::F2 ,NSF2FunctionKey},
+ {Key::F3 ,NSF3FunctionKey},
+ {Key::F4 ,NSF4FunctionKey},
+ {Key::F5 ,NSF5FunctionKey},
+ {Key::F6 ,NSF6FunctionKey},
+ {Key::F7 ,NSF7FunctionKey},
+ {Key::F8 ,NSF8FunctionKey},
+ {Key::F9 ,NSF9FunctionKey},
+ {Key::F10 ,NSF10FunctionKey},
+ {Key::F11 ,NSF11FunctionKey},
+ {Key::F12 ,NSF12FunctionKey},
+ {Key::F13 ,NSF13FunctionKey},
+ {Key::F14 ,NSF14FunctionKey},
+ {Key::F15 ,NSF15FunctionKey},
+ {Key::F16 ,NSF16FunctionKey}, //* ... NSF35FunctionKey */
+ {Key::MENU ,NSMenuFunctionKey},
+ {Key::HELP ,NSHelpFunctionKey},
+ {Key::STOP ,NSStopFunctionKey},
+ {Key::LAUNCH0 ,NSUserFunctionKey},
+ {Key::SPACE ,0x0020},
+ {Key::EXCLAM ,'!'},
+ {Key::QUOTEDBL ,'\"'},
+ {Key::NUMBERSIGN ,'#'},
+ {Key::DOLLAR ,'$'},
+ {Key::PERCENT ,'\%'},
+ {Key::AMPERSAND ,'&'},
+ {Key::APOSTROPHE ,'\''},
+ {Key::PARENLEFT ,'('},
+ {Key::PARENRIGHT ,')'},
+ {Key::ASTERISK ,'*'},
+ {Key::PLUS ,'+'},
+ {Key::COMMA ,','},
+ {Key::MINUS ,'-'},
+ {Key::PERIOD ,'.'},
+ {Key::SLASH ,'/'},
+ {Key::KEY_0 ,'0'},
+ {Key::KEY_1 ,'1'},
+ {Key::KEY_2 ,'2'},
+ {Key::KEY_3 ,'3'},
+ {Key::KEY_4 ,'4'},
+ {Key::KEY_5 ,'5'},
+ {Key::KEY_6 ,'6'},
+ {Key::KEY_7 ,'7'},
+ {Key::KEY_8 ,'8'},
+ {Key::KEY_9 ,'9'},
+ {Key::COLON ,':'},
+ {Key::SEMICOLON ,';'},
+ {Key::LESS ,'<'},
+ {Key::EQUAL ,'='},
+ {Key::GREATER ,'>'},
+ {Key::QUESTION ,'?'},
+ {Key::AT ,'@'},
+ {Key::A ,'a'},
+ {Key::B ,'b'},
+ {Key::C ,'c'},
+ {Key::D ,'d'},
+ {Key::E ,'e'},
+ {Key::F ,'f'},
+ {Key::G ,'g'},
+ {Key::H ,'h'},
+ {Key::I ,'i'},
+ {Key::J ,'j'},
+ {Key::K ,'k'},
+ {Key::L ,'l'},
+ {Key::M ,'m'},
+ {Key::N ,'n'},
+ {Key::O ,'o'},
+ {Key::P ,'p'},
+ {Key::Q ,'q'},
+ {Key::R ,'r'},
+ {Key::S ,'s'},
+ {Key::T ,'t'},
+ {Key::U ,'u'},
+ {Key::V ,'v'},
+ {Key::W ,'w'},
+ {Key::X ,'x'},
+ {Key::Y ,'y'},
+ {Key::Z ,'z'},
+ {Key::BRACKETLEFT ,'['},
+ {Key::BACKSLASH ,'\\'},
+ {Key::BRACKETRIGHT ,']'},
+ {Key::ASCIICIRCUM ,'^'},
+ {Key::UNDERSCORE ,'_'},
+ {Key::QUOTELEFT ,'`'},
+ {Key::BRACELEFT ,'{'},
+ {Key::BAR ,'|'},
+ {Key::BRACERIGHT ,'}'},
+ {Key::ASCIITILDE ,'~'},
+ {Key::NONE ,0x0000}
+ /* clang-format on */
+};
+
+String KeyMappingOSX::keycode_get_native_string(Key p_keycode) {
+ const _KeyCodeText *kct = &_native_keycodes[0];
+
+ while (kct->text) {
+ if (kct->code == p_keycode) {
+ return String::chr(kct->text);
+ }
+ kct++;
+ }
+ return String();
+}
+
+unsigned int KeyMappingOSX::keycode_get_native_mask(Key p_keycode) {
+ unsigned int mask = 0;
+ if ((p_keycode & KeyModifierMask::CTRL) != Key::NONE) {
+ mask |= NSEventModifierFlagControl;
+ }
+ if ((p_keycode & KeyModifierMask::ALT) != Key::NONE) {
+ mask |= NSEventModifierFlagOption;
+ }
+ if ((p_keycode & KeyModifierMask::SHIFT) != Key::NONE) {
+ mask |= NSEventModifierFlagShift;
+ }
+ if ((p_keycode & KeyModifierMask::META) != Key::NONE) {
+ mask |= NSEventModifierFlagCommand;
+ }
+ if ((p_keycode & KeyModifierMask::KPAD) != Key::NONE) {
+ mask |= NSEventModifierFlagNumericPad;
+ }
+ return mask;
+}
diff --git a/platform/osx/os_osx.h b/platform/osx/os_osx.h
index 60dec1fe3f..5bb5b3320e 100644
--- a/platform/osx/os_osx.h
+++ b/platform/osx/os_osx.h
@@ -40,9 +40,7 @@
#include "servers/audio_server.h"
class OS_OSX : public OS_Unix {
- virtual void delete_main_loop() override;
-
- bool force_quit;
+ bool force_quit = false;
JoypadOSX *joypad_osx = nullptr;
@@ -55,13 +53,15 @@ class OS_OSX : public OS_Unix {
CrashHandler crash_handler;
- MainLoop *main_loop;
+ CFRunLoopObserverRef pre_wait_observer;
- static void pre_wait_observer_cb(CFRunLoopObserverRef p_observer, CFRunLoopActivity p_activiy, void *p_context);
+ MainLoop *main_loop = nullptr;
-public:
String open_with_filename;
+ static _FORCE_INLINE_ String get_framework_executable(const String &p_path);
+ static void pre_wait_observer_cb(CFRunLoopObserverRef p_observer, CFRunLoopActivity p_activiy, void *p_context);
+
protected:
virtual void initialize_core() override;
virtual void initialize() override;
@@ -70,8 +70,12 @@ protected:
virtual void initialize_joypads() override;
virtual void set_main_loop(MainLoop *p_main_loop) override;
+ virtual void delete_main_loop() override;
public:
+ String get_open_with_filename() const;
+ void set_open_with_filename(const String &p_path);
+
virtual String get_name() const override;
virtual void alert(const String &p_alert, const String &p_title = "ALERT!") override;
@@ -89,26 +93,27 @@ public:
virtual String get_system_dir(SystemDir p_dir, bool p_shared_storage = true) const override;
- Error shell_open(String p_uri) override;
+ virtual Error shell_open(String p_uri) override;
- String get_locale() const override;
+ virtual String get_locale() const override;
virtual String get_executable_path() const override;
virtual Error create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id = nullptr, bool p_open_console = false) override;
virtual Error create_instance(const List<String> &p_arguments, ProcessID *r_child_id = nullptr) override;
- virtual String get_unique_id() const override; //++
+ virtual String get_unique_id() const override;
virtual bool _check_internal_feature_support(const String &p_feature) override;
- void run();
-
virtual void disable_crash_handler() override;
virtual bool is_disable_crash_handler() const override;
virtual Error move_to_trash(const String &p_path) override;
+ void run();
+
OS_OSX();
+ ~OS_OSX();
};
#endif
diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm
index 32d0e6dd94..9288e658cf 100644
--- a/platform/osx/os_osx.mm
+++ b/platform/osx/os_osx.mm
@@ -31,241 +31,45 @@
#include "os_osx.h"
#include "core/version_generated.gen.h"
+#include "main/main.h"
#include "dir_access_osx.h"
#include "display_server_osx.h"
-#include "main/main.h"
+#include "godot_application.h"
+#include "godot_application_delegate.h"
+#include "osx_terminal_logger.h"
#include <dlfcn.h>
#include <libproc.h>
#include <mach-o/dyld.h>
-#include <os/log.h>
-
-#define DS_OSX ((DisplayServerOSX *)(DisplayServerOSX::get_singleton()))
-
-/*************************************************************************/
-/* GodotApplication */
-/*************************************************************************/
-
-@interface GodotApplication : NSApplication
-@end
-
-@implementation GodotApplication
-
-- (void)sendEvent:(NSEvent *)event {
- if (DS_OSX) {
- DS_OSX->_send_event(event);
- }
-
- // From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
- // This works around an AppKit bug, where key up events while holding
- // down the command key don't get sent to the key window.
- if ([event type] == NSEventTypeKeyUp && ([event modifierFlags] & NSEventModifierFlagCommand)) {
- [[self keyWindow] sendEvent:event];
- } else {
- [super sendEvent:event];
- }
-}
-
-@end
-
-/*************************************************************************/
-/* GodotApplicationDelegate */
-/*************************************************************************/
-
-@interface GodotApplicationDelegate : NSObject
-- (void)forceUnbundledWindowActivationHackStep1;
-- (void)forceUnbundledWindowActivationHackStep2;
-- (void)forceUnbundledWindowActivationHackStep3;
-@end
-
-@implementation GodotApplicationDelegate
-
-- (void)forceUnbundledWindowActivationHackStep1 {
- // Step 1: Switch focus to macOS SystemUIServer process.
- // Required to perform step 2, TransformProcessType will fail if app is already the in focus.
- for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.systemuiserver"]) {
- [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
- break;
- }
- [self performSelector:@selector(forceUnbundledWindowActivationHackStep2)
- withObject:nil
- afterDelay:0.02];
-}
-
-- (void)forceUnbundledWindowActivationHackStep2 {
- // Step 2: Register app as foreground process.
- ProcessSerialNumber psn = { 0, kCurrentProcess };
- (void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
- [self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
-}
-
-- (void)forceUnbundledWindowActivationHackStep3 {
- // Step 3: Switch focus back to app window.
- [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
-}
-
-- (void)applicationDidFinishLaunching:(NSNotification *)notice {
- NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
- if (nsappname == nil || isatty(STDOUT_FILENO) || isatty(STDIN_FILENO) || isatty(STDERR_FILENO)) {
- // If the executable is started from terminal or is not bundled, macOS WindowServer won't register and activate app window correctly (menu and title bar are grayed out and input ignored).
- [self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
- }
-}
-
-- (void)applicationDidResignActive:(NSNotification *)notification {
- if (OS::get_singleton()->get_main_loop()) {
- OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_OUT);
- }
-}
-- (void)applicationDidBecomeActive:(NSNotification *)notification {
- if (OS::get_singleton()->get_main_loop()) {
- OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_APPLICATION_FOCUS_IN);
- }
-}
-
-- (void)globalMenuCallback:(id)sender {
- if (DS_OSX) {
- return DS_OSX->_menu_callback(sender);
- }
-}
-
-- (NSMenu *)applicationDockMenu:(NSApplication *)sender {
- if (DS_OSX) {
- return DS_OSX->_get_dock_menu();
+_FORCE_INLINE_ String OS_OSX::get_framework_executable(const String &p_path) {
+ // Append framework executable name, or return as is if p_path is not a framework.
+ DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
+ if (da->dir_exists(p_path) && da->file_exists(p_path.plus_file(p_path.get_file().get_basename()))) {
+ return p_path.plus_file(p_path.get_file().get_basename());
} else {
- return nullptr;
- }
-}
-
-- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
- // Note: may be called called before main loop init!
- char *utfs = strdup([filename UTF8String]);
- ((OS_OSX *)OS_OSX::get_singleton())->open_with_filename.parse_utf8(utfs);
- free(utfs);
-
-#ifdef TOOLS_ENABLED
- // Open new instance
- if (OS_OSX::get_singleton()->get_main_loop()) {
- List<String> args;
- args.push_back(((OS_OSX *)OS_OSX::get_singleton())->open_with_filename);
- String exec = OS_OSX::get_singleton()->get_executable_path();
- OS_OSX::get_singleton()->create_process(exec, args);
- }
-#endif
- return YES;
-}
-
-- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
- if (DS_OSX) {
- DS_OSX->_send_window_event(DS_OSX->windows[DisplayServerOSX::MAIN_WINDOW_ID], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST);
- }
- return NSTerminateCancel;
-}
-
-- (void)showAbout:(id)sender {
- if (OS_OSX::get_singleton()->get_main_loop()) {
- OS_OSX::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_ABOUT);
+ return p_path;
}
}
-@end
-
-/*************************************************************************/
-/* OSXTerminalLogger */
-/*************************************************************************/
-
-class OSXTerminalLogger : public StdLogger {
-public:
- virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify = false, ErrorType p_type = ERR_ERROR) {
- if (!should_log(true)) {
- return;
- }
-
- const char *err_details;
- if (p_rationale && p_rationale[0])
- err_details = p_rationale;
- else
- err_details = p_code;
-
- switch (p_type) {
- case ERR_WARNING:
- os_log_info(OS_LOG_DEFAULT,
- "WARNING: %{public}s\nat: %{public}s (%{public}s:%i)",
- err_details, p_function, p_file, p_line);
- logf_error("\E[1;33mWARNING:\E[0;93m %s\n", err_details);
- logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
- break;
- case ERR_SCRIPT:
- os_log_error(OS_LOG_DEFAULT,
- "SCRIPT ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
- err_details, p_function, p_file, p_line);
- logf_error("\E[1;35mSCRIPT ERROR:\E[0;95m %s\n", err_details);
- logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
- break;
- case ERR_SHADER:
- os_log_error(OS_LOG_DEFAULT,
- "SHADER ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
- err_details, p_function, p_file, p_line);
- logf_error("\E[1;36mSHADER ERROR:\E[0;96m %s\n", err_details);
- logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
- break;
- case ERR_ERROR:
- default:
- os_log_error(OS_LOG_DEFAULT,
- "ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
- err_details, p_function, p_file, p_line);
- logf_error("\E[1;31mERROR:\E[0;91m %s\n", err_details);
- logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
- break;
- }
- }
-};
-
-/*************************************************************************/
-/* OS_OSX */
-/*************************************************************************/
-
-String OS_OSX::get_unique_id() const {
- static String serial_number;
-
- if (serial_number.is_empty()) {
- io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
- CFStringRef serialNumberAsCFString = nullptr;
- if (platformExpert) {
- serialNumberAsCFString = (CFStringRef)IORegistryEntryCreateCFProperty(platformExpert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
- IOObjectRelease(platformExpert);
- }
+void OS_OSX::pre_wait_observer_cb(CFRunLoopObserverRef p_observer, CFRunLoopActivity p_activiy, void *p_context) {
+ // Prevent main loop from sleeping and redraw window during resize / modal popups.
- NSString *serialNumberAsNSString = nil;
- if (serialNumberAsCFString) {
- serialNumberAsNSString = [NSString stringWithString:(NSString *)serialNumberAsCFString];
- CFRelease(serialNumberAsCFString);
+ if (get_singleton()->get_main_loop()) {
+ Main::force_redraw();
+ if (!Main::is_iterating()) { // Avoid cyclic loop.
+ Main::iteration();
}
-
- serial_number = [serialNumberAsNSString UTF8String];
}
- return serial_number;
+ CFRunLoopWakeUp(CFRunLoopGetCurrent()); // Prevent main loop from sleeping.
}
-void OS_OSX::alert(const String &p_alert, const String &p_title) {
- NSAlert *window = [[NSAlert alloc] init];
- NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
- NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
-
- [window addButtonWithTitle:@"OK"];
- [window setMessageText:ns_title];
- [window setInformativeText:ns_alert];
- [window setAlertStyle:NSAlertStyleWarning];
+void OS_OSX::initialize() {
+ crash_handler.initialize();
- id key_window = [[NSApplication sharedApplication] keyWindow];
- [window runModal];
- [window release];
- if (key_window) {
- [key_window makeKeyAndOrderFront:nil];
- }
+ initialize_core();
}
void OS_OSX::initialize_core() {
@@ -276,17 +80,6 @@ void OS_OSX::initialize_core() {
DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_FILESYSTEM);
}
-void OS_OSX::initialize_joypads() {
- joypad_osx = memnew(JoypadOSX(Input::get_singleton()));
-}
-
-void OS_OSX::initialize() {
- crash_handler.initialize();
-
- initialize_core();
- //ensure_user_data_dir();
-}
-
void OS_OSX::finalize() {
#ifdef COREMIDI_ENABLED
midi_driver.close();
@@ -299,42 +92,63 @@ void OS_OSX::finalize() {
}
}
+void OS_OSX::initialize_joypads() {
+ joypad_osx = memnew(JoypadOSX(Input::get_singleton()));
+}
+
void OS_OSX::set_main_loop(MainLoop *p_main_loop) {
main_loop = p_main_loop;
}
void OS_OSX::delete_main_loop() {
- if (!main_loop)
+ if (!main_loop) {
return;
+ }
+
memdelete(main_loop);
main_loop = nullptr;
}
+String OS_OSX::get_open_with_filename() const {
+ return open_with_filename;
+}
+
+void OS_OSX::set_open_with_filename(const String &p_path) {
+ open_with_filename = p_path;
+}
+
String OS_OSX::get_name() const {
return "macOS";
}
-_FORCE_INLINE_ String _get_framework_executable(const String p_path) {
- // Append framework executable name, or return as is if p_path is not a framework.
- DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- if (da->dir_exists(p_path) && da->file_exists(p_path.plus_file(p_path.get_file().get_basename()))) {
- return p_path.plus_file(p_path.get_file().get_basename());
- } else {
- return p_path;
+void OS_OSX::alert(const String &p_alert, const String &p_title) {
+ NSAlert *window = [[NSAlert alloc] init];
+ NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
+ NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
+
+ [window addButtonWithTitle:@"OK"];
+ [window setMessageText:ns_title];
+ [window setInformativeText:ns_alert];
+ [window setAlertStyle:NSAlertStyleWarning];
+
+ id key_window = [[NSApplication sharedApplication] keyWindow];
+ [window runModal];
+ if (key_window) {
+ [key_window makeKeyAndOrderFront:nil];
}
}
Error OS_OSX::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
- String path = _get_framework_executable(p_path);
+ String path = get_framework_executable(p_path);
if (!FileAccess::exists(path)) {
- // This code exists so gdnative can load .dylib files from within the executable path.
- path = _get_framework_executable(get_executable_path().get_base_dir().plus_file(p_path.get_file()));
+ // Load .dylib or framework from within the executable path.
+ path = get_framework_executable(get_executable_path().get_base_dir().plus_file(p_path.get_file()));
}
if (!FileAccess::exists(path)) {
- // This code exists so gdnative can load .dylib files from a standard macOS location.
- path = _get_framework_executable(get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(p_path.get_file()));
+ // Load .dylib or framework from a standard macOS location.
+ path = get_framework_executable(get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(p_path.get_file()));
}
p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
@@ -393,8 +207,8 @@ String OS_OSX::get_bundle_resource_dir() const {
NSBundle *main = [NSBundle mainBundle];
if (main) {
- NSString *resourcePath = [main resourcePath];
- ret.parse_utf8([resourcePath UTF8String]);
+ NSString *resource_path = [main resourcePath];
+ ret.parse_utf8([resource_path UTF8String]);
}
return ret;
}
@@ -404,9 +218,9 @@ String OS_OSX::get_bundle_icon_path() const {
NSBundle *main = [NSBundle mainBundle];
if (main) {
- NSString *iconPath = [[main infoDictionary] objectForKey:@"CFBundleIconFile"];
- if (iconPath) {
- ret.parse_utf8([iconPath UTF8String]);
+ NSString *icon_path = [[main infoDictionary] objectForKey:@"CFBundleIconFile"];
+ if (icon_path) {
+ ret.parse_utf8([icon_path UTF8String]);
}
}
return ret;
@@ -449,9 +263,7 @@ String OS_OSX::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
if (found) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
if (paths && [paths count] >= 1) {
- char *utfs = strdup([[paths firstObject] UTF8String]);
- ret.parse_utf8(utfs);
- free(utfs);
+ ret.parse_utf8([[paths firstObject] UTF8String]);
}
}
@@ -475,12 +287,9 @@ String OS_OSX::get_locale() const {
}
String OS_OSX::get_executable_path() const {
- int ret;
- pid_t pid;
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
-
- pid = getpid();
- ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
+ int pid = getpid();
+ pid_t ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
if (ret <= 0) {
return OS::get_executable_path();
} else {
@@ -491,18 +300,6 @@ String OS_OSX::get_executable_path() const {
}
}
-Error OS_OSX::create_instance(const List<String> &p_arguments, ProcessID *r_child_id) {
- // If executable is bundled, always execute editor instances as an app bundle to ensure app window is registered and activated correctly.
- NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
- if (nsappname != nil) {
- String path;
- path.parse_utf8([[[NSBundle mainBundle] bundlePath] UTF8String]);
- return create_process(path, p_arguments, r_child_id, false);
- } else {
- return create_process(get_executable_path(), p_arguments, r_child_id, false);
- }
-}
-
Error OS_OSX::create_process(const String &p_path, const List<String> &p_arguments, ProcessID *r_child_id, bool p_open_console) {
if (@available(macOS 10.15, *)) {
// Use NSWorkspace if path is an .app bundle.
@@ -532,7 +329,6 @@ Error OS_OSX::create_process(const String &p_path, const List<String> &p_argumen
dispatch_semaphore_signal(lock);
}];
dispatch_semaphore_wait(lock, dispatch_time(DISPATCH_TIME_NOW, 20000000000)); // 20 sec timeout, wait for app to launch.
- dispatch_release(lock);
if (err == OK) {
if (r_child_id) {
@@ -549,17 +345,66 @@ Error OS_OSX::create_process(const String &p_path, const List<String> &p_argumen
}
}
-void OS_OSX::pre_wait_observer_cb(CFRunLoopObserverRef p_observer, CFRunLoopActivity p_activiy, void *p_context) {
- // Prevent main loop from sleeping and redraw window during resize / modal popups.
+Error OS_OSX::create_instance(const List<String> &p_arguments, ProcessID *r_child_id) {
+ // If executable is bundled, always execute editor instances as an app bundle to ensure app window is registered and activated correctly.
+ NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
+ if (nsappname != nil) {
+ String path;
+ path.parse_utf8([[[NSBundle mainBundle] bundlePath] UTF8String]);
+ return create_process(path, p_arguments, r_child_id, false);
+ } else {
+ return create_process(get_executable_path(), p_arguments, r_child_id, false);
+ }
+}
- if (get_singleton()->get_main_loop()) {
- Main::force_redraw();
- if (!Main::is_iterating()) { // Avoid cyclic loop.
- Main::iteration();
+String OS_OSX::get_unique_id() const {
+ static String serial_number;
+
+ if (serial_number.is_empty()) {
+ io_service_t platform_expert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
+ CFStringRef serial_number_cf_string = nullptr;
+ if (platform_expert) {
+ serial_number_cf_string = (CFStringRef)IORegistryEntryCreateCFProperty(platform_expert, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0);
+ IOObjectRelease(platform_expert);
+ }
+
+ NSString *serial_number_ns_string = nil;
+ if (serial_number_cf_string) {
+ serial_number_ns_string = [NSString stringWithString:(__bridge NSString *)serial_number_cf_string];
+ CFRelease(serial_number_cf_string);
+ }
+
+ if (serial_number_ns_string) {
+ serial_number.parse_utf8([serial_number_ns_string UTF8String]);
}
}
- CFRunLoopWakeUp(CFRunLoopGetCurrent()); // Prevent main loop from sleeping.
+ return serial_number;
+}
+
+bool OS_OSX::_check_internal_feature_support(const String &p_feature) {
+ return p_feature == "pc";
+}
+
+void OS_OSX::disable_crash_handler() {
+ crash_handler.disable();
+}
+
+bool OS_OSX::is_disable_crash_handler() const {
+ return crash_handler.is_disabled();
+}
+
+Error OS_OSX::move_to_trash(const String &p_path) {
+ NSFileManager *fm = [NSFileManager defaultManager];
+ NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
+ NSError *err;
+
+ if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
+ ERR_PRINT("trashItemAtURL error: " + String::utf8(err.localizedDescription.UTF8String));
+ return FAILED;
+ }
+
+ return OK;
}
void OS_OSX::run() {
@@ -571,14 +416,11 @@ void OS_OSX::run() {
main_loop->initialize();
- CFRunLoopObserverRef pre_wait_observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, &pre_wait_observer_cb, nullptr);
- CFRunLoopAddObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
-
bool quit = false;
while (!force_quit && !quit) {
@try {
if (DisplayServer::get_singleton()) {
- DisplayServer::get_singleton()->process_events(); // get rid of pending events
+ DisplayServer::get_singleton()->process_events(); // Get rid of pending events.
}
joypad_osx->process_joypads();
@@ -590,25 +432,9 @@ void OS_OSX::run() {
}
};
- CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
- CFRelease(pre_wait_observer);
-
main_loop->finalize();
}
-Error OS_OSX::move_to_trash(const String &p_path) {
- NSFileManager *fm = [NSFileManager defaultManager];
- NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
- NSError *err;
-
- if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
- ERR_PRINT("trashItemAtURL error: " + String::utf8(err.localizedDescription.UTF8String));
- return FAILED;
- }
-
- return OK;
-}
-
OS_OSX::OS_OSX() {
main_loop = nullptr;
force_quit = false;
@@ -623,17 +449,17 @@ OS_OSX::OS_OSX() {
DisplayServerOSX::register_osx_driver();
- // Implicitly create shared NSApplication instance
+ // Implicitly create shared NSApplication instance.
[GodotApplication sharedApplication];
- // In case we are unbundled, make us a proper UI application
+ // In case we are unbundled, make us a proper UI application.
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Menu bar setup must go between sharedApplication above and
// finishLaunching below, in order to properly emulate the behavior
- // of NSApplicationMain
+ // of NSApplicationMain.
- NSMenu *main_menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
+ NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
[NSApp setMainMenu:main_menu];
[NSApp finishLaunching];
@@ -641,7 +467,10 @@ OS_OSX::OS_OSX() {
ERR_FAIL_COND(!delegate);
[NSApp setDelegate:delegate];
- //process application:openFile: event
+ pre_wait_observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, true, 0, &pre_wait_observer_cb, nullptr);
+ CFRunLoopAddObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
+
+ // Process application:openFile: event.
while (true) {
NSEvent *event = [NSApp
nextEventMatchingMask:NSEventMaskAny
@@ -659,14 +488,7 @@ OS_OSX::OS_OSX() {
[NSApp activateIgnoringOtherApps:YES];
}
-bool OS_OSX::_check_internal_feature_support(const String &p_feature) {
- return p_feature == "pc";
-}
-
-void OS_OSX::disable_crash_handler() {
- crash_handler.disable();
-}
-
-bool OS_OSX::is_disable_crash_handler() const {
- return crash_handler.is_disabled();
+OS_OSX::~OS_OSX() {
+ CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), pre_wait_observer, kCFRunLoopCommonModes);
+ CFRelease(pre_wait_observer);
}
diff --git a/platform/osx/osx_terminal_logger.h b/platform/osx/osx_terminal_logger.h
new file mode 100644
index 0000000000..8413509c4b
--- /dev/null
+++ b/platform/osx/osx_terminal_logger.h
@@ -0,0 +1,44 @@
+/*************************************************************************/
+/* osx_terminal_logger.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 OSX_TERMINAL_LOGGER_H
+#define OSX_TERMINAL_LOGGER_H
+
+#ifdef OSX_ENABLED
+
+#include "core/io/logger.h"
+
+class OSXTerminalLogger : public StdLogger {
+public:
+ virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify = false, ErrorType p_type = ERR_ERROR) override;
+};
+
+#endif // OSX_ENABLED
+#endif // OSX_TERMINAL_LOGGER_H
diff --git a/platform/osx/osx_terminal_logger.mm b/platform/osx/osx_terminal_logger.mm
new file mode 100644
index 0000000000..c1dca111a7
--- /dev/null
+++ b/platform/osx/osx_terminal_logger.mm
@@ -0,0 +1,81 @@
+/*************************************************************************/
+/* osx_terminal_logger.mm */
+/*************************************************************************/
+/* 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 "osx_terminal_logger.h"
+
+#ifdef OSX_ENABLED
+
+#include <os/log.h>
+
+void OSXTerminalLogger::log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, ErrorType p_type) {
+ if (!should_log(true)) {
+ return;
+ }
+
+ const char *err_details;
+ if (p_rationale && p_rationale[0])
+ err_details = p_rationale;
+ else
+ err_details = p_code;
+
+ switch (p_type) {
+ case ERR_WARNING:
+ os_log_info(OS_LOG_DEFAULT,
+ "WARNING: %{public}s\nat: %{public}s (%{public}s:%i)",
+ err_details, p_function, p_file, p_line);
+ logf_error("\E[1;33mWARNING:\E[0;93m %s\n", err_details);
+ logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
+ break;
+ case ERR_SCRIPT:
+ os_log_error(OS_LOG_DEFAULT,
+ "SCRIPT ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
+ err_details, p_function, p_file, p_line);
+ logf_error("\E[1;35mSCRIPT ERROR:\E[0;95m %s\n", err_details);
+ logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
+ break;
+ case ERR_SHADER:
+ os_log_error(OS_LOG_DEFAULT,
+ "SHADER ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
+ err_details, p_function, p_file, p_line);
+ logf_error("\E[1;36mSHADER ERROR:\E[0;96m %s\n", err_details);
+ logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
+ break;
+ case ERR_ERROR:
+ default:
+ os_log_error(OS_LOG_DEFAULT,
+ "ERROR: %{public}s\nat: %{public}s (%{public}s:%i)",
+ err_details, p_function, p_file, p_line);
+ logf_error("\E[1;31mERROR:\E[0;91m %s\n", err_details);
+ logf_error("\E[0;90m at: %s (%s:%i)\E[0m\n", p_function, p_file, p_line);
+ break;
+ }
+}
+
+#endif // OSX_ENABLED
diff --git a/platform/osx/vulkan_context_osx.mm b/platform/osx/vulkan_context_osx.mm
index f32fab1eee..bdabc24c28 100644
--- a/platform/osx/vulkan_context_osx.mm
+++ b/platform/osx/vulkan_context_osx.mm
@@ -44,7 +44,7 @@ Error VulkanContextOSX::window_create(DisplayServer::WindowID p_window_id, Displ
createInfo.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
createInfo.pNext = nullptr;
createInfo.flags = 0;
- createInfo.pView = p_window;
+ createInfo.pView = (__bridge const void *)p_window;
VkSurfaceKHR surface;
VkResult err = vkCreateMacOSSurfaceMVK(get_instance(), &createInfo, nullptr, &surface);
diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp
index b340129a16..20268b3f6a 100644
--- a/platform/windows/display_server_windows.cpp
+++ b/platform/windows/display_server_windows.cpp
@@ -546,6 +546,15 @@ DisplayServer::WindowID DisplayServerWindows::create_sub_window(WindowMode p_mod
wd.no_focus = true;
}
+ // Inherit icons from MAIN_WINDOW for all sub windows.
+ HICON mainwindow_icon = (HICON)SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_GETICON, ICON_SMALL, 0);
+ if (mainwindow_icon) {
+ SendMessage(windows[window_id].hWnd, WM_SETICON, ICON_SMALL, (LPARAM)mainwindow_icon);
+ }
+ mainwindow_icon = (HICON)SendMessage(windows[MAIN_WINDOW_ID].hWnd, WM_GETICON, ICON_BIG, 0);
+ if (mainwindow_icon) {
+ SendMessage(windows[window_id].hWnd, WM_SETICON, ICON_BIG, (LPARAM)mainwindow_icon);
+ }
return window_id;
}
@@ -2701,12 +2710,17 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
case WM_WINDOWPOSCHANGED: {
Rect2i window_client_rect;
+ Rect2i window_rect;
{
RECT rect;
GetClientRect(hWnd, &rect);
ClientToScreen(hWnd, (POINT *)&rect.left);
ClientToScreen(hWnd, (POINT *)&rect.right);
window_client_rect = Rect2i(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
+
+ RECT wrect;
+ GetWindowRect(hWnd, &wrect);
+ window_rect = Rect2i(wrect.left, wrect.top, wrect.right - wrect.left, wrect.bottom - wrect.top);
}
WINDOWPOS *window_pos_params = (WINDOWPOS *)lParam;
@@ -2726,7 +2740,7 @@ LRESULT DisplayServerWindows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
window.minimized = true;
} else if (IsZoomed(hWnd)) {
window.maximized = true;
- } else if (window_client_rect.position == screen_position && window_client_rect.size == screen_size) {
+ } else if (window_rect.position == screen_position && window_rect.size == screen_size) {
window.fullscreen = true;
}
diff --git a/scene/2d/navigation_region_2d.cpp b/scene/2d/navigation_region_2d.cpp
index 4bead978f1..e685ad8f67 100644
--- a/scene/2d/navigation_region_2d.cpp
+++ b/scene/2d/navigation_region_2d.cpp
@@ -104,8 +104,8 @@ void NavigationPolygon::_set_polygons(const TypedArray<Vector<int32_t>> &p_array
}
}
-Array NavigationPolygon::_get_polygons() const {
- Array ret;
+TypedArray<Vector<int32_t>> NavigationPolygon::_get_polygons() const {
+ TypedArray<Vector<int32_t>> ret;
ret.resize(polygons.size());
for (int i = 0; i < ret.size(); i++) {
ret[i] = polygons[i].indices;
@@ -122,8 +122,8 @@ void NavigationPolygon::_set_outlines(const TypedArray<Vector<Vector2>> &p_array
rect_cache_dirty = true;
}
-Array NavigationPolygon::_get_outlines() const {
- Array ret;
+TypedArray<Vector<Vector2>> NavigationPolygon::_get_outlines() const {
+ TypedArray<Vector<Vector2>> ret;
ret.resize(outlines.size());
for (int i = 0; i < ret.size(); i++) {
ret[i] = outlines[i];
diff --git a/scene/2d/navigation_region_2d.h b/scene/2d/navigation_region_2d.h
index 012debb584..487a578401 100644
--- a/scene/2d/navigation_region_2d.h
+++ b/scene/2d/navigation_region_2d.h
@@ -55,10 +55,10 @@ protected:
static void _bind_methods();
void _set_polygons(const TypedArray<Vector<int32_t>> &p_array);
- Array _get_polygons() const;
+ TypedArray<Vector<int32_t>> _get_polygons() const;
void _set_outlines(const TypedArray<Vector<Vector2>> &p_array);
- Array _get_outlines() const;
+ TypedArray<Vector<Vector2>> _get_outlines() const;
public:
#ifdef TOOLS_ENABLED
diff --git a/scene/2d/ray_cast_2d.cpp b/scene/2d/ray_cast_2d.cpp
index 9521667854..51b3e676f9 100644
--- a/scene/2d/ray_cast_2d.cpp
+++ b/scene/2d/ray_cast_2d.cpp
@@ -279,6 +279,13 @@ void RayCast2D::remove_exception(const CollisionObject2D *p_node) {
void RayCast2D::clear_exceptions() {
exclude.clear();
+
+ if (exclude_parent_body && is_inside_tree()) {
+ CollisionObject2D *parent = Object::cast_to<CollisionObject2D>(get_parent());
+ if (parent) {
+ exclude.insert(parent->get_rid());
+ }
+ }
}
void RayCast2D::set_collide_with_areas(bool p_enabled) {
diff --git a/scene/3d/ray_cast_3d.cpp b/scene/3d/ray_cast_3d.cpp
index b71c54dcf9..b251aa38ba 100644
--- a/scene/3d/ray_cast_3d.cpp
+++ b/scene/3d/ray_cast_3d.cpp
@@ -259,6 +259,13 @@ void RayCast3D::remove_exception(const CollisionObject3D *p_node) {
void RayCast3D::clear_exceptions() {
exclude.clear();
+
+ if (exclude_parent_body && is_inside_tree()) {
+ CollisionObject3D *parent = Object::cast_to<CollisionObject3D>(get_parent());
+ if (parent) {
+ exclude.insert(parent->get_rid());
+ }
+ }
}
void RayCast3D::set_collide_with_areas(bool p_enabled) {
diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp
index 31f3b306b7..ad2434cd8b 100644
--- a/scene/gui/option_button.cpp
+++ b/scene/gui/option_button.cpp
@@ -118,6 +118,11 @@ void OptionButton::_notification(int p_what) {
bool OptionButton::_set(const StringName &p_name, const Variant &p_value) {
Vector<String> components = String(p_name).split("/", true, 2);
if (components.size() >= 2 && components[0] == "popup") {
+ String property = components[2];
+ if (property != "text" && property != "icon" && property != "id" && property != "disabled" && property != "separator") {
+ return false;
+ }
+
bool valid;
popup->set(String(p_name).trim_prefix("popup/"), p_value, &valid);
@@ -136,6 +141,11 @@ bool OptionButton::_set(const StringName &p_name, const Variant &p_value) {
bool OptionButton::_get(const StringName &p_name, Variant &r_ret) const {
Vector<String> components = String(p_name).split("/", true, 2);
if (components.size() >= 2 && components[0] == "popup") {
+ String property = components[2];
+ if (property != "text" && property != "icon" && property != "id" && property != "disabled" && property != "separator") {
+ return false;
+ }
+
bool valid;
r_ret = popup->get(String(p_name).trim_prefix("popup/"), &valid);
return valid;
@@ -151,14 +161,6 @@ void OptionButton::_get_property_list(List<PropertyInfo> *p_list) const {
pi.usage &= ~(popup->get_item_icon(i).is_null() ? PROPERTY_USAGE_STORAGE : 0);
p_list->push_back(pi);
- pi = PropertyInfo(Variant::INT, vformat("popup/item_%d/checkable", i), PROPERTY_HINT_ENUM, "No,As checkbox,As radio button");
- pi.usage &= ~(!popup->is_item_checkable(i) ? PROPERTY_USAGE_STORAGE : 0);
- p_list->push_back(pi);
-
- pi = PropertyInfo(Variant::BOOL, vformat("popup/item_%d/checked", i));
- pi.usage &= ~(!popup->is_item_checked(i) ? PROPERTY_USAGE_STORAGE : 0);
- p_list->push_back(pi);
-
pi = PropertyInfo(Variant::INT, vformat("popup/item_%d/id", i), PROPERTY_HINT_RANGE, "0,10,1,or_greater");
p_list->push_back(pi);
@@ -186,10 +188,13 @@ void OptionButton::pressed() {
popup->set_size(Size2(size.width, 0));
// If not triggered by the mouse, start the popup with the checked item selected.
- if (popup->get_item_count() > 0 &&
- ((get_action_mode() == ActionMode::ACTION_MODE_BUTTON_PRESS && Input::get_singleton()->is_action_just_pressed("ui_accept")) ||
- (get_action_mode() == ActionMode::ACTION_MODE_BUTTON_RELEASE && Input::get_singleton()->is_action_just_released("ui_accept")))) {
- popup->set_current_index(current > -1 ? current : 0);
+ if (popup->get_item_count() > 0) {
+ if ((get_action_mode() == ActionMode::ACTION_MODE_BUTTON_PRESS && Input::get_singleton()->is_action_just_pressed("ui_accept")) ||
+ (get_action_mode() == ActionMode::ACTION_MODE_BUTTON_RELEASE && Input::get_singleton()->is_action_just_released("ui_accept"))) {
+ popup->set_current_index(current > -1 ? current : 0);
+ } else {
+ popup->scroll_to_item(current > -1 ? current : 0);
+ }
}
popup->popup();
@@ -267,7 +272,20 @@ bool OptionButton::is_item_disabled(int p_idx) const {
void OptionButton::set_item_count(int p_count) {
ERR_FAIL_COND(p_count < 0);
+
+ int count_old = get_item_count();
+ if (p_count == count_old) {
+ return;
+ }
+
popup->set_item_count(p_count);
+
+ if (p_count > count_old) {
+ for (int i = count_old; i < p_count; i++) {
+ popup->set_item_as_radio_checkable(i, true);
+ }
+ }
+
notify_property_list_changed();
}
@@ -297,7 +315,7 @@ void OptionButton::_select(int p_which, bool p_emit) {
current = NONE_SELECTED;
set_text("");
- set_icon(NULL);
+ set_icon(nullptr);
} else {
ERR_FAIL_INDEX(p_which, popup->get_item_count());
diff --git a/scene/gui/panel.cpp b/scene/gui/panel.cpp
index 86858fdc78..c88e4ae2f2 100644
--- a/scene/gui/panel.cpp
+++ b/scene/gui/panel.cpp
@@ -30,35 +30,14 @@
#include "panel.h"
-#include "core/string/print_string.h"
-
void Panel::_notification(int p_what) {
if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- Ref<StyleBox> style = mode == MODE_BACKGROUND ? get_theme_stylebox(SNAME("panel")) : get_theme_stylebox(SNAME("panel_fg"));
+ Ref<StyleBox> style = get_theme_stylebox(SNAME("panel"));
style->draw(ci, Rect2(Point2(), get_size()));
}
}
-void Panel::set_mode(Mode p_mode) {
- mode = p_mode;
- update();
-}
-
-Panel::Mode Panel::get_mode() const {
- return mode;
-}
-
-void Panel::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_mode", "mode"), &Panel::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"), &Panel::get_mode);
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Background,Foreground"), "set_mode", "get_mode");
-
- BIND_ENUM_CONSTANT(MODE_BACKGROUND);
- BIND_ENUM_CONSTANT(MODE_FOREGROUND);
-}
-
Panel::Panel() {
// Has visible stylebox, so stop by default.
set_mouse_filter(MOUSE_FILTER_STOP);
diff --git a/scene/gui/panel.h b/scene/gui/panel.h
index 37f14c250c..5d2e912680 100644
--- a/scene/gui/panel.h
+++ b/scene/gui/panel.h
@@ -36,26 +36,11 @@
class Panel : public Control {
GDCLASS(Panel, Control);
-public:
- enum Mode {
- MODE_BACKGROUND,
- MODE_FOREGROUND,
- };
-
-private:
- Mode mode = MODE_BACKGROUND;
-
protected:
void _notification(int p_what);
- static void _bind_methods();
public:
- void set_mode(Mode p_mode);
- Mode get_mode() const;
-
Panel();
};
-VARIANT_ENUM_CAST(Panel::Mode)
-
#endif // PANEL_H
diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp
index 6d43bbdcf3..6e0f1c5198 100644
--- a/scene/gui/popup_menu.cpp
+++ b/scene/gui/popup_menu.cpp
@@ -108,7 +108,6 @@ Size2 PopupMenu::_get_contents_minimum_size() const {
int PopupMenu::_get_item_height(int p_item) const {
ERR_FAIL_INDEX_V(p_item, items.size(), 0);
- ERR_FAIL_COND_V(p_item < 0, 0);
int icon_height = items[p_item].get_icon_size().height;
if (items[p_item].checkable_type && !items[p_item].separator) {
@@ -141,23 +140,6 @@ int PopupMenu::_get_items_total_height() const {
return items_total_height - vsep;
}
-void PopupMenu::_scroll_to_item(int p_item) {
- ERR_FAIL_INDEX(p_item, items.size());
- ERR_FAIL_COND(p_item < 0);
-
- // Scroll item into view (upwards)
- if (items[p_item]._ofs_cache < -control->get_position().y) {
- int amnt_over = items[p_item]._ofs_cache + control->get_position().y;
- scroll_container->set_v_scroll(scroll_container->get_v_scroll() + amnt_over);
- }
-
- // Scroll item into view (downwards)
- if (items[p_item]._ofs_cache + items[p_item]._height_cache > -control->get_position().y + scroll_container->get_size().height) {
- int amnt_over = items[p_item]._ofs_cache + items[p_item]._height_cache + control->get_position().y - scroll_container->get_size().height;
- scroll_container->set_v_scroll(scroll_container->get_v_scroll() + amnt_over);
- }
-}
-
int PopupMenu::_get_mouse_over(const Point2 &p_over) const {
if (p_over.x < 0 || p_over.x >= get_size().width) {
return -1;
@@ -276,7 +258,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
if (!items[i].separator && !items[i].disabled) {
mouse_over = i;
emit_signal(SNAME("id_focused"), i);
- _scroll_to_item(i);
+ scroll_to_item(i);
control->update();
set_input_as_handled();
match_found = true;
@@ -290,7 +272,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
if (!items[i].separator && !items[i].disabled) {
mouse_over = i;
emit_signal(SNAME("id_focused"), i);
- _scroll_to_item(i);
+ scroll_to_item(i);
control->update();
set_input_as_handled();
break;
@@ -308,7 +290,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
if (!items[i].separator && !items[i].disabled) {
mouse_over = i;
emit_signal(SNAME("id_focused"), i);
- _scroll_to_item(i);
+ scroll_to_item(i);
control->update();
set_input_as_handled();
match_found = true;
@@ -322,7 +304,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
if (!items[i].separator && !items[i].disabled) {
mouse_over = i;
emit_signal(SNAME("id_focused"), i);
- _scroll_to_item(i);
+ scroll_to_item(i);
control->update();
set_input_as_handled();
break;
@@ -472,7 +454,7 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
if (items[i].text.findn(search_string) == 0) {
mouse_over = i;
emit_signal(SNAME("id_focused"), i);
- _scroll_to_item(i);
+ scroll_to_item(i);
control->update();
set_input_as_handled();
break;
@@ -1324,7 +1306,7 @@ bool PopupMenu::is_item_shortcut_disabled(int p_idx) const {
void PopupMenu::set_current_index(int p_idx) {
ERR_FAIL_INDEX(p_idx, items.size());
mouse_over = p_idx;
- _scroll_to_item(mouse_over);
+ scroll_to_item(mouse_over);
control->update();
}
@@ -1352,6 +1334,20 @@ int PopupMenu::get_item_count() const {
return items.size();
}
+void PopupMenu::scroll_to_item(int p_item) {
+ ERR_FAIL_INDEX(p_item, items.size());
+
+ // Scroll item into view (upwards).
+ if (items[p_item]._ofs_cache - scroll_container->get_v_scroll() < -control->get_position().y) {
+ scroll_container->set_v_scroll(items[p_item]._ofs_cache + control->get_position().y);
+ }
+
+ // Scroll item into view (downwards).
+ if (items[p_item]._ofs_cache + items[p_item]._height_cache - scroll_container->get_v_scroll() > -control->get_position().y + scroll_container->get_size().height) {
+ scroll_container->set_v_scroll(items[p_item]._ofs_cache + items[p_item]._height_cache + control->get_position().y);
+ }
+}
+
bool PopupMenu::activate_item_by_event(const Ref<InputEvent> &p_event, bool p_for_global_only) {
Key code = Key::NONE;
Ref<InputEventKey> k = p_event;
@@ -1625,7 +1621,7 @@ bool PopupMenu::_set(const StringName &p_name, const Variant &p_value) {
} else if (property == "id") {
set_item_id(item_index, p_value);
return true;
- } else if (components[1] == "disabled") {
+ } else if (property == "disabled") {
set_item_disabled(item_index, p_value);
return true;
} else if (property == "separator") {
@@ -1698,7 +1694,7 @@ bool PopupMenu::_get(const StringName &p_name, Variant &r_ret) const {
} else if (property == "id") {
r_ret = get_item_id(item_index);
return true;
- } else if (components[1] == "disabled") {
+ } else if (property == "disabled") {
r_ret = is_item_disabled(item_index);
return true;
} else if (property == "separator") {
@@ -1804,6 +1800,8 @@ void PopupMenu::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_item_count", "count"), &PopupMenu::set_item_count);
ClassDB::bind_method(D_METHOD("get_item_count"), &PopupMenu::get_item_count);
+ ClassDB::bind_method(D_METHOD("scroll_to_item", "index"), &PopupMenu::scroll_to_item);
+
ClassDB::bind_method(D_METHOD("remove_item", "index"), &PopupMenu::remove_item);
ClassDB::bind_method(D_METHOD("add_separator", "label", "id"), &PopupMenu::add_separator, DEFVAL(String()), DEFVAL(-1));
diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h
index 7c2212d82d..5ce55209d4 100644
--- a/scene/gui/popup_menu.h
+++ b/scene/gui/popup_menu.h
@@ -103,7 +103,6 @@ class PopupMenu : public Popup {
int _get_item_height(int p_item) const;
int _get_items_total_height() const;
- void _scroll_to_item(int p_item);
void _shape_item(int p_item);
@@ -218,6 +217,8 @@ public:
void set_item_count(int p_count);
int get_item_count() const;
+ void scroll_to_item(int p_item);
+
bool activate_item_by_event(const Ref<InputEvent> &p_event, bool p_for_global_only = false);
void activate_item(int p_item);
diff --git a/scene/gui/tab_bar.cpp b/scene/gui/tab_bar.cpp
index 5a551ec5a5..b1baacd887 100644
--- a/scene/gui/tab_bar.cpp
+++ b/scene/gui/tab_bar.cpp
@@ -761,6 +761,8 @@ void TabBar::_update_hover() {
return;
}
+ ERR_FAIL_COND(tabs.is_empty());
+
const Point2 &pos = get_local_mouse_position();
// Test hovering to display right or close button.
int hover_now = -1;
@@ -1436,7 +1438,6 @@ void TabBar::_get_property_list(List<PropertyInfo> *p_list) const {
}
void TabBar::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_update_hover"), &TabBar::_update_hover);
ClassDB::bind_method(D_METHOD("set_tab_count", "count"), &TabBar::set_tab_count);
ClassDB::bind_method(D_METHOD("get_tab_count"), &TabBar::get_tab_count);
ClassDB::bind_method(D_METHOD("set_current_tab", "tab_idx"), &TabBar::set_current_tab);
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index e33ce0b017..9a6c87276f 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -4409,21 +4409,29 @@ Point2 Tree::get_scroll() const {
return ofs;
}
-void Tree::scroll_to_item(TreeItem *p_item) {
+void Tree::scroll_to_item(TreeItem *p_item, bool p_center_on_item) {
if (!is_visible_in_tree()) {
- // hack to work around crash in get_item_rect() if Tree is not in tree.
- return;
+ return; // Hack to work around crash in get_item_rect() if Tree is not in tree.
}
- // make sure the scrollbar min and max are up to date with latest changes.
update_scrollbars();
- const Rect2 r = get_item_rect(p_item);
+ const real_t tree_height = get_size().y;
+ const Rect2 item_rect = get_item_rect(p_item);
+ const real_t item_y = item_rect.position.y;
+ const real_t item_height = item_rect.size.y + cache.vseparation;
- if (r.position.y <= v_scroll->get_value()) {
- v_scroll->set_value(r.position.y);
- } else if (r.position.y + r.size.y + 2 * cache.vseparation > v_scroll->get_value() + get_size().y) {
- v_scroll->set_value(r.position.y + r.size.y + 2 * cache.vseparation - get_size().y);
+ if (p_center_on_item) {
+ v_scroll->set_value(item_y - (tree_height - item_height) / 2.0f);
+ } else {
+ if (item_y < v_scroll->get_value()) {
+ v_scroll->set_value(item_y);
+ } else {
+ const real_t new_position = item_y + item_height - tree_height;
+ if (new_position > v_scroll->get_value()) {
+ v_scroll->set_value(new_position);
+ }
+ }
}
}
@@ -4868,7 +4876,7 @@ void Tree::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_column_title_language", "column"), &Tree::get_column_title_language);
ClassDB::bind_method(D_METHOD("get_scroll"), &Tree::get_scroll);
- ClassDB::bind_method(D_METHOD("scroll_to_item", "item"), &Tree::scroll_to_item);
+ ClassDB::bind_method(D_METHOD("scroll_to_item", "item", "center_on_item"), &Tree::scroll_to_item, DEFVAL(false));
ClassDB::bind_method(D_METHOD("set_h_scroll_enabled", "h_scroll"), &Tree::set_h_scroll_enabled);
ClassDB::bind_method(D_METHOD("is_h_scroll_enabled"), &Tree::is_h_scroll_enabled);
diff --git a/scene/gui/tree.h b/scene/gui/tree.h
index c24763a0e4..255a4f0576 100644
--- a/scene/gui/tree.h
+++ b/scene/gui/tree.h
@@ -682,7 +682,7 @@ public:
TreeItem *get_item_with_text(const String &p_find) const;
Point2 get_scroll() const;
- void scroll_to_item(TreeItem *p_item);
+ void scroll_to_item(TreeItem *p_item, bool p_center_on_item = false);
void set_h_scroll_enabled(bool p_enable);
bool is_h_scroll_enabled() const;
void set_v_scroll_enabled(bool p_enable);
diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp
index 6bb710b1d9..c03faa2c2d 100644
--- a/scene/resources/resource_format_text.cpp
+++ b/scene/resources/resource_format_text.cpp
@@ -1951,7 +1951,7 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_r
}
Error ResourceFormatSaverText::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
- if (p_path.ends_with(".sct") && p_resource->get_class() != "PackedScene") {
+ if (p_path.ends_with(".tscn") && !Ref<PackedScene>(p_resource).is_valid()) {
return ERR_FILE_UNRECOGNIZED;
}
@@ -1960,14 +1960,14 @@ Error ResourceFormatSaverText::save(const String &p_path, const RES &p_resource,
}
bool ResourceFormatSaverText::recognize(const RES &p_resource) const {
- return true; // all recognized!
+ return true; // All resources recognized!
}
void ResourceFormatSaverText::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
- if (p_resource->get_class() == "PackedScene") {
- p_extensions->push_back("tscn"); //text scene
+ if (Ref<PackedScene>(p_resource).is_valid()) {
+ p_extensions->push_back("tscn"); // Text scene.
} else {
- p_extensions->push_back("tres"); //text resource
+ p_extensions->push_back("tres"); // Text resource.
}
}
diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp
index 1f77cc0570..1e84947b87 100644
--- a/scene/resources/tile_set.cpp
+++ b/scene/resources/tile_set.cpp
@@ -4434,7 +4434,7 @@ void TileSetAtlasSource::_update_padded_texture() {
Ref<Image> image;
image.instantiate();
- image->create(size.x, size.y, false, Image::FORMAT_RGBA8);
+ image->create(size.x, size.y, false, src->get_format());
for (KeyValue<Vector2i, TileAlternativesData> kv : tiles) {
for (int frame = 0; frame < (int)kv.value.animation_frames_durations.size(); frame++) {
diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp
index 1683756a3e..dae61c8609 100644
--- a/scene/resources/visual_shader.cpp
+++ b/scene/resources/visual_shader.cpp
@@ -131,7 +131,7 @@ void VisualShaderNode::set_input_port_default_value(int p_port, const Variant &p
} break;
case Variant::VECTOR2: {
Vector2 pv = p_prev_value;
- value = Vector3(pv.x, pv.y, 0.0);
+ value = Vector3(pv.x, pv.y, pv.y);
} break;
case Variant::VECTOR3: {
value = p_prev_value;
@@ -289,7 +289,7 @@ String VisualShaderNode::generate_global(Shader::Mode p_mode, VisualShader::Type
return String();
}
-String VisualShaderNode::generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+String VisualShaderNode::generate_global_per_node(Shader::Mode p_mode, int p_id) const {
return String();
}
@@ -472,7 +472,7 @@ String VisualShaderNodeCustom::generate_code(Shader::Mode p_mode, VisualShader::
return code;
}
-String VisualShaderNodeCustom::generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+String VisualShaderNodeCustom::generate_global_per_node(Shader::Mode p_mode, int p_id) const {
String ret;
if (GDVIRTUAL_CALL(_get_global_code, p_mode, ret)) {
String code = "// " + get_caption() + "\n";
@@ -1485,7 +1485,7 @@ Error VisualShader::_write_node(Type type, StringBuilder &global_code, StringBui
class_name = vsnode->get_script_instance()->get_script()->get_path();
}
if (!r_classes.has(class_name)) {
- global_code_per_node += vsnode->generate_global_per_node(get_mode(), type, node);
+ global_code_per_node += vsnode->generate_global_per_node(get_mode(), node);
for (int i = 0; i < TYPE_MAX; i++) {
global_code_per_func[Type(i)] += vsnode->generate_global_per_func(get_mode(), Type(i), node);
}
@@ -2146,7 +2146,11 @@ void VisualShader::_update_shader() const {
global_compute_code += " return __rand_from_seed(seed) * (to - from) + from;\n";
global_compute_code += "}\n\n";
- global_compute_code += "vec3 __randv_range(inout uint seed, vec3 from, vec3 to) {\n";
+ global_compute_code += "vec2 __randv2_range(inout uint seed, vec2 from, vec2 to) {\n";
+ global_compute_code += " return vec2(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y));\n";
+ global_compute_code += "}\n\n";
+
+ global_compute_code += "vec3 __randv3_range(inout uint seed, vec3 from, vec3 to) {\n";
global_compute_code += " return vec3(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z));\n";
global_compute_code += "}\n\n";
diff --git a/scene/resources/visual_shader.h b/scene/resources/visual_shader.h
index e85bf696b0..d3b5365893 100644
--- a/scene/resources/visual_shader.h
+++ b/scene/resources/visual_shader.h
@@ -275,7 +275,7 @@ public:
virtual Vector<VisualShader::DefaultTextureParam> get_default_texture_parameters(VisualShader::Type p_type, int p_id) const;
virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const;
- virtual String generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const;
+ virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const;
virtual String generate_global_per_func(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const;
// If no output is connected, the output var passed will be empty. If no input is connected and input is NIL, the input var passed will be empty.
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const = 0;
@@ -335,7 +335,7 @@ protected:
void _set_input_port_default_value(int p_port, const Variant &p_value);
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override;
- virtual String generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
+ virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override;
static void _bind_methods();
diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp
index 1205ba91c4..f2479199ee 100644
--- a/scene/resources/visual_shader_nodes.cpp
+++ b/scene/resources/visual_shader_nodes.cpp
@@ -5694,7 +5694,7 @@ String VisualShaderNodeTextureUniformTriplanar::get_input_port_name(int p_port)
return "";
}
-String VisualShaderNodeTextureUniformTriplanar::generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+String VisualShaderNodeTextureUniformTriplanar::generate_global_per_node(Shader::Mode p_mode, int p_id) const {
String code;
code += "// TRIPLANAR FUNCTION GLOBAL CODE\n";
diff --git a/scene/resources/visual_shader_nodes.h b/scene/resources/visual_shader_nodes.h
index 5c7a674d34..eeeb91a3ee 100644
--- a/scene/resources/visual_shader_nodes.h
+++ b/scene/resources/visual_shader_nodes.h
@@ -2136,7 +2136,7 @@ public:
virtual bool is_input_port_default(int p_port, Shader::Mode p_mode) const override;
- virtual String generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
+ virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override;
virtual String generate_global_per_func(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override;
diff --git a/scene/resources/visual_shader_particle_nodes.cpp b/scene/resources/visual_shader_particle_nodes.cpp
index 3376d6aa0b..1885211d57 100644
--- a/scene/resources/visual_shader_particle_nodes.cpp
+++ b/scene/resources/visual_shader_particle_nodes.cpp
@@ -39,6 +39,9 @@ int VisualShaderNodeParticleEmitter::get_output_port_count() const {
}
VisualShaderNodeParticleEmitter::PortType VisualShaderNodeParticleEmitter::get_output_port_type(int p_port) const {
+ if (mode_2d) {
+ return PORT_TYPE_VECTOR_2D;
+ }
return PORT_TYPE_VECTOR_3D;
}
@@ -54,6 +57,9 @@ bool VisualShaderNodeParticleEmitter::has_output_port_preview(int p_port) const
}
void VisualShaderNodeParticleEmitter::set_mode_2d(bool p_enabled) {
+ if (mode_2d == p_enabled) {
+ return;
+ }
mode_2d = p_enabled;
emit_changed();
}
@@ -111,7 +117,7 @@ String VisualShaderNodeParticleSphereEmitter::get_input_port_name(int p_port) co
return String();
}
-String VisualShaderNodeParticleSphereEmitter::generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+String VisualShaderNodeParticleSphereEmitter::generate_global_per_node(Shader::Mode p_mode, int p_id) const {
String code;
code += "vec2 __get_random_point_in_circle(inout uint seed, float radius, float inner_radius) {\n";
@@ -129,7 +135,7 @@ String VisualShaderNodeParticleSphereEmitter::generate_code(Shader::Mode p_mode,
String code;
if (mode_2d) {
- code += " " + p_output_vars[0] + " = vec3(__get_random_point_in_circle(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ", " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + "), 0.0);\n";
+ code += " " + p_output_vars[0] + " = __get_random_point_in_circle(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ", " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ");\n";
} else {
code += " " + p_output_vars[0] + " = __get_random_point_in_sphere(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ", " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ");\n";
}
@@ -154,11 +160,27 @@ int VisualShaderNodeParticleBoxEmitter::get_input_port_count() const {
VisualShaderNodeParticleBoxEmitter::PortType VisualShaderNodeParticleBoxEmitter::get_input_port_type(int p_port) const {
if (p_port == 0) {
+ if (mode_2d) {
+ return PORT_TYPE_VECTOR_2D;
+ }
return PORT_TYPE_VECTOR_3D;
}
return PORT_TYPE_SCALAR;
}
+void VisualShaderNodeParticleBoxEmitter::set_mode_2d(bool p_enabled) {
+ if (mode_2d == p_enabled) {
+ return;
+ }
+ if (p_enabled) {
+ set_input_port_default_value(0, Vector2(), get_input_port_default_value(0));
+ } else {
+ set_input_port_default_value(0, Vector3(), get_input_port_default_value(0));
+ }
+ mode_2d = p_enabled;
+ emit_changed();
+}
+
String VisualShaderNodeParticleBoxEmitter::get_input_port_name(int p_port) const {
if (p_port == 0) {
return "extents";
@@ -166,7 +188,7 @@ String VisualShaderNodeParticleBoxEmitter::get_input_port_name(int p_port) const
return String();
}
-String VisualShaderNodeParticleBoxEmitter::generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+String VisualShaderNodeParticleBoxEmitter::generate_global_per_node(Shader::Mode p_mode, int p_id) const {
String code;
code += "vec2 __get_random_point_in_box2d(inout uint seed, vec2 extents) {\n";
@@ -185,7 +207,7 @@ String VisualShaderNodeParticleBoxEmitter::generate_global_per_node(Shader::Mode
String VisualShaderNodeParticleBoxEmitter::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
if (mode_2d) {
- code += " " + p_output_vars[0] + " = vec3(__get_random_point_in_box2d(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ".xy), 0.0);\n";
+ code += " " + p_output_vars[0] + " = __get_random_point_in_box2d(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ");\n";
} else {
code += " " + p_output_vars[0] + " = __get_random_point_in_box3d(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ");\n";
}
@@ -221,7 +243,7 @@ String VisualShaderNodeParticleRingEmitter::get_input_port_name(int p_port) cons
return String();
}
-String VisualShaderNodeParticleRingEmitter::generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+String VisualShaderNodeParticleRingEmitter::generate_global_per_node(Shader::Mode p_mode, int p_id) const {
String code;
code += "vec2 __get_random_point_on_ring2d(inout uint seed, float radius, float inner_radius) {\n";
@@ -243,7 +265,7 @@ String VisualShaderNodeParticleRingEmitter::generate_code(Shader::Mode p_mode, V
String code;
if (mode_2d) {
- code = " " + p_output_vars[0] + " = vec3(__get_random_point_on_ring2d(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ", " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + "), 0.0);\n";
+ code = " " + p_output_vars[0] + " = __get_random_point_on_ring2d(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ", " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ");\n";
} else {
code = " " + p_output_vars[0] + " = __get_random_point_on_ring3d(__seed, " + (p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0]) + ", " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ", " + (p_input_vars[2].is_empty() ? (String)get_input_port_default_value(2) : p_input_vars[2]) + ");\n";
}
@@ -269,18 +291,24 @@ int VisualShaderNodeParticleMeshEmitter::get_output_port_count() const {
VisualShaderNodeParticleBoxEmitter::PortType VisualShaderNodeParticleMeshEmitter::get_output_port_type(int p_port) const {
switch (p_port) {
- case 0:
- return PORT_TYPE_VECTOR_3D; // position
- case 1:
- return PORT_TYPE_VECTOR_3D; // normal
- case 2:
- return PORT_TYPE_VECTOR_3D; // color
- case 3:
- return PORT_TYPE_SCALAR; // alpha
- case 4:
- return PORT_TYPE_VECTOR_3D; // uv
- case 5:
- return PORT_TYPE_VECTOR_3D; // uv2
+ case 0: // position
+ if (mode_2d) {
+ return PORT_TYPE_VECTOR_2D;
+ }
+ return PORT_TYPE_VECTOR_3D;
+ case 1: // normal
+ if (mode_2d) {
+ return PORT_TYPE_VECTOR_2D;
+ }
+ return PORT_TYPE_VECTOR_3D;
+ case 2: // color
+ return PORT_TYPE_VECTOR_3D;
+ case 3: // alpha
+ return PORT_TYPE_SCALAR;
+ case 4: // uv
+ return PORT_TYPE_VECTOR_2D;
+ case 5: // uv2
+ return PORT_TYPE_VECTOR_2D;
}
return PORT_TYPE_SCALAR;
}
@@ -341,18 +369,22 @@ String VisualShaderNodeParticleMeshEmitter::generate_global(Shader::Mode p_mode,
return code;
}
-String VisualShaderNodeParticleMeshEmitter::_generate_code(VisualShader::Type p_type, int p_id, const String *p_output_vars, int p_index, const String &p_texture_name, bool p_ignore_mode2d) const {
+String VisualShaderNodeParticleMeshEmitter::_generate_code(VisualShader::Type p_type, int p_id, const String *p_output_vars, int p_index, const String &p_texture_name, PortType p_port_type) const {
String code;
if (is_output_port_connected(p_index)) {
- if (mode_2d && !p_ignore_mode2d) {
- code += " " + p_output_vars[p_index] + " = vec3(";
- code += "texelFetch(";
- code += make_unique_id(p_type, p_id, p_texture_name) + ", ";
- code += "ivec2(__scalar_ibuff, 0), 0).xy, 0.0);\n";
- } else {
- code += " " + p_output_vars[p_index] + " = texelFetch(";
- code += make_unique_id(p_type, p_id, p_texture_name) + ", ";
- code += "ivec2(__scalar_ibuff, 0), 0).xyz;\n";
+ switch (p_port_type) {
+ case PORT_TYPE_VECTOR_2D: {
+ code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xy;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
+ } break;
+ case PORT_TYPE_VECTOR_3D: {
+ if (mode_2d) {
+ code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xy;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
+ } else {
+ code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xyz;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
+ }
+ } break;
+ default:
+ break;
}
}
return code;
@@ -362,27 +394,22 @@ String VisualShaderNodeParticleMeshEmitter::generate_code(Shader::Mode p_mode, V
String code;
code += " __scalar_ibuff = int(__rand_from_seed(__seed) * 65535.0) % " + itos(position_texture->get_width()) + ";\n";
- code += _generate_code(p_type, p_id, p_output_vars, 0, "mesh_vx");
- code += _generate_code(p_type, p_id, p_output_vars, 1, "mesh_nm");
+ code += _generate_code(p_type, p_id, p_output_vars, 0, "mesh_vx", VisualShaderNode::PORT_TYPE_VECTOR_3D);
+ code += _generate_code(p_type, p_id, p_output_vars, 1, "mesh_nm", VisualShaderNode::PORT_TYPE_VECTOR_3D);
if (is_output_port_connected(2) || is_output_port_connected(3)) {
- code += " __vec4_buff = texelFetch(";
- code += make_unique_id(p_type, p_id, "mesh_col") + ", ";
- code += "ivec2(__scalar_ibuff, 0), 0);\n";
+ code += vformat(" __vec4_buff = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0);\n", make_unique_id(p_type, p_id, "mesh_col"));
+
if (is_output_port_connected(2)) {
code += " " + p_output_vars[2] + " = __vec4_buff.rgb;\n";
- } else {
- code += " " + p_output_vars[2] + " = vec3(0.0);\n";
}
if (is_output_port_connected(3)) {
code += " " + p_output_vars[3] + " = __vec4_buff.a;\n";
- } else {
- code += " " + p_output_vars[3] + " = 0.0;\n";
}
}
- code += _generate_code(p_type, p_id, p_output_vars, 4, "mesh_uv", true);
- code += _generate_code(p_type, p_id, p_output_vars, 5, "mesh_uv2", true);
+ code += _generate_code(p_type, p_id, p_output_vars, 4, "mesh_uv", VisualShaderNode::PORT_TYPE_VECTOR_2D);
+ code += _generate_code(p_type, p_id, p_output_vars, 5, "mesh_uv2", VisualShaderNode::PORT_TYPE_VECTOR_2D);
return code;
}
@@ -876,10 +903,11 @@ void VisualShaderNodeParticleRandomness::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_op_type", "type"), &VisualShaderNodeParticleRandomness::set_op_type);
ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeParticleRandomness::get_op_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector"), "set_op_type", "get_op_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3"), "set_op_type", "get_op_type");
BIND_ENUM_CONSTANT(OP_TYPE_SCALAR);
- BIND_ENUM_CONSTANT(OP_TYPE_VECTOR);
+ BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D);
+ BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D);
BIND_ENUM_CONSTANT(OP_TYPE_MAX);
}
@@ -898,8 +926,13 @@ int VisualShaderNodeParticleRandomness::get_output_port_count() const {
}
VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness::get_output_port_type(int p_port) const {
- if (op_type == OP_TYPE_VECTOR) {
- return PORT_TYPE_VECTOR_3D;
+ switch (op_type) {
+ case OP_TYPE_VECTOR_2D:
+ return PORT_TYPE_VECTOR_2D;
+ case OP_TYPE_VECTOR_3D:
+ return PORT_TYPE_VECTOR_3D;
+ default:
+ break;
}
return PORT_TYPE_SCALAR;
}
@@ -913,8 +946,13 @@ int VisualShaderNodeParticleRandomness::get_input_port_count() const {
}
VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness::get_input_port_type(int p_port) const {
- if (op_type == OP_TYPE_VECTOR) {
- return PORT_TYPE_VECTOR_3D;
+ switch (op_type) {
+ case OP_TYPE_VECTOR_2D:
+ return PORT_TYPE_VECTOR_2D;
+ case OP_TYPE_VECTOR_3D:
+ return PORT_TYPE_VECTOR_3D;
+ default:
+ break;
}
return PORT_TYPE_SCALAR;
}
@@ -930,10 +968,18 @@ String VisualShaderNodeParticleRandomness::get_input_port_name(int p_port) const
String VisualShaderNodeParticleRandomness::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
- if (op_type == OP_TYPE_SCALAR) {
- code += vformat(" %s = __randf_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
- } else if (op_type == OP_TYPE_VECTOR) {
- code += vformat(" %s = __randv_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
+ switch (op_type) {
+ case OP_TYPE_SCALAR: {
+ code += vformat(" %s = __randf_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
+ } break;
+ case OP_TYPE_VECTOR_2D: {
+ code += vformat(" %s = __randv2_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
+ } break;
+ case OP_TYPE_VECTOR_3D: {
+ code += vformat(" %s = __randv3_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
+ } break;
+ default:
+ break;
}
return code;
}
@@ -943,12 +989,21 @@ void VisualShaderNodeParticleRandomness::set_op_type(OpType p_op_type) {
if (op_type == p_op_type) {
return;
}
- if (p_op_type == OP_TYPE_SCALAR) {
- set_input_port_default_value(0, 0.0);
- set_input_port_default_value(1, 1.0);
- } else {
- set_input_port_default_value(0, Vector3(-1.0, -1.0, -1.0));
- set_input_port_default_value(1, Vector3(1.0, 1.0, 1.0));
+ switch (p_op_type) {
+ case OP_TYPE_SCALAR: {
+ set_input_port_default_value(0, 0.0, get_input_port_default_value(0));
+ set_input_port_default_value(1, 0.0, get_input_port_default_value(1));
+ } break;
+ case OP_TYPE_VECTOR_2D: {
+ set_input_port_default_value(0, Vector2(), get_input_port_default_value(0));
+ set_input_port_default_value(1, Vector2(), get_input_port_default_value(1));
+ } break;
+ case OP_TYPE_VECTOR_3D: {
+ set_input_port_default_value(0, Vector3(), get_input_port_default_value(0));
+ set_input_port_default_value(1, Vector3(), get_input_port_default_value(1));
+ } break;
+ default:
+ break;
}
op_type = p_op_type;
emit_changed();
@@ -963,7 +1018,7 @@ bool VisualShaderNodeParticleRandomness::has_output_port_preview(int p_port) con
}
VisualShaderNodeParticleRandomness::VisualShaderNodeParticleRandomness() {
- set_input_port_default_value(0, 0.0);
+ set_input_port_default_value(0, -1.0);
set_input_port_default_value(1, 1.0);
}
diff --git a/scene/resources/visual_shader_particle_nodes.h b/scene/resources/visual_shader_particle_nodes.h
index ce0d896c01..0b91cba5e0 100644
--- a/scene/resources/visual_shader_particle_nodes.h
+++ b/scene/resources/visual_shader_particle_nodes.h
@@ -48,7 +48,7 @@ public:
virtual String get_output_port_name(int p_port) const override;
virtual bool has_output_port_preview(int p_port) const override;
- void set_mode_2d(bool p_enabled);
+ virtual void set_mode_2d(bool p_enabled);
bool is_mode_2d() const;
Vector<StringName> get_editable_properties() const override;
@@ -68,7 +68,7 @@ public:
virtual PortType get_input_port_type(int p_port) const override;
virtual String get_input_port_name(int p_port) const override;
- virtual String generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
+ virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override;
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override;
VisualShaderNodeParticleSphereEmitter();
@@ -83,8 +83,9 @@ public:
virtual int get_input_port_count() const override;
virtual PortType get_input_port_type(int p_port) const override;
virtual String get_input_port_name(int p_port) const override;
+ virtual void set_mode_2d(bool p_enabled) override;
- virtual String generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
+ virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override;
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override;
VisualShaderNodeParticleBoxEmitter();
@@ -100,7 +101,7 @@ public:
virtual PortType get_input_port_type(int p_port) const override;
virtual String get_input_port_name(int p_port) const override;
- virtual String generate_global_per_node(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
+ virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override;
virtual String generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview = false) const override;
VisualShaderNodeParticleRingEmitter();
@@ -118,7 +119,7 @@ class VisualShaderNodeParticleMeshEmitter : public VisualShaderNodeParticleEmitt
Ref<ImageTexture> uv_texture;
Ref<ImageTexture> uv2_texture;
- String _generate_code(VisualShader::Type p_type, int p_id, const String *p_output_vars, int p_index, const String &p_texture_name, bool p_ignore_mode2d = false) const;
+ String _generate_code(VisualShader::Type p_type, int p_id, const String *p_output_vars, int p_index, const String &p_texture_name, PortType p_port_type) const;
void _update_texture(const Vector<Vector2> &p_array, Ref<ImageTexture> &r_texture);
void _update_texture(const Vector<Vector3> &p_array, Ref<ImageTexture> &r_texture);
@@ -213,7 +214,8 @@ class VisualShaderNodeParticleRandomness : public VisualShaderNode {
public:
enum OpType {
OP_TYPE_SCALAR,
- OP_TYPE_VECTOR,
+ OP_TYPE_VECTOR_2D,
+ OP_TYPE_VECTOR_3D,
OP_TYPE_MAX,
};
diff --git a/scene/resources/visual_shader_sdf_nodes.cpp b/scene/resources/visual_shader_sdf_nodes.cpp
index 559831c3c2..cbd3ebd83b 100644
--- a/scene/resources/visual_shader_sdf_nodes.cpp
+++ b/scene/resources/visual_shader_sdf_nodes.cpp
@@ -41,7 +41,7 @@ int VisualShaderNodeSDFToScreenUV::get_input_port_count() const {
}
VisualShaderNodeSDFToScreenUV::PortType VisualShaderNodeSDFToScreenUV::get_input_port_type(int p_port) const {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
String VisualShaderNodeSDFToScreenUV::get_input_port_name(int p_port) const {
@@ -53,7 +53,7 @@ int VisualShaderNodeSDFToScreenUV::get_output_port_count() const {
}
VisualShaderNodeSDFToScreenUV::PortType VisualShaderNodeSDFToScreenUV::get_output_port_type(int p_port) const {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
String VisualShaderNodeSDFToScreenUV::get_output_port_name(int p_port) const {
@@ -61,7 +61,7 @@ String VisualShaderNodeSDFToScreenUV::get_output_port_name(int p_port) const {
}
String VisualShaderNodeSDFToScreenUV::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
- return " " + p_output_vars[0] + " = vec3(sdf_to_screen_uv(" + (p_input_vars[0].is_empty() ? "vec2(0.0)" : p_input_vars[0] + ".xy") + "), 0.0f);\n";
+ return " " + p_output_vars[0] + " = sdf_to_screen_uv(" + (p_input_vars[0].is_empty() ? "vec2(0.0)" : p_input_vars[0]) + ");\n";
}
VisualShaderNodeSDFToScreenUV::VisualShaderNodeSDFToScreenUV() {
@@ -78,7 +78,7 @@ int VisualShaderNodeScreenUVToSDF::get_input_port_count() const {
}
VisualShaderNodeScreenUVToSDF::PortType VisualShaderNodeScreenUVToSDF::get_input_port_type(int p_port) const {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
String VisualShaderNodeScreenUVToSDF::get_input_port_name(int p_port) const {
@@ -90,7 +90,7 @@ int VisualShaderNodeScreenUVToSDF::get_output_port_count() const {
}
VisualShaderNodeScreenUVToSDF::PortType VisualShaderNodeScreenUVToSDF::get_output_port_type(int p_port) const {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
String VisualShaderNodeScreenUVToSDF::get_output_port_name(int p_port) const {
@@ -105,7 +105,7 @@ bool VisualShaderNodeScreenUVToSDF::is_input_port_default(int p_port, Shader::Mo
}
String VisualShaderNodeScreenUVToSDF::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
- return " " + p_output_vars[0] + " = vec3(screen_uv_to_sdf(" + (p_input_vars[0].is_empty() ? "SCREEN_UV" : p_input_vars[0] + ".xy") + "), 0.0f);\n";
+ return " " + p_output_vars[0] + " = screen_uv_to_sdf(" + (p_input_vars[0].is_empty() ? "SCREEN_UV" : p_input_vars[0]) + ");\n";
}
VisualShaderNodeScreenUVToSDF::VisualShaderNodeScreenUVToSDF() {
@@ -122,7 +122,7 @@ int VisualShaderNodeTextureSDF::get_input_port_count() const {
}
VisualShaderNodeTextureSDF::PortType VisualShaderNodeTextureSDF::get_input_port_type(int p_port) const {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
String VisualShaderNodeTextureSDF::get_input_port_name(int p_port) const {
@@ -142,7 +142,7 @@ String VisualShaderNodeTextureSDF::get_output_port_name(int p_port) const {
}
String VisualShaderNodeTextureSDF::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
- return " " + p_output_vars[0] + " = texture_sdf(" + (p_input_vars[0].is_empty() ? "vec2(0.0)" : p_input_vars[0] + ".xy") + ");\n";
+ return " " + p_output_vars[0] + " = texture_sdf(" + (p_input_vars[0].is_empty() ? "vec2(0.0)" : p_input_vars[0]) + ");\n";
}
VisualShaderNodeTextureSDF::VisualShaderNodeTextureSDF() {
@@ -159,7 +159,7 @@ int VisualShaderNodeTextureSDFNormal::get_input_port_count() const {
}
VisualShaderNodeTextureSDFNormal::PortType VisualShaderNodeTextureSDFNormal::get_input_port_type(int p_port) const {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
String VisualShaderNodeTextureSDFNormal::get_input_port_name(int p_port) const {
@@ -171,7 +171,7 @@ int VisualShaderNodeTextureSDFNormal::get_output_port_count() const {
}
VisualShaderNodeTextureSDFNormal::PortType VisualShaderNodeTextureSDFNormal::get_output_port_type(int p_port) const {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
String VisualShaderNodeTextureSDFNormal::get_output_port_name(int p_port) const {
@@ -179,7 +179,7 @@ String VisualShaderNodeTextureSDFNormal::get_output_port_name(int p_port) const
}
String VisualShaderNodeTextureSDFNormal::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
- return " " + p_output_vars[0] + " = vec3(texture_sdf_normal(" + (p_input_vars[0].is_empty() ? "vec2(0.0)" : p_input_vars[0] + ".xy") + "), 0.0f);\n";
+ return " " + p_output_vars[0] + " = texture_sdf_normal(" + (p_input_vars[0].is_empty() ? "vec2(0.0)" : p_input_vars[0]) + ");\n";
}
VisualShaderNodeTextureSDFNormal::VisualShaderNodeTextureSDFNormal() {
@@ -197,7 +197,7 @@ int VisualShaderNodeSDFRaymarch::get_input_port_count() const {
VisualShaderNodeSDFRaymarch::PortType VisualShaderNodeSDFRaymarch::get_input_port_type(int p_port) const {
if (p_port == 0 || p_port == 1) {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
return PORT_TYPE_SCALAR;
}
@@ -221,7 +221,7 @@ VisualShaderNodeSDFRaymarch::PortType VisualShaderNodeSDFRaymarch::get_output_po
} else if (p_port == 1) {
return PORT_TYPE_BOOLEAN;
} else if (p_port == 2) {
- return PORT_TYPE_VECTOR_3D;
+ return PORT_TYPE_VECTOR_2D;
}
return PORT_TYPE_SCALAR;
}
@@ -245,13 +245,13 @@ String VisualShaderNodeSDFRaymarch::generate_code(Shader::Mode p_mode, VisualSha
if (p_input_vars[0].is_empty()) {
code += " vec2 __from_pos = vec2(0.0f);\n";
} else {
- code += " vec2 __from_pos = " + p_input_vars[0] + ".xy;\n";
+ code += " vec2 __from_pos = " + p_input_vars[0] + ";\n";
}
if (p_input_vars[1].is_empty()) {
code += " vec2 __to_pos = vec2(0.0f);\n";
} else {
- code += " vec2 __to_pos = " + p_input_vars[1] + ".xy;\n";
+ code += " vec2 __to_pos = " + p_input_vars[1] + ";\n";
}
code += "\n vec2 __at = __from_pos;\n";
@@ -271,7 +271,7 @@ String VisualShaderNodeSDFRaymarch::generate_code(Shader::Mode p_mode, VisualSha
code += " float __dist = min(__max_dist, __accum);\n";
code += " " + p_output_vars[0] + " = __dist;\n";
code += " " + p_output_vars[1] + " = __accum < __max_dist;\n";
- code += " " + p_output_vars[2] + " = vec3(__from_pos + __dir * __dist, 0.0f);\n";
+ code += " " + p_output_vars[2] + " = __from_pos + __dir * __dist;\n";
code += " }\n";
diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp
index 584abbc351..ac181cb5eb 100644
--- a/servers/rendering_server.cpp
+++ b/servers/rendering_server.cpp
@@ -933,7 +933,7 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa
}
}
- ERR_FAIL_COND_V_MSG((bsformat & RS::ARRAY_FORMAT_BLEND_SHAPE_MASK) != (format & RS::ARRAY_FORMAT_BLEND_SHAPE_MASK), ERR_INVALID_PARAMETER, "Blend shape format must match the main array format for Vertex, Normal and Tangent arrays.");
+ ERR_FAIL_COND_V_MSG(bsformat != (format & RS::ARRAY_FORMAT_BLEND_SHAPE_MASK), ERR_INVALID_PARAMETER, "Blend shape format must match the main array format for Vertex, Normal and Tangent arrays.");
}
}
diff --git a/servers/rendering_server.h b/servers/rendering_server.h
index 472fff1bf1..d21f3a3299 100644
--- a/servers/rendering_server.h
+++ b/servers/rendering_server.h
@@ -259,7 +259,7 @@ public:
ARRAY_FORMAT_WEIGHTS = 1 << ARRAY_WEIGHTS,
ARRAY_FORMAT_INDEX = 1 << ARRAY_INDEX,
- ARRAY_FORMAT_BLEND_SHAPE_MASK = (~(ARRAY_FORMAT_COLOR | ARRAY_FORMAT_TEX_UV | ARRAY_FORMAT_TEX_UV2 | ARRAY_FORMAT_BONES | ARRAY_FORMAT_WEIGHTS | ARRAY_FORMAT_CUSTOM0 | ARRAY_FORMAT_CUSTOM1 | ARRAY_FORMAT_CUSTOM2 | ARRAY_FORMAT_CUSTOM3 | ARRAY_FORMAT_INDEX)) & 0x7FFFFFFF,
+ ARRAY_FORMAT_BLEND_SHAPE_MASK = ARRAY_FORMAT_VERTEX | ARRAY_FORMAT_NORMAL | ARRAY_FORMAT_TANGENT,
ARRAY_FORMAT_CUSTOM_BASE = (ARRAY_INDEX + 1),
ARRAY_FORMAT_CUSTOM_BITS = 3,
diff --git a/tests/scene/test_animation.h b/tests/scene/test_animation.h
new file mode 100644
index 0000000000..9199713fd9
--- /dev/null
+++ b/tests/scene/test_animation.h
@@ -0,0 +1,314 @@
+/*************************************************************************/
+/* test_animation.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 TEST_ANIMATION_H
+#define TEST_ANIMATION_H
+
+#include "scene/resources/animation.h"
+
+#include "tests/test_macros.h"
+
+namespace TestAnimation {
+
+TEST_CASE("[Animation] Empty animation getters") {
+ const Ref<Animation> animation = memnew(Animation);
+
+ CHECK(Math::is_equal_approx(animation->get_length(), real_t(1.0)));
+ CHECK(Math::is_equal_approx(animation->get_step(), real_t(0.1)));
+}
+
+TEST_CASE("[Animation] Create value track") {
+ // This creates an animation that makes the node "Enemy" move to the right by
+ // 100 pixels in 0.5 seconds.
+ Ref<Animation> animation = memnew(Animation);
+ const int track_index = animation->add_track(Animation::TYPE_VALUE);
+ CHECK(track_index == 0);
+ animation->track_set_path(track_index, NodePath("Enemy:position:x"));
+ animation->track_insert_key(track_index, 0.0, 0);
+ animation->track_insert_key(track_index, 0.5, 100);
+
+ CHECK(animation->get_track_count() == 1);
+ CHECK(!animation->track_is_compressed(0));
+ CHECK(int(animation->track_get_key_value(0, 0)) == 0);
+ CHECK(int(animation->track_get_key_value(0, 1)) == 100);
+
+ CHECK(Math::is_equal_approx(animation->value_track_interpolate(0, -0.2), 0.0));
+ CHECK(Math::is_equal_approx(animation->value_track_interpolate(0, 0.0), 0.0));
+ CHECK(Math::is_equal_approx(animation->value_track_interpolate(0, 0.2), 40.0));
+ CHECK(Math::is_equal_approx(animation->value_track_interpolate(0, 0.4), 80.0));
+ CHECK(Math::is_equal_approx(animation->value_track_interpolate(0, 0.5), 100.0));
+ CHECK(Math::is_equal_approx(animation->value_track_interpolate(0, 0.6), 100.0));
+
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 0), real_t(1.0)));
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 1), real_t(1.0)));
+
+ ERR_PRINT_OFF;
+ // Nonexistent keys.
+ CHECK(animation->track_get_key_value(0, 2).is_null());
+ CHECK(animation->track_get_key_value(0, -1).is_null());
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 2), real_t(-1.0)));
+ // Nonexistent track (and keys).
+ CHECK(animation->track_get_key_value(1, 0).is_null());
+ CHECK(animation->track_get_key_value(1, 1).is_null());
+ CHECK(animation->track_get_key_value(1, 2).is_null());
+ CHECK(animation->track_get_key_value(1, -1).is_null());
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(1, 0), real_t(-1.0)));
+
+ // This is a value track, so the methods below should return errors.
+ CHECK(animation->position_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->rotation_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->scale_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(Math::is_zero_approx(animation->bezier_track_interpolate(0, 0.0)));
+ CHECK(animation->blend_shape_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[Animation] Create 3D position track") {
+ Ref<Animation> animation = memnew(Animation);
+ const int track_index = animation->add_track(Animation::TYPE_POSITION_3D);
+ animation->track_set_path(track_index, NodePath("Enemy:position"));
+ animation->position_track_insert_key(track_index, 0.0, Vector3(0, 1, 2));
+ animation->position_track_insert_key(track_index, 0.5, Vector3(3.5, 4, 5));
+
+ CHECK(animation->get_track_count() == 1);
+ CHECK(!animation->track_is_compressed(0));
+ CHECK(Vector3(animation->track_get_key_value(0, 0)).is_equal_approx(Vector3(0, 1, 2)));
+ CHECK(Vector3(animation->track_get_key_value(0, 1)).is_equal_approx(Vector3(3.5, 4, 5)));
+
+ Vector3 r_interpolation;
+
+ CHECK(animation->position_track_interpolate(0, -0.2, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(0, 1, 2)));
+
+ CHECK(animation->position_track_interpolate(0, 0.0, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(0, 1, 2)));
+
+ CHECK(animation->position_track_interpolate(0, 0.2, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(1.4, 2.2, 3.2)));
+
+ CHECK(animation->position_track_interpolate(0, 0.4, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(2.8, 3.4, 4.4)));
+
+ CHECK(animation->position_track_interpolate(0, 0.5, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(3.5, 4, 5)));
+
+ CHECK(animation->position_track_interpolate(0, 0.6, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(3.5, 4, 5)));
+
+ // 3D position tracks always use linear interpolation for performance reasons.
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 0), real_t(1.0)));
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 1), real_t(1.0)));
+
+ // This is a 3D position track, so the methods below should return errors.
+ ERR_PRINT_OFF;
+ CHECK(animation->value_track_interpolate(0, 0.0).is_null());
+ CHECK(animation->rotation_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->scale_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(Math::is_zero_approx(animation->bezier_track_interpolate(0, 0.0)));
+ CHECK(animation->blend_shape_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[Animation] Create 3D rotation track") {
+ Ref<Animation> animation = memnew(Animation);
+ const int track_index = animation->add_track(Animation::TYPE_ROTATION_3D);
+ animation->track_set_path(track_index, NodePath("Enemy:rotation"));
+ animation->rotation_track_insert_key(track_index, 0.0, Quaternion(Vector3(0, 1, 2)));
+ animation->rotation_track_insert_key(track_index, 0.5, Quaternion(Vector3(3.5, 4, 5)));
+
+ CHECK(animation->get_track_count() == 1);
+ CHECK(!animation->track_is_compressed(0));
+ CHECK(Quaternion(animation->track_get_key_value(0, 0)).is_equal_approx(Quaternion(Vector3(0, 1, 2))));
+ CHECK(Quaternion(animation->track_get_key_value(0, 1)).is_equal_approx(Quaternion(Vector3(3.5, 4, 5))));
+
+ Quaternion r_interpolation;
+
+ CHECK(animation->rotation_track_interpolate(0, -0.2, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Quaternion(0.403423, 0.259035, 0.73846, 0.47416)));
+
+ CHECK(animation->rotation_track_interpolate(0, 0.0, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Quaternion(0.403423, 0.259035, 0.73846, 0.47416)));
+
+ CHECK(animation->rotation_track_interpolate(0, 0.2, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Quaternion(0.336182, 0.30704, 0.751515, 0.477425)));
+
+ CHECK(animation->rotation_track_interpolate(0, 0.4, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Quaternion(0.266585, 0.352893, 0.759303, 0.477344)));
+
+ CHECK(animation->rotation_track_interpolate(0, 0.5, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Quaternion(0.231055, 0.374912, 0.761204, 0.476048)));
+
+ CHECK(animation->rotation_track_interpolate(0, 0.6, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Quaternion(0.231055, 0.374912, 0.761204, 0.476048)));
+
+ // 3D rotation tracks always use linear interpolation for performance reasons.
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 0), real_t(1.0)));
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 1), real_t(1.0)));
+
+ // This is a 3D rotation track, so the methods below should return errors.
+ ERR_PRINT_OFF;
+ CHECK(animation->value_track_interpolate(0, 0.0).is_null());
+ CHECK(animation->position_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->scale_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(Math::is_zero_approx(animation->bezier_track_interpolate(0, 0.0)));
+ CHECK(animation->blend_shape_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[Animation] Create 3D scale track") {
+ Ref<Animation> animation = memnew(Animation);
+ const int track_index = animation->add_track(Animation::TYPE_SCALE_3D);
+ animation->track_set_path(track_index, NodePath("Enemy:scale"));
+ animation->scale_track_insert_key(track_index, 0.0, Vector3(0, 1, 2));
+ animation->scale_track_insert_key(track_index, 0.5, Vector3(3.5, 4, 5));
+
+ CHECK(animation->get_track_count() == 1);
+ CHECK(!animation->track_is_compressed(0));
+ CHECK(Vector3(animation->track_get_key_value(0, 0)).is_equal_approx(Vector3(0, 1, 2)));
+ CHECK(Vector3(animation->track_get_key_value(0, 1)).is_equal_approx(Vector3(3.5, 4, 5)));
+
+ Vector3 r_interpolation;
+
+ CHECK(animation->scale_track_interpolate(0, -0.2, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(0, 1, 2)));
+
+ CHECK(animation->scale_track_interpolate(0, 0.0, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(0, 1, 2)));
+
+ CHECK(animation->scale_track_interpolate(0, 0.2, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(1.4, 2.2, 3.2)));
+
+ CHECK(animation->scale_track_interpolate(0, 0.4, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(2.8, 3.4, 4.4)));
+
+ CHECK(animation->scale_track_interpolate(0, 0.5, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(3.5, 4, 5)));
+
+ CHECK(animation->scale_track_interpolate(0, 0.6, &r_interpolation) == OK);
+ CHECK(r_interpolation.is_equal_approx(Vector3(3.5, 4, 5)));
+
+ // 3D scale tracks always use linear interpolation for performance reasons.
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 0), real_t(1.0)));
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 1), real_t(1.0)));
+
+ // This is a 3D scale track, so the methods below should return errors.
+ ERR_PRINT_OFF;
+ CHECK(animation->value_track_interpolate(0, 0.0).is_null());
+ CHECK(animation->position_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->rotation_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(Math::is_zero_approx(animation->bezier_track_interpolate(0, 0.0)));
+ CHECK(animation->blend_shape_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[Animation] Create blend shape track") {
+ Ref<Animation> animation = memnew(Animation);
+ const int track_index = animation->add_track(Animation::TYPE_BLEND_SHAPE);
+ animation->track_set_path(track_index, NodePath("Enemy:scale"));
+ // Negative values for blend shapes should work as expected.
+ animation->blend_shape_track_insert_key(track_index, 0.0, -1.0);
+ animation->blend_shape_track_insert_key(track_index, 0.5, 1.0);
+
+ CHECK(animation->get_track_count() == 1);
+ CHECK(!animation->track_is_compressed(0));
+
+ float r_blend = 0.0f;
+
+ CHECK(animation->blend_shape_track_get_key(0, 0, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, -1.0f));
+
+ CHECK(animation->blend_shape_track_get_key(0, 1, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, 1.0f));
+
+ CHECK(animation->blend_shape_track_interpolate(0, -0.2, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, -1.0f));
+
+ CHECK(animation->blend_shape_track_interpolate(0, 0.0, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, -1.0f));
+
+ CHECK(animation->blend_shape_track_interpolate(0, 0.2, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, -0.2f));
+
+ CHECK(animation->blend_shape_track_interpolate(0, 0.4, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, 0.6f));
+
+ CHECK(animation->blend_shape_track_interpolate(0, 0.5, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, 1.0f));
+
+ CHECK(animation->blend_shape_track_interpolate(0, 0.6, &r_blend) == OK);
+ CHECK(Math::is_equal_approx(r_blend, 1.0f));
+
+ // Blend shape tracks always use linear interpolation for performance reasons.
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 0), real_t(1.0)));
+ CHECK(Math::is_equal_approx(animation->track_get_key_transition(0, 1), real_t(1.0)));
+
+ // This is a blend shape track, so the methods below should return errors.
+ ERR_PRINT_OFF;
+ CHECK(animation->value_track_interpolate(0, 0.0).is_null());
+ CHECK(animation->position_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->rotation_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->scale_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(Math::is_zero_approx(animation->bezier_track_interpolate(0, 0.0)));
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[Animation] Create Bezier track") {
+ Ref<Animation> animation = memnew(Animation);
+ const int track_index = animation->add_track(Animation::TYPE_BEZIER);
+ animation->track_set_path(track_index, NodePath("Enemy:scale"));
+ animation->bezier_track_insert_key(track_index, 0.0, -1.0, Vector2(-1, -1), Vector2(1, 1));
+ animation->bezier_track_insert_key(track_index, 0.5, 1.0, Vector2(0, 1), Vector2(1, 0.5));
+
+ CHECK(animation->get_track_count() == 1);
+ CHECK(!animation->track_is_compressed(0));
+
+ CHECK(Math::is_equal_approx(animation->bezier_track_get_key_value(0, 0), real_t(-1.0)));
+ CHECK(Math::is_equal_approx(animation->bezier_track_get_key_value(0, 1), real_t(1.0)));
+
+ CHECK(Math::is_equal_approx(animation->bezier_track_interpolate(0, -0.2), real_t(-1.0)));
+ CHECK(Math::is_equal_approx(animation->bezier_track_interpolate(0, 0.0), real_t(-1.0)));
+ CHECK(Math::is_equal_approx(animation->bezier_track_interpolate(0, 0.2), real_t(-0.76057207584381)));
+ CHECK(Math::is_equal_approx(animation->bezier_track_interpolate(0, 0.4), real_t(-0.39975279569626)));
+ CHECK(Math::is_equal_approx(animation->bezier_track_interpolate(0, 0.5), real_t(1.0)));
+ CHECK(Math::is_equal_approx(animation->bezier_track_interpolate(0, 0.6), real_t(1.0)));
+
+ // This is a bezier track, so the methods below should return errors.
+ ERR_PRINT_OFF;
+ CHECK(animation->value_track_interpolate(0, 0.0).is_null());
+ CHECK(animation->position_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->rotation_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->scale_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ CHECK(animation->blend_shape_track_interpolate(0, 0.0, nullptr) == ERR_INVALID_PARAMETER);
+ ERR_PRINT_ON;
+}
+
+} // namespace TestAnimation
+
+#endif // TEST_ANIMATION_H
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 3b51a6d805..504b83c2b0 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -73,6 +73,7 @@
#include "tests/core/variant/test_array.h"
#include "tests/core/variant/test_dictionary.h"
#include "tests/core/variant/test_variant.h"
+#include "tests/scene/test_animation.h"
#include "tests/scene/test_code_edit.h"
#include "tests/scene/test_curve.h"
#include "tests/scene/test_gradient.h"