diff options
70 files changed, 1458 insertions, 1210 deletions
diff --git a/.github/workflows/javascript_builds.yml b/.github/workflows/javascript_builds.yml index 8167a48eae..421906c77f 100644 --- a/.github/workflows/javascript_builds.yml +++ b/.github/workflows/javascript_builds.yml @@ -5,7 +5,7 @@ on: [push, pull_request] env: GODOT_BASE_BRANCH: master SCONS_CACHE_LIMIT: 4096 - EM_VERSION: latest + EM_VERSION: 1.39.20 EM_CACHE_FOLDER: 'emsdk-cache' jobs: diff --git a/.github/workflows/linux_builds.yml b/.github/workflows/linux_builds.yml index a05bb09931..198727b30e 100644 --- a/.github/workflows/linux_builds.yml +++ b/.github/workflows/linux_builds.yml @@ -9,7 +9,7 @@ env: jobs: linux-editor: runs-on: "ubuntu-20.04" - name: Editor w/ Mono (target=release_debug, tools=yes) + name: Editor w/ Mono (target=release_debug, tools=yes, tests=yes) steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/macos_builds.yml b/.github/workflows/macos_builds.yml index d9f41f09f7..bd3340111e 100644 --- a/.github/workflows/macos_builds.yml +++ b/.github/workflows/macos_builds.yml @@ -10,7 +10,7 @@ jobs: macos-editor: runs-on: "macos-latest" - name: Editor (target=release_debug, tools=yes) + name: Editor (target=release_debug, tools=yes, tests=yes) steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/windows_builds.yml b/.github/workflows/windows_builds.yml index 2bc3fcfdaa..0d3c78b45d 100644 --- a/.github/workflows/windows_builds.yml +++ b/.github/workflows/windows_builds.yml @@ -14,7 +14,7 @@ jobs: runs-on: "windows-latest" # Windows Editor - checkout with the plugin - name: Editor (target=release_debug, tools=yes) + name: Editor (target=release_debug, tools=yes, tests=yes) steps: - uses: actions/checkout@v2 @@ -1,25 +1,29 @@ -[](https://godotengine.org) +# Godot Engine -## Godot Engine +<p align="center"> + <a href="https://godotengine.org"> + <img src="logo.svg" width="400" alt="Godot Engine logo"> + </a> +</p> -Homepage: https://godotengine.org +## 2D and 3D cross-platform game engine -#### 2D and 3D cross-platform game engine +**[Godot Engine](https://godotengine.org) is a feature-packed, cross-platform +game engine to create 2D and 3D games from a unified interface.** It provides a +comprehensive set of common tools, so that users can focus on making games +without having to reinvent the wheel. Games can be exported in one click to a +number of platforms, including the major desktop platforms (Linux, macOS, +Windows), mobile platforms (Android, iOS), as well as Web-based platforms +(HTML5) and +[consoles](https://docs.godotengine.org/en/latest/tutorials/platform/consoles.html). -Godot Engine is a feature-packed, cross-platform game engine to create 2D and -3D games from a unified interface. It provides a comprehensive set of common -tools, so that users can focus on making games without having to reinvent the -wheel. Games can be exported in one click to a number of platforms, including -the major desktop platforms (Linux, Mac OSX, Windows) as well as mobile -(Android, iOS) and web-based (HTML5) platforms. - -#### Free, open source and community-driven +## Free, open source and community-driven Godot is completely free and open source under the very permissive MIT license. No strings attached, no royalties, nothing. The users' games are theirs, down to the last line of engine code. Godot's development is fully independent and community-driven, empowering users to help shape their engine to match their -expectations. It is supported by the Software Freedom Conservancy +expectations. It is supported by the [Software Freedom Conservancy](https://sfconservancy.org/) not-for-profit. Before being open sourced in February 2014, Godot had been developed by Juan @@ -28,43 +32,45 @@ years as an in-house engine, used to publish several work-for-hire titles.  -### Getting the engine +## Getting the engine -#### Binary downloads +### Binary downloads Official binaries for the Godot editor and the export templates can be found [on the homepage](https://godotengine.org/download). -#### Compiling from source +### Compiling from source [See the official docs](https://docs.godotengine.org/en/latest/development/compiling/) for compilation instructions for every supported platform. -### Community and contributing +## Community and contributing Godot is not only an engine but an ever-growing community of users and engine developers. The main community channels are listed [on the homepage](https://godotengine.org/community). -To get in touch with the developers, the best way is to join the -[#godotengine IRC channel](https://webchat.freenode.net/?channels=godotengine) +To get in touch with the engine developers, the best way is to join the +[#godotengine-devel IRC channel](https://webchat.freenode.net/?channels=godotengine-devel) on Freenode. To get started contributing to the project, see the [contributing guide](CONTRIBUTING.md). -### Documentation and demos +## Documentation and demos The official documentation is hosted on [ReadTheDocs](https://docs.godotengine.org). It is maintained by the Godot community in its own [GitHub repository](https://github.com/godotengine/godot-docs). The [class reference](https://docs.godotengine.org/en/latest/classes/) -is also accessible from within the engine. +is also accessible from the Godot editor. The official demos are maintained in their own [GitHub repository](https://github.com/godotengine/godot-demo-projects) as well. -There are also a number of other learning resources provided by the community, -such as text and video tutorials, demos, etc. Consult the [community channels](https://godotengine.org/community) -for more info. +There are also a number of other +[learning resources](https://docs.godotengine.org/en/latest/community/tutorials.html) +provided by the community, such as text and video tutorials, demos, etc. +Consult the [community channels](https://godotengine.org/community) +for more information. [](https://github.com/godotengine/godot/actions) [](https://www.codetriage.com/godotengine/godot) diff --git a/core/local_vector.h b/core/local_vector.h index d97f3330dc..b0dbd22b29 100644 --- a/core/local_vector.h +++ b/core/local_vector.h @@ -73,10 +73,10 @@ public: void remove(U p_index) { ERR_FAIL_UNSIGNED_INDEX(p_index, count); + count--; for (U i = p_index; i < count; i++) { data[i] = data[i + 1]; } - count--; if (!__has_trivial_destructor(T) && !force_trivial) { data[count].~T(); } diff --git a/core/project_settings.cpp b/core/project_settings.cpp index e08a44d0c1..960a0ec1b0 100644 --- a/core/project_settings.cpp +++ b/core/project_settings.cpp @@ -659,6 +659,12 @@ void ProjectSettings::set_builtin_order(const String &p_name) { } } +bool ProjectSettings::is_builtin_setting(const String &p_name) const { + // Return true because a false negative is worse than a false positive. + ERR_FAIL_COND_V_MSG(!props.has(p_name), true, "Request for nonexistent project setting: " + p_name + "."); + return props[p_name].order < NO_BUILTIN_ORDER_BASE; +} + void ProjectSettings::clear(const String &p_name) { ERR_FAIL_COND_MSG(!props.has(p_name), "Request for nonexistent project setting: " + p_name + "."); props.erase(p_name); diff --git a/core/project_settings.h b/core/project_settings.h index 659ee402b3..686f6f3873 100644 --- a/core/project_settings.h +++ b/core/project_settings.h @@ -142,6 +142,7 @@ public: int get_order(const String &p_name) const; void set_order(const String &p_name, int p_order); void set_builtin_order(const String &p_name); + bool is_builtin_setting(const String &p_name) const; Error setup(const String &p_path, const String &p_main_pack, bool p_upwards = false); diff --git a/core/variant_call.cpp b/core/variant_call.cpp index b96fd0c103..91af127d32 100644 --- a/core/variant_call.cpp +++ b/core/variant_call.cpp @@ -2350,9 +2350,9 @@ void register_variant_methods() { _VariantCall::add_variant_constant(Variant::VECTOR3, "FORWARD", Vector3(0, 0, -1)); _VariantCall::add_variant_constant(Variant::VECTOR3, "BACK", Vector3(0, 0, 1)); - _VariantCall::add_constant(Variant::VECTOR3I, "AXIS_X", Vector3::AXIS_X); - _VariantCall::add_constant(Variant::VECTOR3I, "AXIS_Y", Vector3::AXIS_Y); - _VariantCall::add_constant(Variant::VECTOR3I, "AXIS_Z", Vector3::AXIS_Z); + _VariantCall::add_constant(Variant::VECTOR3I, "AXIS_X", Vector3i::AXIS_X); + _VariantCall::add_constant(Variant::VECTOR3I, "AXIS_Y", Vector3i::AXIS_Y); + _VariantCall::add_constant(Variant::VECTOR3I, "AXIS_Z", Vector3i::AXIS_Z); _VariantCall::add_variant_constant(Variant::VECTOR3I, "ZERO", Vector3i(0, 0, 0)); _VariantCall::add_variant_constant(Variant::VECTOR3I, "ONE", Vector3i(1, 1, 1)); @@ -2366,8 +2366,8 @@ void register_variant_methods() { _VariantCall::add_constant(Variant::VECTOR2, "AXIS_X", Vector2::AXIS_X); _VariantCall::add_constant(Variant::VECTOR2, "AXIS_Y", Vector2::AXIS_Y); - _VariantCall::add_constant(Variant::VECTOR2I, "AXIS_X", Vector2::AXIS_X); - _VariantCall::add_constant(Variant::VECTOR2I, "AXIS_Y", Vector2::AXIS_Y); + _VariantCall::add_constant(Variant::VECTOR2I, "AXIS_X", Vector2i::AXIS_X); + _VariantCall::add_constant(Variant::VECTOR2I, "AXIS_Y", Vector2i::AXIS_Y); _VariantCall::add_variant_constant(Variant::VECTOR2, "ZERO", Vector2(0, 0)); _VariantCall::add_variant_constant(Variant::VECTOR2, "ONE", Vector2(1, 1)); diff --git a/doc/classes/Animation.xml b/doc/classes/Animation.xml index 09811d5617..68f0a630ef 100644 --- a/doc/classes/Animation.xml +++ b/doc/classes/Animation.xml @@ -7,10 +7,10 @@ An Animation resource contains data used to animate everything in the engine. Animations are divided into tracks, and each track must be linked to a node. The state of that node can be changed through time, by adding timed keys (events) to the track. [codeblock] # This creates an animation that makes the node "Enemy" move to the right by - # 100 pixels in 1 second. + # 100 pixels in 0.5 seconds. var animation = Animation.new() var track_index = animation.add_track(Animation.TYPE_VALUE) - animation.track_set_path(track_index, "Enemy:position.x") + animation.track_set_path(track_index, "Enemy:position:x") animation.track_insert_key(track_index, 0.0, 0) animation.track_insert_key(track_index, 0.5, 100) [/codeblock] diff --git a/doc/classes/Button.xml b/doc/classes/Button.xml index 675441d842..de05cfcd13 100644 --- a/doc/classes/Button.xml +++ b/doc/classes/Button.xml @@ -5,6 +5,18 @@ </brief_description> <description> Button is the standard themed button. It can contain text and an icon, and will display them according to the current [Theme]. + [b]Example of creating a button and assigning an action when pressed by code:[/b] + [codeblock] + func _ready(): + var button = Button.new() + button.text = "Click me" + button.connect("pressed", self, "_button_pressed") + add_child(button) + + func _button_pressed(): + print("Hello world!") + [/codeblock] + Buttons (like all Control nodes) can also be created in the editor, but some situations may require creating them from code. </description> <tutorials> </tutorials> diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml index cac4d6f36e..899988022f 100644 --- a/doc/classes/CanvasItem.xml +++ b/doc/classes/CanvasItem.xml @@ -316,7 +316,16 @@ <argument index="4" name="clip_w" type="int" default="-1"> </argument> <description> - Draws a string using a custom font. + Draws [code]text[/code] using the specified [code]font[/code] at the [code]position[/code] (top-left corner). The text will have its color multiplied by [code]modulate[/code]. If [code]clip_w[/code] is greater than or equal to 0, the text will be clipped if it exceeds the specified width. + [b]Example using the default project font:[/b] + [codeblock] + # If using this method in a script that redraws constantly, move the + # `default_font` declaration to a member variable assigned in `_ready()` + # so the Control is only created once. + var default_font = Control.new().get_font("font") + draw_string(default_font, Vector2(64, 64), "Hello world") + [/codeblock] + See also [method Font.draw]. </description> </method> <method name="draw_style_box"> diff --git a/doc/classes/EditorInterface.xml b/doc/classes/EditorInterface.xml index 8b2b9c9350..9da36b51f9 100644 --- a/doc/classes/EditorInterface.xml +++ b/doc/classes/EditorInterface.xml @@ -51,8 +51,8 @@ <return type="Control"> </return> <description> - Returns the editor's [Viewport] instance. - [b]Note:[/b] This returns the main editor viewport containing the whole editor, not the 2D or 3D viewports specifically. + Returns the main editor control. Use this as a parent for main screens. + [b]Note:[/b] This returns the main editor control containing the whole editor, not the 2D or 3D viewports specifically. </description> </method> <method name="get_file_system_dock"> diff --git a/doc/classes/File.xml b/doc/classes/File.xml index 20bc39ef1f..d91203d91f 100644 --- a/doc/classes/File.xml +++ b/doc/classes/File.xml @@ -257,6 +257,7 @@ </argument> <description> Opens an encrypted file in write or read mode. You need to pass a binary key to encrypt/decrypt it. + [b]Note:[/b] The provided key must be 32 bytes long. </description> </method> <method name="open_encrypted_with_pass"> diff --git a/doc/classes/Font.xml b/doc/classes/Font.xml index 30b8c1fe76..ce6a25e191 100644 --- a/doc/classes/Font.xml +++ b/doc/classes/Font.xml @@ -26,6 +26,7 @@ </argument> <description> Draw [code]string[/code] into a canvas item using the font at a given position, with [code]modulate[/code] color, and optionally clipping the width. [code]position[/code] specifies the baseline, not the top. To draw from the top, [i]ascent[/i] must be added to the Y axis. + See also [method CanvasItem.draw_string]. </description> </method> <method name="draw_char" qualifiers="const"> diff --git a/doc/classes/JSON.xml b/doc/classes/JSON.xml index 7bd2edcb1c..2e837dea1d 100644 --- a/doc/classes/JSON.xml +++ b/doc/classes/JSON.xml @@ -15,7 +15,7 @@ <argument index="0" name="json" type="String"> </argument> <description> - Parses a JSON encoded string and returns a [JSONParseResult] containing the result. + Parses a JSON-encoded string and returns a [JSONParseResult] containing the result. </description> </method> <method name="print"> @@ -29,6 +29,7 @@ </argument> <description> Converts a [Variant] var to JSON text and returns the result. Useful for serializing data to store or send over the network. + [b]Note:[/b] The JSON specification does not define integer or float types, but only a [i]number[/i] type. Therefore, converting a Variant to JSON text will convert all numerical values to [float] types. </description> </method> </methods> diff --git a/doc/classes/JSONParseResult.xml b/doc/classes/JSONParseResult.xml index 4444e08593..4dbceb35e9 100644 --- a/doc/classes/JSONParseResult.xml +++ b/doc/classes/JSONParseResult.xml @@ -15,21 +15,21 @@ The error type if the JSON source was not successfully parsed. See the [enum Error] constants. </member> <member name="error_line" type="int" setter="set_error_line" getter="get_error_line" default="-1"> - The line number where the error occurred if JSON source was not successfully parsed. + The line number where the error occurred if the JSON source was not successfully parsed. </member> <member name="error_string" type="String" setter="set_error_string" getter="get_error_string" default=""""> - The error message if JSON source was not successfully parsed. See the [enum Error] constants. + The error message if the JSON source was not successfully parsed. See the [enum Error] constants. </member> <member name="result" type="Variant" setter="set_result" getter="get_result"> - A [Variant] containing the parsed JSON. Use [method @GDScript.typeof] or the [code]is[/code] keyword to check if it is what you expect. For example, if the JSON source starts with curly braces ([code]{}[/code]), a [Dictionary] will be returned. If the JSON source starts with braces ([code][][/code]), an [Array] will be returned. - [b]Note:[/b] The JSON specification does not define integer or float types, but only a number type. Therefore, parsing a JSON text will convert all numerical values to float types. + A [Variant] containing the parsed JSON. Use [method @GDScript.typeof] or the [code]is[/code] keyword to check if it is what you expect. For example, if the JSON source starts with curly braces ([code]{}[/code]), a [Dictionary] will be returned. If the JSON source starts with brackets ([code][][/code]), an [Array] will be returned. + [b]Note:[/b] The JSON specification does not define integer or float types, but only a [i]number[/i] type. Therefore, parsing a JSON text will convert all numerical values to [float] types. [b]Note:[/b] JSON objects do not preserve key order like Godot dictionaries, thus, you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements: [codeblock] var p = JSON.parse('["hello", "world", "!"]') if typeof(p.result) == TYPE_ARRAY: print(p.result[0]) # Prints "hello" else: - print("unexpected results") + push_error("Unexpected results.") [/codeblock] </member> </members> diff --git a/doc/classes/String.xml b/doc/classes/String.xml index 7e55f8bd9a..ded64761d0 100644 --- a/doc/classes/String.xml +++ b/doc/classes/String.xml @@ -895,8 +895,8 @@ <argument index="2" name="maxsplit" type="int" default="0"> </argument> <description> - Splits the string by a [code]delimiter[/code] string and returns an array of the substrings. - If [code]maxsplit[/code] is specified, it defines the number of splits to do from the left up to [code]maxsplit[/code]. The default value of 0 means that all items are split. + Splits the string by a [code]delimiter[/code] string and returns an array of the substrings. The [code]delimiter[/code] can be of any length. + If [code]maxsplit[/code] is specified, it defines the number of splits to do from the left up to [code]maxsplit[/code]. The default value of [code]0[/code] means that all items are split. Example: [codeblock] var some_string = "One,Two,Three,Four" @@ -905,6 +905,7 @@ print(some_array[0]) # Prints "One" print(some_array[1]) # Prints "Two,Three,Four" [/codeblock] + If you need to split strings with more complex rules, use the [RegEx] class instead. </description> </method> <method name="split_floats"> diff --git a/doc/classes/TextEdit.xml b/doc/classes/TextEdit.xml index b7240655af..d4abac15c0 100644 --- a/doc/classes/TextEdit.xml +++ b/doc/classes/TextEdit.xml @@ -430,6 +430,9 @@ <member name="v_scroll_speed" type="float" setter="set_v_scroll_speed" getter="get_v_scroll_speed" default="80.0"> Vertical scroll sensitivity. </member> + <member name="virtual_keyboard_enabled" type="bool" setter="set_virtual_keyboard_enabled" getter="is_virtual_keyboard_enabled" default="true"> + If [code]true[/code], the native virtual keyboard is shown when focused on platforms that support it. + </member> <member name="wrap_enabled" type="bool" setter="set_wrap_enabled" getter="is_wrap_enabled" default="false"> If [code]true[/code], enables text wrapping when it goes beyond the edge of what is visible. </member> diff --git a/doc/classes/Thread.xml b/doc/classes/Thread.xml index 4d6e89fa6f..5c63d01322 100644 --- a/doc/classes/Thread.xml +++ b/doc/classes/Thread.xml @@ -7,7 +7,8 @@ A unit of execution in a process. Can run methods on [Object]s simultaneously. The use of synchronization via [Mutex] or [Semaphore] is advised if working with shared objects. </description> <tutorials> - <link>https://docs.godotengine.org/en/latest/tutorials/threads/using_multiple_threads.html</link> + <link title="Using multiple threads">https://docs.godotengine.org/en/latest/tutorials/threads/using_multiple_threads.html</link> + <link title="Thread-safe APIs">https://docs.godotengine.org/en/latest/tutorials/threads/thread_safe_apis.html</link> </tutorials> <methods> <method name="get_id" qualifiers="const"> diff --git a/doc/classes/TreeItem.xml b/doc/classes/TreeItem.xml index 126d6b4180..22e643a51d 100644 --- a/doc/classes/TreeItem.xml +++ b/doc/classes/TreeItem.xml @@ -118,7 +118,7 @@ <return type="TreeItem"> </return> <description> - Returns the TreeItem's child items. + Returns the TreeItem's first child item or a null object if there is none. </description> </method> <method name="get_custom_bg_color" qualifiers="const"> @@ -196,7 +196,7 @@ <return type="TreeItem"> </return> <description> - Returns the next TreeItem in the tree. + Returns the next TreeItem in the tree or a null object if there is none. </description> </method> <method name="get_next_visible"> @@ -205,7 +205,7 @@ <argument index="0" name="wrap" type="bool" default="false"> </argument> <description> - Returns the next visible TreeItem in the tree. + Returns the next visible TreeItem in the tree or a null object if there is none. If [code]wrap[/code] is enabled, the method will wrap around to the first visible element in the tree when called on the last visible element, otherwise it returns [code]null[/code]. </description> </method> @@ -213,14 +213,14 @@ <return type="TreeItem"> </return> <description> - Returns the parent TreeItem. + Returns the parent TreeItem or a null object if there is none. </description> </method> <method name="get_prev"> <return type="TreeItem"> </return> <description> - Returns the previous TreeItem in the tree. + Returns the previous TreeItem in the tree or a null object if there is none. </description> </method> <method name="get_prev_visible"> @@ -229,7 +229,7 @@ <argument index="0" name="wrap" type="bool" default="false"> </argument> <description> - Returns the previous visible TreeItem in the tree. + Returns the previous visible TreeItem in the tree or a null object if there is none. If [code]wrap[/code] is enabled, the method will wrap around to the last visible element in the tree when called on the first visible element, otherwise it returns [code]null[/code]. </description> </method> diff --git a/doc/tools/makerst.py b/doc/tools/makerst.py index c0bba38799..b594f652b3 100755 --- a/doc/tools/makerst.py +++ b/doc/tools/makerst.py @@ -565,6 +565,8 @@ def make_rst_class(class_def, state, dry_run, output_dir): # type: (ClassDef, S index += 1 + f.write(make_footer()) + def escape_rst(text, until_pos=-1): # type: (str) -> str # Escape \ character, otherwise it ends up as an escape character in rst @@ -600,6 +602,43 @@ def escape_rst(text, until_pos=-1): # type: (str) -> str return text +def format_codeblock(code_type, post_text, indent_level, state): # types: str, str, int, state + end_pos = post_text.find("[/" + code_type + "]") + if end_pos == -1: + print_error("[" + code_type + "] without a closing tag, file: {}".format(state.current_class), state) + return None + + code_text = post_text[len("[" + code_type + "]") : end_pos] + post_text = post_text[end_pos:] + + # Remove extraneous tabs + code_pos = 0 + while True: + code_pos = code_text.find("\n", code_pos) + if code_pos == -1: + break + + to_skip = 0 + while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t": + to_skip += 1 + + if to_skip > indent_level: + print_error( + "Four spaces should be used for indentation within [" + + code_type + + "], file: {}".format(state.current_class), + state, + ) + + if len(code_text[code_pos + to_skip + 1 :]) == 0: + code_text = code_text[:code_pos] + "\n" + code_pos += 1 + else: + code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1 :] + code_pos += 5 - to_skip + return ["\n[" + code_type + "]" + code_text + post_text, len("\n[" + code_type + "]" + code_text)] + + def rstize_text(text, state): # type: (str, State) -> str # Linebreak + tabs in the XML should become two line breaks unless in a "codeblock" pos = 0 @@ -616,43 +655,17 @@ def rstize_text(text, state): # type: (str, State) -> str post_text = text[pos + 1 :] # Handle codeblocks - if post_text.startswith("[codeblock]"): - end_pos = post_text.find("[/codeblock]") - if end_pos == -1: - print_error("[codeblock] without a closing tag, file: {}".format(state.current_class), state) + if ( + post_text.startswith("[codeblock]") + or post_text.startswith("[gdscript]") + or post_text.startswith("[csharp]") + ): + block_type = post_text[1:].split("]")[0] + result = format_codeblock(block_type, post_text, indent_level, state) + if result is None: return "" - - code_text = post_text[len("[codeblock]") : end_pos] - post_text = post_text[end_pos:] - - # Remove extraneous tabs - code_pos = 0 - while True: - code_pos = code_text.find("\n", code_pos) - if code_pos == -1: - break - - to_skip = 0 - while code_pos + to_skip + 1 < len(code_text) and code_text[code_pos + to_skip + 1] == "\t": - to_skip += 1 - - if to_skip > indent_level: - print_error( - "Four spaces should be used for indentation within [codeblock], file: {}".format( - state.current_class - ), - state, - ) - - if len(code_text[code_pos + to_skip + 1 :]) == 0: - code_text = code_text[:code_pos] + "\n" - code_pos += 1 - else: - code_text = code_text[:code_pos] + "\n " + code_text[code_pos + to_skip + 1 :] - code_pos += 5 - to_skip - - text = pre_text + "\n[codeblock]" + code_text + post_text - pos += len("\n[codeblock]" + code_text) + text = pre_text + result[0] + pos += result[1] # Handle normal text else: @@ -697,7 +710,7 @@ def rstize_text(text, state): # type: (str, State) -> str else: # command cmd = tag_text space_pos = tag_text.find(" ") - if cmd == "/codeblock": + if cmd == "/codeblock" or cmd == "/gdscript" or cmd == "/csharp": tag_text = "" tag_depth -= 1 inside_code = False @@ -813,6 +826,20 @@ def rstize_text(text, state): # type: (str, State) -> str tag_depth += 1 tag_text = "\n::\n" inside_code = True + elif cmd == "gdscript": + tag_depth += 1 + tag_text = "\n .. code-tab:: gdscript GDScript\n" + inside_code = True + elif cmd == "csharp": + tag_depth += 1 + tag_text = "\n .. code-tab:: csharp\n" + inside_code = True + elif cmd == "codeblocks": + tag_depth += 1 + tag_text = "\n.. tabs::" + elif cmd == "/codeblocks": + tag_depth -= 1 + tag_text = "" elif cmd == "br": # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly tag_text = "\n\n" @@ -995,7 +1022,10 @@ def make_method_signature( out += " **)**" if isinstance(method_def, MethodDef) and method_def.qualifiers is not None: - out += " " + method_def.qualifiers + # Use substitutions for abbreviations. This is used to display tooltips on hover. + # See `make_footer()` for descriptions. + for qualifier in method_def.qualifiers.split(): + out += " |" + qualifier + "|" return ret_type, out @@ -1004,6 +1034,18 @@ def make_heading(title, underline): # type: (str, str) -> str return title + "\n" + (underline * len(title)) + "\n\n" +def make_footer(): # type: () -> str + # Generate reusable abbreviation substitutions. + # This way, we avoid bloating the generated rST with duplicate abbreviations. + # fmt: off + return ( + ".. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)`\n" + ".. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)`\n" + ".. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`" + ) + # fmt: on + + def make_url(link): # type: (str) -> str match = GODOT_DOCS_PATTERN.search(link) if match: diff --git a/editor/doc_data.cpp b/editor/doc_data.cpp index 75b16b4510..791b49319a 100644 --- a/editor/doc_data.cpp +++ b/editor/doc_data.cpp @@ -316,8 +316,7 @@ void DocData::generate(bool p_basic_types) { if (name == "ProjectSettings") { // Special case for project settings, so that settings are not taken from the current project's settings - if (E->get().name == "script" || - ProjectSettings::get_singleton()->get_order(E->get().name) >= ProjectSettings::NO_BUILTIN_ORDER_BASE) { + if (E->get().name == "script" || !ProjectSettings::get_singleton()->is_builtin_setting(E->get().name)) { continue; } if (E->get().usage & PROPERTY_USAGE_EDITOR) { diff --git a/editor/editor_help.cpp b/editor/editor_help.cpp index 2a59aadd61..bce34db740 100644 --- a/editor/editor_help.cpp +++ b/editor/editor_help.cpp @@ -1252,6 +1252,55 @@ static void _add_text_to_rt(const String &p_bbcode, RichTextLabel *p_rt) { String bbcode = p_bbcode.dedent().replace("\t", "").replace("\r", "").strip_edges(); + // Select the correct code examples + switch ((int)EDITOR_GET("text_editor/help/class_reference_examples")) { + case 0: // GDScript + bbcode = bbcode.replace("[gdscript]", "[codeblock]"); + bbcode = bbcode.replace("[/gdscript]", "[/codeblock]"); + + for (int pos = bbcode.find("[csharp]"); pos != -1; pos = bbcode.find("[csharp]")) { + if (bbcode.find("[/csharp]") == -1) { + WARN_PRINT("Unclosed [csharp] block or parse fail in code (search for tag errors)"); + break; + } + + bbcode.erase(pos, bbcode.find("[/csharp]") + 9 - pos); + while (bbcode[pos] == '\n') { + bbcode.erase(pos, 1); + } + } + break; + case 1: // C# + bbcode = bbcode.replace("[csharp]", "[codeblock]"); + bbcode = bbcode.replace("[/csharp]", "[/codeblock]"); + + for (int pos = bbcode.find("[gdscript]"); pos != -1; pos = bbcode.find("[gdscript]")) { + if (bbcode.find("[/gdscript]") == -1) { + WARN_PRINT("Unclosed [gdscript] block or parse fail in code (search for tag errors)"); + break; + } + + bbcode.erase(pos, bbcode.find("[/gdscript]") + 11 - pos); + while (bbcode[pos] == '\n') { + bbcode.erase(pos, 1); + } + } + break; + case 2: // GDScript and C# + bbcode = bbcode.replace("[csharp]", "[b]C#:[/b]\n[codeblock]"); + bbcode = bbcode.replace("[gdscript]", "[b]GDScript:[/b]\n[codeblock]"); + + bbcode = bbcode.replace("[/csharp]", "[/codeblock]"); + bbcode = bbcode.replace("[/gdscript]", "[/codeblock]"); + break; + } + + // Remove codeblocks (they would be printed otherwise) + bbcode = bbcode.replace("[codeblocks]\n", ""); + bbcode = bbcode.replace("\n[/codeblocks]", ""); + bbcode = bbcode.replace("[codeblocks]", ""); + bbcode = bbcode.replace("[/codeblocks]", ""); + // remove extra new lines around code blocks bbcode = bbcode.replace("[codeblock]\n", "[codeblock]"); bbcode = bbcode.replace("\n[/codeblock]", "[/codeblock]"); diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index 3a1a0d5b01..a3438b3601 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -495,6 +495,8 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { hints["text_editor/help/help_source_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_source_font_size", PROPERTY_HINT_RANGE, "8,48,1"); _initial_set("text_editor/help/help_title_font_size", 23); hints["text_editor/help/help_title_font_size"] = PropertyInfo(Variant::INT, "text_editor/help/help_title_font_size", PROPERTY_HINT_RANGE, "8,48,1"); + _initial_set("text_editor/help/class_reference_examples", 0); + hints["text_editor/help/class_reference_examples"] = PropertyInfo(Variant::INT, "text_editor/help/class_reference_examples", PROPERTY_HINT_ENUM, "GDScript,C#,GDScript and C#"); /* Editors */ diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp index a93763810b..8d54bc8021 100644 --- a/editor/editor_themes.cpp +++ b/editor/editor_themes.cpp @@ -85,7 +85,8 @@ static Ref<StyleBoxLine> make_line_stylebox(Color p_color, int p_thickness = 1, return style; } -Ref<ImageTexture> editor_generate_icon(int p_index, bool p_convert_color, float p_scale = EDSCALE, bool p_force_filter = false) { +#ifdef MODULE_SVG_ENABLED +static Ref<ImageTexture> editor_generate_icon(int p_index, bool p_convert_color, float p_scale = EDSCALE, bool p_force_filter = false) { Ref<ImageTexture> icon = memnew(ImageTexture); Ref<Image> img = memnew(Image); @@ -99,6 +100,7 @@ Ref<ImageTexture> editor_generate_icon(int p_index, bool p_convert_color, float return icon; } +#endif #ifndef ADD_CONVERT_COLOR #define ADD_CONVERT_COLOR(dictionary, old_color, new_color) dictionary[Color::html(old_color)] = Color::html(new_color) diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index 6c7f4eb908..20eef1cebd 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -1922,14 +1922,18 @@ void ScriptEditor::_update_script_names() { Vector<String> disambiguated_script_names; Vector<String> full_script_paths; for (int j = 0; j < sedata.size(); j++) { - disambiguated_script_names.append(sedata[j].name); + disambiguated_script_names.append(sedata[j].name.replace("(*)", "")); full_script_paths.append(sedata[j].tooltip); } EditorNode::disambiguate_filenames(full_script_paths, disambiguated_script_names); for (int j = 0; j < sedata.size(); j++) { - sedata.write[j].name = disambiguated_script_names[j]; + if (sedata[j].name.ends_with("(*)")) { + sedata.write[j].name = disambiguated_script_names[j] + "(*)"; + } else { + sedata.write[j].name = disambiguated_script_names[j]; + } } EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_child(i)); diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp index 1a88562c13..4b89ca1216 100644 --- a/editor/plugins/script_text_editor.cpp +++ b/editor/plugins/script_text_editor.cpp @@ -1639,6 +1639,7 @@ void ScriptTextEditor::_enable_code_editor() { code_editor->get_text_edit()->connect("breakpoint_toggled", callable_mp(this, &ScriptTextEditor::_breakpoint_toggled)); code_editor->get_text_edit()->connect("symbol_lookup", callable_mp(this, &ScriptTextEditor::_lookup_symbol)); code_editor->get_text_edit()->connect("symbol_validate", callable_mp(this, &ScriptTextEditor::_validate_symbol)); + code_editor->get_text_edit()->connect("info_clicked", callable_mp(this, &ScriptTextEditor::_lookup_connections)); code_editor->get_text_edit()->connect("gui_input", callable_mp(this, &ScriptTextEditor::_text_edit_gui_input)); code_editor->show_toggle_scripts_button(); diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp index 0af2b120bd..53bd1150ec 100644 --- a/editor/plugins/visual_shader_editor_plugin.cpp +++ b/editor/plugins/visual_shader_editor_plugin.cpp @@ -874,6 +874,8 @@ void VisualShaderEditor::_update_graph() { Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); Color function_color = EDITOR_GET("text_editor/highlighting/function_color"); + Color number_color = EDITOR_GET("text_editor/highlighting/number_color"); + Color members_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); expression_box->set_syntax_highlighter(expression_syntax_highlighter); expression_box->add_theme_color_override("background_color", background_color); @@ -884,8 +886,10 @@ void VisualShaderEditor::_update_graph() { expression_box->add_theme_font_override("font", get_theme_font("expression", "EditorFonts")); expression_box->add_theme_color_override("font_color", text_color); + expression_syntax_highlighter->set_number_color(number_color); expression_syntax_highlighter->set_symbol_color(symbol_color); expression_syntax_highlighter->set_function_color(function_color); + expression_syntax_highlighter->set_member_variable_color(members_color); expression_syntax_highlighter->add_color_region("/*", "*/", comment_color, false); expression_syntax_highlighter->add_color_region("//", "", comment_color, true); @@ -1743,6 +1747,8 @@ void VisualShaderEditor::_notification(int p_what) { Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); Color function_color = EDITOR_GET("text_editor/highlighting/function_color"); + Color number_color = EDITOR_GET("text_editor/highlighting/number_color"); + Color members_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); preview_text->add_theme_color_override("background_color", background_color); @@ -1752,8 +1758,10 @@ void VisualShaderEditor::_notification(int p_what) { preview_text->add_theme_font_override("font", get_theme_font("expression", "EditorFonts")); preview_text->add_theme_color_override("font_color", text_color); + syntax_highlighter->set_number_color(number_color); syntax_highlighter->set_symbol_color(symbol_color); syntax_highlighter->set_function_color(function_color); + syntax_highlighter->set_member_variable_color(members_color); syntax_highlighter->clear_color_regions(); syntax_highlighter->add_color_region("/*", "*/", comment_color, false); syntax_highlighter->add_color_region("//", "", comment_color, true); diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp index a68742a985..35311b32eb 100644 --- a/editor/project_manager.cpp +++ b/editor/project_manager.cpp @@ -475,10 +475,12 @@ private: set_message(TTR("Couldn't create project.godot in project path."), MESSAGE_ERROR); } else { f->store_line("[gd_resource type=\"Environment\" load_steps=2 format=2]"); + f->store_line(""); f->store_line("[sub_resource type=\"Sky\" id=1]"); + f->store_line(""); f->store_line("[resource]"); f->store_line("background_mode = 2"); - f->store_line("background_sky = SubResource( 1 )"); + f->store_line("sky = SubResource( 1 )"); memdelete(f); } } diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp index 0257e31ee7..9be1a7c2fe 100644 --- a/editor/project_settings_editor.cpp +++ b/editor/project_settings_editor.cpp @@ -30,8 +30,6 @@ #include "project_settings_editor.h" -#include "core/global_constants.h" -#include "core/os/keyboard.h" #include "core/project_settings.h" #include "editor/editor_export.h" #include "editor/editor_node.h" @@ -48,175 +46,157 @@ void ProjectSettingsEditor::popup_project_settings() { popup_centered_clamped(Size2(900, 700) * EDSCALE, 0.8); } - globals_editor->update_category_list(); + _add_feature_overrides(); + inspector->update_category_list(); + localization_editor->update_translations(); autoload_settings->update_autoload(); plugin_settings->update_plugins(); - set_process_unhandled_input(true); } -void ProjectSettingsEditor::_unhandled_input(const Ref<InputEvent> &p_event) { - const Ref<InputEventKey> k = p_event; - - if (k.is_valid() && k->is_pressed()) { - if (k->get_keycode_with_modifiers() == (KEY_MASK_CMD | KEY_F)) { - if (search_button->is_pressed()) { - search_box->grab_focus(); - search_box->select_all(); - } else { - // This toggles the search bar display while giving the button its "pressed" appearance - search_button->set_pressed(true); - } - - set_input_as_handled(); - } - } +void ProjectSettingsEditor::queue_save() { + timer->start(); } -void ProjectSettingsEditor::_notification(int p_what) { - switch (p_what) { - case NOTIFICATION_VISIBILITY_CHANGED: { - if (!is_visible()) { - EditorSettings::get_singleton()->set_project_metadata("dialog_bounds", "project_settings", Rect2(get_position(), get_size())); - set_process_unhandled_input(false); - } - } break; - case NOTIFICATION_ENTER_TREE: { - globals_editor->edit(ProjectSettings::get_singleton()); - - search_button->set_icon(get_theme_icon("Search", "EditorIcons")); - search_box->set_right_icon(get_theme_icon("Search", "EditorIcons")); - search_box->set_clear_button_enabled(true); - - restart_close_button->set_icon(get_theme_icon("Close", "EditorIcons")); - restart_container->add_theme_style_override("panel", get_theme_stylebox("bg", "Tree")); - restart_icon->set_texture(get_theme_icon("StatusWarning", "EditorIcons")); - restart_label->add_theme_color_override("font_color", get_theme_color("warning_color", "Editor")); - - } break; - case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { - search_button->set_icon(get_theme_icon("Search", "EditorIcons")); - search_box->set_right_icon(get_theme_icon("Search", "EditorIcons")); - search_box->set_clear_button_enabled(true); - } break; - } +void ProjectSettingsEditor::set_plugins_page() { + tab_container->set_current_tab(plugin_settings->get_index()); } void ProjectSettingsEditor::update_plugins() { plugin_settings->update_plugins(); } -void ProjectSettingsEditor::_item_selected(const String &p_path) { - const String &selected_path = p_path; - if (selected_path == String()) { - return; +void ProjectSettingsEditor::_setting_edited(const String &p_name) { + queue_save(); +} + +void ProjectSettingsEditor::_advanced_pressed() { + if (advanced->is_pressed()) { + _update_advanced_bar(); + advanced_bar->show(); + } else { + advanced_bar->hide(); } - category->set_text(globals_editor->get_current_section()); - property->set_text(selected_path); - popup_copy_to_feature->set_disabled(false); } -void ProjectSettingsEditor::_item_adds(String) { - _item_add(); +void ProjectSettingsEditor::_setting_selected(const String &p_path) { + if (p_path == String()) { + return; + } + + category_box->set_text(inspector->get_current_section()); + property_box->set_text(p_path); + + if (advanced_bar->is_visible()) { + _update_advanced_bar(); // set_text doesn't trigger text_changed + } } -void ProjectSettingsEditor::_item_add() { +void ProjectSettingsEditor::_add_setting() { + String setting = _get_setting_name(); + // Initialize the property with the default value for the given type. // The type list starts at 1 (as we exclude Nil), so add 1 to the selected value. Callable::CallError ce; const Variant value = Variant::construct(Variant::Type(type->get_selected() + 1), nullptr, 0, ce); - String catname = category->get_text().strip_edges(); - String propname = property->get_text().strip_edges(); + undo_redo->create_action(TTR("Add Project Setting")); + undo_redo->add_do_property(ps, setting, value); + undo_redo->add_undo_property(ps, setting, ps->has_setting(setting) ? ps->get(setting) : Variant()); - if (propname.empty()) { - return; - } + undo_redo->add_do_method(inspector, "update_category_list"); + undo_redo->add_undo_method(inspector, "update_category_list"); + undo_redo->add_do_method(this, "queue_save"); + undo_redo->add_undo_method(this, "queue_save"); + undo_redo->commit_action(); - if (catname.empty()) { - catname = "global"; - } + inspector->set_current_section(setting.get_slice("/", 1)); +} - String name = catname + "/" + propname; +void ProjectSettingsEditor::_delete_setting() { + String setting = _get_setting_name(); + Variant value = ps->get(setting); + int order = ps->get_order(setting); - undo_redo->create_action(TTR("Add Global Property")); + undo_redo->create_action(TTR("Delete Item")); - undo_redo->add_do_property(ProjectSettings::get_singleton(), name, value); + undo_redo->add_do_method(ps, "clear", setting); + undo_redo->add_undo_method(ps, "set", setting, value); + undo_redo->add_undo_method(ps, "set_order", setting, order); - if (ProjectSettings::get_singleton()->has_setting(name)) { - undo_redo->add_undo_property(ProjectSettings::get_singleton(), name, ProjectSettings::get_singleton()->get(name)); - } else { - undo_redo->add_undo_property(ProjectSettings::get_singleton(), name, Variant()); - } + undo_redo->add_do_method(inspector, "update_category_list"); + undo_redo->add_undo_method(inspector, "update_category_list"); + undo_redo->add_do_method(this, "queue_save"); + undo_redo->add_undo_method(this, "queue_save"); - undo_redo->add_do_method(globals_editor, "update_category_list"); - undo_redo->add_undo_method(globals_editor, "update_category_list"); - undo_redo->add_do_method(this, "_settings_changed"); - undo_redo->add_undo_method(this, "_settings_changed"); undo_redo->commit_action(); - globals_editor->set_current_section(catname); - - _settings_changed(); + property_box->clear(); } -void ProjectSettingsEditor::_item_del() { - String path = globals_editor->get_inspector()->get_selected_path(); - if (path == String()) { - EditorNode::get_singleton()->show_warning(TTR("Select a setting item first!")); - return; - } +void ProjectSettingsEditor::_text_field_changed(const String &p_text) { + _update_advanced_bar(); +} - String property = globals_editor->get_current_section().plus_file(path); +void ProjectSettingsEditor::_feature_selected(int p_index) { + _update_advanced_bar(); +} - if (!ProjectSettings::get_singleton()->has_setting(property)) { - EditorNode::get_singleton()->show_warning(vformat(TTR("No property '%s' exists."), property)); - return; - } +void ProjectSettingsEditor::_update_advanced_bar() { + const String property_text = property_box->get_text().strip_edges(); - if (ProjectSettings::get_singleton()->get_order(property) < ProjectSettings::NO_BUILTIN_ORDER_BASE) { - EditorNode::get_singleton()->show_warning(vformat(TTR("Setting '%s' is internal, and it can't be deleted."), property)); - return; - } - - undo_redo->create_action(TTR("Delete Item")); + String error_msg = ""; + bool disable_add = true; + bool disable_del = true; - Variant value = ProjectSettings::get_singleton()->get(property); - int order = ProjectSettings::get_singleton()->get_order(property); + if (!property_box->get_text().empty()) { + const String setting = _get_setting_name(); + bool setting_exists = ps->has_setting(setting); + if (setting_exists) { + error_msg = TTR(" - Cannot add already existing setting."); - undo_redo->add_do_method(ProjectSettings::get_singleton(), "clear", property); - undo_redo->add_undo_method(ProjectSettings::get_singleton(), "set", property, value); - undo_redo->add_undo_method(ProjectSettings::get_singleton(), "set_order", property, order); + disable_del = ps->is_builtin_setting(setting); + if (disable_del) { + String msg = TTR(" - Cannot delete built-in setting."); + error_msg += (error_msg == "") ? msg : "\n" + msg; + } + } else { + bool bad_category = false; // Allow empty string. + Vector<String> cats = category_box->get_text().strip_edges().split("/"); + for (int i = 0; i < cats.size(); i++) { + if (!cats[i].is_valid_identifier()) { + bad_category = true; + error_msg = TTR(" - Invalid category name."); + break; + } + } - undo_redo->add_do_method(globals_editor, "update_category_list"); - undo_redo->add_undo_method(globals_editor, "update_category_list"); + disable_add = !bad_category; - undo_redo->add_do_method(this, "_settings_changed"); - undo_redo->add_undo_method(this, "_settings_changed"); + if (!property_text.is_valid_identifier()) { + disable_add = true; + String msg = TTR(" - Invalid property name."); + error_msg += (error_msg == "") ? msg : "\n" + msg; + } + } + } - undo_redo->commit_action(); -} + add_button->set_disabled(disable_add); + del_button->set_disabled(disable_del); -void ProjectSettingsEditor::_save() { - Error err = ProjectSettings::get_singleton()->save(); - message->set_text(err != OK ? TTR("Error saving settings.") : TTR("Settings saved OK.")); - message->popup_centered(Size2(300, 100) * EDSCALE); + error_label->set_text(error_msg); + error_label->set_visible(error_msg != ""); } -void ProjectSettingsEditor::_settings_prop_edited(const String &p_name) { - // Method needed to discard the mandatory argument of the property_edited signal - _settings_changed(); -} +String ProjectSettingsEditor::_get_setting_name() const { + const String cat = category_box->get_text(); + const String name = (cat.empty() ? "global" : cat.strip_edges()).plus_file(property_box->get_text().strip_edges()); + const String feature = feature_override->get_item_text(feature_override->get_selected()); -void ProjectSettingsEditor::_settings_changed() { - timer->start(); + return (feature == "") ? name : (name + "." + feature); } -void ProjectSettingsEditor::queue_save() { - _settings_changed(); -} - -void ProjectSettingsEditor::_copy_to_platform_about_to_show() { +void ProjectSettingsEditor::_add_feature_overrides() { Set<String> presets; presets.insert("bptc"); @@ -230,25 +210,26 @@ void ProjectSettingsEditor::_copy_to_platform_about_to_show() { presets.insert("standalone"); presets.insert("32"); presets.insert("64"); - // Not available as an export platform yet, so it needs to be added manually - presets.insert("Server"); + presets.insert("Server"); // Not available as an export platform yet, so it needs to be added manually - for (int i = 0; i < EditorExport::get_singleton()->get_export_platform_count(); i++) { + EditorExport *ee = EditorExport::get_singleton(); + + for (int i = 0; i < ee->get_export_platform_count(); i++) { List<String> p; - EditorExport::get_singleton()->get_export_platform(i)->get_platform_features(&p); + ee->get_export_platform(i)->get_platform_features(&p); for (List<String>::Element *E = p.front(); E; E = E->next()) { presets.insert(E->get()); } } - for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) { + for (int i = 0; i < ee->get_export_preset_count(); i++) { List<String> p; - EditorExport::get_singleton()->get_export_preset(i)->get_platform()->get_preset_features(EditorExport::get_singleton()->get_export_preset(i), &p); + ee->get_export_preset(i)->get_platform()->get_preset_features(ee->get_export_preset(i), &p); for (List<String>::Element *E = p.front(); E; E = E->next()) { presets.insert(E->get()); } - String custom = EditorExport::get_singleton()->get_export_preset(i)->get_custom_features(); + String custom = ee->get_export_preset(i)->get_custom_features(); Vector<String> custom_list = custom.split(","); for (int j = 0; j < custom_list.size(); j++) { String f = custom_list[j].strip_edges(); @@ -258,70 +239,14 @@ void ProjectSettingsEditor::_copy_to_platform_about_to_show() { } } - popup_copy_to_feature->get_popup()->clear(); - int id = 0; + feature_override->clear(); + feature_override->add_item("", 0); // So it is always on top. + int id = 1; for (Set<String>::Element *E = presets.front(); E; E = E->next()) { - popup_copy_to_feature->get_popup()->add_item(E->get(), id++); + feature_override->add_item(E->get(), id++); } } -void ProjectSettingsEditor::_copy_to_platform(int p_which) { - String path = globals_editor->get_inspector()->get_selected_path(); - if (path == String()) { - EditorNode::get_singleton()->show_warning(TTR("Select a setting item first!")); - return; - } - - String property = globals_editor->get_current_section().plus_file(path); - - undo_redo->create_action(TTR("Override for Feature")); - - Variant value = ProjectSettings::get_singleton()->get(property); - if (property.find(".") != -1) { //overwriting overwrite, keep overwrite - undo_redo->add_do_method(ProjectSettings::get_singleton(), "clear", property); - undo_redo->add_undo_method(ProjectSettings::get_singleton(), "set", property, value); - } - - String feature = popup_copy_to_feature->get_popup()->get_item_text(p_which); - String new_path = property + "." + feature; - - undo_redo->add_do_method(ProjectSettings::get_singleton(), "set", new_path, value); - if (ProjectSettings::get_singleton()->has_setting(new_path)) { - undo_redo->add_undo_method(ProjectSettings::get_singleton(), "set", new_path, ProjectSettings::get_singleton()->get(new_path)); - } - - undo_redo->add_do_method(globals_editor, "update_category_list"); - undo_redo->add_undo_method(globals_editor, "update_category_list"); - - undo_redo->add_do_method(this, "_settings_changed"); - undo_redo->add_undo_method(this, "_settings_changed"); - - undo_redo->commit_action(); -} - -void ProjectSettingsEditor::_toggle_search_bar(bool p_pressed) { - globals_editor->get_inspector()->set_use_filter(p_pressed); - - if (p_pressed) { - search_bar->show(); - add_prop_bar->hide(); - search_box->grab_focus(); - search_box->select_all(); - } else { - search_box->clear(); - search_bar->hide(); - add_prop_bar->show(); - } -} - -void ProjectSettingsEditor::set_plugins_page() { - tab_container->set_current_tab(plugin_settings->get_index()); -} - -TabContainer *ProjectSettingsEditor::get_tabs() { - return tab_container; -} - void ProjectSettingsEditor::_editor_restart() { EditorNode::get_singleton()->save_all_scenes(); EditorNode::get_singleton()->restart_editor(); @@ -335,17 +260,48 @@ void ProjectSettingsEditor::_editor_restart_close() { restart_container->hide(); } -void ProjectSettingsEditor::_bind_methods() { - ClassDB::bind_method(D_METHOD("_unhandled_input"), &ProjectSettingsEditor::_unhandled_input); - ClassDB::bind_method(D_METHOD("_save"), &ProjectSettingsEditor::_save); +void ProjectSettingsEditor::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_VISIBILITY_CHANGED: { + if (!is_visible()) { + EditorSettings::get_singleton()->set_project_metadata("dialog_bounds", "project_settings", Rect2(get_position(), get_size())); + if (advanced->is_pressed()) { + advanced->set_pressed(false); + advanced_bar->hide(); + } + } + } break; + case NOTIFICATION_ENTER_TREE: { + inspector->edit(ps); + + error_label->add_theme_color_override("font_color", error_label->get_theme_color("error_color", "Editor")); + add_button->set_icon(get_theme_icon("Add", "EditorIcons")); + del_button->set_icon(get_theme_icon("Remove", "EditorIcons")); + + search_box->set_right_icon(get_theme_icon("Search", "EditorIcons")); + search_box->set_clear_button_enabled(true); + + restart_close_button->set_icon(get_theme_icon("Close", "EditorIcons")); + restart_container->add_theme_style_override("panel", get_theme_stylebox("bg", "Tree")); + restart_icon->set_texture(get_theme_icon("StatusWarning", "EditorIcons")); + restart_label->add_theme_color_override("font_color", get_theme_color("warning_color", "Editor")); + } break; + case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { + search_box->set_right_icon(get_theme_icon("Search", "EditorIcons")); + search_box->set_clear_button_enabled(true); + } break; + } +} - ClassDB::bind_method(D_METHOD("get_tabs"), &ProjectSettingsEditor::get_tabs); +void ProjectSettingsEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("queue_save"), &ProjectSettingsEditor::queue_save); } ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) { singleton = this; set_title(TTR("Project Settings (project.godot)")); + ps = ProjectSettings::get_singleton(); undo_redo = &p_data->get_undo_redo(); data = p_data; @@ -354,103 +310,110 @@ ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) { tab_container->set_use_hidden_tabs_for_min_size(true); add_child(tab_container); - VBoxContainer *props_base = memnew(VBoxContainer); - props_base->set_name(TTR("General")); - props_base->set_alignment(BoxContainer::ALIGN_BEGIN); - props_base->set_v_size_flags(Control::SIZE_EXPAND_FILL); - tab_container->add_child(props_base); - - HBoxContainer *hbc = memnew(HBoxContainer); - hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL); - props_base->add_child(hbc); - - search_button = memnew(Button); - search_button->set_text(TTR("Search")); - search_button->set_toggle_mode(true); - search_button->set_pressed(false); - search_button->connect("toggled", callable_mp(this, &ProjectSettingsEditor::_toggle_search_bar)); - hbc->add_child(search_button); - - hbc->add_child(memnew(VSeparator)); - - add_prop_bar = memnew(HBoxContainer); - add_prop_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL); - hbc->add_child(add_prop_bar); - - Label *l = memnew(Label); - l->set_text(TTR("Category:")); - add_prop_bar->add_child(l); - - category = memnew(LineEdit); - category->set_h_size_flags(Control::SIZE_EXPAND_FILL); - category->connect("text_entered", callable_mp(this, &ProjectSettingsEditor::_item_adds)); - add_prop_bar->add_child(category); - - l = memnew(Label); - l->set_text(TTR("Property:")); - add_prop_bar->add_child(l); - - property = memnew(LineEdit); - property->set_h_size_flags(Control::SIZE_EXPAND_FILL); - property->connect("text_entered", callable_mp(this, &ProjectSettingsEditor::_item_adds)); - add_prop_bar->add_child(property); - - l = memnew(Label); - l->set_text(TTR("Type:")); - add_prop_bar->add_child(l); - - type = memnew(OptionButton); - type->set_h_size_flags(Control::SIZE_EXPAND_FILL); - add_prop_bar->add_child(type); - - // Start at 1 to avoid adding "Nil" as an option - for (int i = 1; i < Variant::VARIANT_MAX; i++) { - type->add_item(Variant::get_type_name(Variant::Type(i))); + VBoxContainer *general_editor = memnew(VBoxContainer); + general_editor->set_name(TTR("General")); + general_editor->set_alignment(BoxContainer::ALIGN_BEGIN); + general_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); + tab_container->add_child(general_editor); + + VBoxContainer *header = memnew(VBoxContainer); + header->set_h_size_flags(Control::SIZE_EXPAND_FILL); + general_editor->add_child(header); + + { + // Search bar. + search_bar = memnew(HBoxContainer); + search_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL); + header->add_child(search_bar); + + search_box = memnew(LineEdit); + search_box->set_custom_minimum_size(Size2(300, 0)); + search_bar->add_child(search_box); + + search_bar->add_spacer(); + + advanced = memnew(CheckButton); + advanced->set_text(TTR("Advanced")); + advanced->connect("pressed", callable_mp(this, &ProjectSettingsEditor::_advanced_pressed)); + search_bar->add_child(advanced); } - Button *add = memnew(Button); - add->set_text(TTR("Add")); - add->connect("pressed", callable_mp(this, &ProjectSettingsEditor::_item_add)); - add_prop_bar->add_child(add); + { + // Advanced bar. + advanced_bar = memnew(VBoxContainer); + advanced_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL); + advanced_bar->hide(); + header->add_child(advanced_bar); + + HBoxContainer *hbc = memnew(HBoxContainer); + hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL); + advanced_bar->add_margin_child(TTR("Add or remove custom project settings."), hbc, true); + + category_box = memnew(LineEdit); + category_box->set_custom_minimum_size(Size2(140, 0) * EDSCALE); + category_box->connect("text_changed", callable_mp(this, &ProjectSettingsEditor::_text_field_changed)); + category_box->set_placeholder(TTR("Category")); + hbc->add_child(category_box); + + Label *l = memnew(Label); + l->set_text("/"); + hbc->add_child(l); + + property_box = memnew(LineEdit); + property_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); + property_box->set_placeholder(TTR("Property")); + property_box->connect("text_changed", callable_mp(this, &ProjectSettingsEditor::_text_field_changed)); + hbc->add_child(property_box); + + l = memnew(Label); + l->set_text(TTR("Type:")); + hbc->add_child(l); + + type = memnew(OptionButton); + type->set_custom_minimum_size(Size2(70, 0) * EDSCALE); + hbc->add_child(type); + + // Start at 1 to avoid adding "Nil" as an option + for (int i = 1; i < Variant::VARIANT_MAX; i++) { + type->add_item(Variant::get_type_name(Variant::Type(i))); + } - search_bar = memnew(HBoxContainer); - search_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL); - search_bar->hide(); - hbc->add_child(search_bar); + l = memnew(Label); + l->set_text(TTR("Feature Override:")); + hbc->add_child(l); - search_box = memnew(LineEdit); - search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); - search_bar->add_child(search_box); + feature_override = memnew(OptionButton); + feature_override->set_custom_minimum_size(Size2(70, 0) * EDSCALE); + feature_override->connect("item_selected", callable_mp(this, &ProjectSettingsEditor::_feature_selected)); + hbc->add_child(feature_override); - globals_editor = memnew(SectionedInspector); - globals_editor->get_inspector()->set_undo_redo(EditorNode::get_singleton()->get_undo_redo()); - globals_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); - globals_editor->register_search_box(search_box); - globals_editor->get_inspector()->connect("property_selected", callable_mp(this, &ProjectSettingsEditor::_item_selected)); - globals_editor->get_inspector()->connect("property_edited", callable_mp(this, &ProjectSettingsEditor::_settings_prop_edited)); - globals_editor->get_inspector()->connect("restart_requested", callable_mp(this, &ProjectSettingsEditor::_editor_restart_request)); - props_base->add_child(globals_editor); + hbc->add_spacer(); - Button *del = memnew(Button); - del->set_text(TTR("Delete")); - del->connect("pressed", callable_mp(this, &ProjectSettingsEditor::_item_del)); - hbc->add_child(del); + add_button = memnew(Button); + add_button->connect("pressed", callable_mp(this, &ProjectSettingsEditor::_add_setting)); + hbc->add_child(add_button); - add_prop_bar->add_child(memnew(VSeparator)); + del_button = memnew(Button); + del_button->connect("pressed", callable_mp(this, &ProjectSettingsEditor::_delete_setting)); + hbc->add_child(del_button); - popup_copy_to_feature = memnew(MenuButton); - popup_copy_to_feature->set_text(TTR("Override For...")); - popup_copy_to_feature->set_disabled(true); - add_prop_bar->add_child(popup_copy_to_feature); + error_label = memnew(Label); + advanced_bar->add_child(error_label); + } - popup_copy_to_feature->get_popup()->connect("id_pressed", callable_mp(this, &ProjectSettingsEditor::_copy_to_platform)); - popup_copy_to_feature->get_popup()->connect("about_to_popup", callable_mp(this, &ProjectSettingsEditor::_copy_to_platform_about_to_show)); + header->add_child(memnew(HSeparator)); - get_ok()->set_text(TTR("Close")); - set_hide_on_ok(true); + inspector = memnew(SectionedInspector); + inspector->get_inspector()->set_undo_redo(EditorNode::get_singleton()->get_undo_redo()); + inspector->set_v_size_flags(Control::SIZE_EXPAND_FILL); + inspector->register_search_box(search_box); + inspector->get_inspector()->connect("property_selected", callable_mp(this, &ProjectSettingsEditor::_setting_selected)); + inspector->get_inspector()->connect("property_edited", callable_mp(this, &ProjectSettingsEditor::_setting_edited)); + inspector->get_inspector()->connect("restart_requested", callable_mp(this, &ProjectSettingsEditor::_editor_restart_request)); + general_editor->add_child(inspector); restart_container = memnew(PanelContainer); - props_base->add_child(restart_container); + general_editor->add_child(restart_container); HBoxContainer *restart_hb = memnew(HBoxContainer); restart_container->hide(); @@ -475,27 +438,24 @@ ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) { restart_close_button->connect("pressed", callable_mp(this, &ProjectSettingsEditor::_editor_restart_close)); restart_hb->add_child(restart_close_button); - message = memnew(AcceptDialog); - add_child(message); - inputmap_editor = memnew(InputMapEditor); inputmap_editor->set_name(TTR("Input Map")); - inputmap_editor->connect("inputmap_changed", callable_mp(this, &ProjectSettingsEditor::_settings_changed)); + inputmap_editor->connect("inputmap_changed", callable_mp(this, &ProjectSettingsEditor::queue_save)); tab_container->add_child(inputmap_editor); localization_editor = memnew(LocalizationEditor); localization_editor->set_name(TTR("Localization")); - localization_editor->connect("localization_changed", callable_mp(this, &ProjectSettingsEditor::_settings_changed)); + localization_editor->connect("localization_changed", callable_mp(this, &ProjectSettingsEditor::queue_save)); tab_container->add_child(localization_editor); autoload_settings = memnew(EditorAutoloadSettings); autoload_settings->set_name(TTR("AutoLoad")); - autoload_settings->connect("autoload_changed", callable_mp(this, &ProjectSettingsEditor::_settings_changed)); + autoload_settings->connect("autoload_changed", callable_mp(this, &ProjectSettingsEditor::queue_save)); tab_container->add_child(autoload_settings); shaders_global_variables_editor = memnew(ShaderGlobalsEditor); shaders_global_variables_editor->set_name(TTR("Shader Globals")); - shaders_global_variables_editor->connect("globals_changed", callable_mp(this, &ProjectSettingsEditor::_settings_changed)); + shaders_global_variables_editor->connect("globals_changed", callable_mp(this, &ProjectSettingsEditor::queue_save)); tab_container->add_child(shaders_global_variables_editor); plugin_settings = memnew(EditorPluginSettings); @@ -504,7 +464,10 @@ ProjectSettingsEditor::ProjectSettingsEditor(EditorData *p_data) { timer = memnew(Timer); timer->set_wait_time(1.5); - timer->connect("timeout", callable_mp(ProjectSettings::get_singleton(), &ProjectSettings::save)); + timer->connect("timeout", callable_mp(ps, &ProjectSettings::save)); timer->set_one_shot(true); add_child(timer); + + get_ok()->set_text(TTR("Close")); + set_hide_on_ok(true); } diff --git a/editor/project_settings_editor.h b/editor/project_settings_editor.h index c99c2fe9a2..0d7e19b242 100644 --- a/editor/project_settings_editor.h +++ b/editor/project_settings_editor.h @@ -35,12 +35,11 @@ #include "editor/editor_data.h" #include "editor/editor_plugin_settings.h" #include "editor/editor_sectioned_inspector.h" +#include "editor/input_map_editor.h" +#include "editor/localization_editor.h" +#include "editor/shader_globals_editor.h" #include "editor_autoload_settings.h" -#include "input_map_editor.h" -#include "localization_editor.h" -#include "scene/gui/dialogs.h" #include "scene/gui/tab_container.h" -#include "shader_globals_editor.h" class ProjectSettingsEditor : public AcceptDialog { GDCLASS(ProjectSettingsEditor, AcceptDialog); @@ -53,28 +52,31 @@ class ProjectSettingsEditor : public AcceptDialog { INPUT_MOUSE_BUTTON }; - TabContainer *tab_container; - AcceptDialog *message; + static ProjectSettingsEditor *singleton; + ProjectSettings *ps; Timer *timer; - HBoxContainer *search_bar; - Button *search_button; - LineEdit *search_box; - HBoxContainer *add_prop_bar; - LineEdit *category; - LineEdit *property; - OptionButton *type; - - SectionedInspector *globals_editor; - - MenuButton *popup_copy_to_feature; - + TabContainer *tab_container; + SectionedInspector *inspector; InputMapEditor *inputmap_editor; LocalizationEditor *localization_editor; EditorAutoloadSettings *autoload_settings; ShaderGlobalsEditor *shaders_global_variables_editor; EditorPluginSettings *plugin_settings; + HBoxContainer *search_bar; + LineEdit *search_box; + CheckButton *advanced; + + VBoxContainer *advanced_bar; + LineEdit *category_box; + LineEdit *property_box; + Button *add_button; + Button *del_button; + OptionButton *type; + OptionButton *feature_override; + Label *error_label; + Label *restart_label; TextureRect *restart_icon; PanelContainer *restart_container; @@ -83,30 +85,25 @@ class ProjectSettingsEditor : public AcceptDialog { EditorData *data; UndoRedo *undo_redo; - void _item_selected(const String &); - void _item_adds(String); - void _item_add(); - void _item_del(); - void _save(); - - void _settings_prop_edited(const String &p_name); - void _settings_changed(); + void _advanced_pressed(); + void _update_advanced_bar(); + void _text_field_changed(const String &p_text); + void _feature_selected(int p_index); - void _copy_to_platform(int p_which); - void _copy_to_platform_about_to_show(); - - void _toggle_search_bar(bool p_pressed); - - ProjectSettingsEditor(); - - static ProjectSettingsEditor *singleton; + String _get_setting_name() const; + void _setting_edited(const String &p_name); + void _setting_selected(const String &p_path); + void _add_setting(); + void _delete_setting(); void _editor_restart_request(); void _editor_restart(); void _editor_restart_close(); + void _add_feature_overrides(); + ProjectSettingsEditor(); + protected: - void _unhandled_input(const Ref<InputEvent> &p_event); void _notification(int p_what); static void _bind_methods(); @@ -117,8 +114,7 @@ public: void update_plugins(); EditorAutoloadSettings *get_autoload_settings() { return autoload_settings; } - - TabContainer *get_tabs(); + TabContainer *get_tabs() { return tab_container; } void queue_save(); diff --git a/main/main.cpp b/main/main.cpp index 9978be7ab7..c5500a1f66 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -262,25 +262,20 @@ void Main::print_help(const char *p_binary) { OS::get_singleton()->print(" -h, --help Display this help message.\n"); OS::get_singleton()->print(" --version Display the version string.\n"); OS::get_singleton()->print(" -v, --verbose Use verbose stdout mode.\n"); - OS::get_singleton()->print( - " --quiet Quiet mode, silences stdout messages. Errors are still displayed.\n"); + OS::get_singleton()->print(" --quiet Quiet mode, silences stdout messages. Errors are still displayed.\n"); OS::get_singleton()->print("\n"); OS::get_singleton()->print("Run options:\n"); #ifdef TOOLS_ENABLED OS::get_singleton()->print(" -e, --editor Start the editor instead of running the scene.\n"); - OS::get_singleton()->print( - " -p, --project-manager Start the project manager, even if a project is auto-detected.\n"); + OS::get_singleton()->print(" -p, --project-manager Start the project manager, even if a project is auto-detected.\n"); #endif OS::get_singleton()->print(" -q, --quit Quit after the first iteration.\n"); - OS::get_singleton()->print( - " -l, --language <locale> Use a specific locale (<locale> being a two-letter code).\n"); - OS::get_singleton()->print( - " --path <directory> Path to a project (<directory> must contain a 'project.godot' file).\n"); + OS::get_singleton()->print(" -l, --language <locale> Use a specific locale (<locale> being a two-letter code).\n"); + OS::get_singleton()->print(" --path <directory> Path to a project (<directory> must contain a 'project.godot' file).\n"); OS::get_singleton()->print(" -u, --upwards Scan folders upwards for project.godot file.\n"); OS::get_singleton()->print(" --main-pack <file> Path to a pack (.pck) file to load.\n"); - OS::get_singleton()->print( - " --render-thread <mode> Render thread mode ('unsafe', 'safe', 'separate').\n"); + OS::get_singleton()->print(" --render-thread <mode> Render thread mode ('unsafe', 'safe', 'separate').\n"); OS::get_singleton()->print(" --remote-fs <address> Remote filesystem (<host/IP>[:<port>] address).\n"); OS::get_singleton()->print(" --remote-fs-password <password> Password for remote filesystem.\n"); @@ -321,12 +316,9 @@ void Main::print_help(const char *p_binary) { OS::get_singleton()->print(" --resolution <W>x<H> Request window resolution.\n"); OS::get_singleton()->print(" --position <X>,<Y> Request window position.\n"); OS::get_singleton()->print(" --low-dpi Force low-DPI mode (macOS and Windows only).\n"); - OS::get_singleton()->print( - " --no-window Disable window creation (Windows only). Useful together with --script.\n"); - OS::get_singleton()->print( - " --enable-vsync-via-compositor When vsync is enabled, vsync via the OS' window compositor (Windows only).\n"); - OS::get_singleton()->print( - " --disable-vsync-via-compositor Disable vsync via the OS' window compositor (Windows only).\n"); + OS::get_singleton()->print(" --no-window Disable window creation (Windows only). Useful together with --script.\n"); + OS::get_singleton()->print(" --enable-vsync-via-compositor When vsync is enabled, vsync via the OS' window compositor (Windows only).\n"); + OS::get_singleton()->print(" --disable-vsync-via-compositor Disable vsync via the OS' window compositor (Windows only).\n"); OS::get_singleton()->print(" --single-window Use a single window (no separate subwindows).\n"); OS::get_singleton()->print(" --tablet-driver Tablet input driver ("); for (int i = 0; i < OS::get_singleton()->get_tablet_driver_count(); i++) { @@ -340,62 +332,38 @@ void Main::print_help(const char *p_binary) { OS::get_singleton()->print("Debug options:\n"); OS::get_singleton()->print(" -d, --debug Debug (local stdout debugger).\n"); - OS::get_singleton()->print( - " -b, --breakpoints Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n"); + OS::get_singleton()->print(" -b, --breakpoints Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n"); OS::get_singleton()->print(" --profiling Enable profiling in the script debugger.\n"); - OS::get_singleton()->print( - " --gpu-abort Abort on GPU errors (usually validation layer errors), may help see the problem if your system freezes.\n"); - OS::get_singleton()->print( - " --remote-debug <uri> Remote debug (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007).\n"); + OS::get_singleton()->print(" --gpu-abort Abort on GPU errors (usually validation layer errors), may help see the problem if your system freezes.\n"); + OS::get_singleton()->print(" --remote-debug <uri> Remote debug (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007).\n"); #if defined(DEBUG_ENABLED) && !defined(SERVER_ENABLED) OS::get_singleton()->print(" --debug-collisions Show collision shapes when running the scene.\n"); OS::get_singleton()->print(" --debug-navigation Show navigation polygons when running the scene.\n"); #endif - OS::get_singleton()->print( - " --frame-delay <ms> Simulate high CPU load (delay each frame by <ms> milliseconds).\n"); - OS::get_singleton()->print( - " --time-scale <scale> Force time scale (higher values are faster, 1.0 is normal speed).\n"); - OS::get_singleton()->print( - " --disable-render-loop Disable render loop so rendering only occurs when called explicitly from script.\n"); - OS::get_singleton()->print( - " --disable-crash-handler Disable crash handler when supported by the platform code.\n"); - OS::get_singleton()->print( - " --fixed-fps <fps> Force a fixed number of frames per second. This setting disables real-time synchronization.\n"); + OS::get_singleton()->print(" --frame-delay <ms> Simulate high CPU load (delay each frame by <ms> milliseconds).\n"); + OS::get_singleton()->print(" --time-scale <scale> Force time scale (higher values are faster, 1.0 is normal speed).\n"); + OS::get_singleton()->print(" --disable-render-loop Disable render loop so rendering only occurs when called explicitly from script.\n"); + OS::get_singleton()->print(" --disable-crash-handler Disable crash handler when supported by the platform code.\n"); + OS::get_singleton()->print(" --fixed-fps <fps> Force a fixed number of frames per second. This setting disables real-time synchronization.\n"); OS::get_singleton()->print(" --print-fps Print the frames per second to the stdout.\n"); OS::get_singleton()->print("\n"); OS::get_singleton()->print("Standalone tools:\n"); OS::get_singleton()->print(" -s, --script <script> Run a script.\n"); - OS::get_singleton()->print( - " --check-only Only parse for errors and quit (use with --script).\n"); + OS::get_singleton()->print(" --check-only Only parse for errors and quit (use with --script).\n"); #ifdef TOOLS_ENABLED - OS::get_singleton()->print( - " --export <preset> <path> Export the project using the given preset and matching release template. The preset name should match one defined in export_presets.cfg.\n"); - OS::get_singleton()->print( - " <path> should be absolute or relative to the project directory, and include the filename for the binary (e.g. 'builds/game.exe'). The target directory should exist.\n"); + OS::get_singleton()->print(" --export <preset> <path> Export the project using the given preset and matching release template. The preset name should match one defined in export_presets.cfg.\n"); + OS::get_singleton()->print(" <path> should be absolute or relative to the project directory, and include the filename for the binary (e.g. 'builds/game.exe'). The target directory should exist.\n"); OS::get_singleton()->print(" --export-debug <preset> <path> Same as --export, but using the debug template.\n"); - OS::get_singleton()->print( - " --export-pack <preset> <path> Same as --export, but only export the game pack for the given preset. The <path> extension determines whether it will be in PCK or ZIP format.\n"); - OS::get_singleton()->print( - " --doctool <path> Dump the engine API reference to the given <path> in XML format, merging if existing files are found.\n"); - OS::get_singleton()->print( - " --no-docbase Disallow dumping the base types (used with --doctool).\n"); - OS::get_singleton()->print( - " --build-solutions Build the scripting solutions (e.g. for C# projects). Implies --editor and requires a valid project to edit.\n"); + OS::get_singleton()->print(" --export-pack <preset> <path> Same as --export, but only export the game pack for the given preset. The <path> extension determines whether it will be in PCK or ZIP format.\n"); + OS::get_singleton()->print(" --doctool <path> Dump the engine API reference to the given <path> in XML format, merging if existing files are found.\n"); + OS::get_singleton()->print(" --no-docbase Disallow dumping the base types (used with --doctool).\n"); + OS::get_singleton()->print(" --build-solutions Build the scripting solutions (e.g. for C# projects). Implies --editor and requires a valid project to edit.\n"); #ifdef DEBUG_METHODS_ENABLED - OS::get_singleton()->print( - " --gdnative-generate-json-api Generate JSON dump of the Godot API for GDNative bindings.\n"); + OS::get_singleton()->print(" --gdnative-generate-json-api Generate JSON dump of the Godot API for GDNative bindings.\n"); #endif #ifdef TESTS_ENABLED - OS::get_singleton()->print(" --test <test> Run a unit test ["); - const char **test_names = tests_get_names(); - const char *comma = ""; - while (*test_names) { - OS::get_singleton()->print("%s'%s'", comma, *test_names); - test_names++; - comma = ", "; - } - OS::get_singleton()->print("].\n"); + OS::get_singleton()->print(" --test [--help] Run unit tests. Use --test --help for more information.\n"); #endif OS::get_singleton()->print("\n"); #endif @@ -404,7 +372,7 @@ void Main::print_help(const char *p_binary) { int Main::test_entrypoint(int argc, char *argv[], bool &tests_need_run) { #ifdef TESTS_ENABLED for (int x = 0; x < argc; x++) { - if (strncmp(argv[x], "--test", 6) == 0) { + if ((strncmp(argv[x], "--test", 6) == 0) && (strlen(argv[x]) == 6)) { tests_need_run = true; OS::get_singleton()->initialize(); StringName::setup(); diff --git a/misc/dist/linux/x-godot-project.xml b/misc/dist/linux/x-godot-project.xml index 0572e4e54e..9f28bab2ae 100644 --- a/misc/dist/linux/x-godot-project.xml +++ b/misc/dist/linux/x-godot-project.xml @@ -1,8 +1,8 @@ <?xml version="1.0"?> - <mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="application/x-godot-project"> - <comment>Godot Engine project</comment> - <icon name="godot" /> - <glob pattern="*.godot" weight="100" /> +<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info"> + <mime-type type="application/x-godot-project"> + <comment>Godot Engine project</comment> + <icon name="godot" /> + <glob pattern="*.godot" weight="100" /> </mime-type> </mime-info> diff --git a/modules/bullet/rigid_body_bullet.cpp b/modules/bullet/rigid_body_bullet.cpp index 5c1144b875..32c3240a35 100644 --- a/modules/bullet/rigid_body_bullet.cpp +++ b/modules/bullet/rigid_body_bullet.cpp @@ -897,8 +897,7 @@ void RigidBodyBullet::on_exit_area(AreaBullet *p_area) { } void RigidBodyBullet::reload_space_override_modificator() { - // Make sure that kinematic bodies have their total gravity calculated - if (!is_active() && PhysicsServer3D::BODY_MODE_KINEMATIC != mode) { + if (mode == PhysicsServer3D::BODY_MODE_STATIC) { return; } diff --git a/modules/bullet/space_bullet.cpp b/modules/bullet/space_bullet.cpp index 2b60f8df36..d0515e7c97 100644 --- a/modules/bullet/space_bullet.cpp +++ b/modules/bullet/space_bullet.cpp @@ -177,6 +177,7 @@ bool BulletPhysicsDirectSpaceState::cast_motion(const RID &p_shape, const Transf bt_xform_to.getOrigin() += bt_motion; if ((bt_xform_to.getOrigin() - bt_xform_from.getOrigin()).fuzzyZero()) { + shape->destroy_bt_shape(btShape); return false; } diff --git a/modules/csg/csg_shape.cpp b/modules/csg/csg_shape.cpp index 6d99392485..8f2ebc7232 100644 --- a/modules/csg/csg_shape.cpp +++ b/modules/csg/csg_shape.cpp @@ -132,18 +132,13 @@ void CSGShape3D::_make_dirty() { return; } - if (dirty) { - return; - } - - dirty = true; - if (parent) { parent->_make_dirty(); - } else { - //only parent will do + } else if (!dirty) { call_deferred("_update_shape"); } + + dirty = true; } CSGBrush *CSGShape3D::_get_brush() { @@ -652,7 +647,7 @@ CSGShape3D::~CSGShape3D() { ////////////////////////////////// CSGBrush *CSGCombiner3D::_build_brush() { - return nullptr; //does not build anything + return memnew(CSGBrush); //does not build anything } CSGCombiner3D::CSGCombiner3D() { diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp index ed3924f2d2..64977ad237 100644 --- a/modules/enet/networked_multiplayer_enet.cpp +++ b/modules/enet/networked_multiplayer_enet.cpp @@ -104,6 +104,7 @@ Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int if (dtls_enabled) { enet_host_dtls_server_setup(host, dtls_key.ptr(), dtls_cert.ptr()); } + enet_host_refuse_new_connections(host, refuse_connections); #endif _setup_compressor(); @@ -160,6 +161,7 @@ Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_por if (dtls_enabled) { enet_host_dtls_client_setup(host, dtls_cert.ptr(), dtls_verify, p_address.utf8().get_data()); } + enet_host_refuse_new_connections(host, refuse_connections); #endif _setup_compressor(); @@ -641,7 +643,9 @@ int NetworkedMultiplayerENet::get_unique_id() const { void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) { refuse_connections = p_enable; #ifdef GODOT_ENET - enet_host_refuse_new_connections(host, p_enable); + if (active) { + enet_host_refuse_new_connections(host, p_enable); + } #endif } diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml index c86b974f47..9e40a69712 100644 --- a/modules/gdscript/doc_classes/@GDScript.xml +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -112,7 +112,7 @@ </argument> <description> Returns the arc tangent of [code]s[/code] in radians. Use it to get the angle from an angle's tangent in trigonometry: [code]atan(tan(angle)) == angle[/code]. - The method cannot know in which quadrant the angle should fall. See [method atan2] if you have both [code]y[code] and [code]x[/code]. + The method cannot know in which quadrant the angle should fall. See [method atan2] if you have both [code]y[/code] and [code]x[/code]. [codeblock] a = atan(0.5) # a is 0.463648 [/codeblock] @@ -735,16 +735,17 @@ <argument index="0" name="json" type="String"> </argument> <description> - Parse JSON text to a Variant (use [method typeof] to check if it is what you expect). - Be aware that the JSON specification does not define integer or float types, but only a number type. Therefore, parsing a JSON text will convert all numerical values to [float] types. - Note that JSON objects do not preserve key order like Godot dictionaries, thus you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements: + Parse JSON text to a Variant. (Use [method typeof] to check if the Variant's type is what you expect.) + [b]Note:[/b] The JSON specification does not define integer or float types, but only a [i]number[/i] type. Therefore, parsing a JSON text will convert all numerical values to [float] types. + [b]Note:[/b] JSON objects do not preserve key order like Godot dictionaries, thus, you should not rely on keys being in a certain order if a dictionary is constructed from JSON. In contrast, JSON arrays retain the order of their elements: [codeblock] - p = parse_json('["a", "b", "c"]') - if typeof(p) == TYPE_ARRAY: - print(p[0]) # Prints a + var p = JSON.parse('["hello", "world", "!"]') + if typeof(p.result) == TYPE_ARRAY: + print(p.result[0]) # Prints "hello" else: - print("unexpected results") + push_error("Unexpected results.") [/codeblock] + See also [JSON] for an alternative way to parse JSON text. </description> </method> <method name="polar2cartesian"> @@ -1220,12 +1221,16 @@ <argument index="0" name="var" type="Variant"> </argument> <description> - Converts a Variant [code]var[/code] to JSON text and return the result. Useful for serializing data to store or send over the network. + Converts a [Variant] [code]var[/code] to JSON text and return the result. Useful for serializing data to store or send over the network. [codeblock] + # Both numbers below are integers. a = { "a": 1, "b": 2 } b = to_json(a) print(b) # {"a":1, "b":2} + # Both numbers above are floats, even if they display without any decimal places. [/codeblock] + [b]Note:[/b] The JSON specification does not define integer or float types, but only a [i]number[/i] type. Therefore, converting a [Variant] to JSON text will convert all numerical values to [float] types. + See also [JSON] for an alternative way to convert a [Variant] to JSON text. </description> </method> <method name="type_exists"> @@ -1268,9 +1273,9 @@ j = to_json([1, 2, 3]) v = validate_json(j) if not v: - print("valid") + print("Valid JSON.") else: - prints("invalid", v) + push_error("Invalid JSON: " + v) [/codeblock] </description> </method> diff --git a/modules/gdscript/editor/gdscript_highlighter.cpp b/modules/gdscript/editor/gdscript_highlighter.cpp index aba3e07134..ae1f2893f1 100644 --- a/modules/gdscript/editor/gdscript_highlighter.cpp +++ b/modules/gdscript/editor/gdscript_highlighter.cpp @@ -82,6 +82,10 @@ Dictionary GDScriptSyntaxHighlighter::_get_line_syntax_highlighting(int p_line) const String &str = text_edit->get_line(p_line); const int line_length = str.length(); Color prev_color; + + if (in_region != -1 && str.length() == 0) { + color_region_cache[p_line] = in_region; + } for (int j = 0; j < str.length(); j++) { Dictionary highlighter_info; diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 4098425518..1e72216ad2 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -71,6 +71,10 @@ static StringName get_real_class_name(const StringName &p_source) { return p_source; } +void GDScriptAnalyzer::cleanup() { + underscore_map.clear(); +} + static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) { GDScriptParser::DataType type; type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; @@ -494,7 +498,7 @@ void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_clas if (member.variable->initializer != nullptr) { if (!is_type_compatible(datatype, member.variable->initializer->get_datatype(), true)) { - push_error(vformat(R"(Value of type "%s" cannot be assigned to variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer); + push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer); } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) { #ifdef DEBUG_ENABLED parser->push_warning(member.variable->initializer, GDScriptWarning::NARROWING_CONVERSION); @@ -989,7 +993,7 @@ void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable if (p_variable->initializer != nullptr) { if (!is_type_compatible(type, p_variable->initializer->get_datatype(), true)) { - push_error(vformat(R"(Value of type "%s" cannot be assigned to variable of type "%s".)", p_variable->initializer->get_datatype().to_string(), type.to_string()), p_variable->initializer); + push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", p_variable->initializer->get_datatype().to_string(), type.to_string()), p_variable->initializer); #ifdef DEBUG_ENABLED } else if (type.builtin_type == Variant::INT && p_variable->initializer->get_datatype().builtin_type == Variant::FLOAT) { parser->push_warning(p_variable->initializer, GDScriptWarning::NARROWING_CONVERSION); @@ -1369,11 +1373,61 @@ void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assig push_error("Cannot assign a new value to a constant.", p_assignment->assignee); } - if (!is_type_compatible(p_assignment->assignee->get_datatype(), p_assignment->assigned_value->get_datatype(), true)) { - if (p_assignment->assignee->get_datatype().is_hard_type()) { - push_error(vformat(R"(Cannot assign a value of type "%s" to a target of type "%s".)", p_assignment->assigned_value->get_datatype().to_string(), p_assignment->assignee->get_datatype().to_string()), p_assignment->assigned_value); + Variant::Operator vop = Variant::Operator::OP_EQUAL; + switch (p_assignment->operation) { + case GDScriptParser::AssignmentNode::OP_NONE: + vop = Variant::Operator::OP_EQUAL; + break; + case GDScriptParser::AssignmentNode::OP_ADDITION: + vop = Variant::Operator::OP_ADD; + break; + case GDScriptParser::AssignmentNode::OP_SUBTRACTION: + vop = Variant::Operator::OP_SUBTRACT; + break; + case GDScriptParser::AssignmentNode::OP_MULTIPLICATION: + vop = Variant::Operator::OP_MULTIPLY; + break; + case GDScriptParser::AssignmentNode::OP_DIVISION: + vop = Variant::Operator::OP_DIVIDE; + break; + case GDScriptParser::AssignmentNode::OP_MODULO: + vop = Variant::Operator::OP_MODULE; + break; + case GDScriptParser::AssignmentNode::OP_BIT_SHIFT_LEFT: + vop = Variant::Operator::OP_SHIFT_LEFT; + break; + case GDScriptParser::AssignmentNode::OP_BIT_SHIFT_RIGHT: + vop = Variant::Operator::OP_SHIFT_RIGHT; + break; + case GDScriptParser::AssignmentNode::OP_BIT_AND: + vop = Variant::Operator::OP_BIT_AND; + break; + case GDScriptParser::AssignmentNode::OP_BIT_OR: + vop = Variant::Operator::OP_BIT_OR; + break; + case GDScriptParser::AssignmentNode::OP_BIT_XOR: + vop = Variant::Operator::OP_BIT_XOR; + break; + } + + if (!p_assignment->assignee->get_datatype().is_variant() && !p_assignment->assigned_value->get_datatype().is_variant()) { + bool compatible = true; + GDScriptParser::DataType op_type = p_assignment->assigned_value->get_datatype(); + if (vop != Variant::OP_EQUAL) { + op_type = get_operation_type(vop, p_assignment->assignee->get_datatype(), p_assignment->assigned_value->get_datatype(), compatible); + } + + if (compatible) { + compatible = is_type_compatible(p_assignment->assignee->get_datatype(), op_type, true); + if (!compatible) { + if (p_assignment->assignee->get_datatype().is_hard_type()) { + push_error(vformat(R"(Cannot assign a value of type "%s" to a target of type "%s".)", p_assignment->assigned_value->get_datatype().to_string(), p_assignment->assignee->get_datatype().to_string()), p_assignment->assigned_value); + } else { + // TODO: Warning in this case. + } + } } else { - // TODO: Warning in this case. + push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", p_assignment->assignee->get_datatype().to_string(), p_assignment->assigned_value->get_datatype().to_string()), p_assignment); } } @@ -1488,7 +1542,19 @@ void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_o if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) { p_binary_op->is_constant = true; if (p_binary_op->variant_op < Variant::OP_MAX) { - p_binary_op->reduced_value = Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value); + bool valid = false; + Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value, p_binary_op->reduced_value, valid); + if (!valid) { + if (p_binary_op->reduced_value.get_type() == Variant::STRING) { + push_error(vformat(R"(%s in operator %s.)", p_binary_op->reduced_value, Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op); + } else { + push_error(vformat(R"(Invalid operands to operator %s, %s and %s.".)", + Variant::get_operator_name(p_binary_op->variant_op), + Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()), + Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())), + p_binary_op); + } + } } else { if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) { GDScriptParser::DataType test_type = right_type; @@ -2019,7 +2085,7 @@ void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNod GDScriptParser::ClassNode *outer = base_class->outer; while (outer != nullptr) { if (outer->has_member(name)) { - const GDScriptParser::ClassNode::Member &member = base_class->get_member(name); + const GDScriptParser::ClassNode::Member &member = outer->get_member(name); if (member.type == GDScriptParser::ClassNode::Member::CONSTANT) { // TODO: Make sure loops won't cause problem. And make special error message for those. // For out-of-order resolution: diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index 85183d3272..06d3530cb6 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -113,6 +113,8 @@ public: Error analyze(); GDScriptAnalyzer(GDScriptParser *p_parser); + + static void cleanup(); }; #endif // GDSCRIPT_ANALYZER_H diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index af07457750..1f3e1c1e40 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -94,6 +94,10 @@ Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) { return Variant::VARIANT_MAX; } +void GDScriptParser::cleanup() { + builtin_types.clear(); +} + GDScriptFunctions::Function GDScriptParser::get_builtin_function(const StringName &p_name) { for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) { if (p_name == GDScriptFunctions::get_func_name(GDScriptFunctions::Function(i))) { diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index a741ae0cc7..c9ab3d4e12 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -1335,6 +1335,7 @@ public: void print_tree(const GDScriptParser &p_parser); }; #endif // DEBUG_ENABLED + static void cleanup(); }; #endif // GDSCRIPT_PARSER_H diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp index 5c1d2f6f1b..c554cbac05 100644 --- a/modules/gdscript/register_types.cpp +++ b/modules/gdscript/register_types.cpp @@ -35,6 +35,7 @@ #include "core/os/dir_access.h" #include "core/os/file_access.h" #include "gdscript.h" +#include "gdscript_analyzer.h" #include "gdscript_cache.h" #include "gdscript_tokenizer.h" @@ -57,6 +58,8 @@ GDScriptCache *gdscript_cache = nullptr; #include "language_server/gdscript_language_server.h" #endif // !GDSCRIPT_NO_LSP +Ref<GDScriptEditorTranslationParserPlugin> gdscript_translation_parser_plugin; + class EditorExportGDScript : public EditorExportPlugin { GDCLASS(EditorExportGDScript, EditorExportPlugin); @@ -120,7 +123,6 @@ void register_gdscript_types() { #ifdef TOOLS_ENABLED EditorNode::add_init_callback(_editor_init); - Ref<GDScriptEditorTranslationParserPlugin> gdscript_translation_parser_plugin; gdscript_translation_parser_plugin.instance(); EditorTranslationParser::get_singleton()->add_parser(gdscript_translation_parser_plugin, EditorTranslationParser::STANDARD); #endif // TOOLS_ENABLED @@ -142,4 +144,12 @@ void unregister_gdscript_types() { ResourceSaver::remove_resource_format_saver(resource_saver_gd); resource_saver_gd.unref(); + +#ifdef TOOLS_ENABLED + EditorTranslationParser::get_singleton()->remove_parser(gdscript_translation_parser_plugin, EditorTranslationParser::STANDARD); + gdscript_translation_parser_plugin.unref(); +#endif // TOOLS_ENABLED + + GDScriptParser::cleanup(); + GDScriptAnalyzer::cleanup(); } diff --git a/modules/regex/doc_classes/RegEx.xml b/modules/regex/doc_classes/RegEx.xml index c00fa96b2e..312275842a 100644 --- a/modules/regex/doc_classes/RegEx.xml +++ b/modules/regex/doc_classes/RegEx.xml @@ -11,7 +11,7 @@ regex.compile("\\w-(\\d+)") [/codeblock] The search pattern must be escaped first for GDScript before it is escaped for the expression. For example, [code]compile("\\d+")[/code] would be read by RegEx as [code]\d+[/code]. Similarly, [code]compile("\"(?:\\\\.|[^\"])*\"")[/code] would be read as [code]"(?:\\.|[^"])*"[/code]. - Using [method search] you can find the pattern within the given text. If a pattern is found, [RegExMatch] is returned and you can retrieve details of the results using functions such as [method RegExMatch.get_string] and [method RegExMatch.get_start]. + Using [method search], you can find the pattern within the given text. If a pattern is found, [RegExMatch] is returned and you can retrieve details of the results using methods such as [method RegExMatch.get_string] and [method RegExMatch.get_start]. [codeblock] var regex = RegEx.new() regex.compile("\\w-(\\d+)") @@ -19,7 +19,7 @@ if result: print(result.get_string()) # Would print n-0123 [/codeblock] - The results of capturing groups [code]()[/code] can be retrieved by passing the group number to the various functions in [RegExMatch]. Group 0 is the default and will always refer to the entire pattern. In the above example, calling [code]result.get_string(1)[/code] would give you [code]0123[/code]. + The results of capturing groups [code]()[/code] can be retrieved by passing the group number to the various methods in [RegExMatch]. Group 0 is the default and will always refer to the entire pattern. In the above example, calling [code]result.get_string(1)[/code] would give you [code]0123[/code]. This version of RegEx also supports named capturing groups, and the names can be used to retrieve the results. If two or more groups have the same name, the name would only refer to the first one with a match. [codeblock] var regex = RegEx.new() @@ -34,6 +34,15 @@ print(result.get_string("digit")) # Would print 01 03 0 3f 42 [/codeblock] + [b]Example of splitting a string using a RegEx:[/b] + [codeblock] + var regex = RegEx.new() + regex.compile("\\S+") # Negated whitespace character class. + var results = [] + for match in regex.search_all("One Two \n\tThree"): + results.push_back(match.get_string()) + # The `results` array now contains "One", "Two", "Three". + [/codeblock] [b]Note:[/b] Godot's regex implementation is based on the [url=https://www.pcre.org/]PCRE2[/url] library. You can view the full pattern reference [url=https://www.pcre.org/current/doc/html/pcre2pattern.html]here[/url]. [b]Tip:[/b] You can use [url=https://regexr.com/]Regexr[/url] to test regular expressions online. </description> diff --git a/platform/iphone/display_server_iphone.mm b/platform/iphone/display_server_iphone.mm index aafee49594..1721da3db6 100644 --- a/platform/iphone/display_server_iphone.mm +++ b/platform/iphone/display_server_iphone.mm @@ -492,7 +492,22 @@ Size2i DisplayServerIPhone::screen_get_size(int p_screen) const { } Rect2i DisplayServerIPhone::screen_get_usable_rect(int p_screen) const { - return Rect2i(screen_get_position(p_screen), screen_get_size(p_screen)); + if (@available(iOS 11, *)) { + UIEdgeInsets insets = UIEdgeInsetsZero; + UIView *view = AppDelegate.viewController.godotView; + + if ([view respondsToSelector:@selector(safeAreaInsets)]) { + insets = [view safeAreaInsets]; + } + + float scale = screen_get_scale(p_screen); + Size2i insets_position = Size2i(insets.left, insets.top) * scale; + Size2i insets_size = Size2i(insets.left + insets.right, insets.top + insets.bottom) * scale; + + return Rect2i(screen_get_position(p_screen) + insets_position, screen_get_size(p_screen) - insets_size); + } else { + return Rect2i(screen_get_position(p_screen), screen_get_size(p_screen)); + } } int DisplayServerIPhone::screen_get_dpi(int p_screen) const { diff --git a/platform/iphone/godot_view_renderer.mm b/platform/iphone/godot_view_renderer.mm index 1fc822b457..045fb451f0 100644 --- a/platform/iphone/godot_view_renderer.mm +++ b/platform/iphone/godot_view_renderer.mm @@ -44,7 +44,6 @@ @interface GodotViewRenderer () -@property(assign, nonatomic) BOOL hasFinishedLocaleSetup; @property(assign, nonatomic) BOOL hasFinishedProjectDataSetup; @property(assign, nonatomic) BOOL hasStartedMain; @property(assign, nonatomic) BOOL hasFinishedSetup; @@ -58,9 +57,8 @@ return NO; } - if (!self.hasFinishedLocaleSetup) { - [self setupLocaleAndUUID]; - return YES; + if (!OS::get_singleton()) { + exit(0); } if (!self.hasFinishedProjectDataSetup) { @@ -79,33 +77,6 @@ return NO; } -- (void)setupLocaleAndUUID { - self.hasFinishedLocaleSetup = YES; - - if (!OS::get_singleton()) { - exit(0); - } - - NSString *locale_code = [[NSLocale currentLocale] localeIdentifier]; - OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String])); - - NSString *uuid; - if ([[UIDevice currentDevice] respondsToSelector:@selector(identifierForVendor)]) { - uuid = [UIDevice currentDevice].identifierForVendor.UUIDString; - } else { - // before iOS 6, so just generate an identifier and store it - uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"identiferForVendor"]; - if (!uuid) { - CFUUIDRef cfuuid = CFUUIDCreate(NULL); - uuid = [(NSString *)CFUUIDCreateString(NULL, cfuuid) autorelease]; - CFRelease(cfuuid); - [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:@"identifierForVendor"]; - } - } - - OSIPhone::get_singleton()->set_unique_id(String::utf8([uuid UTF8String])); -} - - (void)setupProjectData { self.hasFinishedProjectDataSetup = YES; diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h index f3bde46717..c6f95869ee 100644 --- a/platform/iphone/os_iphone.h +++ b/platform/iphone/os_iphone.h @@ -84,8 +84,6 @@ private: virtual void finalize() override; String user_data_dir; - String unique_id; - String locale_code; bool is_focused = false; @@ -118,10 +116,8 @@ public: void set_user_data_dir(String p_dir); virtual String get_user_data_dir() const override; - void set_locale(String p_locale); virtual String get_locale() const override; - void set_unique_id(String p_id); virtual String get_unique_id() const override; virtual void vibrate_handheld(int p_duration_ms = 500) override; diff --git a/platform/iphone/os_iphone.mm b/platform/iphone/os_iphone.mm index f0bbbd39ca..a7366ffdec 100644 --- a/platform/iphone/os_iphone.mm +++ b/platform/iphone/os_iphone.mm @@ -305,20 +305,20 @@ String OSIPhone::get_user_data_dir() const { return user_data_dir; } -void OSIPhone::set_locale(String p_locale) { - locale_code = p_locale; -} - String OSIPhone::get_locale() const { - return locale_code; -} + NSString *preferedLanguage = [NSLocale preferredLanguages].firstObject; + + if (preferedLanguage) { + return String::utf8([preferedLanguage UTF8String]).replace("-", "_"); + } -void OSIPhone::set_unique_id(String p_id) { - unique_id = p_id; + NSString *localeIdentifier = [[NSLocale currentLocale] localeIdentifier]; + return String::utf8([localeIdentifier UTF8String]).replace("-", "_"); } String OSIPhone::get_unique_id() const { - return unique_id; + NSString *uuid = [UIDevice currentDevice].identifierForVendor.UUIDString; + return String::utf8([uuid UTF8String]); } void OSIPhone::vibrate_handheld(int p_duration_ms) { diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp index 4aec6d256c..d35941bdcd 100644 --- a/platform/linuxbsd/display_server_x11.cpp +++ b/platform/linuxbsd/display_server_x11.cpp @@ -881,6 +881,46 @@ void DisplayServerX11::window_set_transient(WindowID p_window, WindowID p_parent } } +// Helper method. Assumes that the window id has already been checked and exists. +void DisplayServerX11::_update_size_hints(WindowID p_window) { + WindowData &wd = windows[p_window]; + WindowMode window_mode = window_get_mode(p_window); + XSizeHints *xsh = XAllocSizeHints(); + + // Always set the position and size hints - they should be synchronized with the actual values after the window is mapped anyway + xsh->flags |= PPosition | PSize; + xsh->x = wd.position.x; + xsh->y = wd.position.y; + xsh->width = wd.size.width; + xsh->height = wd.size.height; + + if (window_mode == WINDOW_MODE_FULLSCREEN) { + // Do not set any other hints to prevent the window manager from ignoring the fullscreen flags + } else if (window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) { + // If resizing is disabled, use the forced size + xsh->flags |= PMinSize | PMaxSize; + xsh->min_width = wd.size.x; + xsh->max_width = wd.size.x; + xsh->min_height = wd.size.y; + xsh->max_height = wd.size.y; + } else { + // Otherwise, just respect min_size and max_size + if (wd.min_size != Size2i()) { + xsh->flags |= PMinSize; + xsh->min_width = wd.min_size.x; + xsh->min_height = wd.min_size.y; + } + if (wd.max_size != Size2i()) { + xsh->flags |= PMaxSize; + xsh->max_width = wd.max_size.x; + xsh->max_height = wd.max_size.y; + } + } + + XSetWMNormalHints(x11_display, wd.x11_window, xsh); + XFree(xsh); +} + Point2i DisplayServerX11::window_get_position(WindowID p_window) const { _THREAD_SAFE_METHOD_ @@ -934,25 +974,8 @@ void DisplayServerX11::window_set_max_size(const Size2i p_size, WindowID p_windo } wd.max_size = p_size; - if (!window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) { - XSizeHints *xsh; - xsh = XAllocSizeHints(); - xsh->flags = 0L; - if (wd.min_size != Size2i()) { - xsh->flags |= PMinSize; - xsh->min_width = wd.min_size.x; - xsh->min_height = wd.min_size.y; - } - if (wd.max_size != Size2i()) { - xsh->flags |= PMaxSize; - xsh->max_width = wd.max_size.x; - xsh->max_height = wd.max_size.y; - } - XSetWMNormalHints(x11_display, wd.x11_window, xsh); - XFree(xsh); - - XFlush(x11_display); - } + _update_size_hints(p_window); + XFlush(x11_display); } Size2i DisplayServerX11::window_get_max_size(WindowID p_window) const { @@ -976,25 +999,8 @@ void DisplayServerX11::window_set_min_size(const Size2i p_size, WindowID p_windo } wd.min_size = p_size; - if (!window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) { - XSizeHints *xsh; - xsh = XAllocSizeHints(); - xsh->flags = 0L; - if (wd.min_size != Size2i()) { - xsh->flags |= PMinSize; - xsh->min_width = wd.min_size.x; - xsh->min_height = wd.min_size.y; - } - if (wd.max_size != Size2i()) { - xsh->flags |= PMaxSize; - xsh->max_width = wd.max_size.x; - xsh->max_height = wd.max_size.y; - } - XSetWMNormalHints(x11_display, wd.x11_window, xsh); - XFree(xsh); - - XFlush(x11_display); - } + _update_size_hints(p_window); + XFlush(x11_display); } Size2i DisplayServerX11::window_get_min_size(WindowID p_window) const { @@ -1027,37 +1033,15 @@ void DisplayServerX11::window_set_size(const Size2i p_size, WindowID p_window) { int old_w = xwa.width; int old_h = xwa.height; - // If window resizable is disabled we need to update the attributes first - XSizeHints *xsh; - xsh = XAllocSizeHints(); - if (!window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) { - xsh->flags = PMinSize | PMaxSize; - xsh->min_width = size.x; - xsh->max_width = size.x; - xsh->min_height = size.y; - xsh->max_height = size.y; - } else { - xsh->flags = 0L; - if (wd.min_size != Size2i()) { - xsh->flags |= PMinSize; - xsh->min_width = wd.min_size.x; - xsh->min_height = wd.min_size.y; - } - if (wd.max_size != Size2i()) { - xsh->flags |= PMaxSize; - xsh->max_width = wd.max_size.x; - xsh->max_height = wd.max_size.y; - } - } - XSetWMNormalHints(x11_display, wd.x11_window, xsh); - XFree(xsh); + // Update our videomode width and height + wd.size = size; + + // Update the size hints first to make sure the window size can be set + _update_size_hints(p_window); // Resize the window XResizeWindow(x11_display, wd.x11_window, size.x, size.y); - // Update our videomode width and height - wd.size = size; - for (int timeout = 0; timeout < 50; ++timeout) { XSync(x11_display, False); XGetWindowAttributes(x11_display, wd.x11_window, &xwa); @@ -1213,14 +1197,9 @@ void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled) { XChangeProperty(x11_display, wd.x11_window, property, property, 32, PropModeReplace, (unsigned char *)&hints, 5); } - if (p_enabled && window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) { + if (p_enabled) { // Set the window as resizable to prevent window managers to ignore the fullscreen state flag. - XSizeHints *xsh; - - xsh = XAllocSizeHints(); - xsh->flags = 0L; - XSetWMNormalHints(x11_display, wd.x11_window, xsh); - XFree(xsh); + _update_size_hints(p_window); } // Using EWMH -- Extended Window Manager Hints @@ -1248,30 +1227,7 @@ void DisplayServerX11::_set_wm_fullscreen(WindowID p_window, bool p_enabled) { if (!p_enabled) { // Reset the non-resizable flags if we un-set these before. - Size2i size = window_get_size(p_window); - XSizeHints *xsh; - xsh = XAllocSizeHints(); - if (window_get_flag(WINDOW_FLAG_RESIZE_DISABLED, p_window)) { - xsh->flags = PMinSize | PMaxSize; - xsh->min_width = size.x; - xsh->max_width = size.x; - xsh->min_height = size.y; - xsh->max_height = size.y; - } else { - xsh->flags = 0L; - if (wd.min_size != Size2i()) { - xsh->flags |= PMinSize; - xsh->min_width = wd.min_size.x; - xsh->min_height = wd.min_size.y; - } - if (wd.max_size != Size2i()) { - xsh->flags |= PMaxSize; - xsh->max_width = wd.max_size.x; - xsh->max_height = wd.max_size.y; - } - } - XSetWMNormalHints(x11_display, wd.x11_window, xsh); - XFree(xsh); + _update_size_hints(p_window); // put back or remove decorations according to the last set borderless state Hints hints; @@ -1329,13 +1285,13 @@ void DisplayServerX11::window_set_mode(WindowMode p_mode, WindowID p_window) { } break; case WINDOW_MODE_FULLSCREEN: { //Remove full-screen + wd.fullscreen = false; + _set_wm_fullscreen(p_window, false); //un-maximize required for always on top bool on_top = window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window); - wd.fullscreen = false; - window_set_position(wd.last_position_before_fs, p_window); if (on_top) { @@ -1381,15 +1337,16 @@ void DisplayServerX11::window_set_mode(WindowMode p_mode, WindowID p_window) { } break; case WINDOW_MODE_FULLSCREEN: { wd.last_position_before_fs = wd.position; + if (window_get_flag(WINDOW_FLAG_ALWAYS_ON_TOP, p_window)) { _set_wm_maximized(p_window, true); } - _set_wm_fullscreen(p_window, true); + wd.fullscreen = true; + _set_wm_fullscreen(p_window, true); } break; case WINDOW_MODE_MAXIMIZED: { _set_wm_maximized(p_window, true); - } break; } } @@ -1456,37 +1413,11 @@ void DisplayServerX11::window_set_flag(WindowFlags p_flag, bool p_enabled, Windo switch (p_flag) { case WINDOW_FLAG_RESIZE_DISABLED: { - XSizeHints *xsh; - xsh = XAllocSizeHints(); - if (p_enabled) { - Size2i size = window_get_size(p_window); - - xsh->flags = PMinSize | PMaxSize; - xsh->min_width = size.x; - xsh->max_width = size.x; - xsh->min_height = size.y; - xsh->max_height = size.y; - } else { - xsh->flags = 0L; - if (wd.min_size != Size2i()) { - xsh->flags |= PMinSize; - xsh->min_width = wd.min_size.x; - xsh->min_height = wd.min_size.y; - } - if (wd.max_size != Size2i()) { - xsh->flags |= PMaxSize; - xsh->max_width = wd.max_size.x; - xsh->max_height = wd.max_size.y; - } - } - - XSetWMNormalHints(x11_display, wd.x11_window, xsh); - XFree(xsh); - wd.resize_disabled = p_enabled; - XFlush(x11_display); + _update_size_hints(p_window); + XFlush(x11_display); } break; case WINDOW_FLAG_BORDERLESS: { Hints hints; @@ -3305,20 +3236,6 @@ DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, u windows[id] = wd; { - if (p_flags & WINDOW_FLAG_RESIZE_DISABLED_BIT) { - XSizeHints *xsh; - xsh = XAllocSizeHints(); - - xsh->flags = PMinSize | PMaxSize; - xsh->min_width = p_rect.size.width; - xsh->max_width = p_rect.size.width; - xsh->min_height = p_rect.size.height; - xsh->max_height = p_rect.size.height; - - XSetWMNormalHints(x11_display, wd.x11_window, xsh); - XFree(xsh); - } - bool make_utility = false; if (p_flags & WINDOW_FLAG_BORDERLESS_BIT) { @@ -3368,18 +3285,7 @@ DisplayServerX11::WindowID DisplayServerX11::_create_window(WindowMode p_mode, u } } - if (id != MAIN_WINDOW_ID) { - XSizeHints my_hints = XSizeHints(); - - my_hints.flags = PPosition | PSize; /* I want to specify position and size */ - my_hints.x = p_rect.position.x; /* The origin and size coords I want */ - my_hints.y = p_rect.position.y; - my_hints.width = p_rect.size.width; - my_hints.height = p_rect.size.height; - - XSetNormalHints(x11_display, wd.x11_window, &my_hints); - XMoveWindow(x11_display, wd.x11_window, p_rect.position.x, p_rect.position.y); - } + _update_size_hints(id); #if defined(VULKAN_ENABLED) if (context_vulkan) { diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h index 0ba1359145..8e1f941bbf 100644 --- a/platform/linuxbsd/display_server_x11.h +++ b/platform/linuxbsd/display_server_x11.h @@ -235,6 +235,7 @@ class DisplayServerX11 : public DisplayServer { void _update_real_mouse_position(const WindowData &wd); bool _window_maximize_check(WindowID p_window, const char *p_atom_name) const; + void _update_size_hints(WindowID p_window); void _set_wm_fullscreen(WindowID p_window, bool p_enabled); void _set_wm_maximized(WindowID p_window, bool p_enabled); diff --git a/platform/linuxbsd/joypad_linux.cpp b/platform/linuxbsd/joypad_linux.cpp index 5edaf35c50..fda1358dfd 100644 --- a/platform/linuxbsd/joypad_linux.cpp +++ b/platform/linuxbsd/joypad_linux.cpp @@ -311,16 +311,9 @@ void JoypadLinux::open_joypad(const char *p_path) { return; } - //check if the device supports basic gamepad events, prevents certain keyboards from - //being detected as joypads + // 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) || test_bit(ABS_HAT0X, absbit) || - test_bit(ABS_GAS, absbit) || test_bit(ABS_RUDDER, absbit)) && - (test_bit(BTN_A, keybit) || test_bit(BTN_THUMBL, keybit) || - test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_1, keybit))) && - !(test_bit(EV_ABS, evbit) && - test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit) && - test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit))) { + test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit))) { close(fd); return; } diff --git a/platform/windows/joypad_windows.cpp b/platform/windows/joypad_windows.cpp index 65caee3035..d1454c9096 100644 --- a/platform/windows/joypad_windows.cpp +++ b/platform/windows/joypad_windows.cpp @@ -146,8 +146,8 @@ bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) { if (have_device(instance->guidInstance) || num == -1) return false; - d_joypads[joypad_count] = dinput_gamepad(); - dinput_gamepad *joy = &d_joypads[joypad_count]; + d_joypads[num] = dinput_gamepad(); + dinput_gamepad *joy = &d_joypads[num]; const DWORD devtype = (instance->dwDevType & 0xFF); @@ -171,7 +171,7 @@ bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) { WORD version = 0; sprintf_s(uid, "%04x%04x%04x%04x%04x%04x%04x%04x", type, 0, vendor, 0, product, 0, version, 0); - id_to_change = joypad_count; + id_to_change = num; slider_count = 0; joy->di_joy->SetDataFormat(&c_dfDIJoystick2); diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp index 39ac10a46e..e17085cafc 100644 --- a/scene/gui/text_edit.cpp +++ b/scene/gui/text_edit.cpp @@ -1631,7 +1631,7 @@ void TextEdit::_notification(int p_what) { DisplayServer::get_singleton()->window_set_ime_position(get_global_position() + cursor_pos, get_viewport()->get_window_id()); } - if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_VIRTUAL_KEYBOARD)) { + if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_VIRTUAL_KEYBOARD) && virtual_keyboard_enabled) { DisplayServer::get_singleton()->virtual_keyboard_show(get_text(), get_global_rect(), true); } } break; @@ -1647,7 +1647,7 @@ void TextEdit::_notification(int p_what) { ime_text = ""; ime_selection = Point2(); - if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_VIRTUAL_KEYBOARD)) { + if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_VIRTUAL_KEYBOARD) && virtual_keyboard_enabled) { DisplayServer::get_singleton()->virtual_keyboard_hide(); } } break; @@ -4889,6 +4889,7 @@ void TextEdit::_update_caches() { cache.folded_eol_icon = get_theme_icon("GuiEllipsis", "EditorIcons"); cache.executing_icon = get_theme_icon("MainPlay", "EditorIcons"); text.set_font(cache.font); + text.clear_width_cache(); if (syntax_highlighter.is_valid()) { syntax_highlighter->set_text_edit(this); @@ -6692,6 +6693,10 @@ void TextEdit::set_shortcut_keys_enabled(bool p_enabled) { _generate_context_menu(); } +void TextEdit::set_virtual_keyboard_enabled(bool p_enable) { + virtual_keyboard_enabled = p_enable; +} + void TextEdit::set_selecting_enabled(bool p_enabled) { selecting_enabled = p_enabled; @@ -6710,6 +6715,10 @@ bool TextEdit::is_shortcut_keys_enabled() const { return shortcut_keys_enabled; } +bool TextEdit::is_virtual_keyboard_enabled() const { + return virtual_keyboard_enabled; +} + PopupMenu *TextEdit::get_menu() const { return menu; } @@ -6762,6 +6771,8 @@ void TextEdit::_bind_methods() { ClassDB::bind_method(D_METHOD("is_context_menu_enabled"), &TextEdit::is_context_menu_enabled); ClassDB::bind_method(D_METHOD("set_shortcut_keys_enabled", "enable"), &TextEdit::set_shortcut_keys_enabled); ClassDB::bind_method(D_METHOD("is_shortcut_keys_enabled"), &TextEdit::is_shortcut_keys_enabled); + ClassDB::bind_method(D_METHOD("set_virtual_keyboard_enabled", "enable"), &TextEdit::set_virtual_keyboard_enabled); + ClassDB::bind_method(D_METHOD("is_virtual_keyboard_enabled"), &TextEdit::is_virtual_keyboard_enabled); ClassDB::bind_method(D_METHOD("set_selecting_enabled", "enable"), &TextEdit::set_selecting_enabled); ClassDB::bind_method(D_METHOD("is_selecting_enabled"), &TextEdit::is_selecting_enabled); @@ -6853,6 +6864,7 @@ void TextEdit::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::BOOL, "override_selected_font_color"), "set_override_selected_font_color", "is_overriding_selected_font_color"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "context_menu_enabled"), "set_context_menu_enabled", "is_context_menu_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_keys_enabled"), "set_shortcut_keys_enabled", "is_shortcut_keys_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "virtual_keyboard_enabled"), "set_virtual_keyboard_enabled", "is_virtual_keyboard_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "selecting_enabled"), "set_selecting_enabled", "is_selecting_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smooth_scrolling"), "set_smooth_scroll_enable", "is_smooth_scroll_enabled"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "v_scroll_speed"), "set_v_scroll_speed", "get_v_scroll_speed"); diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h index 5a6ed99845..a6bc9963cc 100644 --- a/scene/gui/text_edit.h +++ b/scene/gui/text_edit.h @@ -386,6 +386,8 @@ private: bool context_menu_enabled; bool shortcut_keys_enabled; + bool virtual_keyboard_enabled = true; + int executing_line; void _generate_context_menu(); @@ -749,6 +751,9 @@ public: void set_shortcut_keys_enabled(bool p_enabled); bool is_shortcut_keys_enabled() const; + void set_virtual_keyboard_enabled(bool p_enable); + bool is_virtual_keyboard_enabled() const; + PopupMenu *get_menu() const; String get_text_for_completion(); diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp index 2449b3bd35..adefb53862 100644 --- a/scene/main/scene_tree.cpp +++ b/scene/main/scene_tree.cpp @@ -880,7 +880,10 @@ void SceneTree::_call_input_pause(const StringName &p_group, const StringName &p if (n->get_script_instance()) { n->get_script_instance()->call(p_method, (const Variant **)v, 1, err); } - n->call(p_method, (const Variant **)v, 1, err); + MethodBind *method = ClassDB::get_method(n->get_class_name(), p_method); + if (method) { + method->call(n, (const Variant **)v, 1, err); + } } call_lock--; diff --git a/scene/main/window.cpp b/scene/main/window.cpp index 8c985242f1..a5c5be8a44 100644 --- a/scene/main/window.cpp +++ b/scene/main/window.cpp @@ -527,11 +527,11 @@ void Window::_update_window_size() { size.x = MAX(size_limit.x, size.x); size.y = MAX(size_limit.y, size.y); - if (max_size.x > 0 && max_size.x > min_size.x && max_size.x > size.x) { + if (max_size.x > 0 && max_size.x > min_size.x && size.x > max_size.x) { size.x = max_size.x; } - if (max_size.y > 0 && max_size.y > min_size.y && max_size.y > size.y) { + if (max_size.y > 0 && max_size.y > min_size.y && size.y > max_size.y) { size.y = max_size.y; } diff --git a/scene/resources/syntax_highlighter.cpp b/scene/resources/syntax_highlighter.cpp index 9c8f9334a9..4479b822c0 100644 --- a/scene/resources/syntax_highlighter.cpp +++ b/scene/resources/syntax_highlighter.cpp @@ -158,6 +158,10 @@ Dictionary CodeHighlighter::_get_line_syntax_highlighting(int p_line) { const String &str = text_edit->get_line(p_line); const int line_length = str.length(); Color prev_color; + + if (in_region != -1 && str.length() == 0) { + color_region_cache[p_line] = in_region; + } for (int j = 0; j < line_length; j++) { Dictionary highlighter_info; diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp index 8b84ce9e8c..e4851ad9f7 100644 --- a/scene/resources/visual_shader.cpp +++ b/scene/resources/visual_shader.cpp @@ -71,7 +71,15 @@ bool VisualShaderNode::is_output_port_connected(int p_port) const { } void VisualShaderNode::set_output_port_connected(int p_port, bool p_connected) { - connected_output_ports[p_port] = p_connected; + if (p_connected) { + connected_output_ports[p_port] = true; + ++connected_output_count; + } else { + --connected_output_count; + if (connected_output_count == 0) { + connected_output_ports[p_port] = false; + } + } } bool VisualShaderNode::is_input_port_connected(int p_port) const { diff --git a/scene/resources/visual_shader.h b/scene/resources/visual_shader.h index d74269cfc6..05d8950be9 100644 --- a/scene/resources/visual_shader.h +++ b/scene/resources/visual_shader.h @@ -184,6 +184,7 @@ class VisualShaderNode : public Resource { Map<int, Variant> default_input_values; Map<int, bool> connected_input_ports; Map<int, bool> connected_output_ports; + int connected_output_count = 0; protected: bool simple_decl; diff --git a/tests/test_astar.cpp b/tests/test_astar.cpp deleted file mode 100644 index cb5fcfe37b..0000000000 --- a/tests/test_astar.cpp +++ /dev/null @@ -1,409 +0,0 @@ -/*************************************************************************/ -/* test_astar.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "test_astar.h" - -#include "core/math/a_star.h" -#include "core/math/math_funcs.h" -#include "core/os/os.h" - -#include <math.h> -#include <stdio.h> - -namespace TestAStar { - -class ABCX : public AStar { -public: - enum { A, - B, - C, - X }; - - ABCX() { - add_point(A, Vector3(0, 0, 0)); - add_point(B, Vector3(1, 0, 0)); - add_point(C, Vector3(0, 1, 0)); - add_point(X, Vector3(0, 0, 1)); - connect_points(A, B); - connect_points(A, C); - connect_points(B, C); - connect_points(X, A); - } - - // Disable heuristic completely - float _compute_cost(int p_from, int p_to) { - if (p_from == A && p_to == C) { - return 1000; - } - return 100; - } -}; - -bool test_abc() { - ABCX abcx; - Vector<int> path = abcx.get_id_path(ABCX::A, ABCX::C); - bool ok = path.size() == 3; - int i = 0; - ok = ok && path[i++] == ABCX::A; - ok = ok && path[i++] == ABCX::B; - ok = ok && path[i++] == ABCX::C; - return ok; -} - -bool test_abcx() { - ABCX abcx; - Vector<int> path = abcx.get_id_path(ABCX::X, ABCX::C); - bool ok = path.size() == 4; - int i = 0; - ok = ok && path[i++] == ABCX::X; - ok = ok && path[i++] == ABCX::A; - ok = ok && path[i++] == ABCX::B; - ok = ok && path[i++] == ABCX::C; - return ok; -} - -bool test_add_remove() { - AStar a; - bool ok = true; - - // Manual tests - a.add_point(1, Vector3(0, 0, 0)); - a.add_point(2, Vector3(0, 1, 0)); - a.add_point(3, Vector3(1, 1, 0)); - a.add_point(4, Vector3(2, 0, 0)); - a.connect_points(1, 2, true); - a.connect_points(1, 3, true); - a.connect_points(1, 4, false); - - ok = ok && (a.are_points_connected(2, 1)); - ok = ok && (a.are_points_connected(4, 1)); - ok = ok && (a.are_points_connected(2, 1, false)); - ok = ok && (a.are_points_connected(4, 1, false) == false); - - a.disconnect_points(1, 2, true); - ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4 - ok = ok && (a.get_point_connections(2).size() == 0); - - a.disconnect_points(4, 1, false); - ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4 - ok = ok && (a.get_point_connections(4).size() == 0); - - a.disconnect_points(4, 1, true); - ok = ok && (a.get_point_connections(1).size() == 1); // 3 - ok = ok && (a.get_point_connections(4).size() == 0); - - a.connect_points(2, 3, false); - ok = ok && (a.get_point_connections(2).size() == 1); // 3 - ok = ok && (a.get_point_connections(3).size() == 1); // 1 - - a.connect_points(2, 3, true); - ok = ok && (a.get_point_connections(2).size() == 1); // 3 - ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 - - a.disconnect_points(2, 3, false); - ok = ok && (a.get_point_connections(2).size() == 0); - ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 - - a.connect_points(4, 3, true); - ok = ok && (a.get_point_connections(3).size() == 3); // 1, 2, 4 - ok = ok && (a.get_point_connections(4).size() == 1); // 3 - - a.disconnect_points(3, 4, false); - ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2 - ok = ok && (a.get_point_connections(4).size() == 1); // 3 - - a.remove_point(3); - ok = ok && (a.get_point_connections(1).size() == 0); - ok = ok && (a.get_point_connections(2).size() == 0); - ok = ok && (a.get_point_connections(4).size() == 0); - - a.add_point(0, Vector3(0, -1, 0)); - a.add_point(3, Vector3(2, 1, 0)); - // 0: (0, -1) - // 1: (0, 0) - // 2: (0, 1) - // 3: (2, 1) - // 4: (2, 0) - - // Tests for get_closest_position_in_segment - a.connect_points(2, 3); - ok = ok && (a.get_closest_position_in_segment(Vector3(0.5, 0.5, 0)) == Vector3(0.5, 1, 0)); - - a.connect_points(3, 4); - a.connect_points(0, 3); - a.connect_points(1, 4); - a.disconnect_points(1, 4, false); - a.disconnect_points(4, 3, false); - a.disconnect_points(3, 4, false); - // Remaining edges: <2, 3>, <0, 3>, <1, 4> (directed) - ok = ok && (a.get_closest_position_in_segment(Vector3(2, 0.5, 0)) == Vector3(1.75, 0.75, 0)); - ok = ok && (a.get_closest_position_in_segment(Vector3(-1, 0.2, 0)) == Vector3(0, 0, 0)); - ok = ok && (a.get_closest_position_in_segment(Vector3(3, 2, 0)) == Vector3(2, 1, 0)); - - Math::seed(0); - - // Random tests for connectivity checks - for (int i = 0; i < 20000; i++) { - int u = Math::rand() % 5; - int v = Math::rand() % 4; - if (u == v) { - v = 4; - } - if (Math::rand() % 2 == 1) { - // Add a (possibly existing) directed edge and confirm connectivity - a.connect_points(u, v, false); - ok = ok && (a.are_points_connected(u, v, false)); - } else { - // Remove a (possibly nonexistent) directed edge and confirm disconnectivity - a.disconnect_points(u, v, false); - ok = ok && (a.are_points_connected(u, v, false) == false); - } - } - - // Random tests for point removal - for (int i = 0; i < 20000; i++) { - a.clear(); - for (int j = 0; j < 5; j++) { - a.add_point(j, Vector3(0, 0, 0)); - } - - // Add or remove random edges - for (int j = 0; j < 10; j++) { - int u = Math::rand() % 5; - int v = Math::rand() % 4; - if (u == v) { - v = 4; - } - if (Math::rand() % 2 == 1) { - a.connect_points(u, v, false); - } else { - a.disconnect_points(u, v, false); - } - } - - // Remove point 0 - a.remove_point(0); - // White box: this will check all edges remaining in the segments set - for (int j = 1; j < 5; j++) { - ok = ok && (a.are_points_connected(0, j, true) == false); - } - } - - // It's been great work, cheers \(^ ^)/ - return ok; -} - -bool test_solutions() { - // Random stress tests with Floyd-Warshall - - const int N = 30; - Math::seed(0); - - for (int test = 0; test < 1000; test++) { - AStar a; - Vector3 p[N]; - bool adj[N][N] = { { false } }; - - // Assign initial coordinates - for (int u = 0; u < N; u++) { - p[u].x = Math::rand() % 100; - p[u].y = Math::rand() % 100; - p[u].z = Math::rand() % 100; - a.add_point(u, p[u]); - } - - // Generate a random sequence of operations - for (int i = 0; i < 1000; i++) { - // Pick two different vertices - int u, v; - u = Math::rand() % N; - v = Math::rand() % (N - 1); - if (u == v) { - v = N - 1; - } - - // Pick a random operation - int op = Math::rand(); - switch (op % 9) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - // Add edge (u, v); possibly bidirectional - a.connect_points(u, v, op % 2); - adj[u][v] = true; - if (op % 2) { - adj[v][u] = true; - } - break; - case 6: - case 7: - // Remove edge (u, v); possibly bidirectional - a.disconnect_points(u, v, op % 2); - adj[u][v] = false; - if (op % 2) { - adj[v][u] = false; - } - break; - case 8: - // Remove point u and add it back; clears adjacent edges and changes coordinates - a.remove_point(u); - p[u].x = Math::rand() % 100; - p[u].y = Math::rand() % 100; - p[u].z = Math::rand() % 100; - a.add_point(u, p[u]); - for (v = 0; v < N; v++) { - adj[u][v] = adj[v][u] = false; - } - break; - } - } - - // Floyd-Warshall - float d[N][N]; - for (int u = 0; u < N; u++) { - for (int v = 0; v < N; v++) { - d[u][v] = (u == v || adj[u][v]) ? p[u].distance_to(p[v]) : INFINITY; - } - } - - for (int w = 0; w < N; w++) { - for (int u = 0; u < N; u++) { - for (int v = 0; v < N; v++) { - if (d[u][v] > d[u][w] + d[w][v]) { - d[u][v] = d[u][w] + d[w][v]; - } - } - } - } - - // Display statistics - int count = 0; - for (int u = 0; u < N; u++) { - for (int v = 0; v < N; v++) { - if (adj[u][v]) { - count++; - } - } - } - printf("Test #%4d: %3d edges, ", test + 1, count); - count = 0; - for (int u = 0; u < N; u++) { - for (int v = 0; v < N; v++) { - if (!Math::is_inf(d[u][v])) { - count++; - } - } - } - printf("%3d/%d pairs of reachable points\n", count - N, N * (N - 1)); - - // Check A*'s output - bool match = true; - for (int u = 0; u < N; u++) { - for (int v = 0; v < N; v++) { - if (u != v) { - Vector<int> route = a.get_id_path(u, v); - if (!Math::is_inf(d[u][v])) { - // Reachable - if (route.size() == 0) { - printf("From %d to %d: A* did not find a path\n", u, v); - match = false; - goto exit; - } - float astar_dist = 0; - for (int i = 1; i < route.size(); i++) { - if (!adj[route[i - 1]][route[i]]) { - printf("From %d to %d: edge (%d, %d) does not exist\n", - u, v, route[i - 1], route[i]); - match = false; - goto exit; - } - astar_dist += p[route[i - 1]].distance_to(p[route[i]]); - } - if (!Math::is_equal_approx(astar_dist, d[u][v])) { - printf("From %d to %d: Floyd-Warshall gives %.6f, A* gives %.6f\n", - u, v, d[u][v], astar_dist); - match = false; - goto exit; - } - } else { - // Unreachable - if (route.size() > 0) { - printf("From %d to %d: A* somehow found a nonexistent path\n", u, v); - match = false; - goto exit; - } - } - } - } - } - - exit: - if (!match) { - return false; - } - } - return true; -} - -typedef bool (*TestFunc)(); - -TestFunc test_funcs[] = { - test_abc, - test_abcx, - test_add_remove, - test_solutions, - nullptr -}; - -MainLoop *test() { - int count = 0; - int passed = 0; - - while (true) { - if (!test_funcs[count]) { - break; - } - bool pass = test_funcs[count](); - if (pass) { - passed++; - } - OS::get_singleton()->print("\t%s\n", pass ? "PASS" : "FAILED"); - - count++; - } - OS::get_singleton()->print("\n"); - OS::get_singleton()->print("Passed %i of %i tests\n", passed, count); - return nullptr; -} - -} // namespace TestAStar diff --git a/tests/test_astar.h b/tests/test_astar.h index 0992812c18..bef6127471 100644 --- a/tests/test_astar.h +++ b/tests/test_astar.h @@ -31,11 +31,338 @@ #ifndef TEST_ASTAR_H #define TEST_ASTAR_H -#include "core/os/main_loop.h" +#include "core/math/a_star.h" +#include "core/math/math_funcs.h" +#include "core/os/os.h" + +#include <math.h> +#include <stdio.h> + +#include "tests/test_macros.h" namespace TestAStar { -MainLoop *test(); +class ABCX : public AStar { +public: + enum { + A, + B, + C, + X, + }; + + ABCX() { + add_point(A, Vector3(0, 0, 0)); + add_point(B, Vector3(1, 0, 0)); + add_point(C, Vector3(0, 1, 0)); + add_point(X, Vector3(0, 0, 1)); + connect_points(A, B); + connect_points(A, C); + connect_points(B, C); + connect_points(X, A); + } + + // Disable heuristic completely. + float _compute_cost(int p_from, int p_to) { + if (p_from == A && p_to == C) { + return 1000; + } + return 100; + } +}; + +TEST_CASE("[AStar] ABC path") { + ABCX abcx; + Vector<int> path = abcx.get_id_path(ABCX::A, ABCX::C); + REQUIRE(path.size() == 3); + CHECK(path[0] == ABCX::A); + CHECK(path[1] == ABCX::B); + CHECK(path[2] == ABCX::C); +} + +TEST_CASE("[AStar] ABCX path") { + ABCX abcx; + Vector<int> path = abcx.get_id_path(ABCX::X, ABCX::C); + REQUIRE(path.size() == 4); + CHECK(path[0] == ABCX::X); + CHECK(path[1] == ABCX::A); + CHECK(path[2] == ABCX::B); + CHECK(path[3] == ABCX::C); +} + +TEST_CASE("[AStar] Add/Remove") { + AStar a; + + // Manual tests. + a.add_point(1, Vector3(0, 0, 0)); + a.add_point(2, Vector3(0, 1, 0)); + a.add_point(3, Vector3(1, 1, 0)); + a.add_point(4, Vector3(2, 0, 0)); + a.connect_points(1, 2, true); + a.connect_points(1, 3, true); + a.connect_points(1, 4, false); + + CHECK(a.are_points_connected(2, 1)); + CHECK(a.are_points_connected(4, 1)); + CHECK(a.are_points_connected(2, 1, false)); + CHECK_FALSE(a.are_points_connected(4, 1, false)); + + a.disconnect_points(1, 2, true); + CHECK(a.get_point_connections(1).size() == 2); // 3, 4 + CHECK(a.get_point_connections(2).size() == 0); + + a.disconnect_points(4, 1, false); + CHECK(a.get_point_connections(1).size() == 2); // 3, 4 + CHECK(a.get_point_connections(4).size() == 0); + + a.disconnect_points(4, 1, true); + CHECK(a.get_point_connections(1).size() == 1); // 3 + CHECK(a.get_point_connections(4).size() == 0); + + a.connect_points(2, 3, false); + CHECK(a.get_point_connections(2).size() == 1); // 3 + CHECK(a.get_point_connections(3).size() == 1); // 1 + + a.connect_points(2, 3, true); + CHECK(a.get_point_connections(2).size() == 1); // 3 + CHECK(a.get_point_connections(3).size() == 2); // 1, 2 + + a.disconnect_points(2, 3, false); + CHECK(a.get_point_connections(2).size() == 0); + CHECK(a.get_point_connections(3).size() == 2); // 1, 2 + + a.connect_points(4, 3, true); + CHECK(a.get_point_connections(3).size() == 3); // 1, 2, 4 + CHECK(a.get_point_connections(4).size() == 1); // 3 + + a.disconnect_points(3, 4, false); + CHECK(a.get_point_connections(3).size() == 2); // 1, 2 + CHECK(a.get_point_connections(4).size() == 1); // 3 + + a.remove_point(3); + CHECK(a.get_point_connections(1).size() == 0); + CHECK(a.get_point_connections(2).size() == 0); + CHECK(a.get_point_connections(4).size() == 0); + + a.add_point(0, Vector3(0, -1, 0)); + a.add_point(3, Vector3(2, 1, 0)); + // 0: (0, -1) + // 1: (0, 0) + // 2: (0, 1) + // 3: (2, 1) + // 4: (2, 0) + + // Tests for get_closest_position_in_segment. + a.connect_points(2, 3); + CHECK(a.get_closest_position_in_segment(Vector3(0.5, 0.5, 0)) == Vector3(0.5, 1, 0)); + + a.connect_points(3, 4); + a.connect_points(0, 3); + a.connect_points(1, 4); + a.disconnect_points(1, 4, false); + a.disconnect_points(4, 3, false); + a.disconnect_points(3, 4, false); + // Remaining edges: <2, 3>, <0, 3>, <1, 4> (directed). + CHECK(a.get_closest_position_in_segment(Vector3(2, 0.5, 0)) == Vector3(1.75, 0.75, 0)); + CHECK(a.get_closest_position_in_segment(Vector3(-1, 0.2, 0)) == Vector3(0, 0, 0)); + CHECK(a.get_closest_position_in_segment(Vector3(3, 2, 0)) == Vector3(2, 1, 0)); + + Math::seed(0); + + // Random tests for connectivity checks + for (int i = 0; i < 20000; i++) { + int u = Math::rand() % 5; + int v = Math::rand() % 4; + if (u == v) { + v = 4; + } + if (Math::rand() % 2 == 1) { + // Add a (possibly existing) directed edge and confirm connectivity. + a.connect_points(u, v, false); + CHECK(a.are_points_connected(u, v, false)); + } else { + // Remove a (possibly nonexistent) directed edge and confirm disconnectivity. + a.disconnect_points(u, v, false); + CHECK_FALSE(a.are_points_connected(u, v, false)); + } + } + + // Random tests for point removal. + for (int i = 0; i < 20000; i++) { + a.clear(); + for (int j = 0; j < 5; j++) { + a.add_point(j, Vector3(0, 0, 0)); + } + + // Add or remove random edges. + for (int j = 0; j < 10; j++) { + int u = Math::rand() % 5; + int v = Math::rand() % 4; + if (u == v) { + v = 4; + } + if (Math::rand() % 2 == 1) { + a.connect_points(u, v, false); + } else { + a.disconnect_points(u, v, false); + } + } + + // Remove point 0. + a.remove_point(0); + // White box: this will check all edges remaining in the segments set. + for (int j = 1; j < 5; j++) { + CHECK_FALSE(a.are_points_connected(0, j, true)); + } + } + // It's been great work, cheers. \(^ ^)/ +} + +TEST_CASE("[Stress][AStar] Find paths") { + // Random stress tests with Floyd-Warshall. + const int N = 30; + Math::seed(0); + + for (int test = 0; test < 1000; test++) { + AStar a; + Vector3 p[N]; + bool adj[N][N] = { { false } }; + + // Assign initial coordinates. + for (int u = 0; u < N; u++) { + p[u].x = Math::rand() % 100; + p[u].y = Math::rand() % 100; + p[u].z = Math::rand() % 100; + a.add_point(u, p[u]); + } + // Generate a random sequence of operations. + for (int i = 0; i < 1000; i++) { + // Pick two different vertices. + int u, v; + u = Math::rand() % N; + v = Math::rand() % (N - 1); + if (u == v) { + v = N - 1; + } + // Pick a random operation. + int op = Math::rand(); + switch (op % 9) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + // Add edge (u, v); possibly bidirectional. + a.connect_points(u, v, op % 2); + adj[u][v] = true; + if (op % 2) { + adj[v][u] = true; + } + break; + case 6: + case 7: + // Remove edge (u, v); possibly bidirectional. + a.disconnect_points(u, v, op % 2); + adj[u][v] = false; + if (op % 2) { + adj[v][u] = false; + } + break; + case 8: + // Remove point u and add it back; clears adjacent edges and changes coordinates. + a.remove_point(u); + p[u].x = Math::rand() % 100; + p[u].y = Math::rand() % 100; + p[u].z = Math::rand() % 100; + a.add_point(u, p[u]); + for (v = 0; v < N; v++) { + adj[u][v] = adj[v][u] = false; + } + break; + } + } + // Floyd-Warshall. + float d[N][N]; + for (int u = 0; u < N; u++) { + for (int v = 0; v < N; v++) { + d[u][v] = (u == v || adj[u][v]) ? p[u].distance_to(p[v]) : INFINITY; + } + } + for (int w = 0; w < N; w++) { + for (int u = 0; u < N; u++) { + for (int v = 0; v < N; v++) { + if (d[u][v] > d[u][w] + d[w][v]) { + d[u][v] = d[u][w] + d[w][v]; + } + } + } + } + // Display statistics. + int count = 0; + for (int u = 0; u < N; u++) { + for (int v = 0; v < N; v++) { + if (adj[u][v]) { + count++; + } + } + } + print_verbose(vformat("Test #%4d: %3d edges, ", test + 1, count)); + count = 0; + for (int u = 0; u < N; u++) { + for (int v = 0; v < N; v++) { + if (!Math::is_inf(d[u][v])) { + count++; + } + } + } + print_verbose(vformat("%3d/%d pairs of reachable points\n", count - N, N * (N - 1))); + + // Check A*'s output. + bool match = true; + for (int u = 0; u < N; u++) { + for (int v = 0; v < N; v++) { + if (u != v) { + Vector<int> route = a.get_id_path(u, v); + if (!Math::is_inf(d[u][v])) { + // Reachable. + if (route.size() == 0) { + print_verbose(vformat("From %d to %d: A* did not find a path\n", u, v)); + match = false; + goto exit; + } + float astar_dist = 0; + for (int i = 1; i < route.size(); i++) { + if (!adj[route[i - 1]][route[i]]) { + print_verbose(vformat("From %d to %d: edge (%d, %d) does not exist\n", + u, v, route[i - 1], route[i])); + match = false; + goto exit; + } + astar_dist += p[route[i - 1]].distance_to(p[route[i]]); + } + if (!Math::is_equal_approx(astar_dist, d[u][v])) { + print_verbose(vformat("From %d to %d: Floyd-Warshall gives %.6f, A* gives %.6f\n", + u, v, d[u][v], astar_dist)); + match = false; + goto exit; + } + } else { + // Unreachable. + if (route.size() > 0) { + print_verbose(vformat("From %d to %d: A* somehow found a nonexistent path\n", u, v)); + match = false; + goto exit; + } + } + } + } + } + exit: + CHECK_MESSAGE(match, "Found all paths."); + } } -#endif +} // namespace TestAStar + +#endif // TEST_ASTAR_H diff --git a/tests/test_color.h b/tests/test_color.h new file mode 100644 index 0000000000..3633f2746d --- /dev/null +++ b/tests/test_color.h @@ -0,0 +1,213 @@ +/*************************************************************************/ +/* test_color.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_COLOR_H +#define TEST_COLOR_H + +#include "core/color.h" + +#include "thirdparty/doctest/doctest.h" + +namespace TestColor { + +TEST_CASE("[Color] Constructor methods") { + const Color blue_rgba = Color(0.25098, 0.376471, 1, 0.501961); + // HTML currently uses ARGB notation, which is contrary to the CSS standard. + // This may be changed to RGBA in 4.0. + const Color blue_html = Color::html("#804060ff"); + const Color blue_hex = Color::hex(0x4060ff80); + const Color blue_hex64 = Color::hex64(0x4040'6060'ffff'8080); + + CHECK_MESSAGE( + blue_rgba.is_equal_approx(blue_html), + "Creation with HTML notation should result in components approximately equal to the default constructor."); + CHECK_MESSAGE( + blue_rgba.is_equal_approx(blue_hex), + "Creation with a 32-bit hexadecimal number should result in components approximately equal to the default constructor."); + CHECK_MESSAGE( + blue_rgba.is_equal_approx(blue_hex64), + "Creation with a 64-bit hexadecimal number should result in components approximately equal to the default constructor."); + + ERR_PRINT_OFF; + const Color html_invalid = Color::html("invalid"); + ERR_PRINT_ON; + + CHECK_MESSAGE( + html_invalid.is_equal_approx(Color()), + "Creation with invalid HTML notation should result in a Color with the default values."); + + const Color green_rgba = Color(0, 1, 0, 0.25); + const Color green_hsva = Color(0, 0, 0).from_hsv(120 / 360.0, 1, 1, 0.25); + + CHECK_MESSAGE( + green_rgba.is_equal_approx(green_hsva), + "Creation with HSV notation should result in components approximately equal to the default constructor."); +} + +TEST_CASE("[Color] Operators") { + const Color blue = Color(0.2, 0.2, 1); + const Color dark_red = Color(0.3, 0.1, 0.1); + + // Color components may be negative. Also, the alpha component may be greater than 1.0. + CHECK_MESSAGE( + (blue + dark_red).is_equal_approx(Color(0.5, 0.3, 1.1, 2)), + "Color addition should behave as expected."); + CHECK_MESSAGE( + (blue - dark_red).is_equal_approx(Color(-0.1, 0.1, 0.9, 0)), + "Color subtraction should behave as expected."); + CHECK_MESSAGE( + (blue * 2).is_equal_approx(Color(0.4, 0.4, 2, 2)), + "Color multiplication with a scalar should behave as expected."); + CHECK_MESSAGE( + (blue / 2).is_equal_approx(Color(0.1, 0.1, 0.5, 0.5)), + "Color division with a scalar should behave as expected."); + CHECK_MESSAGE( + (blue * dark_red).is_equal_approx(Color(0.06, 0.02, 0.1)), + "Color multiplication with another Color should behave as expected."); + CHECK_MESSAGE( + (blue / dark_red).is_equal_approx(Color(0.666667, 2, 10)), + "Color division with another Color should behave as expected."); + CHECK_MESSAGE( + (-blue).is_equal_approx(Color(0.8, 0.8, 0, 0)), + "Color negation should behave as expected (affecting the alpha channel, unlike `invert()`)."); +} + +TEST_CASE("[Color] Reading methods") { + const Color dark_blue = Color(0, 0, 0.5, 0.4); + + CHECK_MESSAGE( + Math::is_equal_approx(dark_blue.get_h(), 240 / 360.0), + "The returned HSV hue should match the expected value."); + CHECK_MESSAGE( + Math::is_equal_approx(dark_blue.get_s(), 1), + "The returned HSV saturation should match the expected value."); + CHECK_MESSAGE( + Math::is_equal_approx(dark_blue.get_v(), 0.5), + "The returned HSV value should match the expected value."); +} + +TEST_CASE("[Color] Conversion methods") { + const Color cyan = Color(0, 1, 1); + const Color cyan_transparent = Color(0, 1, 1, 0); + + CHECK_MESSAGE( + cyan.to_html() == "ff00ffff", + "The returned RGB HTML color code should match the expected value."); + CHECK_MESSAGE( + cyan_transparent.to_html() == "0000ffff", + "The returned RGBA HTML color code should match the expected value."); + CHECK_MESSAGE( + cyan.to_argb32() == 0xff00ffff, + "The returned 32-bit RGB number should match the expected value."); + CHECK_MESSAGE( + cyan.to_abgr32() == 0xffffff00, + "The returned 32-bit BGR number should match the expected value."); + CHECK_MESSAGE( + cyan.to_rgba32() == 0x00ffffff, + "The returned 32-bit BGR number should match the expected value."); + CHECK_MESSAGE( + cyan.to_argb64() == 0xffff'0000'ffff'ffff, + "The returned 64-bit RGB number should match the expected value."); + CHECK_MESSAGE( + cyan.to_abgr64() == 0xffff'ffff'ffff'0000, + "The returned 64-bit BGR number should match the expected value."); + CHECK_MESSAGE( + cyan.to_rgba64() == 0x0000'ffff'ffff'ffff, + "The returned 64-bit BGR number should match the expected value."); + CHECK_MESSAGE( + String(cyan) == "0, 1, 1, 1", + "The string representation should match the expected value."); +} + +TEST_CASE("[Color] Named colors") { + CHECK_MESSAGE( + Color::named("red").is_equal_approx(Color(1, 0, 0)), + "The named color \"red\" should match the expected value."); + + // Named colors have their names automatically normalized. + CHECK_MESSAGE( + Color::named("white_smoke").is_equal_approx(Color(0.96, 0.96, 0.96)), + "The named color \"white_smoke\" should match the expected value."); + CHECK_MESSAGE( + Color::named("Slate Blue").is_equal_approx(Color(0.42, 0.35, 0.80)), + "The named color \"Slate Blue\" should match the expected value."); + + ERR_PRINT_OFF; + CHECK_MESSAGE( + Color::named("doesn't exist").is_equal_approx(Color()), + "The invalid named color \"doesn't exist\" should result in a Color with the default values."); + ERR_PRINT_ON; +} + +TEST_CASE("[Color] Validation methods") { + CHECK_MESSAGE( + Color::html_is_valid("#4080ff"), + "Valid HTML color (with leading #) should be considered valid."); + CHECK_MESSAGE( + Color::html_is_valid("4080ff"), + "Valid HTML color (without leading #) should be considered valid."); + CHECK_MESSAGE( + !Color::html_is_valid("12345"), + "Invalid HTML color should be considered invalid."); + CHECK_MESSAGE( + !Color::html_is_valid("#fuf"), + "Invalid HTML color should be considered invalid."); +} + +TEST_CASE("[Color] Manipulation methods") { + const Color blue = Color(0, 0, 1, 0.4); + + CHECK_MESSAGE( + blue.inverted().is_equal_approx(Color(1, 1, 0, 0.4)), + "Inverted color should have its red, green and blue components inverted."); + CHECK_MESSAGE( + blue.contrasted().is_equal_approx(Color(0.5, 0.5, 0.5, 0.4)), + "Contrasted pure blue should be fully gray."); + + const Color purple = Color(0.5, 0.2, 0.5, 0.25); + + CHECK_MESSAGE( + purple.lightened(0.2).is_equal_approx(Color(0.6, 0.36, 0.6, 0.25)), + "Color should be lightened by the expected amount."); + CHECK_MESSAGE( + purple.darkened(0.2).is_equal_approx(Color(0.4, 0.16, 0.4, 0.25)), + "Color should be darkened by the expected amount."); + + const Color red = Color(1, 0, 0, 0.2); + const Color yellow = Color(1, 1, 0, 0.8); + + CHECK_MESSAGE( + red.lerp(yellow, 0.5).is_equal_approx(Color(1, 0.5, 0, 0.5)), + "Red interpolated with yellow should be orange (with interpolated alpha)."); +} + +} // namespace TestColor + +#endif // TEST_COLOR_H diff --git a/tests/test_macros.h b/tests/test_macros.h new file mode 100644 index 0000000000..e4494ce11a --- /dev/null +++ b/tests/test_macros.h @@ -0,0 +1,50 @@ +/*************************************************************************/ +/* test_macros.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef TEST_MACROS_H +#define TEST_MACROS_H + +// See documentation for doctest at: +// https://github.com/onqtam/doctest/blob/master/doc/markdown/readme.md#reference +#include "thirdparty/doctest/doctest.h" + +// The test is skipped with this, run pending tests with `--test --no-skip`. +#define TEST_CASE_PENDING(name) TEST_CASE(name *doctest::skip()) + +// Temporarily disable error prints to test failure paths. +// This allows to avoid polluting the test summary with error messages. +// The `_print_error_enabled` boolean is defined in `core/print_string.cpp` and +// works at global scope. It's used by various loggers in `should_log()` method, +// which are used by error macros which call into `OS::print_error`, effectively +// disabling any error messages to be printed from the engine side (not tests). +#define ERR_PRINT_OFF _print_error_enabled = false; +#define ERR_PRINT_ON _print_error_enabled = true; + +#endif // TEST_MACROS_H diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 84d2fe1f6c..137882841c 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -32,11 +32,10 @@ #include "core/list.h" -#ifdef DEBUG_ENABLED - #include "test_astar.h" #include "test_basis.h" #include "test_class_db.h" +#include "test_color.h" #include "test_gdscript.h" #include "test_gui.h" #include "test_math.h" @@ -52,39 +51,14 @@ #include "modules/modules_tests.gen.h" -#include "thirdparty/doctest/doctest.h" - -const char **tests_get_names() { - static const char *test_names[] = { - "*", - "all", - "math", - "basis", - "physics_2d", - "physics_3d", - "render", - "oa_hash_map", - "class_db", - "gui", - "shaderlang", - "gd_tokenizer", - "gd_parser", - "gd_compiler", - "gd_bytecode", - "ordered_hash_map", - "astar", - nullptr - }; - - return test_names; -} +#include "tests/test_macros.h" int test_main(int argc, char *argv[]) { - // doctest runner for when legacy unit tests are no found + // Doctest runner. doctest::Context test_context; List<String> valid_arguments; - // clean arguments of --test from the args + // Clean arguments of "--test" from the args. int argument_count = 0; for (int x = 0; x < argc; x++) { if (strncmp(argv[x], "--test", 6) != 0) { @@ -92,15 +66,15 @@ int test_main(int argc, char *argv[]) { argument_count++; } } - - // convert godot command line arguments back to standard arguments. + // Convert Godot command line arguments back to standard arguments. char **args = new char *[valid_arguments.size()]; for (int x = 0; x < valid_arguments.size(); x++) { - // operation to convert godot string to non wchar string - const char *str = valid_arguments[x].utf8().ptr(); - // allocate the string copy + // Operation to convert Godot string to non wchar string. + CharString cs = valid_arguments[x].utf8(); + const char *str = cs.get_data(); + // Allocate the string copy. args[x] = new char[strlen(str) + 1]; - // copy this into memory + // Copy this into memory. std::memcpy(args[x], str, strlen(str) + 1); } @@ -109,22 +83,11 @@ int test_main(int argc, char *argv[]) { test_context.setOption("order-by", "name"); test_context.setOption("abort-after", 5); test_context.setOption("no-breaks", true); - delete[] args; - return test_context.run(); -} - -#else -const char **tests_get_names() { - static const char *test_names[] = { - nullptr - }; - - return test_names; -} + for (int x = 0; x < valid_arguments.size(); x++) { + delete[] args[x]; + } + delete[] args; -int test_main(int argc, char *argv[]) { - return 0; + return test_context.run(); } - -#endif diff --git a/tests/test_main.h b/tests/test_main.h index 8273b74eac..983bfde402 100644 --- a/tests/test_main.h +++ b/tests/test_main.h @@ -31,11 +31,6 @@ #ifndef TEST_MAIN_H #define TEST_MAIN_H -#include "core/list.h" -#include "core/os/main_loop.h" -#include "core/ustring.h" - -const char **tests_get_names(); int test_main(int argc, char *argv[]); #endif // TEST_MAIN_H diff --git a/tests/test_string.h b/tests/test_string.h index 310be31f4b..22019a64c6 100644 --- a/tests/test_string.h +++ b/tests/test_string.h @@ -44,7 +44,7 @@ #include "modules/regex/regex.h" #endif -#include "thirdparty/doctest/doctest.h" +#include "tests/test_macros.h" namespace TestString { diff --git a/tests/test_validate_testing.h b/tests/test_validate_testing.h index 5be7d45185..24acdec96c 100644 --- a/tests/test_validate_testing.h +++ b/tests/test_validate_testing.h @@ -33,10 +33,26 @@ #include "core/os/os.h" -#include "thirdparty/doctest/doctest.h" +#include "tests/test_macros.h" -TEST_CASE("Validate Test will always pass") { - CHECK(true); +TEST_SUITE("Validate tests") { + TEST_CASE("Always pass") { + CHECK(true); + } + TEST_CASE_PENDING("Pending tests are skipped") { + if (!doctest::getContextOptions()->no_skip) { // Normal run. + FAIL("This should be skipped if `--no-skip` is NOT set (missing `doctest::skip()` decorator?)"); + } else { + CHECK_MESSAGE(true, "Pending test is run with `--no-skip`"); + } + } + TEST_CASE("Muting Godot error messages") { + ERR_PRINT_OFF; + CHECK_MESSAGE(!_print_error_enabled, "Error printing should be disabled."); + ERR_PRINT("Still waiting for Godot!"); // This should never get printed! + ERR_PRINT_ON; + CHECK_MESSAGE(_print_error_enabled, "Error printing should be re-enabled."); + } } #endif // TEST_VALIDATE_TESTING_H diff --git a/tests/test_variant.h b/tests/test_variant.h index 06dcfde664..a384a3e91f 100644 --- a/tests/test_variant.h +++ b/tests/test_variant.h @@ -34,7 +34,7 @@ #include "core/variant.h" #include "core/variant_parser.h" -#include "thirdparty/doctest/doctest.h" +#include "tests/test_macros.h" namespace TestVariant { |