diff options
82 files changed, 1819 insertions, 1732 deletions
diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp index b16e2fdf87..62d83b2e04 100644 --- a/core/bind/core_bind.cpp +++ b/core/bind/core_bind.cpp @@ -2444,7 +2444,7 @@ void _Directory::_bind_methods() { ClassDB::bind_method(D_METHOD("get_drive", "idx"), &_Directory::get_drive); ClassDB::bind_method(D_METHOD("get_current_drive"), &_Directory::get_current_drive); ClassDB::bind_method(D_METHOD("change_dir", "todir"), &_Directory::change_dir); - ClassDB::bind_method(D_METHOD("get_current_dir", "include_drive"), &_Directory::get_current_dir, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("get_current_dir"), &_Directory::get_current_dir); ClassDB::bind_method(D_METHOD("make_dir", "path"), &_Directory::make_dir); ClassDB::bind_method(D_METHOD("make_dir_recursive", "path"), &_Directory::make_dir_recursive); ClassDB::bind_method(D_METHOD("file_exists", "path"), &_Directory::file_exists); diff --git a/doc/classes/AnimationNodeStateMachine.xml b/doc/classes/AnimationNodeStateMachine.xml index 4ff39b7500..3b351a3345 100644 --- a/doc/classes/AnimationNodeStateMachine.xml +++ b/doc/classes/AnimationNodeStateMachine.xml @@ -28,17 +28,6 @@ Adds a new node to the graph. The [code]position[/code] is used for display in the editor. </description> </method> - <method name="replace_node"> - <return type="void"> - </return> - <argument index="0" name="name" type="String"> - </argument> - <argument index="1" name="node" type="AnimationNode"> - </argument> - <description> - Replaces the node and keeps its transitions unchanged. - </description> - </method> <method name="add_transition"> <return type="void"> </return> @@ -194,6 +183,16 @@ Renames the given node. </description> </method> + <method name="replace_node"> + <return type="void"> + </return> + <argument index="0" name="name" type="StringName"> + </argument> + <argument index="1" name="node" type="AnimationNode"> + </argument> + <description> + </description> + </method> <method name="set_end_node"> <return type="void"> </return> diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml index 6401feb95c..20296bbf45 100644 --- a/doc/classes/Array.xml +++ b/doc/classes/Array.xml @@ -116,7 +116,7 @@ </description> </method> <method name="back"> - <return type="void"> + <return type="Variant"> </return> <description> Returns the last element of the array, or [code]null[/code] if the array is empty. @@ -213,7 +213,7 @@ </description> </method> <method name="front"> - <return type="void"> + <return type="Variant"> </return> <description> Returns the first element of the array, or [code]null[/code] if the array is empty. @@ -260,28 +260,28 @@ </description> </method> <method name="max"> - <return type="void"> + <return type="Variant"> </return> <description> Returns the maximum value contained in the array if all elements are of comparable types. If the elements can't be compared, [code]null[/code] is returned. </description> </method> <method name="min"> - <return type="void"> + <return type="Variant"> </return> <description> Returns the minimum value contained in the array if all elements are of comparable types. If the elements can't be compared, [code]null[/code] is returned. </description> </method> <method name="pop_back"> - <return type="void"> + <return type="Variant"> </return> <description> Removes and returns the last element of the array. Returns [code]null[/code] if the array is empty. </description> </method> <method name="pop_front"> - <return type="void"> + <return type="Variant"> </return> <description> Removes and returns the first element of the array. Returns [code]null[/code] if the array is empty. diff --git a/doc/classes/Dictionary.xml b/doc/classes/Dictionary.xml index 062e72388f..540ebf3931 100644 --- a/doc/classes/Dictionary.xml +++ b/doc/classes/Dictionary.xml @@ -98,7 +98,7 @@ </description> </method> <method name="get"> - <return type="void"> + <return type="Variant"> </return> <argument index="0" name="key" type="Variant"> </argument> diff --git a/doc/classes/Signal.xml b/doc/classes/Signal.xml index 51490caf6f..1a05c02b60 100644 --- a/doc/classes/Signal.xml +++ b/doc/classes/Signal.xml @@ -33,7 +33,7 @@ </description> </method> <method name="disconnect"> - <return type="void"> + <return type="Variant"> </return> <argument index="0" name="callable" type="Callable"> </argument> diff --git a/doc/classes/Transform.xml b/doc/classes/Transform.xml index 72f9c5493a..e4d367c344 100644 --- a/doc/classes/Transform.xml +++ b/doc/classes/Transform.xml @@ -149,7 +149,7 @@ </description> </method> <method name="xform"> - <return type="void"> + <return type="Variant"> </return> <argument index="0" name="v" type="Variant"> </argument> @@ -158,7 +158,7 @@ </description> </method> <method name="xform_inv"> - <return type="void"> + <return type="Variant"> </return> <argument index="0" name="v" type="Variant"> </argument> diff --git a/doc/classes/Transform2D.xml b/doc/classes/Transform2D.xml index 164efd4e5e..af93d4c654 100644 --- a/doc/classes/Transform2D.xml +++ b/doc/classes/Transform2D.xml @@ -151,7 +151,7 @@ </description> </method> <method name="xform"> - <return type="void"> + <return type="Variant"> </return> <argument index="0" name="v" type="Variant"> </argument> @@ -160,7 +160,7 @@ </description> </method> <method name="xform_inv"> - <return type="void"> + <return type="Variant"> </return> <argument index="0" name="v" type="Variant"> </argument> diff --git a/doc/classes/VisibilityEnabler.xml b/doc/classes/VisibilityEnabler.xml index 82b952fda6..7ab6c52e6c 100644 --- a/doc/classes/VisibilityEnabler.xml +++ b/doc/classes/VisibilityEnabler.xml @@ -5,6 +5,7 @@ </brief_description> <description> The VisibilityEnabler will disable [RigidBody] and [AnimationPlayer] nodes when they are not visible. It will only affect other nodes within the same scene as the VisibilityEnabler itself. + Note that VisibilityEnabler will not affect nodes added after scene initialization. </description> <tutorials> </tutorials> diff --git a/doc/classes/VisibilityEnabler2D.xml b/doc/classes/VisibilityEnabler2D.xml index 98c3e5d78d..3f9bf6887a 100644 --- a/doc/classes/VisibilityEnabler2D.xml +++ b/doc/classes/VisibilityEnabler2D.xml @@ -5,6 +5,7 @@ </brief_description> <description> The VisibilityEnabler2D will disable [RigidBody2D], [AnimationPlayer], and other nodes when they are not visible. It will only affect nodes with the same root node as the VisibilityEnabler2D, and the root node itself. + Note that VisibilityEnabler2D will not affect nodes added after scene initialization. </description> <tutorials> </tutorials> diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 16f6883b31..61480c3c20 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -3612,6 +3612,7 @@ void EditorNode::register_editor_types() { ClassDB::register_class<ScriptCreateDialog>(); ClassDB::register_class<EditorFeatureProfile>(); ClassDB::register_class<EditorSpinSlider>(); + ClassDB::register_virtual_class<FileSystemDock>(); // FIXME: Is this stuff obsolete, or should it be ported to new APIs? ClassDB::register_class<EditorScenePostImport>(); @@ -6704,6 +6705,9 @@ EditorNode::EditorNode() { screenshot_timer->connect("timeout", callable_mp(this, &EditorNode::_request_screenshot)); add_child(screenshot_timer); screenshot_timer->set_owner(get_owner()); + + String exec = OS::get_singleton()->get_executable_path(); + EditorSettings::get_singleton()->set_project_metadata("editor_metadata", "executable_path", exec); // Save editor executable path for third-party tools } EditorNode::~EditorNode() { diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp index 5204a4d579..07a63c39ba 100644 --- a/editor/editor_plugin.cpp +++ b/editor/editor_plugin.cpp @@ -226,6 +226,10 @@ EditorFileSystem *EditorInterface::get_resource_file_system() { return EditorFileSystem::get_singleton(); } +FileSystemDock *EditorInterface::get_file_system_dock() { + return EditorNode::get_singleton()->get_filesystem_dock(); +} + EditorSelection *EditorInterface::get_selection() { return EditorNode::get_singleton()->get_editor_selection(); } @@ -295,6 +299,7 @@ void EditorInterface::_bind_methods() { ClassDB::bind_method(D_METHOD("select_file", "file"), &EditorInterface::select_file); ClassDB::bind_method(D_METHOD("get_selected_path"), &EditorInterface::get_selected_path); ClassDB::bind_method(D_METHOD("get_current_path"), &EditorInterface::get_current_path); + ClassDB::bind_method(D_METHOD("get_file_system_dock"), &EditorInterface::get_file_system_dock); ClassDB::bind_method(D_METHOD("set_plugin_enabled", "plugin", "enabled"), &EditorInterface::set_plugin_enabled); ClassDB::bind_method(D_METHOD("is_plugin_enabled", "plugin"), &EditorInterface::is_plugin_enabled); diff --git a/editor/editor_plugin.h b/editor/editor_plugin.h index 0313ef2b26..cd3f4d0638 100644 --- a/editor/editor_plugin.h +++ b/editor/editor_plugin.h @@ -53,6 +53,7 @@ class EditorSpatialGizmoPlugin; class EditorResourcePreview; class EditorFileSystem; class EditorToolAddons; +class FileSystemDock; class ScriptEditor; class EditorInterface : public Node { @@ -88,6 +89,8 @@ public: EditorResourcePreview *get_resource_previewer(); EditorFileSystem *get_resource_file_system(); + FileSystemDock *get_file_system_dock(); + Control *get_base_control(); void set_plugin_enabled(const String &p_plugin, bool p_enabled); diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp index e9e1b3be43..962d95736f 100644 --- a/editor/filesystem_dock.cpp +++ b/editor/filesystem_dock.cpp @@ -1287,12 +1287,12 @@ void FileSystemDock::_make_scene_confirm() { editor->get_editor_data().set_scene_path(idx, scene_name); } -void FileSystemDock::_file_deleted(String p_file) { - emit_signal("file_deleted", p_file); +void FileSystemDock::_file_removed(String p_file) { + emit_signal("file_removed", p_file); } -void FileSystemDock::_folder_deleted(String p_folder) { - emit_signal("folder_deleted", p_folder); +void FileSystemDock::_folder_removed(String p_folder) { + emit_signal("folder_removed", p_folder); } void FileSystemDock::_rename_operation_confirm() { @@ -2613,8 +2613,8 @@ FileSystemDock::FileSystemDock(EditorNode *p_editor) { add_child(owners_editor); remove_dialog = memnew(DependencyRemoveDialog); - remove_dialog->connect("file_removed", callable_mp(this, &FileSystemDock::_file_deleted)); - remove_dialog->connect("folder_removed", callable_mp(this, &FileSystemDock::_folder_deleted)); + remove_dialog->connect("file_removed", callable_mp(this, &FileSystemDock::_file_removed)); + remove_dialog->connect("folder_removed", callable_mp(this, &FileSystemDock::_folder_removed)); add_child(remove_dialog); move_dialog = memnew(EditorDirDialog); diff --git a/editor/filesystem_dock.h b/editor/filesystem_dock.h index 00f8cd9d50..6d2d8510d1 100644 --- a/editor/filesystem_dock.h +++ b/editor/filesystem_dock.h @@ -210,8 +210,8 @@ private: void _update_favorites_list_after_move(const Map<String, String> &p_files_renames, const Map<String, String> &p_folders_renames) const; void _update_project_settings_after_move(const Map<String, String> &p_renames) const; - void _file_deleted(String p_file); - void _folder_deleted(String p_folder); + void _file_removed(String p_file); + void _folder_removed(String p_folder); void _files_moved(String p_old_file, String p_new_file); void _folder_moved(String p_old_folder, String p_new_folder); diff --git a/methods.py b/methods.py index 28c6d0c097..56c495468d 100644 --- a/methods.py +++ b/methods.py @@ -193,25 +193,6 @@ void unregister_module_types() { return module_list -def win32_spawn(sh, escape, cmd, args, env): - import subprocess - newargs = ' '.join(args[1:]) - cmdline = cmd + " " + newargs - startupinfo = subprocess.STARTUPINFO() - for e in env: - if type(env[e]) != type(""): - env[e] = str(env[e]) - proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env) - _, err = proc.communicate() - rv = proc.wait() - if rv: - print("=====") - print(err) - print("=====") - return rv - - def disable_module(self): self.disabled_modules.append(self.current_module) diff --git a/modules/mono/config.py b/modules/mono/config.py index 70cb464c7a..a5d3059ecc 100644 --- a/modules/mono/config.py +++ b/modules/mono/config.py @@ -9,7 +9,7 @@ def configure(env): env.use_ptrcall = True env.add_module_version_string('mono') - from SCons.Script import BoolVariable, PathVariable, Variables + from SCons.Script import BoolVariable, PathVariable, Variables, Help envvars = Variables() envvars.Add(PathVariable('mono_prefix', 'Path to the mono installation directory for the target platform and architecture', '', PathVariable.PathAccept)) @@ -18,6 +18,7 @@ def configure(env): envvars.Add(BoolVariable('copy_mono_root', 'Make a copy of the mono installation directory to bundle with the editor', False)) envvars.Add(BoolVariable('xbuild_fallback', 'If MSBuild is not found, fallback to xbuild', False)) envvars.Update(env) + Help(envvars.GenerateHelpText(env)) if env['platform'] == 'javascript': # Mono wasm already has zlib builtin, so we need this workaround to avoid symbol collisions diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index c3608693f1..28bacbd0f0 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -150,8 +150,8 @@ void CSharpLanguage::finish() { for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { CSharpScriptBinding &script_binding = E->value(); - if (script_binding.gchandle.is_valid()) { - script_binding.gchandle->release(); + if (!script_binding.gchandle.is_released()) { + script_binding.gchandle.release(); script_binding.inited = false; } } @@ -461,8 +461,11 @@ static String variant_type_to_managed_name(const String &p_var_type_name) { Variant::BOOL, Variant::INT, Variant::VECTOR2, + Variant::VECTOR2I, Variant::RECT2, + Variant::RECT2I, Variant::VECTOR3, + Variant::VECTOR3I, Variant::TRANSFORM2D, Variant::PLANE, Variant::QUAT, @@ -676,7 +679,7 @@ void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) { void CSharpLanguage::frame() { if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != NULL) { - const Ref<MonoGCHandle> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle; + const Ref<MonoGCHandleRef> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle; if (task_scheduler_handle.is_valid()) { MonoObject *task_scheduler = task_scheduler_handle->get_target(); @@ -804,7 +807,7 @@ void CSharpLanguage::reload_assemblies(bool p_soft_reload) { for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) { ManagedCallable *managed_callable = elem->self(); - MonoDelegate *delegate = (MonoDelegate *)managed_callable->delegate_handle->get_target(); + MonoDelegate *delegate = (MonoDelegate *)managed_callable->delegate_handle.get_target(); Array serialized_data; MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data); @@ -1278,6 +1281,7 @@ bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) { void CSharpLanguage::_on_scripts_domain_unloaded() { for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) { CSharpScriptBinding &script_binding = E->value(); + script_binding.gchandle.release(); script_binding.inited = false; } @@ -1286,7 +1290,7 @@ void CSharpLanguage::_on_scripts_domain_unloaded() { for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) { ManagedCallable *managed_callable = elem->self(); - managed_callable->delegate_handle.unref(); + managed_callable->delegate_handle.release(); managed_callable->delegate_invoke = NULL; } } @@ -1328,33 +1332,33 @@ void CSharpLanguage::set_language_index(int p_idx) { lang_idx = p_idx; } -void CSharpLanguage::release_script_gchandle(Ref<MonoGCHandle> &p_gchandle) { +void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) { - if (!p_gchandle->is_released()) { // Do not lock unnecessarily + if (!p_gchandle.is_released()) { // Do not lock unnecessarily MutexLock lock(get_singleton()->script_gchandle_release_mutex); - p_gchandle->release(); + p_gchandle.release(); } } -void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle) { +void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, MonoGCHandleData &p_gchandle) { - uint32_t pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(p_expected_obj); // We might lock after this, so pin it + uint32_t pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(p_expected_obj); // We might lock after this, so pin it - if (!p_gchandle->is_released()) { // Do not lock unnecessarily + if (!p_gchandle.is_released()) { // Do not lock unnecessarily MutexLock lock(get_singleton()->script_gchandle_release_mutex); - MonoObject *target = p_gchandle->get_target(); + MonoObject *target = p_gchandle.get_target(); // We release the gchandle if it points to the MonoObject* we expect (otherwise it was // already released and could have been replaced) or if we can't get its target MonoObject* // (which doesn't necessarily mean it was released, and we want it released in order to // avoid locking other threads unnecessarily). if (target == p_expected_obj || target == NULL) { - p_gchandle->release(); + p_gchandle.release(); } } - MonoGCHandle::free_handle(pinned_gchandle); + GDMonoUtils::free_gchandle(pinned_gchandle); } CSharpLanguage::CSharpLanguage() { @@ -1399,7 +1403,7 @@ bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_b r_script_binding.inited = true; r_script_binding.type_name = type_name; r_script_binding.wrapper_class = type_class; // cache - r_script_binding.gchandle = MonoGCHandle::create_strong(mono_object); + r_script_binding.gchandle = MonoGCHandleData::new_strong_handle(mono_object); r_script_binding.owner = p_object; // Tie managed to unmanaged @@ -1464,10 +1468,11 @@ void CSharpLanguage::free_instance_binding_data(void *p_data) { if (script_binding.inited) { // Set the native instance field to IntPtr.Zero, if not yet garbage collected. // This is done to avoid trying to dispose the native instance from Dispose(bool). - MonoObject *mono_object = script_binding.gchandle->get_target(); + MonoObject *mono_object = script_binding.gchandle.get_target(); if (mono_object) { CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, NULL); } + script_binding.gchandle.release(); } script_bindings.erase(data); @@ -1487,26 +1492,26 @@ void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) { CRASH_COND(!data); CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); - Ref<MonoGCHandle> &gchandle = script_binding.gchandle; + MonoGCHandleData &gchandle = script_binding.gchandle; if (!script_binding.inited) return; - if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 + if (ref_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 GD_MONO_SCOPE_THREAD_ATTACH; // The reference count was increased after the managed side was the only one referencing our owner. // This means the owner is being referenced again by the unmanaged side, // so the owner must hold the managed side alive again to avoid it from being GCed. - MonoObject *target = gchandle->get_target(); + MonoObject *target = gchandle.get_target(); if (!target) return; // Called after the managed side was collected, so nothing to do here // Release the current weak handle and replace it with a strong handle. - uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(target); - gchandle->release(); - gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE); + MonoGCHandleData strong_gchandle = MonoGCHandleData::new_strong_handle(target); + gchandle.release(); + gchandle = strong_gchandle; } } @@ -1523,27 +1528,27 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) { CRASH_COND(!data); CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); - Ref<MonoGCHandle> &gchandle = script_binding.gchandle; + MonoGCHandleData &gchandle = script_binding.gchandle; int refcount = ref_owner->reference_get_count(); if (!script_binding.inited) return refcount == 0; - if (refcount == 1 && gchandle.is_valid() && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 + if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 GD_MONO_SCOPE_THREAD_ATTACH; // If owner owner is no longer referenced by the unmanaged side, // the managed instance takes responsibility of deleting the owner when GCed. - MonoObject *target = gchandle->get_target(); + MonoObject *target = gchandle.get_target(); if (!target) return refcount == 0; // Called after the managed side was collected, so nothing to do here // Release the current strong handle and replace it with a weak handle. - uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(target); - gchandle->release(); - gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE); + MonoGCHandleData weak_gchandle = MonoGCHandleData::new_weak_handle(target); + gchandle.release(); + gchandle = weak_gchandle; return false; } @@ -1551,7 +1556,7 @@ bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) { return refcount == 0; } -CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle) { +CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) { CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script))); @@ -1571,8 +1576,8 @@ CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpS MonoObject *CSharpInstance::get_mono_object() const { - ERR_FAIL_COND_V(gchandle.is_null(), NULL); - return gchandle->get_target(); + ERR_FAIL_COND_V(gchandle.is_released(), NULL); + return gchandle.get_target(); } Object *CSharpInstance::get_owner() { @@ -1945,10 +1950,6 @@ bool CSharpInstance::_unreference_owner_unsafe() { } MonoObject *CSharpInstance::_internal_new_managed() { -#ifdef DEBUG_ENABLED - CRASH_COND(!gchandle.is_valid()); -#endif - // Search the constructor first, to fail with an error if it's not found before allocating anything else. GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0); ERR_FAIL_NULL_V_MSG(ctor, NULL, @@ -1975,7 +1976,7 @@ MonoObject *CSharpInstance::_internal_new_managed() { } // Tie managed to unmanaged - gchandle = MonoGCHandle::create_strong(mono_object); + gchandle = MonoGCHandleData::new_strong_handle(mono_object); if (base_ref) _reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback) @@ -1994,7 +1995,7 @@ void CSharpInstance::mono_object_disposed(MonoObject *p_obj) { #ifdef DEBUG_ENABLED CRASH_COND(base_ref); - CRASH_COND(gchandle.is_null()); + CRASH_COND(gchandle.is_released()); #endif CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle); } @@ -2003,7 +2004,7 @@ void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_f #ifdef DEBUG_ENABLED CRASH_COND(!base_ref); - CRASH_COND(gchandle.is_null()); + CRASH_COND(gchandle.is_released()); #endif r_remove_script_instance = false; @@ -2069,7 +2070,7 @@ void CSharpInstance::refcount_incremented() { Reference *ref_owner = Object::cast_to<Reference>(owner); - if (ref_owner->reference_get_count() > 1 && gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 + if (ref_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 GD_MONO_SCOPE_THREAD_ATTACH; // The reference count was increased after the managed side was the only one referencing our owner. @@ -2077,9 +2078,9 @@ void CSharpInstance::refcount_incremented() { // so the owner must hold the managed side alive again to avoid it from being GCed. // Release the current weak handle and replace it with a strong handle. - uint32_t strong_gchandle = MonoGCHandle::new_strong_handle(gchandle->get_target()); - gchandle->release(); - gchandle->set_handle(strong_gchandle, MonoGCHandle::STRONG_HANDLE); + MonoGCHandleData strong_gchandle = MonoGCHandleData::new_strong_handle(gchandle.get_target()); + gchandle.release(); + gchandle = strong_gchandle; } } @@ -2094,16 +2095,16 @@ bool CSharpInstance::refcount_decremented() { int refcount = ref_owner->reference_get_count(); - if (refcount == 1 && !gchandle->is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 + if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0 GD_MONO_SCOPE_THREAD_ATTACH; // If owner owner is no longer referenced by the unmanaged side, // the managed instance takes responsibility of deleting the owner when GCed. // Release the current strong handle and replace it with a weak handle. - uint32_t weak_gchandle = MonoGCHandle::new_weak_handle(gchandle->get_target()); - gchandle->release(); - gchandle->set_handle(weak_gchandle, MonoGCHandle::WEAK_HANDLE); + MonoGCHandleData weak_gchandle = MonoGCHandleData::new_weak_handle(gchandle.get_target()); + gchandle.release(); + gchandle = weak_gchandle; return false; } @@ -2269,7 +2270,7 @@ CSharpInstance::~CSharpInstance() { destructing_script_instance = true; - if (gchandle.is_valid()) { + if (!gchandle.is_released()) { if (!predelete_notified && !ref_dying) { // This destructor is not called from the owners destructor. // This could be being called from the owner's set_script_instance method, @@ -2277,7 +2278,7 @@ CSharpInstance::~CSharpInstance() { // we must call Dispose here, because Dispose calls owner->set_script_instance(NULL) // and that would mess up with the new script instance if called later. - MonoObject *mono_object = gchandle->get_target(); + MonoObject *mono_object = gchandle.get_target(); if (mono_object) { MonoException *exc = NULL; @@ -2289,7 +2290,7 @@ CSharpInstance::~CSharpInstance() { } } - gchandle->release(); // Make sure the gchandle is released + gchandle.release(); // Make sure the gchandle is released } // If not being called from the owner's destructor, and we still hold a reference to the owner @@ -2449,7 +2450,7 @@ bool CSharpScript::_update_exports() { return false; } - uint32_t tmp_pinned_gchandle = MonoGCHandle::new_strong_handle_pinned(tmp_object); // pin it (not sure if needed) + uint32_t tmp_pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(tmp_object); // pin it (not sure if needed) GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0); @@ -2464,7 +2465,7 @@ bool CSharpScript::_update_exports() { if (ctor_exc) { // TODO: Should we free 'tmp_native' if the exception was thrown after its creation? - MonoGCHandle::free_handle(tmp_pinned_gchandle); + GDMonoUtils::free_gchandle(tmp_pinned_gchandle); tmp_object = NULL; ERR_PRINT("Exception thrown from constructor of temporary MonoObject:"); @@ -2543,7 +2544,7 @@ bool CSharpScript::_update_exports() { GDMonoUtils::debug_print_unhandled_exception(exc); } - MonoGCHandle::free_handle(tmp_pinned_gchandle); + GDMonoUtils::free_gchandle(tmp_pinned_gchandle); tmp_object = NULL; if (tmp_native && !base_ref) { @@ -3035,22 +3036,6 @@ void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMon bool CSharpScript::can_instance() const { #ifdef TOOLS_ENABLED - if (Engine::get_singleton()->is_editor_hint()) { - - // Hack to lower the risk of attached scripts not being added to the C# project - if (!get_path().empty() && get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted... - if (_create_project_solution_if_needed()) { - CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(), - "Compile", - ProjectSettings::get_singleton()->globalize_path(get_path())); - } else { - ERR_PRINT("C# project could not be created; cannot add file: '" + get_path() + "'."); - } - } - } -#endif - -#ifdef TOOLS_ENABLED bool extra_cond = tool || ScriptServer::is_scripting_enabled(); #else bool extra_cond = true; @@ -3109,8 +3094,8 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg CRASH_COND(data == NULL); CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); - if (script_binding.inited && script_binding.gchandle.is_valid()) { - MonoObject *mono_object = script_binding.gchandle->get_target(); + if (script_binding.inited && !script_binding.gchandle.is_released()) { + MonoObject *mono_object = script_binding.gchandle.get_target(); if (mono_object) { MonoException *exc = NULL; GDMonoUtils::dispose(mono_object, &exc); @@ -3120,6 +3105,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg } } + script_binding.gchandle.release(); // Just in case script_binding.inited = false; } } @@ -3148,7 +3134,7 @@ CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_arg } // Tie managed to unmanaged - instance->gchandle = MonoGCHandle::create_strong(mono_object); + instance->gchandle = MonoGCHandleData::new_strong_handle(mono_object); if (instance->base_ref) instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback) diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index 77f9ddb71a..53b4aa6c20 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -240,7 +240,7 @@ class CSharpInstance : public ScriptInstance { bool destructing_script_instance = false; Ref<CSharpScript> script; - Ref<MonoGCHandle> gchandle; + MonoGCHandleData gchandle; Vector<Callable> event_signal_callables; @@ -258,7 +258,7 @@ class CSharpInstance : public ScriptInstance { // Do not use unless you know what you are doing friend void GDMonoInternals::tie_managed_to_unmanaged(MonoObject *, Object *); - static CSharpInstance *create_for_managed_type(Object *p_owner, CSharpScript *p_script, const Ref<MonoGCHandle> &p_gchandle); + static CSharpInstance *create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle); void _call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount); @@ -326,8 +326,14 @@ struct CSharpScriptBinding { bool inited; StringName type_name; GDMonoClass *wrapper_class; - Ref<MonoGCHandle> gchandle; + MonoGCHandleData gchandle; Object *owner; + + CSharpScriptBinding() : + inited(false), + wrapper_class(NULL), + owner(NULL) { + } }; class ManagedCallableMiddleman : public Object { @@ -414,8 +420,8 @@ public: _FORCE_INLINE_ EditorPlugin *get_godotsharp_editor() const { return godotsharp_editor; } #endif - static void release_script_gchandle(Ref<MonoGCHandle> &p_gchandle); - static void release_script_gchandle(MonoObject *p_expected_obj, Ref<MonoGCHandle> &p_gchandle); + static void release_script_gchandle(MonoGCHandleData &p_gchandle); + static void release_script_gchandle(MonoObject *p_expected_obj, MonoGCHandleData &p_gchandle); bool debug_break(const String &p_error, bool p_allow_continue = true); bool debug_break_parse(const String &p_file, int p_line, const String &p_error); diff --git a/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs index b531b6aeee..326c49f096 100644 --- a/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs +++ b/modules/mono/editor/GodotTools/GodotTools.Core/StringExtensions.cs @@ -30,7 +30,7 @@ namespace GodotTools.Core path = string.Join(Path.DirectorySeparatorChar.ToString(), parts).Trim(); - return rooted ? Path.DirectorySeparatorChar.ToString() + path : path; + return rooted ? Path.DirectorySeparatorChar + path : path; } private static readonly string driveRoot = Path.GetPathRoot(Environment.CurrentDirectory); diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs index 36961eb45e..f0e0d1b33d 100644 --- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectExtensions.cs @@ -1,5 +1,7 @@ using GodotTools.Core; using System; +using System.Collections.Generic; +using System.IO; using DotNet.Globbing; using Microsoft.Build.Construction; @@ -7,16 +9,15 @@ namespace GodotTools.ProjectEditor { public static class ProjectExtensions { - public static bool HasItem(this ProjectRootElement root, string itemType, string include) + public static ProjectItemElement FindItemOrNull(this ProjectRootElement root, string itemType, string include, bool noCondition = false) { - GlobOptions globOptions = new GlobOptions(); - globOptions.Evaluation.CaseInsensitive = false; + GlobOptions globOptions = new GlobOptions {Evaluation = {CaseInsensitive = false}}; string normalizedInclude = include.NormalizePath(); foreach (var itemGroup in root.ItemGroups) { - if (itemGroup.Condition.Length != 0) + if (noCondition && itemGroup.Condition.Length != 0) continue; foreach (var item in itemGroup.Items) @@ -27,18 +28,65 @@ namespace GodotTools.ProjectEditor var glob = Glob.Parse(item.Include.NormalizePath(), globOptions); if (glob.IsMatch(normalizedInclude)) - { - return true; - } + return item; } } - return false; + return null; + } + public static ProjectItemElement FindItemOrNullAbs(this ProjectRootElement root, string itemType, string include, bool noCondition = false) + { + GlobOptions globOptions = new GlobOptions {Evaluation = {CaseInsensitive = false}}; + + string normalizedInclude = Path.GetFullPath(include).NormalizePath(); + + foreach (var itemGroup in root.ItemGroups) + { + if (noCondition && itemGroup.Condition.Length != 0) + continue; + + foreach (var item in itemGroup.Items) + { + if (item.ItemType != itemType) + continue; + + var glob = Glob.Parse(Path.GetFullPath(item.Include).NormalizePath(), globOptions); + + if (glob.IsMatch(normalizedInclude)) + return item; + } + } + + return null; + } + + public static IEnumerable<ProjectItemElement> FindAllItemsInFolder(this ProjectRootElement root, string itemType, string folder) + { + string absFolderNormalizedWithSep = Path.GetFullPath(folder).NormalizePath() + Path.DirectorySeparatorChar; + + foreach (var itemGroup in root.ItemGroups) + { + foreach (var item in itemGroup.Items) + { + if (item.ItemType != itemType) + continue; + + string absPathNormalized = Path.GetFullPath(item.Include).NormalizePath(); + + if (absPathNormalized.StartsWith(absFolderNormalizedWithSep)) + yield return item; + } + } + } + + public static bool HasItem(this ProjectRootElement root, string itemType, string include, bool noCondition = false) + { + return root.FindItemOrNull(itemType, include, noCondition) != null; } public static bool AddItemChecked(this ProjectRootElement root, string itemType, string include) { - if (!root.HasItem(itemType, include)) + if (!root.HasItem(itemType, include, noCondition: true)) { root.AddItem(itemType, include); return true; @@ -47,6 +95,18 @@ namespace GodotTools.ProjectEditor return false; } + public static bool RemoveItemChecked(this ProjectRootElement root, string itemType, string include) + { + var item = root.FindItemOrNullAbs(itemType, include); + if (item != null) + { + item.Parent.RemoveChild(item); + return true; + } + + return false; + } + public static Guid GetGuid(this ProjectRootElement root) { foreach (var property in root.Properties) diff --git a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs index af36f125f5..1776b46e6a 100644 --- a/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs +++ b/modules/mono/editor/GodotTools/GodotTools.ProjectEditor/ProjectUtils.cs @@ -23,6 +23,79 @@ namespace GodotTools.ProjectEditor root.Save(); } + public static void RenameItemInProjectChecked(string projectPath, string itemType, string oldInclude, string newInclude) + { + var dir = Directory.GetParent(projectPath).FullName; + var root = ProjectRootElement.Open(projectPath); + Debug.Assert(root != null); + + var normalizedOldInclude = oldInclude.NormalizePath(); + var normalizedNewInclude = newInclude.NormalizePath(); + + var item = root.FindItemOrNullAbs(itemType, normalizedOldInclude); + + if (item == null) + return; + + item.Include = normalizedNewInclude.RelativeToPath(dir).Replace("/", "\\"); + root.Save(); + } + + public static void RemoveItemFromProjectChecked(string projectPath, string itemType, string include) + { + var dir = Directory.GetParent(projectPath).FullName; + var root = ProjectRootElement.Open(projectPath); + Debug.Assert(root != null); + + var normalizedInclude = include.NormalizePath(); + + if (root.RemoveItemChecked(itemType, normalizedInclude)) + root.Save(); + } + + public static void RenameItemsToNewFolderInProjectChecked(string projectPath, string itemType, string oldFolder, string newFolder) + { + var dir = Directory.GetParent(projectPath).FullName; + var root = ProjectRootElement.Open(projectPath); + Debug.Assert(root != null); + + bool dirty = false; + + var oldFolderNormalized = oldFolder.NormalizePath(); + var newFolderNormalized = newFolder.NormalizePath(); + string absOldFolderNormalized = Path.GetFullPath(oldFolderNormalized).NormalizePath(); + string absNewFolderNormalized = Path.GetFullPath(newFolderNormalized).NormalizePath(); + + foreach (var item in root.FindAllItemsInFolder(itemType, oldFolderNormalized)) + { + string absPathNormalized = Path.GetFullPath(item.Include).NormalizePath(); + string absNewIncludeNormalized = absNewFolderNormalized + absPathNormalized.Substring(absOldFolderNormalized.Length); + item.Include = absNewIncludeNormalized.RelativeToPath(dir).Replace("/", "\\"); + dirty = true; + } + + if (dirty) + root.Save(); + } + + public static void RemoveItemsInFolderFromProjectChecked(string projectPath, string itemType, string folder) + { + var root = ProjectRootElement.Open(projectPath); + Debug.Assert(root != null); + + var folderNormalized = folder.NormalizePath(); + + var itemsToRemove = root.FindAllItemsInFolder(itemType, folderNormalized).ToList(); + + if (itemsToRemove.Count > 0) + { + foreach (var item in itemsToRemove) + item.Parent.RemoveChild(item); + + root.Save(); + } + } + private static string[] GetAllFilesRecursive(string rootDirectory, string mask) { string[] files = Directory.GetFiles(rootDirectory, mask, SearchOption.AllDirectories); diff --git a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs index 05f84f547b..022005ad0b 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Export/ExportPlugin.cs @@ -96,7 +96,7 @@ namespace GodotTools.Export if (type != Internal.CSharpLanguageType) return; - if (Path.GetExtension(path) != $".{Internal.CSharpLanguageExtension}") + if (Path.GetExtension(path) != Internal.CSharpLanguageExtension) throw new ArgumentException($"Resource of type {Internal.CSharpLanguageType} has an invalid file extension: {path}", nameof(path)); // TODO What if the source file is not part of the game's C# project diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs index e4e391765e..e6d5dd9895 100644 --- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs +++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs @@ -13,6 +13,7 @@ using JetBrains.Annotations; using static GodotTools.Internals.Globals; using File = GodotTools.Utils.File; using OS = GodotTools.Utils.OS; +using Path = System.IO.Path; namespace GodotTools { @@ -61,7 +62,7 @@ namespace GodotTools { Guid = guid, PathRelativeToSolution = name + ".csproj", - Configs = new List<string> { "Debug", "ExportDebug", "ExportRelease" } + Configs = new List<string> {"Debug", "ExportDebug", "ExportRelease"} }; solution.AddNewProject(name, projectInfo); @@ -161,6 +162,36 @@ namespace GodotTools // Once shown a first time, it can be seen again via the Mono menu - it doesn't have to be exclusive from that time on. aboutDialog.PopupExclusive = false; } + + var fileSystemDock = GetEditorInterface().GetFileSystemDock(); + + fileSystemDock.FilesMoved += (file, newFile) => + { + if (Path.GetExtension(file) == Internal.CSharpLanguageExtension) + { + ProjectUtils.RenameItemInProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile", + ProjectSettings.GlobalizePath(file), ProjectSettings.GlobalizePath(newFile)); + } + }; + + fileSystemDock.FileRemoved += file => + { + if (Path.GetExtension(file) == Internal.CSharpLanguageExtension) + ProjectUtils.RemoveItemFromProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile", + ProjectSettings.GlobalizePath(file)); + }; + + fileSystemDock.FolderMoved += (oldFolder, newFolder) => + { + ProjectUtils.RenameItemsToNewFolderInProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile", + ProjectSettings.GlobalizePath(oldFolder), ProjectSettings.GlobalizePath(newFolder)); + }; + + fileSystemDock.FolderRemoved += oldFolder => + { + ProjectUtils.RemoveItemsInFolderFromProjectChecked(GodotSharpDirs.ProjectCsProjPath, "Compile", + ProjectSettings.GlobalizePath(oldFolder)); + }; } } @@ -339,7 +370,7 @@ namespace GodotTools bottomPanelBtn = AddControlToBottomPanel(BottomPanel, "Mono".TTR()); - AddChild(new HotReloadAssemblyWatcher { Name = "HotReloadAssemblyWatcher" }); + AddChild(new HotReloadAssemblyWatcher {Name = "HotReloadAssemblyWatcher"}); menuPopup = new PopupMenu(); menuPopup.Hide(); @@ -387,7 +418,7 @@ namespace GodotTools EditorDef("mono/editor/show_info_on_start", true); // CheckBox in main container - aboutDialogCheckBox = new CheckBox { Text = "Show this warning when starting the editor" }; + aboutDialogCheckBox = new CheckBox {Text = "Show this warning when starting the editor"}; aboutDialogCheckBox.Toggled += enabled => { bool showOnStart = (bool)editorSettings.GetSetting("mono/editor/show_info_on_start"); diff --git a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs index 77740f0e53..e3a4fa7b45 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Ides/Rider/RiderPathLocator.cs @@ -162,7 +162,7 @@ namespace GodotTools.Ides.Rider private static string GetToolboxRiderRootPath(string localAppData) { - var toolboxPath = Path.Combine(localAppData, @"JetBrains\Toolbox"); + var toolboxPath = Path.Combine(localAppData, @"JetBrains/Toolbox"); var settingsJson = Path.Combine(toolboxPath, ".settings.json"); if (File.Exists(settingsJson)) @@ -172,7 +172,7 @@ namespace GodotTools.Ides.Rider toolboxPath = path; } - var toolboxRiderRootPath = Path.Combine(toolboxPath, @"apps\Rider"); + var toolboxRiderRootPath = Path.Combine(toolboxPath, @"apps/Rider"); return toolboxRiderRootPath; } diff --git a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs index 2e121ba879..026a7db89c 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Internals/Internal.cs @@ -8,7 +8,7 @@ namespace GodotTools.Internals public static class Internal { public const string CSharpLanguageType = "CSharpScript"; - public const string CSharpLanguageExtension = "cs"; + public const string CSharpLanguageExtension = ".cs"; public static string UpdateApiAssembliesFromPrebuilt(string config) => internal_UpdateApiAssembliesFromPrebuilt(config); diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index c8430234d6..9a5de6db16 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -2810,8 +2810,11 @@ bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, Ar r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; break; case Variant::VECTOR2: + case Variant::VECTOR2I: case Variant::RECT2: + case Variant::RECT2I: case Variant::VECTOR3: + case Variant::VECTOR3I: r_iarg.default_argument = "new %s" + r_iarg.default_argument; r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL; break; @@ -2891,9 +2894,12 @@ void BindingsGenerator::_populate_builtin_type_interfaces() { } INSERT_STRUCT_TYPE(Vector2) + INSERT_STRUCT_TYPE(Vector2i) INSERT_STRUCT_TYPE(Rect2) + INSERT_STRUCT_TYPE(Rect2i) INSERT_STRUCT_TYPE(Transform2D) INSERT_STRUCT_TYPE(Vector3) + INSERT_STRUCT_TYPE(Vector3i) INSERT_STRUCT_TYPE(Basis) INSERT_STRUCT_TYPE(Quat) INSERT_STRUCT_TYPE(Transform) @@ -3314,7 +3320,10 @@ void BindingsGenerator::_populate_global_constants() { // HARDCODED List<StringName> hardcoded_enums; + hardcoded_enums.push_back("Vector2.Axis"); + hardcoded_enums.push_back("Vector2i.Axis"); hardcoded_enums.push_back("Vector3.Axis"); + hardcoded_enums.push_back("Vector3i.Axis"); for (List<StringName>::Element *E = hardcoded_enums.front(); E; E = E->next()) { // These enums are not generated and must be written manually (e.g.: Vector3.Axis) // Here, we assume core types do not begin with underscore diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs new file mode 100644 index 0000000000..bc2cad8713 --- /dev/null +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Rect2i.cs @@ -0,0 +1,262 @@ +using System; +using System.Runtime.InteropServices; + +namespace Godot +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Rect2i : IEquatable<Rect2i> + { + private Vector2i _position; + private Vector2i _size; + + public Vector2i Position + { + get { return _position; } + set { _position = value; } + } + + public Vector2i Size + { + get { return _size; } + set { _size = value; } + } + + public Vector2i End + { + get { return _position + _size; } + set { _size = value - _position; } + } + + public int Area + { + get { return GetArea(); } + } + + public Rect2i Abs() + { + Vector2i end = End; + Vector2i topLeft = new Vector2i(Mathf.Min(_position.x, end.x), Mathf.Min(_position.y, end.y)); + return new Rect2i(topLeft, _size.Abs()); + } + + public Rect2i Clip(Rect2i b) + { + var newRect = b; + + if (!Intersects(newRect)) + return new Rect2i(); + + newRect._position.x = Mathf.Max(b._position.x, _position.x); + newRect._position.y = Mathf.Max(b._position.y, _position.y); + + Vector2i bEnd = b._position + b._size; + Vector2i end = _position + _size; + + newRect._size.x = Mathf.Min(bEnd.x, end.x) - newRect._position.x; + newRect._size.y = Mathf.Min(bEnd.y, end.y) - newRect._position.y; + + return newRect; + } + + public bool Encloses(Rect2i b) + { + return b._position.x >= _position.x && b._position.y >= _position.y && + b._position.x + b._size.x < _position.x + _size.x && + b._position.y + b._size.y < _position.y + _size.y; + } + + public Rect2i Expand(Vector2i to) + { + var expanded = this; + + Vector2i begin = expanded._position; + Vector2i end = expanded._position + expanded._size; + + if (to.x < begin.x) + begin.x = to.x; + if (to.y < begin.y) + begin.y = to.y; + + if (to.x > end.x) + end.x = to.x; + if (to.y > end.y) + end.y = to.y; + + expanded._position = begin; + expanded._size = end - begin; + + return expanded; + } + + public int GetArea() + { + return _size.x * _size.y; + } + + public Rect2i Grow(int by) + { + var g = this; + + g._position.x -= by; + g._position.y -= by; + g._size.x += by * 2; + g._size.y += by * 2; + + return g; + } + + public Rect2i GrowIndividual(int left, int top, int right, int bottom) + { + var g = this; + + g._position.x -= left; + g._position.y -= top; + g._size.x += left + right; + g._size.y += top + bottom; + + return g; + } + + public Rect2i GrowMargin(Margin margin, int by) + { + var g = this; + + g.GrowIndividual(Margin.Left == margin ? by : 0, + Margin.Top == margin ? by : 0, + Margin.Right == margin ? by : 0, + Margin.Bottom == margin ? by : 0); + + return g; + } + + public bool HasNoArea() + { + return _size.x <= 0 || _size.y <= 0; + } + + public bool HasPoint(Vector2i point) + { + if (point.x < _position.x) + return false; + if (point.y < _position.y) + return false; + + if (point.x >= _position.x + _size.x) + return false; + if (point.y >= _position.y + _size.y) + return false; + + return true; + } + + public bool Intersects(Rect2i b) + { + if (_position.x >= b._position.x + b._size.x) + return false; + if (_position.x + _size.x <= b._position.x) + return false; + if (_position.y >= b._position.y + b._size.y) + return false; + if (_position.y + _size.y <= b._position.y) + return false; + + return true; + } + + public Rect2i Merge(Rect2i b) + { + Rect2i newRect; + + newRect._position.x = Mathf.Min(b._position.x, _position.x); + newRect._position.y = Mathf.Min(b._position.y, _position.y); + + newRect._size.x = Mathf.Max(b._position.x + b._size.x, _position.x + _size.x); + newRect._size.y = Mathf.Max(b._position.y + b._size.y, _position.y + _size.y); + + newRect._size = newRect._size - newRect._position; // Make relative again + + return newRect; + } + + // Constructors + public Rect2i(Vector2i position, Vector2i size) + { + _position = position; + _size = size; + } + public Rect2i(Vector2i position, int width, int height) + { + _position = position; + _size = new Vector2i(width, height); + } + public Rect2i(int x, int y, Vector2i size) + { + _position = new Vector2i(x, y); + _size = size; + } + public Rect2i(int x, int y, int width, int height) + { + _position = new Vector2i(x, y); + _size = new Vector2i(width, height); + } + + public static bool operator ==(Rect2i left, Rect2i right) + { + return left.Equals(right); + } + + public static bool operator !=(Rect2i left, Rect2i right) + { + return !left.Equals(right); + } + + public static implicit operator Rect2(Rect2i value) + { + return new Rect2(value._position, value._size); + } + + public static explicit operator Rect2i(Rect2 value) + { + return new Rect2i((Vector2i)value.Position, (Vector2i)value.Size); + } + + public override bool Equals(object obj) + { + if (obj is Rect2i) + { + return Equals((Rect2i)obj); + } + + return false; + } + + public bool Equals(Rect2i other) + { + return _position.Equals(other._position) && _size.Equals(other._size); + } + + public override int GetHashCode() + { + return _position.GetHashCode() ^ _size.GetHashCode(); + } + + public override string ToString() + { + return String.Format("{0}, {1}", new object[] + { + _position.ToString(), + _size.ToString() + }); + } + + public string ToString(string format) + { + return String.Format("{0}, {1}", new object[] + { + _position.ToString(format), + _size.ToString(format) + }); + } + } +} diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs index 385bfed122..f7b13198f8 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2.cs @@ -76,11 +76,6 @@ namespace Godot } } - public real_t Cross(Vector2 b) - { - return x * b.y - y * b.x; - } - public Vector2 Abs() { return new Vector2(Mathf.Abs(x), Mathf.Abs(y)); @@ -130,6 +125,11 @@ namespace Godot return v; } + public real_t Cross(Vector2 b) + { + return x * b.y - y * b.x; + } + public Vector2 CubicInterpolate(Vector2 b, Vector2 preA, Vector2 postB, real_t t) { var p0 = preA; @@ -234,7 +234,7 @@ namespace Godot public Vector2 Reflect(Vector2 n) { - return 2.0f * n * Dot(n) - this; + return 2 * Dot(n) * n - this; } public Vector2 Rotated(real_t phi) @@ -352,18 +352,18 @@ namespace Godot return left; } - public static Vector2 operator /(Vector2 vec, real_t scale) + public static Vector2 operator /(Vector2 vec, real_t divisor) { - vec.x /= scale; - vec.y /= scale; + vec.x /= divisor; + vec.y /= divisor; return vec; } - public static Vector2 operator /(Vector2 left, Vector2 right) + public static Vector2 operator /(Vector2 vec, Vector2 divisorv) { - left.x /= right.x; - left.y /= right.y; - return left; + vec.x /= divisorv.x; + vec.y /= divisorv.y; + return vec; } public static Vector2 operator %(Vector2 vec, real_t divisor) diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs new file mode 100644 index 0000000000..7dc22d7918 --- /dev/null +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector2i.cs @@ -0,0 +1,380 @@ +using System; +using System.Runtime.InteropServices; + +#if REAL_T_IS_DOUBLE +using real_t = System.Double; +#else +using real_t = System.Single; +#endif + +namespace Godot +{ + /// <summary> + /// 2-element structure that can be used to represent 2D grid coordinates or pairs of integers. + /// </summary> + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vector2i : IEquatable<Vector2i> + { + public enum Axis + { + X = 0, + Y + } + + public int x; + public int y; + + public int this[int index] + { + get + { + switch (index) + { + case 0: + return x; + case 1: + return y; + default: + throw new IndexOutOfRangeException(); + } + } + set + { + switch (index) + { + case 0: + x = value; + return; + case 1: + y = value; + return; + default: + throw new IndexOutOfRangeException(); + } + } + } + + public Vector2i Abs() + { + return new Vector2i(Mathf.Abs(x), Mathf.Abs(y)); + } + + public real_t Angle() + { + return Mathf.Atan2(y, x); + } + + public real_t AngleTo(Vector2i to) + { + return Mathf.Atan2(Cross(to), Dot(to)); + } + + public real_t AngleToPoint(Vector2i to) + { + return Mathf.Atan2(y - to.y, x - to.x); + } + + public real_t Aspect() + { + return x / (real_t)y; + } + + public Vector2i Bounce(Vector2i n) + { + return -Reflect(n); + } + + public int Cross(Vector2i b) + { + return x * b.y - y * b.x; + } + + public int DistanceSquaredTo(Vector2i b) + { + return (b - this).LengthSquared(); + } + + public real_t DistanceTo(Vector2i b) + { + return (b - this).Length(); + } + + public int Dot(Vector2i b) + { + return x * b.x + y * b.y; + } + + public real_t Length() + { + int x2 = x * x; + int y2 = y * y; + + return Mathf.Sqrt(x2 + y2); + } + + public int LengthSquared() + { + int x2 = x * x; + int y2 = y * y; + + return x2 + y2; + } + + public Axis MaxAxis() + { + return x < y ? Axis.Y : Axis.X; + } + + public Axis MinAxis() + { + return x > y ? Axis.Y : Axis.X; + } + + public Vector2i PosMod(int mod) + { + Vector2i v = this; + v.x = Mathf.PosMod(v.x, mod); + v.y = Mathf.PosMod(v.y, mod); + return v; + } + + public Vector2i PosMod(Vector2i modv) + { + Vector2i v = this; + v.x = Mathf.PosMod(v.x, modv.x); + v.y = Mathf.PosMod(v.y, modv.y); + return v; + } + + public Vector2i Reflect(Vector2i n) + { + return 2 * Dot(n) * n - this; + } + + public Vector2i Sign() + { + Vector2i v = this; + v.x = Mathf.Sign(v.x); + v.y = Mathf.Sign(v.y); + return v; + } + + public Vector2i Tangent() + { + return new Vector2i(y, -x); + } + + // Constants + private static readonly Vector2i _zero = new Vector2i(0, 0); + private static readonly Vector2i _one = new Vector2i(1, 1); + + private static readonly Vector2i _up = new Vector2i(0, -1); + private static readonly Vector2i _down = new Vector2i(0, 1); + private static readonly Vector2i _right = new Vector2i(1, 0); + private static readonly Vector2i _left = new Vector2i(-1, 0); + + public static Vector2i Zero { get { return _zero; } } + public static Vector2i One { get { return _one; } } + + public static Vector2i Up { get { return _up; } } + public static Vector2i Down { get { return _down; } } + public static Vector2i Right { get { return _right; } } + public static Vector2i Left { get { return _left; } } + + // Constructors + public Vector2i(int x, int y) + { + this.x = x; + this.y = y; + } + public Vector2i(Vector2i vi) + { + this.x = vi.x; + this.y = vi.y; + } + public Vector2i(Vector2 v) + { + this.x = Mathf.RoundToInt(v.x); + this.y = Mathf.RoundToInt(v.y); + } + + public static Vector2i operator +(Vector2i left, Vector2i right) + { + left.x += right.x; + left.y += right.y; + return left; + } + + public static Vector2i operator -(Vector2i left, Vector2i right) + { + left.x -= right.x; + left.y -= right.y; + return left; + } + + public static Vector2i operator -(Vector2i vec) + { + vec.x = -vec.x; + vec.y = -vec.y; + return vec; + } + + public static Vector2i operator *(Vector2i vec, int scale) + { + vec.x *= scale; + vec.y *= scale; + return vec; + } + + public static Vector2i operator *(int scale, Vector2i vec) + { + vec.x *= scale; + vec.y *= scale; + return vec; + } + + public static Vector2i operator *(Vector2i left, Vector2i right) + { + left.x *= right.x; + left.y *= right.y; + return left; + } + + public static Vector2i operator /(Vector2i vec, int divisor) + { + vec.x /= divisor; + vec.y /= divisor; + return vec; + } + + public static Vector2i operator /(Vector2i vec, Vector2i divisorv) + { + vec.x /= divisorv.x; + vec.y /= divisorv.y; + return vec; + } + + public static Vector2i operator %(Vector2i vec, int divisor) + { + vec.x %= divisor; + vec.y %= divisor; + return vec; + } + + public static Vector2i operator %(Vector2i vec, Vector2i divisorv) + { + vec.x %= divisorv.x; + vec.y %= divisorv.y; + return vec; + } + + public static Vector2i operator &(Vector2i vec, int and) + { + vec.x &= and; + vec.y &= and; + return vec; + } + + public static Vector2i operator &(Vector2i vec, Vector2i andv) + { + vec.x &= andv.x; + vec.y &= andv.y; + return vec; + } + + public static bool operator ==(Vector2i left, Vector2i right) + { + return left.Equals(right); + } + + public static bool operator !=(Vector2i left, Vector2i right) + { + return !left.Equals(right); + } + + public static bool operator <(Vector2i left, Vector2i right) + { + if (left.x.Equals(right.x)) + { + return left.y < right.y; + } + return left.x < right.x; + } + + public static bool operator >(Vector2i left, Vector2i right) + { + if (left.x.Equals(right.x)) + { + return left.y > right.y; + } + return left.x > right.x; + } + + public static bool operator <=(Vector2i left, Vector2i right) + { + if (left.x.Equals(right.x)) + { + return left.y <= right.y; + } + return left.x <= right.x; + } + + public static bool operator >=(Vector2i left, Vector2i right) + { + if (left.x.Equals(right.x)) + { + return left.y >= right.y; + } + return left.x >= right.x; + } + + public static implicit operator Vector2(Vector2i value) + { + return new Vector2(value.x, value.y); + } + + public static explicit operator Vector2i(Vector2 value) + { + return new Vector2i(value); + } + + public override bool Equals(object obj) + { + if (obj is Vector2i) + { + return Equals((Vector2i)obj); + } + + return false; + } + + public bool Equals(Vector2i other) + { + return x == other.x && y == other.y; + } + + public override int GetHashCode() + { + return y.GetHashCode() ^ x.GetHashCode(); + } + + public override string ToString() + { + return String.Format("({0}, {1})", new object[] + { + this.x.ToString(), + this.y.ToString() + }); + } + + public string ToString(string format) + { + return String.Format("({0}, {1})", new object[] + { + this.x.ToString(format), + this.y.ToString(format) + }); + } + } +} diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs index 390036c654..a43836e985 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3.cs @@ -400,20 +400,20 @@ namespace Godot return left; } - public static Vector3 operator /(Vector3 vec, real_t scale) + public static Vector3 operator /(Vector3 vec, real_t divisor) { - vec.x /= scale; - vec.y /= scale; - vec.z /= scale; + vec.x /= divisor; + vec.y /= divisor; + vec.z /= divisor; return vec; } - public static Vector3 operator /(Vector3 left, Vector3 right) + public static Vector3 operator /(Vector3 vec, Vector3 divisorv) { - left.x /= right.x; - left.y /= right.y; - left.z /= right.z; - return left; + vec.x /= divisorv.x; + vec.y /= divisorv.y; + vec.z /= divisorv.z; + return vec; } public static Vector3 operator %(Vector3 vec, real_t divisor) diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs new file mode 100644 index 0000000000..c17f900131 --- /dev/null +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/Vector3i.cs @@ -0,0 +1,402 @@ +using System; +using System.Runtime.InteropServices; + +#if REAL_T_IS_DOUBLE +using real_t = System.Double; +#else +using real_t = System.Single; +#endif + +namespace Godot +{ + /// <summary> + /// 3-element structure that can be used to represent 3D grid coordinates or sets of integers. + /// </summary> + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct Vector3i : IEquatable<Vector3i> + { + public enum Axis + { + X = 0, + Y, + Z + } + + public int x; + public int y; + public int z; + + public int this[int index] + { + get + { + switch (index) + { + case 0: + return x; + case 1: + return y; + case 2: + return z; + default: + throw new IndexOutOfRangeException(); + } + } + set + { + switch (index) + { + case 0: + x = value; + return; + case 1: + y = value; + return; + case 2: + z = value; + return; + default: + throw new IndexOutOfRangeException(); + } + } + } + + public Vector3i Abs() + { + Vector3i v = this; + if (v.x < 0) + { + v.x = -v.x; + } + if (v.y < 0) + { + v.y = -v.y; + } + if (v.z < 0) + { + v.z = -v.z; + } + return v; + } + + public int DistanceSquaredTo(Vector3i b) + { + return (b - this).LengthSquared(); + } + + public real_t DistanceTo(Vector3i b) + { + return (b - this).Length(); + } + + public int Dot(Vector3i b) + { + return x * b.x + y * b.y + z * b.z; + } + + public real_t Length() + { + int x2 = x * x; + int y2 = y * y; + int z2 = z * z; + + return Mathf.Sqrt(x2 + y2 + z2); + } + + public int LengthSquared() + { + int x2 = x * x; + int y2 = y * y; + int z2 = z * z; + + return x2 + y2 + z2; + } + + public Axis MaxAxis() + { + return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X); + } + + public Axis MinAxis() + { + return x < y ? (x < z ? Axis.X : Axis.Z) : (y < z ? Axis.Y : Axis.Z); + } + + public Vector3i PosMod(int mod) + { + Vector3i v = this; + v.x = Mathf.PosMod(v.x, mod); + v.y = Mathf.PosMod(v.y, mod); + v.z = Mathf.PosMod(v.z, mod); + return v; + } + + public Vector3i PosMod(Vector3i modv) + { + Vector3i v = this; + v.x = Mathf.PosMod(v.x, modv.x); + v.y = Mathf.PosMod(v.y, modv.y); + v.z = Mathf.PosMod(v.z, modv.z); + return v; + } + + public Vector3i Sign() + { + Vector3i v = this; + v.x = Mathf.Sign(v.x); + v.y = Mathf.Sign(v.y); + v.z = Mathf.Sign(v.z); + return v; + } + + // Constants + private static readonly Vector3i _zero = new Vector3i(0, 0, 0); + private static readonly Vector3i _one = new Vector3i(1, 1, 1); + + private static readonly Vector3i _up = new Vector3i(0, 1, 0); + private static readonly Vector3i _down = new Vector3i(0, -1, 0); + private static readonly Vector3i _right = new Vector3i(1, 0, 0); + private static readonly Vector3i _left = new Vector3i(-1, 0, 0); + private static readonly Vector3i _forward = new Vector3i(0, 0, -1); + private static readonly Vector3i _back = new Vector3i(0, 0, 1); + + public static Vector3i Zero { get { return _zero; } } + public static Vector3i One { get { return _one; } } + + public static Vector3i Up { get { return _up; } } + public static Vector3i Down { get { return _down; } } + public static Vector3i Right { get { return _right; } } + public static Vector3i Left { get { return _left; } } + public static Vector3i Forward { get { return _forward; } } + public static Vector3i Back { get { return _back; } } + + // Constructors + public Vector3i(int x, int y, int z) + { + this.x = x; + this.y = y; + this.z = z; + } + public Vector3i(Vector3i vi) + { + this.x = vi.x; + this.y = vi.y; + this.z = vi.z; + } + public Vector3i(Vector3 v) + { + this.x = Mathf.RoundToInt(v.x); + this.y = Mathf.RoundToInt(v.y); + this.z = Mathf.RoundToInt(v.z); + } + + public static Vector3i operator +(Vector3i left, Vector3i right) + { + left.x += right.x; + left.y += right.y; + left.z += right.z; + return left; + } + + public static Vector3i operator -(Vector3i left, Vector3i right) + { + left.x -= right.x; + left.y -= right.y; + left.z -= right.z; + return left; + } + + public static Vector3i operator -(Vector3i vec) + { + vec.x = -vec.x; + vec.y = -vec.y; + vec.z = -vec.z; + return vec; + } + + public static Vector3i operator *(Vector3i vec, int scale) + { + vec.x *= scale; + vec.y *= scale; + vec.z *= scale; + return vec; + } + + public static Vector3i operator *(int scale, Vector3i vec) + { + vec.x *= scale; + vec.y *= scale; + vec.z *= scale; + return vec; + } + + public static Vector3i operator *(Vector3i left, Vector3i right) + { + left.x *= right.x; + left.y *= right.y; + left.z *= right.z; + return left; + } + + public static Vector3i operator /(Vector3i vec, int divisor) + { + vec.x /= divisor; + vec.y /= divisor; + vec.z /= divisor; + return vec; + } + + public static Vector3i operator /(Vector3i vec, Vector3i divisorv) + { + vec.x /= divisorv.x; + vec.y /= divisorv.y; + vec.z /= divisorv.z; + return vec; + } + + public static Vector3i operator %(Vector3i vec, int divisor) + { + vec.x %= divisor; + vec.y %= divisor; + vec.z %= divisor; + return vec; + } + + public static Vector3i operator %(Vector3i vec, Vector3i divisorv) + { + vec.x %= divisorv.x; + vec.y %= divisorv.y; + vec.z %= divisorv.z; + return vec; + } + + public static Vector3i operator &(Vector3i vec, int and) + { + vec.x &= and; + vec.y &= and; + vec.z &= and; + return vec; + } + + public static Vector3i operator &(Vector3i vec, Vector3i andv) + { + vec.x &= andv.x; + vec.y &= andv.y; + vec.z &= andv.z; + return vec; + } + + public static bool operator ==(Vector3i left, Vector3i right) + { + return left.Equals(right); + } + + public static bool operator !=(Vector3i left, Vector3i right) + { + return !left.Equals(right); + } + + public static bool operator <(Vector3i left, Vector3i right) + { + if (left.x == right.x) + { + if (left.y == right.y) + return left.z < right.z; + else + return left.y < right.y; + } + + return left.x < right.x; + } + + public static bool operator >(Vector3i left, Vector3i right) + { + if (left.x == right.x) + { + if (left.y == right.y) + return left.z > right.z; + else + return left.y > right.y; + } + + return left.x > right.x; + } + + public static bool operator <=(Vector3i left, Vector3i right) + { + if (left.x == right.x) + { + if (left.y == right.y) + return left.z <= right.z; + else + return left.y < right.y; + } + + return left.x < right.x; + } + + public static bool operator >=(Vector3i left, Vector3i right) + { + if (left.x == right.x) + { + if (left.y == right.y) + return left.z >= right.z; + else + return left.y > right.y; + } + + return left.x > right.x; + } + + public static implicit operator Vector3(Vector3i value) + { + return new Vector3(value.x, value.y, value.z); + } + + public static explicit operator Vector3i(Vector3 value) + { + return new Vector3i(value); + } + + public override bool Equals(object obj) + { + if (obj is Vector3i) + { + return Equals((Vector3i)obj); + } + + return false; + } + + public bool Equals(Vector3i other) + { + return x == other.x && y == other.y && z == other.z; + } + + public override int GetHashCode() + { + return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode(); + } + + public override string ToString() + { + return String.Format("({0}, {1}, {2})", new object[] + { + this.x.ToString(), + this.y.ToString(), + this.z.ToString() + }); + } + + public string ToString(string format) + { + return String.Format("({0}, {1}, {2})", new object[] + { + this.x.ToString(format), + this.y.ToString(format), + this.z.ToString(format) + }); + } + } +} diff --git a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj index 799322c529..ba0bbd7630 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj +++ b/modules/mono/glue/GodotSharp/GodotSharp/GodotSharp.csproj @@ -67,6 +67,7 @@ <Compile Include="Core\Plane.cs" /> <Compile Include="Core\Quat.cs" /> <Compile Include="Core\Rect2.cs" /> + <Compile Include="Core\Rect2i.cs" /> <Compile Include="Core\RID.cs" /> <Compile Include="Core\SignalInfo.cs" /> <Compile Include="Core\SignalAwaiter.cs" /> @@ -75,7 +76,9 @@ <Compile Include="Core\Transform.cs" /> <Compile Include="Core\Transform2D.cs" /> <Compile Include="Core\Vector2.cs" /> + <Compile Include="Core\Vector2i.cs" /> <Compile Include="Core\Vector3.cs" /> + <Compile Include="Core\Vector3i.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <!-- diff --git a/modules/mono/glue/base_object_glue.cpp b/modules/mono/glue/base_object_glue.cpp index f7a2e7f1e7..120668d1ef 100644 --- a/modules/mono/glue/base_object_glue.cpp +++ b/modules/mono/glue/base_object_glue.cpp @@ -70,8 +70,8 @@ void godot_icall_Object_Disposed(MonoObject *p_obj, Object *p_ptr) { if (data) { CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); if (script_binding.inited) { - Ref<MonoGCHandle> &gchandle = script_binding.gchandle; - if (gchandle.is_valid()) { + MonoGCHandleData &gchandle = script_binding.gchandle; + if (!gchandle.is_released()) { CSharpLanguage::release_script_gchandle(p_obj, gchandle); } } @@ -117,8 +117,8 @@ void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolea if (data) { CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get(); if (script_binding.inited) { - Ref<MonoGCHandle> &gchandle = script_binding.gchandle; - if (gchandle.is_valid()) { + MonoGCHandleData &gchandle = script_binding.gchandle; + if (!gchandle.is_released()) { CSharpLanguage::release_script_gchandle(p_obj, gchandle); } } diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index 47eb432490..828ab73c82 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -49,13 +49,13 @@ namespace GodotSharpDirs { String _get_expected_build_config() { #ifdef TOOLS_ENABLED - return "Tools"; + return "Debug"; #else #ifdef DEBUG_ENABLED - return "Debug"; + return "ExportDebug"; #else - return "Release"; + return "ExportRelease"; #endif #endif diff --git a/modules/mono/managed_callable.cpp b/modules/mono/managed_callable.cpp index 75420612fc..a9cf64d1cc 100644 --- a/modules/mono/managed_callable.cpp +++ b/modules/mono/managed_callable.cpp @@ -44,8 +44,8 @@ bool ManagedCallable::compare_equal(const CallableCustom *p_a, const CallableCus const ManagedCallable *a = static_cast<const ManagedCallable *>(p_a); const ManagedCallable *b = static_cast<const ManagedCallable *>(p_b); - MonoDelegate *delegate_a = (MonoDelegate *)a->delegate_handle->get_target(); - MonoDelegate *delegate_b = (MonoDelegate *)b->delegate_handle->get_target(); + MonoDelegate *delegate_a = (MonoDelegate *)a->delegate_handle.get_target(); + MonoDelegate *delegate_b = (MonoDelegate *)b->delegate_handle.get_target(); if (!delegate_a || !delegate_b) { if (!delegate_a && !delegate_b) @@ -66,7 +66,7 @@ bool ManagedCallable::compare_less(const CallableCustom *p_a, const CallableCust uint32_t ManagedCallable::hash() const { // hmm uint32_t hash = delegate_invoke->get_name().hash(); - return hash_djb2_one_64(delegate_handle.ptr()->handle, hash); + return hash_djb2_one_64(delegate_handle.handle, hash); } String ManagedCallable::get_as_text() const { @@ -92,12 +92,12 @@ void ManagedCallable::call(const Variant **p_arguments, int p_argcount, Variant #ifdef GD_MONO_HOT_RELOAD // Lost during hot-reload ERR_FAIL_NULL(delegate_invoke); - ERR_FAIL_COND(delegate_handle.is_null()); + ERR_FAIL_COND(delegate_handle.is_released()); #endif ERR_FAIL_COND(delegate_invoke->get_parameters_count() < p_argcount); - MonoObject *delegate = delegate_handle->get_target(); + MonoObject *delegate = delegate_handle.get_target(); MonoException *exc = NULL; MonoObject *ret = delegate_invoke->invoke(delegate, p_arguments, &exc); @@ -111,7 +111,7 @@ void ManagedCallable::call(const Variant **p_arguments, int p_argcount, Variant } void ManagedCallable::set_delegate(MonoDelegate *p_delegate) { - delegate_handle = MonoGCHandle::create_strong((MonoObject *)p_delegate); + delegate_handle = MonoGCHandleData::new_strong_handle((MonoObject *)p_delegate); MonoMethod *delegate_invoke_raw = mono_get_delegate_invoke(mono_object_get_class((MonoObject *)p_delegate)); const StringName &delegate_invoke_name = CSharpLanguage::get_singleton()->get_string_names().delegate_invoke_method_name; delegate_invoke = memnew(GDMonoMethod(delegate_invoke_name, delegate_invoke_raw)); // TODO: Use pooling for this GDMonoMethod instances @@ -132,12 +132,14 @@ ManagedCallable::ManagedCallable(MonoDelegate *p_delegate) { #endif } -#ifdef GD_MONO_HOT_RELOAD ManagedCallable::~ManagedCallable() { +#ifdef GD_MONO_HOT_RELOAD { MutexLock lock(instances_mutex); instances.remove(&self_instance); instances_pending_reload.erase(this); } -} #endif + + delegate_handle.release(); +} diff --git a/modules/mono/managed_callable.h b/modules/mono/managed_callable.h index 34963a82ea..4f71e14a2f 100644 --- a/modules/mono/managed_callable.h +++ b/modules/mono/managed_callable.h @@ -42,7 +42,7 @@ class ManagedCallable : public CallableCustom { friend class CSharpLanguage; - Ref<MonoGCHandle> delegate_handle; + MonoGCHandleData delegate_handle; GDMonoMethod *delegate_invoke; #ifdef GD_MONO_HOT_RELOAD @@ -60,7 +60,7 @@ public: ObjectID get_object() const override; void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override; - _FORCE_INLINE_ MonoDelegate *get_delegate() { return (MonoDelegate *)delegate_handle->get_target(); } + _FORCE_INLINE_ MonoDelegate *get_delegate() { return (MonoDelegate *)delegate_handle.get_target(); } void set_delegate(MonoDelegate *p_delegate); @@ -71,9 +71,7 @@ public: static constexpr CompareEqualFunc compare_less_func_ptr = &ManagedCallable::compare_less; ManagedCallable(MonoDelegate *p_delegate); -#ifdef GD_MONO_HOT_RELOAD ~ManagedCallable(); -#endif }; #endif // MANAGED_CALLABLE_H diff --git a/modules/mono/mono_gc_handle.cpp b/modules/mono/mono_gc_handle.cpp index feeea848ee..4b6d7269e9 100644 --- a/modules/mono/mono_gc_handle.cpp +++ b/modules/mono/mono_gc_handle.cpp @@ -32,56 +32,35 @@ #include "mono_gd/gd_mono.h" -uint32_t MonoGCHandle::new_strong_handle(MonoObject *p_object) { - - return mono_gchandle_new(p_object, /* pinned: */ false); -} - -uint32_t MonoGCHandle::new_strong_handle_pinned(MonoObject *p_object) { - - return mono_gchandle_new(p_object, /* pinned: */ true); -} - -uint32_t MonoGCHandle::new_weak_handle(MonoObject *p_object) { - - return mono_gchandle_new_weakref(p_object, /* track_resurrection: */ false); -} - -void MonoGCHandle::free_handle(uint32_t p_gchandle) { +void MonoGCHandleData::release() { +#ifdef DEBUG_ENABLED + CRASH_COND(handle && GDMono::get_singleton() == NULL); +#endif - mono_gchandle_free(p_gchandle); + if (handle && GDMono::get_singleton()->is_runtime_initialized()) { + GDMonoUtils::free_gchandle(handle); + handle = 0; + } } -Ref<MonoGCHandle> MonoGCHandle::create_strong(MonoObject *p_object) { - - return memnew(MonoGCHandle(new_strong_handle(p_object), STRONG_HANDLE)); +MonoGCHandleData MonoGCHandleData::new_strong_handle(MonoObject *p_object) { + return MonoGCHandleData(GDMonoUtils::new_strong_gchandle(p_object), gdmono::GCHandleType::STRONG_HANDLE); } -Ref<MonoGCHandle> MonoGCHandle::create_weak(MonoObject *p_object) { - - return memnew(MonoGCHandle(new_weak_handle(p_object), WEAK_HANDLE)); +MonoGCHandleData MonoGCHandleData::new_strong_handle_pinned(MonoObject *p_object) { + return MonoGCHandleData(GDMonoUtils::new_strong_gchandle_pinned(p_object), gdmono::GCHandleType::STRONG_HANDLE); } -void MonoGCHandle::release() { - -#ifdef DEBUG_ENABLED - CRASH_COND(!released && GDMono::get_singleton() == NULL); -#endif - - if (!released && GDMono::get_singleton()->is_runtime_initialized()) { - free_handle(handle); - released = true; - } +MonoGCHandleData MonoGCHandleData::new_weak_handle(MonoObject *p_object) { + return MonoGCHandleData(GDMonoUtils::new_weak_gchandle(p_object), gdmono::GCHandleType::WEAK_HANDLE); } -MonoGCHandle::MonoGCHandle(uint32_t p_handle, HandleType p_handle_type) { +Ref<MonoGCHandleRef> MonoGCHandleRef::create_strong(MonoObject *p_object) { - released = false; - weak = p_handle_type == WEAK_HANDLE; - handle = p_handle; + return memnew(MonoGCHandleRef(MonoGCHandleData::new_strong_handle(p_object))); } -MonoGCHandle::~MonoGCHandle() { +Ref<MonoGCHandleRef> MonoGCHandleRef::create_weak(MonoObject *p_object) { - release(); + return memnew(MonoGCHandleRef(MonoGCHandleData::new_weak_handle(p_object))); } diff --git a/modules/mono/mono_gc_handle.h b/modules/mono/mono_gc_handle.h index 8f664dadd0..705b2265ba 100644 --- a/modules/mono/mono_gc_handle.h +++ b/modules/mono/mono_gc_handle.h @@ -35,44 +35,79 @@ #include "core/reference.h" -class MonoGCHandle : public Reference { +namespace gdmono { - GDCLASS(MonoGCHandle, Reference); +enum class GCHandleType : char { + NIL, + STRONG_HANDLE, + WEAK_HANDLE +}; - bool released; - bool weak; +} - friend class ManagedCallable; +// Manual release of the GC handle must be done when using this struct +struct MonoGCHandleData { uint32_t handle; + gdmono::GCHandleType type; -public: - enum HandleType { - STRONG_HANDLE, - WEAK_HANDLE - }; + _FORCE_INLINE_ bool is_released() const { return !handle; } + _FORCE_INLINE_ bool is_weak() const { return type == gdmono::GCHandleType::WEAK_HANDLE; } - static uint32_t new_strong_handle(MonoObject *p_object); - static uint32_t new_strong_handle_pinned(MonoObject *p_object); - static uint32_t new_weak_handle(MonoObject *p_object); - static void free_handle(uint32_t p_gchandle); + _FORCE_INLINE_ MonoObject *get_target() const { return handle ? mono_gchandle_get_target(handle) : NULL; } - static Ref<MonoGCHandle> create_strong(MonoObject *p_object); - static Ref<MonoGCHandle> create_weak(MonoObject *p_object); + void release(); - _FORCE_INLINE_ bool is_released() { return released; } - _FORCE_INLINE_ bool is_weak() { return weak; } + MonoGCHandleData &operator=(const MonoGCHandleData &p_other) { +#ifdef DEBUG_ENABLED + CRASH_COND(!is_released()); +#endif + handle = p_other.handle; + type = p_other.type; + return *this; + } - _FORCE_INLINE_ MonoObject *get_target() const { return released ? NULL : mono_gchandle_get_target(handle); } + MonoGCHandleData(const MonoGCHandleData &) = default; - _FORCE_INLINE_ void set_handle(uint32_t p_handle, HandleType p_handle_type) { - released = false; - weak = p_handle_type == WEAK_HANDLE; - handle = p_handle; + MonoGCHandleData() : + handle(0), + type(gdmono::GCHandleType::NIL) { } - void release(); - MonoGCHandle(uint32_t p_handle, HandleType p_handle_type); - ~MonoGCHandle(); + MonoGCHandleData(uint32_t p_handle, gdmono::GCHandleType p_type) : + handle(p_handle), + type(p_type) { + } + + static MonoGCHandleData new_strong_handle(MonoObject *p_object); + static MonoGCHandleData new_strong_handle_pinned(MonoObject *p_object); + static MonoGCHandleData new_weak_handle(MonoObject *p_object); +}; + +class MonoGCHandleRef : public Reference { + + GDCLASS(MonoGCHandleRef, Reference); + + MonoGCHandleData data; + +public: + static Ref<MonoGCHandleRef> create_strong(MonoObject *p_object); + static Ref<MonoGCHandleRef> create_weak(MonoObject *p_object); + + _FORCE_INLINE_ bool is_released() const { return data.is_released(); } + _FORCE_INLINE_ bool is_weak() const { return data.is_weak(); } + + _FORCE_INLINE_ MonoObject *get_target() const { return data.get_target(); } + + void release() { data.release(); } + + _FORCE_INLINE_ void set_handle(uint32_t p_handle, gdmono::GCHandleType p_handle_type) { + data = MonoGCHandleData(p_handle, p_handle_type); + } + + MonoGCHandleRef(const MonoGCHandleData &p_gc_handle_data) : + data(p_gc_handle_data) { + } + ~MonoGCHandleRef() { release(); } }; #endif // CSHARP_GC_HANDLE_H diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp index 57b7653a00..6da1db249c 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.cpp +++ b/modules/mono/mono_gd/gd_mono_assembly.cpp @@ -78,7 +78,7 @@ void GDMonoAssembly::fill_search_dirs(Vector<String> &r_search_dirs, const Strin if (p_custom_config.empty()) { r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir()); } else { - String api_config = p_custom_config == "Release" ? "Release" : "Debug"; + String api_config = p_custom_config == "ExportRelease" ? "Release" : "Debug"; r_search_dirs.push_back(GodotSharpDirs::get_res_assemblies_base_dir().plus_file(api_config)); } diff --git a/modules/mono/mono_gd/gd_mono_cache.cpp b/modules/mono/mono_gd/gd_mono_cache.cpp index 7a3234b69b..be0b846702 100644 --- a/modules/mono/mono_gd/gd_mono_cache.cpp +++ b/modules/mono/mono_gd/gd_mono_cache.cpp @@ -103,9 +103,12 @@ void CachedData::clear_godot_api_cache() { rawclass_Dictionary = NULL; class_Vector2 = NULL; + class_Vector2i = NULL; class_Rect2 = NULL; + class_Rect2i = NULL; class_Transform2D = NULL; class_Vector3 = NULL; + class_Vector3i = NULL; class_Basis = NULL; class_Quat = NULL; class_Transform = NULL; @@ -186,7 +189,7 @@ void CachedData::clear_godot_api_cache() { // End of MarshalUtils methods - task_scheduler_handle = Ref<MonoGCHandle>(); + task_scheduler_handle = Ref<MonoGCHandleRef>(); } #define GODOT_API_CLASS(m_class) (GDMono::get_singleton()->get_core_api_assembly()->get_class(BINDINGS_NAMESPACE, #m_class)) @@ -229,9 +232,12 @@ void update_corlib_cache() { void update_godot_api_cache() { CACHE_CLASS_AND_CHECK(Vector2, GODOT_API_CLASS(Vector2)); + CACHE_CLASS_AND_CHECK(Vector2i, GODOT_API_CLASS(Vector2i)); CACHE_CLASS_AND_CHECK(Rect2, GODOT_API_CLASS(Rect2)); + CACHE_CLASS_AND_CHECK(Rect2i, GODOT_API_CLASS(Rect2i)); CACHE_CLASS_AND_CHECK(Transform2D, GODOT_API_CLASS(Transform2D)); CACHE_CLASS_AND_CHECK(Vector3, GODOT_API_CLASS(Vector3)); + CACHE_CLASS_AND_CHECK(Vector3i, GODOT_API_CLASS(Vector3i)); CACHE_CLASS_AND_CHECK(Basis, GODOT_API_CLASS(Basis)); CACHE_CLASS_AND_CHECK(Quat, GODOT_API_CLASS(Quat)); CACHE_CLASS_AND_CHECK(Transform, GODOT_API_CLASS(Transform)); @@ -316,7 +322,7 @@ void update_godot_api_cache() { // TODO Move to CSharpLanguage::init() and do handle disposal MonoObject *task_scheduler = mono_object_new(mono_domain_get(), GODOT_API_CLASS(GodotTaskScheduler)->get_mono_ptr()); GDMonoUtils::runtime_object_init(task_scheduler, GODOT_API_CLASS(GodotTaskScheduler)); - cached_data.task_scheduler_handle = MonoGCHandle::create_strong(task_scheduler); + cached_data.task_scheduler_handle = MonoGCHandleRef::create_strong(task_scheduler); cached_data.godot_api_cache_updated = true; } diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index 74a8d445c6..b2dacee67c 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -73,9 +73,12 @@ struct CachedData { // ----------------------------------------------- GDMonoClass *class_Vector2; + GDMonoClass *class_Vector2i; GDMonoClass *class_Rect2; + GDMonoClass *class_Rect2i; GDMonoClass *class_Transform2D; GDMonoClass *class_Vector3; + GDMonoClass *class_Vector3i; GDMonoClass *class_Basis; GDMonoClass *class_Quat; GDMonoClass *class_Transform; @@ -156,7 +159,7 @@ struct CachedData { // End of MarshalUtils methods - Ref<MonoGCHandle> task_scheduler_handle; + Ref<MonoGCHandleRef> task_scheduler_handle; bool corlib_cache_updated; bool godot_api_cache_updated; diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp index 76d781cc4d..11942c47d9 100644 --- a/modules/mono/mono_gd/gd_mono_field.cpp +++ b/modules/mono/mono_gd/gd_mono_field.cpp @@ -132,11 +132,21 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ break; } + if (tclass == CACHED_CLASS(Vector2i)) { + SET_FROM_STRUCT(Vector2i); + break; + } + if (tclass == CACHED_CLASS(Rect2)) { SET_FROM_STRUCT(Rect2); break; } + if (tclass == CACHED_CLASS(Rect2i)) { + SET_FROM_STRUCT(Rect2i); + break; + } + if (tclass == CACHED_CLASS(Transform2D)) { SET_FROM_STRUCT(Transform2D); break; @@ -147,6 +157,11 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ break; } + if (tclass == CACHED_CLASS(Vector3i)) { + SET_FROM_STRUCT(Vector3i); + break; + } + if (tclass == CACHED_CLASS(Basis)) { SET_FROM_STRUCT(Basis); break; @@ -418,12 +433,21 @@ void GDMonoField::set_value_from_variant(MonoObject *p_object, const Variant &p_ case Variant::VECTOR2: { SET_FROM_STRUCT(Vector2); } break; + case Variant::VECTOR2I: { + SET_FROM_STRUCT(Vector2i); + } break; case Variant::RECT2: { SET_FROM_STRUCT(Rect2); } break; + case Variant::RECT2I: { + SET_FROM_STRUCT(Rect2i); + } break; case Variant::VECTOR3: { SET_FROM_STRUCT(Vector3); } break; + case Variant::VECTOR3I: { + SET_FROM_STRUCT(Vector3i); + } break; case Variant::TRANSFORM2D: { SET_FROM_STRUCT(Transform2D); } break; diff --git a/modules/mono/mono_gd/gd_mono_internals.cpp b/modules/mono/mono_gd/gd_mono_internals.cpp index f343a1d646..53e642f317 100644 --- a/modules/mono/mono_gd/gd_mono_internals.cpp +++ b/modules/mono/mono_gd/gd_mono_internals.cpp @@ -75,7 +75,7 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { script_binding.inited = true; script_binding.type_name = NATIVE_GDMONOCLASS_NAME(klass); script_binding.wrapper_class = klass; - script_binding.gchandle = ref ? MonoGCHandle::create_weak(managed) : MonoGCHandle::create_strong(managed); + script_binding.gchandle = ref ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); script_binding.owner = unmanaged; if (ref) { @@ -101,7 +101,7 @@ void tie_managed_to_unmanaged(MonoObject *managed, Object *unmanaged) { return; } - Ref<MonoGCHandle> gchandle = ref ? MonoGCHandle::create_weak(managed) : MonoGCHandle::create_strong(managed); + MonoGCHandleData gchandle = ref ? MonoGCHandleData::new_weak_handle(managed) : MonoGCHandleData::new_strong_handle(managed); Ref<CSharpScript> script = CSharpScript::create_for_managed_type(klass, native); diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp index f937e09eaf..0de5352752 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.cpp +++ b/modules/mono/mono_gd/gd_mono_marshal.cpp @@ -75,15 +75,24 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type, bool *r_nil_is_ if (vtclass == CACHED_CLASS(Vector2)) return Variant::VECTOR2; + if (vtclass == CACHED_CLASS(Vector2i)) + return Variant::VECTOR2I; + if (vtclass == CACHED_CLASS(Rect2)) return Variant::RECT2; + if (vtclass == CACHED_CLASS(Rect2i)) + return Variant::RECT2I; + if (vtclass == CACHED_CLASS(Transform2D)) return Variant::TRANSFORM2D; if (vtclass == CACHED_CLASS(Vector3)) return Variant::VECTOR3; + if (vtclass == CACHED_CLASS(Vector3i)) + return Variant::VECTOR3I; + if (vtclass == CACHED_CLASS(Basis)) return Variant::BASIS; @@ -413,11 +422,21 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2), &from); } + if (vtclass == CACHED_CLASS(Vector2i)) { + GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_var->operator ::Vector2i()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2i), &from); + } + if (vtclass == CACHED_CLASS(Rect2)) { GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_var->operator ::Rect2()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2), &from); } + if (vtclass == CACHED_CLASS(Rect2i)) { + GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_var->operator ::Rect2i()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2i), &from); + } + if (vtclass == CACHED_CLASS(Transform2D)) { GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_var->operator ::Transform2D()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform2D), &from); @@ -428,6 +447,11 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3), &from); } + if (vtclass == CACHED_CLASS(Vector3i)) { + GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_var->operator ::Vector3i()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3i), &from); + } + if (vtclass == CACHED_CLASS(Basis)) { GDMonoMarshal::M_Basis from = MARSHALLED_OUT(Basis, p_var->operator ::Basis()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Basis), &from); @@ -638,14 +662,26 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty GDMonoMarshal::M_Vector2 from = MARSHALLED_OUT(Vector2, p_var->operator ::Vector2()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2), &from); } + case Variant::VECTOR2I: { + GDMonoMarshal::M_Vector2i from = MARSHALLED_OUT(Vector2i, p_var->operator ::Vector2i()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector2i), &from); + } case Variant::RECT2: { GDMonoMarshal::M_Rect2 from = MARSHALLED_OUT(Rect2, p_var->operator ::Rect2()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2), &from); } + case Variant::RECT2I: { + GDMonoMarshal::M_Rect2i from = MARSHALLED_OUT(Rect2i, p_var->operator ::Rect2i()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Rect2i), &from); + } case Variant::VECTOR3: { GDMonoMarshal::M_Vector3 from = MARSHALLED_OUT(Vector3, p_var->operator ::Vector3()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3), &from); } + case Variant::VECTOR3I: { + GDMonoMarshal::M_Vector3i from = MARSHALLED_OUT(Vector3i, p_var->operator ::Vector3i()); + return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Vector3i), &from); + } case Variant::TRANSFORM2D: { GDMonoMarshal::M_Transform2D from = MARSHALLED_OUT(Transform2D, p_var->operator ::Transform2D()); return mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(Transform2D), &from); @@ -806,15 +842,24 @@ Variant mono_object_to_variant_impl(MonoObject *p_obj, const ManagedType &p_type if (vtclass == CACHED_CLASS(Vector2)) return MARSHALLED_IN(Vector2, unbox_addr<GDMonoMarshal::M_Vector2>(p_obj)); + if (vtclass == CACHED_CLASS(Vector2i)) + return MARSHALLED_IN(Vector2i, unbox_addr<GDMonoMarshal::M_Vector2i>(p_obj)); + if (vtclass == CACHED_CLASS(Rect2)) return MARSHALLED_IN(Rect2, unbox_addr<GDMonoMarshal::M_Rect2>(p_obj)); + if (vtclass == CACHED_CLASS(Rect2i)) + return MARSHALLED_IN(Rect2i, unbox_addr<GDMonoMarshal::M_Rect2i>(p_obj)); + if (vtclass == CACHED_CLASS(Transform2D)) return MARSHALLED_IN(Transform2D, unbox_addr<GDMonoMarshal::M_Transform2D>(p_obj)); if (vtclass == CACHED_CLASS(Vector3)) return MARSHALLED_IN(Vector3, unbox_addr<GDMonoMarshal::M_Vector3>(p_obj)); + if (vtclass == CACHED_CLASS(Vector3i)) + return MARSHALLED_IN(Vector3i, unbox_addr<GDMonoMarshal::M_Vector3i>(p_obj)); + if (vtclass == CACHED_CLASS(Basis)) return MARSHALLED_IN(Basis, unbox_addr<GDMonoMarshal::M_Basis>(p_obj)); diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h index 54ce588baa..7d09f46b00 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ b/modules/mono/mono_gd/gd_mono_marshal.h @@ -201,6 +201,8 @@ M_SignalInfo signal_info_to_managed(const Signal &p_signal); namespace InteropLayout { enum { + MATCHES_int = (sizeof(int32_t) == sizeof(uint32_t)), + MATCHES_float = (sizeof(float) == sizeof(uint32_t)), MATCHES_double = (sizeof(double) == sizeof(uint64_t)), @@ -215,10 +217,18 @@ enum { offsetof(Vector2, x) == (sizeof(real_t) * 0) && offsetof(Vector2, y) == (sizeof(real_t) * 1)), + MATCHES_Vector2i = (MATCHES_int && (sizeof(Vector2i) == (sizeof(int32_t) * 2)) && + offsetof(Vector2i, x) == (sizeof(int32_t) * 0) && + offsetof(Vector2i, y) == (sizeof(int32_t) * 1)), + MATCHES_Rect2 = (MATCHES_Vector2 && (sizeof(Rect2) == (sizeof(Vector2) * 2)) && offsetof(Rect2, position) == (sizeof(Vector2) * 0) && offsetof(Rect2, size) == (sizeof(Vector2) * 1)), + MATCHES_Rect2i = (MATCHES_Vector2i && (sizeof(Rect2i) == (sizeof(Vector2i) * 2)) && + offsetof(Rect2i, position) == (sizeof(Vector2i) * 0) && + offsetof(Rect2i, size) == (sizeof(Vector2i) * 1)), + MATCHES_Transform2D = (MATCHES_Vector2 && (sizeof(Transform2D) == (sizeof(Vector2) * 3))), // No field offset required, it stores an array MATCHES_Vector3 = (MATCHES_real_t && (sizeof(Vector3) == (sizeof(real_t) * 3)) && @@ -226,6 +236,11 @@ enum { offsetof(Vector3, y) == (sizeof(real_t) * 1) && offsetof(Vector3, z) == (sizeof(real_t) * 2)), + MATCHES_Vector3i = (MATCHES_int && (sizeof(Vector3i) == (sizeof(int32_t) * 3)) && + offsetof(Vector3i, x) == (sizeof(int32_t) * 0) && + offsetof(Vector3i, y) == (sizeof(int32_t) * 1) && + offsetof(Vector3i, z) == (sizeof(int32_t) * 2)), + MATCHES_Basis = (MATCHES_Vector3 && (sizeof(Basis) == (sizeof(Vector3) * 3))), // No field offset required, it stores an array MATCHES_Quat = (MATCHES_real_t && (sizeof(Quat) == (sizeof(real_t) * 4)) && @@ -257,7 +272,8 @@ enum { #ifdef GD_MONO_FORCE_INTEROP_STRUCT_COPY /* clang-format off */ static_assert(MATCHES_Vector2 && MATCHES_Rect2 && MATCHES_Transform2D && MATCHES_Vector3 && - MATCHES_Basis && MATCHES_Quat && MATCHES_Transform && MATCHES_AABB && MATCHES_Color && MATCHES_Plane); + MATCHES_Basis && MATCHES_Quat && MATCHES_Transform && MATCHES_AABB && MATCHES_Color && + MATCHES_Plane && MATCHES_Vector2i && MATCHES_Rect2i && MATCHES_Vector3i); /* clang-format on */ #endif @@ -278,6 +294,19 @@ struct M_Vector2 { } }; +struct M_Vector2i { + int32_t x, y; + + static _FORCE_INLINE_ Vector2i convert_to(const M_Vector2i &p_from) { + return Vector2i(p_from.x, p_from.y); + } + + static _FORCE_INLINE_ M_Vector2i convert_from(const Vector2i &p_from) { + M_Vector2i ret = { p_from.x, p_from.y }; + return ret; + } +}; + struct M_Rect2 { M_Vector2 position; M_Vector2 size; @@ -293,6 +322,21 @@ struct M_Rect2 { } }; +struct M_Rect2i { + M_Vector2i position; + M_Vector2i size; + + static _FORCE_INLINE_ Rect2i convert_to(const M_Rect2i &p_from) { + return Rect2i(M_Vector2i::convert_to(p_from.position), + M_Vector2i::convert_to(p_from.size)); + } + + static _FORCE_INLINE_ M_Rect2i convert_from(const Rect2i &p_from) { + M_Rect2i ret = { M_Vector2i::convert_from(p_from.position), M_Vector2i::convert_from(p_from.size) }; + return ret; + } +}; + struct M_Transform2D { M_Vector2 elements[3]; @@ -325,6 +369,19 @@ struct M_Vector3 { } }; +struct M_Vector3i { + int32_t x, y, z; + + static _FORCE_INLINE_ Vector3i convert_to(const M_Vector3i &p_from) { + return Vector3i(p_from.x, p_from.y, p_from.z); + } + + static _FORCE_INLINE_ M_Vector3i convert_from(const Vector3i &p_from) { + M_Vector3i ret = { p_from.x, p_from.y, p_from.z }; + return ret; + } +}; + struct M_Basis { M_Vector3 elements[3]; @@ -450,9 +507,12 @@ struct M_Plane { } DECL_TYPE_MARSHAL_TEMPLATES(Vector2) +DECL_TYPE_MARSHAL_TEMPLATES(Vector2i) DECL_TYPE_MARSHAL_TEMPLATES(Rect2) +DECL_TYPE_MARSHAL_TEMPLATES(Rect2i) DECL_TYPE_MARSHAL_TEMPLATES(Transform2D) DECL_TYPE_MARSHAL_TEMPLATES(Vector3) +DECL_TYPE_MARSHAL_TEMPLATES(Vector3i) DECL_TYPE_MARSHAL_TEMPLATES(Basis) DECL_TYPE_MARSHAL_TEMPLATES(Quat) DECL_TYPE_MARSHAL_TEMPLATES(Transform) diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp index fa04183ea3..cdb26ae61b 100644 --- a/modules/mono/mono_gd/gd_mono_utils.cpp +++ b/modules/mono/mono_gd/gd_mono_utils.cpp @@ -86,10 +86,9 @@ MonoObject *unmanaged_get_managed(Object *unmanaged) { } } - Ref<MonoGCHandle> &gchandle = script_binding.gchandle; - ERR_FAIL_COND_V(gchandle.is_null(), NULL); + MonoGCHandleData &gchandle = script_binding.gchandle; - MonoObject *target = gchandle->get_target(); + MonoObject *target = gchandle.get_target(); if (target) return target; @@ -106,7 +105,7 @@ MonoObject *unmanaged_get_managed(Object *unmanaged) { MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(script_binding.wrapper_class, script_binding.type_name, unmanaged); ERR_FAIL_NULL_V(mono_object, NULL); - gchandle->set_handle(MonoGCHandle::new_strong_handle(mono_object), MonoGCHandle::STRONG_HANDLE); + gchandle = MonoGCHandleData::new_strong_handle(mono_object); // Tie managed to unmanaged Reference *ref = Object::cast_to<Reference>(unmanaged); @@ -156,6 +155,22 @@ bool is_thread_attached() { return mono_domain_get() != NULL; } +uint32_t new_strong_gchandle(MonoObject *p_object) { + return mono_gchandle_new(p_object, /* pinned: */ false); +} + +uint32_t new_strong_gchandle_pinned(MonoObject *p_object) { + return mono_gchandle_new(p_object, /* pinned: */ true); +} + +uint32_t new_weak_gchandle(MonoObject *p_object) { + return mono_gchandle_new_weakref(p_object, /* track_resurrection: */ false); +} + +void free_gchandle(uint32_t p_gchandle) { + mono_gchandle_free(p_gchandle); +} + void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc) { GDMonoMethod *ctor = p_class->get_method(".ctor", 0); ERR_FAIL_NULL(ctor); diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h index 7b7afc44e0..fd02907d87 100644 --- a/modules/mono/mono_gd/gd_mono_utils.h +++ b/modules/mono/mono_gd/gd_mono_utils.h @@ -92,6 +92,11 @@ _FORCE_INLINE_ bool is_main_thread() { return mono_domain_get() != NULL && mono_thread_get_main() == mono_thread_current(); } +uint32_t new_strong_gchandle(MonoObject *p_object); +uint32_t new_strong_gchandle_pinned(MonoObject *p_object); +uint32_t new_weak_gchandle(MonoObject *p_object); +void free_gchandle(uint32_t p_gchandle); + void runtime_object_init(MonoObject *p_this_obj, GDMonoClass *p_class, MonoException **r_exc = NULL); bool mono_delegate_equal(MonoDelegate *p_a, MonoDelegate *p_b); diff --git a/modules/mono/signal_awaiter_utils.cpp b/modules/mono/signal_awaiter_utils.cpp index 28719f7bc6..25e5a41215 100644 --- a/modules/mono/signal_awaiter_utils.cpp +++ b/modules/mono/signal_awaiter_utils.cpp @@ -114,8 +114,15 @@ void SignalAwaiterCallable::call(const Variant **p_arguments, int p_argcount, Va mono_array_setref(signal_args, i, boxed); } + MonoObject *awaiter = awaiter_handle.get_target(); + + if (!awaiter) { + r_call_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL; + return; + } + MonoException *exc = NULL; - CACHED_METHOD_THUNK(SignalAwaiter, SignalCallback).invoke(awaiter_handle->get_target(), signal_args, &exc); + CACHED_METHOD_THUNK(SignalAwaiter, SignalCallback).invoke(awaiter, signal_args, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); @@ -127,10 +134,14 @@ void SignalAwaiterCallable::call(const Variant **p_arguments, int p_argcount, Va SignalAwaiterCallable::SignalAwaiterCallable(Object *p_target, MonoObject *p_awaiter, const StringName &p_signal) : target_id(p_target->get_instance_id()), - awaiter_handle(MonoGCHandle::create_strong(p_awaiter)), + awaiter_handle(MonoGCHandleData::new_strong_handle(p_awaiter)), signal(p_signal) { } +SignalAwaiterCallable::~SignalAwaiterCallable() { + awaiter_handle.release(); +} + bool EventSignalCallable::compare_equal(const CallableCustom *p_a, const CallableCustom *p_b) { const EventSignalCallable *a = static_cast<const EventSignalCallable *>(p_a); const EventSignalCallable *b = static_cast<const EventSignalCallable *>(p_b); @@ -159,7 +170,6 @@ String EventSignalCallable::get_as_text() const { String class_name = owner->get_class(); Ref<Script> script = owner->get_script(); if (script.is_valid() && script->get_path().is_resource_file()) { - class_name += "(" + script->get_path().get_file() + ")"; } StringName signal = event_signal->field->get_name(); diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h index 868d33e335..c550315a23 100644 --- a/modules/mono/signal_awaiter_utils.h +++ b/modules/mono/signal_awaiter_utils.h @@ -40,7 +40,7 @@ Error gd_mono_connect_signal_awaiter(Object *p_source, const StringName &p_signa class SignalAwaiterCallable : public CallableCustom { ObjectID target_id; - Ref<MonoGCHandle> awaiter_handle; + MonoGCHandleData awaiter_handle; StringName signal; public: @@ -64,6 +64,7 @@ public: void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override; SignalAwaiterCallable(Object *p_target, MonoObject *p_awaiter, const StringName &p_signal); + ~SignalAwaiterCallable(); }; class EventSignalCallable : public CallableCustom { diff --git a/modules/ogg/SCsub b/modules/ogg/SCsub index 6a72a519fe..44c7963cd3 100644 --- a/modules/ogg/SCsub +++ b/modules/ogg/SCsub @@ -3,6 +3,9 @@ Import('env') Import('env_modules') +# Only kept to build the thirdparty library used by the theora and webm +# modules. + env_ogg = env_modules.Clone() # Thirdparty source files diff --git a/modules/opus/SCsub b/modules/opus/SCsub index 1db5b0987e..fec2911d6d 100644 --- a/modules/opus/SCsub +++ b/modules/opus/SCsub @@ -3,7 +3,9 @@ Import('env') Import('env_modules') -stub = True +# Only kept to build the thirdparty library used by the webm module. +# AudioStreamOpus was dropped in 3.0 due to incompatibility with the new audio +# engine. If you want to port it, fetch it from the Git history. env_opus = env_modules.Clone() @@ -235,9 +237,5 @@ if env['builtin_opus']: env_thirdparty.disable_warnings() env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) -if not stub: - # Module files - env_opus.add_source_files(env.modules_sources, "*.cpp") -else: - # Module files - env_opus.add_source_files(env.modules_sources, "stub/register_types.cpp") +# Module files +env_opus.add_source_files(env.modules_sources, "register_types.cpp") diff --git a/modules/opus/audio_stream_opus.cpp b/modules/opus/audio_stream_opus.cpp deleted file mode 100644 index a983edee91..0000000000 --- a/modules/opus/audio_stream_opus.cpp +++ /dev/null @@ -1,379 +0,0 @@ -/*************************************************************************/ -/* audio_stream_opus.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 "audio_stream_opus.h" - -/** - @author George Marques <george@gmarqu.es> -*/ - -const float AudioStreamPlaybackOpus::osrate = 48000.0f; - -int AudioStreamPlaybackOpus::_op_read_func(void *_stream, unsigned char *_ptr, int _nbytes) { - FileAccess *fa = (FileAccess *)_stream; - - if (fa->eof_reached()) - return 0; - - uint8_t *dst = (uint8_t *)_ptr; - - int read = fa->get_buffer(dst, _nbytes); - - return read; -} - -int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, int _whence) { - -#ifdef SEEK_SET - FileAccess *fa = (FileAccess *)_stream; - - switch (_whence) { - case SEEK_SET: { - fa->seek(_offset); - } break; - case SEEK_CUR: { - fa->seek(fa->get_position() + _offset); - } break; - case SEEK_END: { - fa->seek_end(_offset); - } break; - default: { - ERR_PRINT("Opus seek function failure: Unexpected value in _whence\n"); - } - } - int ret = fa->eof_reached() ? -1 : 0; - return ret; -#else - return -1; // no seeking -#endif -} - -int AudioStreamPlaybackOpus::_op_close_func(void *_stream) { - if (!_stream) - return 0; - FileAccess *fa = (FileAccess *)_stream; - if (fa->is_open()) - fa->close(); - return 0; -} - -opus_int64 AudioStreamPlaybackOpus::_op_tell_func(void *_stream) { - FileAccess *_fa = (FileAccess *)_stream; - return (opus_int64)_fa->get_position(); -} - -void AudioStreamPlaybackOpus::_clear_stream() { - if (!stream_loaded) - return; - - op_free(opus_file); - _close_file(); - - stream_loaded = false; - stream_channels = 1; - playing = false; -} - -void AudioStreamPlaybackOpus::_close_file() { - if (f) { - memdelete(f); - f = NULL; - } -} - -Error AudioStreamPlaybackOpus::_load_stream() { - - ERR_FAIL_COND_V(!stream_valid, ERR_UNCONFIGURED); - - _clear_stream(); - if (file == "") - return ERR_INVALID_DATA; - - Error err; - f = FileAccess::open(file, FileAccess::READ, &err); - - ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + file + "'."); - - int _err = 0; - - opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err); - - switch (_err) { - case OP_EREAD: { // - Can't read the file. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CANT_READ); - } break; - case OP_EVERSION: // - Unrecognized version number. - case OP_ENOTFORMAT: // - Stream is not Opus data. - case OP_EIMPL: { // - Stream used non-implemented feature. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); - } break; - case OP_EBADLINK: // - Failed to find old data after seeking. - case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks. - case OP_EBADHEADER: { // - Invalid or missing Opus bitstream header. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CORRUPT); - } break; - case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_BUG); - } break; - } - repeats = 0; - stream_loaded = true; - - return OK; -} - -AudioStreamPlaybackOpus::AudioStreamPlaybackOpus() { - loops = false; - playing = false; - f = NULL; - stream_loaded = false; - stream_valid = false; - repeats = 0; - paused = true; - stream_channels = 0; - current_section = 0; - length = 0; - loop_restart_time = 0; - pre_skip = 0; - - _op_callbacks.read = _op_read_func; - _op_callbacks.seek = _op_seek_func; - _op_callbacks.tell = _op_tell_func; - _op_callbacks.close = _op_close_func; -} - -Error AudioStreamPlaybackOpus::set_file(const String &p_file) { - file = p_file; - stream_valid = false; - Error err; - f = FileAccess::open(file, FileAccess::READ, &err); - - ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + file + "'."); - - int _err; - - opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err); - - switch (_err) { - case OP_EREAD: { // - Can't read the file. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CANT_READ); - } break; - case OP_EVERSION: // - Unrecognized version number. - case OP_ENOTFORMAT: // - Stream is not Opus data. - case OP_EIMPL: { // - Stream used non-implemented feature. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); - } break; - case OP_EBADLINK: // - Failed to find old data after seeking. - case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks. - case OP_EBADHEADER: { // - Invalid or missing Opus bitstream header. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CORRUPT); - } break; - case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_BUG); - } break; - } - - const OpusHead *oinfo = op_head(opus_file, -1); - - stream_channels = oinfo->channel_count; - pre_skip = oinfo->pre_skip; - frames_mixed = pre_skip; - ogg_int64_t len = op_pcm_total(opus_file, -1); - if (len < 0) { - length = 0; - } else { - length = (len / osrate); - } - - op_free(opus_file); - memdelete(f); - f = NULL; - stream_valid = true; - - return OK; -} - -void AudioStreamPlaybackOpus::play(float p_from) { - if (playing) - stop(); - - if (_load_stream() != OK) - return; - - frames_mixed = pre_skip; - playing = true; - if (p_from > 0) { - seek(p_from); - } -} - -void AudioStreamPlaybackOpus::stop() { - _clear_stream(); - playing = false; -} - -void AudioStreamPlaybackOpus::seek(float p_time) { - if (!playing) return; - ogg_int64_t pcm_offset = (ogg_int64_t)(p_time * osrate); - bool ok = op_pcm_seek(opus_file, pcm_offset) == 0; - if (!ok) { - ERR_PRINT("Seek time over stream size."); - return; - } - frames_mixed = osrate * p_time; -} - -int AudioStreamPlaybackOpus::mix(int16_t *p_buffer, int p_frames) { - if (!playing) - return 0; - - int total = p_frames; - - while (true) { - - int todo = p_frames; - - if (todo < MIN_MIX) { - break; - } - - int ret = op_read(opus_file, (opus_int16 *)p_buffer, todo * stream_channels, ¤t_section); - if (ret < 0) { - playing = false; - ERR_BREAK_MSG(ret < 0, "Error reading Opus file: " + file + "."); - } else if (ret == 0) { // end of song, reload? - op_free(opus_file); - - _close_file(); - - f = FileAccess::open(file, FileAccess::READ); - - int errv = 0; - opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &errv); - if (errv != 0) { - playing = false; - break; // :( - } - - if (!has_loop()) { - playing = false; - repeats = 1; - break; - } - - if (loop_restart_time) { - bool ok = op_pcm_seek(opus_file, (loop_restart_time * osrate) + pre_skip) == 0; - if (!ok) { - playing = false; - ERR_PRINT("Loop restart time rejected"); - } - - frames_mixed = (loop_restart_time * osrate) + pre_skip; - } else { - frames_mixed = pre_skip; - } - repeats++; - continue; - } - - stream_channels = op_head(opus_file, current_section)->channel_count; - - frames_mixed += ret; - - p_buffer += ret * stream_channels; - p_frames -= ret; - } - - return total - p_frames; -} - -float AudioStreamPlaybackOpus::get_length() const { - if (!stream_loaded) { - if (const_cast<AudioStreamPlaybackOpus *>(this)->_load_stream() != OK) - return 0; - } - return length; -} - -float AudioStreamPlaybackOpus::get_playback_position() const { - - int32_t frames = int32_t(frames_mixed); - if (frames < 0) - frames = 0; - return double(frames) / osrate; -} - -int AudioStreamPlaybackOpus::get_minimum_buffer_size() const { - return MIN_MIX; -} - -AudioStreamPlaybackOpus::~AudioStreamPlaybackOpus() { - _clear_stream(); -} - -RES ResourceFormatLoaderAudioStreamOpus::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress) { - if (r_error) - *r_error = OK; - - AudioStreamOpus *opus_stream = memnew(AudioStreamOpus); - opus_stream->set_file(p_path); - return Ref<AudioStreamOpus>(opus_stream); -} - -void ResourceFormatLoaderAudioStreamOpus::get_recognized_extensions(List<String> *p_extensions) const { - - p_extensions->push_back("opus"); -} -String ResourceFormatLoaderAudioStreamOpus::get_resource_type(const String &p_path) const { - - if (p_path.get_extension().to_lower() == "opus") - return "AudioStreamOpus"; - return ""; -} - -bool ResourceFormatLoaderAudioStreamOpus::handles_type(const String &p_type) const { - return (p_type == "AudioStream" || p_type == "AudioStreamOpus"); -} diff --git a/modules/opus/audio_stream_opus.h b/modules/opus/audio_stream_opus.h deleted file mode 100644 index 343cbc6b83..0000000000 --- a/modules/opus/audio_stream_opus.h +++ /dev/null @@ -1,142 +0,0 @@ -/*************************************************************************/ -/* audio_stream_opus.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 AUDIO_STREAM_OPUS_H -#define AUDIO_STREAM_OPUS_H - -#include "core/io/resource_loader.h" -#include "core/os/file_access.h" -#include "scene/resources/audio_stream.h" - -#include <opus/opusfile.h> - -/** - @author George Marques <george@gmarqu.es> -*/ - -class AudioStreamPlaybackOpus : public AudioStreamPlayback { - - GDCLASS(AudioStreamPlaybackOpus, AudioStreamPlayback); - - enum { - MIN_MIX = 1024 - }; - - FileAccess *f; - - OpusFileCallbacks _op_callbacks; - float length; - static int _op_read_func(void *_stream, unsigned char *_ptr, int _nbytes); - static int _op_seek_func(void *_stream, opus_int64 _offset, int _whence); - static int _op_close_func(void *_stream); - static opus_int64 _op_tell_func(void *_stream); - static const float osrate; - - String file; - int64_t frames_mixed; - - bool stream_loaded; - volatile bool playing; - OggOpusFile *opus_file; - int stream_channels; - int current_section; - int pre_skip; - - bool paused; - bool loops; - int repeats; - - Error _load_stream(); - void _clear_stream(); - void _close_file(); - - bool stream_valid; - float loop_restart_time; - -public: - Error set_file(const String &p_file); - - virtual void play(float p_from = 0); - virtual void stop(); - virtual bool is_playing() const { return playing; } - - virtual void set_loop_restart_time(float p_time) { loop_restart_time = p_time; } - - virtual void set_paused(bool p_paused) { paused = p_paused; } - virtual bool is_paused() const { return paused; } - - virtual void set_loop(bool p_enable) { loops = p_enable; } - virtual bool has_loop() const { return loops; } - - virtual float get_length() const; - - virtual String get_stream_name() const { return ""; } - - virtual int get_loop_count() const { return repeats; } - - virtual float get_playback_position() const; - virtual void seek(float p_time); - - virtual int get_channels() const { return stream_channels; } - virtual int get_mix_rate() const { return osrate; } - - virtual int get_minimum_buffer_size() const; - - virtual int mix(int16_t *p_buffer, int p_frames); - - AudioStreamPlaybackOpus(); - ~AudioStreamPlaybackOpus(); -}; - -class AudioStreamOpus : public AudioStream { - - GDCLASS(AudioStreamOpus, AudioStream); - - String file; - -public: - Ref<AudioStreamPlayback> instance_playback() { - Ref<AudioStreamPlaybackOpus> pb = memnew(AudioStreamPlaybackOpus); - pb->set_file(file); - return pb; - } - - void set_file(const String &p_file) { file = p_file; } -}; - -class ResourceFormatLoaderAudioStreamOpus : public ResourceFormatLoader { -public: - virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL, bool p_use_sub_threads = false, float *r_progress = nullptr); - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String &p_type) const; - virtual String get_resource_type(const String &p_path) const; -}; - -#endif // AUDIO_STREAM_OPUS_H diff --git a/modules/opus/config.py b/modules/opus/config.py index a1cde10ea0..1c8cd12a2d 100644 --- a/modules/opus/config.py +++ b/modules/opus/config.py @@ -3,11 +3,3 @@ def can_build(env, platform): def configure(env): pass - -def get_doc_classes(): - return [ - "AudioStreamOpus", - ] - -def get_doc_path(): - return "doc_classes" diff --git a/modules/opus/register_types.cpp b/modules/opus/register_types.cpp index dff309b49c..a4329e142c 100644 --- a/modules/opus/register_types.cpp +++ b/modules/opus/register_types.cpp @@ -30,23 +30,8 @@ #include "register_types.h" -#include "audio_stream_opus.h" +// Dummy module as libvorbis is needed by other modules (theora ...) -static Ref<ResourceFormatLoaderAudioStreamOpus> opus_stream_loader; +void register_opus_types() {} -void register_opus_types() { - // Sorry guys, do not enable this unless you can figure out a way - // to get Opus to not do any memory allocation or system calls - // in the audio thread. - // Currently the implementation even reads files from the audio thread, - // and this is not how audio programming works. - - //opus_stream_loader = memnew(ResourceFormatLoaderAudioStreamOpus); - //ResourceLoader::add_resource_format_loader(opus_stream_loader); - //ClassDB::register_class<AudioStreamOpus>(); -} - -void unregister_opus_types() { - - //memdelete(opus_stream_loader); -} +void unregister_opus_types() {} diff --git a/modules/opus/stub/register_types.cpp b/modules/opus/stub/register_types.cpp deleted file mode 100644 index a4329e142c..0000000000 --- a/modules/opus/stub/register_types.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/*************************************************************************/ -/* register_types.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 "register_types.h" - -// Dummy module as libvorbis is needed by other modules (theora ...) - -void register_opus_types() {} - -void unregister_opus_types() {} diff --git a/modules/opus/stub/register_types.h b/modules/opus/stub/register_types.h deleted file mode 100644 index 445be4e166..0000000000 --- a/modules/opus/stub/register_types.h +++ /dev/null @@ -1,32 +0,0 @@ -/*************************************************************************/ -/* register_types.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. */ -/*************************************************************************/ - -void register_opus_types(); -void unregister_opus_types(); diff --git a/modules/vorbis/SCsub b/modules/vorbis/SCsub index 3824fdd789..bde4359595 100644 --- a/modules/vorbis/SCsub +++ b/modules/vorbis/SCsub @@ -3,6 +3,9 @@ Import('env') Import('env_modules') +# Only kept to build the thirdparty library used by the theora and webm +# modules. We now use stb_vorbis for AudioStreamOGGVorbis. + env_vorbis = env_modules.Clone() stub = True @@ -50,9 +53,5 @@ if env['builtin_libvorbis']: env_thirdparty.disable_warnings() env_thirdparty.add_source_files(env.modules_sources, thirdparty_sources) -if not stub: - # Module files - env_vorbis.add_source_files(env.modules_sources, "*.cpp") -else: - # Module files - env_vorbis.add_source_files(env.modules_sources, "stub/register_types.cpp") +# Module files +env_vorbis.add_source_files(env.modules_sources, "register_types.cpp") diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp deleted file mode 100644 index 1e8ee9b17e..0000000000 --- a/modules/vorbis/audio_stream_ogg_vorbis.cpp +++ /dev/null @@ -1,406 +0,0 @@ -/*************************************************************************/ -/* audio_stream_ogg_vorbis.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 "audio_stream_ogg_vorbis.h" - -size_t AudioStreamPlaybackOGGVorbis::_ov_read_func(void *p_dst, size_t p_data, size_t p_count, void *_f) { - - //printf("read to %p, %i bytes, %i nmemb, %p\n",p_dst,p_data,p_count,_f); - FileAccess *fa = (FileAccess *)_f; - size_t read_total = p_data * p_count; - - if (fa->eof_reached()) - return 0; - - uint8_t *dst = (uint8_t *)p_dst; - - int read = fa->get_buffer(dst, read_total); - - return read; -} - -int AudioStreamPlaybackOGGVorbis::_ov_seek_func(void *_f, ogg_int64_t offs, int whence) { - - //printf("seek to %p, offs %i, whence %i\n",_f,(int)offs,whence); - -#ifdef SEEK_SET - //printf("seek set defined\n"); - FileAccess *fa = (FileAccess *)_f; - - if (whence == SEEK_SET) { - - fa->seek(offs); - } else if (whence == SEEK_CUR) { - - fa->seek(fa->get_position() + offs); - } else if (whence == SEEK_END) { - - fa->seek_end(offs); - } else { - - ERR_PRINT("Vorbis seek function failure: Unexpected value in _whence\n"); - } - int ret = fa->eof_reached() ? -1 : 0; - //printf("returning %i\n",ret); - return ret; - -#else - return -1; // no seeking -#endif -} -int AudioStreamPlaybackOGGVorbis::_ov_close_func(void *_f) { - - //printf("close %p\n",_f); - if (!_f) - return 0; - FileAccess *fa = (FileAccess *)_f; - if (fa->is_open()) - fa->close(); - return 0; -} -long AudioStreamPlaybackOGGVorbis::_ov_tell_func(void *_f) { - - //printf("close %p\n",_f); - - FileAccess *fa = (FileAccess *)_f; - return fa->get_position(); -} - -int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_buffer, int p_frames) { - - if (!playing) - return 0; - - int total = p_frames; - while (true) { - - int todo = p_frames; - - if (todo < MIN_MIX) { - break; - } - -#ifdef BIG_ENDIAN_ENABLED - long ret = ov_read(&vf, (char *)p_buffer, todo * stream_channels * sizeof(int16_t), 1, 2, 1, ¤t_section); -#else - long ret = ov_read(&vf, (char *)p_buffer, todo * stream_channels * sizeof(int16_t), 0, 2, 1, ¤t_section); -#endif - - if (ret < 0) { - - playing = false; - ERR_BREAK_MSG(ret < 0, "Error reading OGG Vorbis file: " + file + "."); - } else if (ret == 0) { // end of song, reload? - - ov_clear(&vf); - - _close_file(); - - if (!has_loop()) { - - playing = false; - repeats = 1; - break; - } - - f = FileAccess::open(file, FileAccess::READ); - - int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); - if (errv != 0) { - playing = false; - break; // :( - } - - if (loop_restart_time) { - bool ok = ov_time_seek(&vf, loop_restart_time) == 0; - if (!ok) { - playing = false; - ERR_PRINT("Loop restart time rejected"); - } - - frames_mixed = stream_srate * loop_restart_time; - } else { - - frames_mixed = 0; - } - repeats++; - continue; - } - - ret /= stream_channels; - ret /= sizeof(int16_t); - - frames_mixed += ret; - - p_buffer += ret * stream_channels; - p_frames -= ret; - } - - return total - p_frames; -} - -void AudioStreamPlaybackOGGVorbis::play(float p_from) { - - if (playing) - stop(); - - if (_load_stream() != OK) - return; - - frames_mixed = 0; - playing = true; - if (p_from > 0) { - seek(p_from); - } -} - -void AudioStreamPlaybackOGGVorbis::_close_file() { - - if (f) { - - memdelete(f); - f = NULL; - } -} - -bool AudioStreamPlaybackOGGVorbis::is_playing() const { - return playing; -} -void AudioStreamPlaybackOGGVorbis::stop() { - - _clear_stream(); - playing = false; - //_clear(); -} - -float AudioStreamPlaybackOGGVorbis::get_playback_position() const { - - int32_t frames = int32_t(frames_mixed); - if (frames < 0) - frames = 0; - return double(frames) / stream_srate; -} - -void AudioStreamPlaybackOGGVorbis::seek(float p_time) { - - if (!playing) - return; - bool ok = ov_time_seek(&vf, p_time) == 0; - ERR_FAIL_COND(!ok); - frames_mixed = stream_srate * p_time; -} - -String AudioStreamPlaybackOGGVorbis::get_stream_name() const { - - return ""; -} - -void AudioStreamPlaybackOGGVorbis::set_loop(bool p_enable) { - - loops = p_enable; -} - -bool AudioStreamPlaybackOGGVorbis::has_loop() const { - - return loops; -} - -int AudioStreamPlaybackOGGVorbis::get_loop_count() const { - return repeats; -} - -Error AudioStreamPlaybackOGGVorbis::set_file(const String &p_file) { - - file = p_file; - stream_valid = false; - Error err; - f = FileAccess::open(file, FileAccess::READ, &err); - ERR_FAIL_COND_V_MSG(err, err, "Cannot open file '" + p_file + "'."); - - int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); - switch (errv) { - - case OV_EREAD: { // - A read from media returned an error. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CANT_READ); - } break; - case OV_EVERSION: // - Vorbis version mismatch. - case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); - } break; - case OV_EBADHEADER: { // - Invalid Vorbis bitstream header. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CORRUPT); - } break; - case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_BUG); - } break; - } - const vorbis_info *vinfo = ov_info(&vf, -1); - stream_channels = vinfo->channels; - stream_srate = vinfo->rate; - length = ov_time_total(&vf, -1); - ov_clear(&vf); - memdelete(f); - f = NULL; - stream_valid = true; - - return OK; -} - -Error AudioStreamPlaybackOGGVorbis::_load_stream() { - - ERR_FAIL_COND_V(!stream_valid, ERR_UNCONFIGURED); - - _clear_stream(); - if (file == "") - return ERR_INVALID_DATA; - - Error err; - f = FileAccess::open(file, FileAccess::READ, &err); - ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + file + "'."); - - int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks); - switch (errv) { - - case OV_EREAD: { // - A read from media returned an error. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CANT_READ); - } break; - case OV_EVERSION: // - Vorbis version mismatch. - case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); - } break; - case OV_EBADHEADER: { // - Invalid Vorbis bitstream header. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_FILE_CORRUPT); - } break; - case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption. - memdelete(f); - f = NULL; - ERR_FAIL_V(ERR_BUG); - } break; - } - repeats = 0; - stream_loaded = true; - - return OK; -} - -float AudioStreamPlaybackOGGVorbis::get_length() const { - - if (!stream_loaded) { - if (const_cast<AudioStreamPlaybackOGGVorbis *>(this)->_load_stream() != OK) - return 0; - } - return length; -} - -void AudioStreamPlaybackOGGVorbis::_clear_stream() { - - if (!stream_loaded) - return; - - ov_clear(&vf); - _close_file(); - - stream_loaded = false; - //stream_channels=1; - playing = false; -} - -void AudioStreamPlaybackOGGVorbis::set_paused(bool p_paused) { - - paused = p_paused; -} - -bool AudioStreamPlaybackOGGVorbis::is_paused() const { - - return paused; -} - -AudioStreamPlaybackOGGVorbis::AudioStreamPlaybackOGGVorbis() { - - loops = false; - playing = false; - _ov_callbacks.read_func = _ov_read_func; - _ov_callbacks.seek_func = _ov_seek_func; - _ov_callbacks.close_func = _ov_close_func; - _ov_callbacks.tell_func = _ov_tell_func; - f = NULL; - stream_loaded = false; - stream_valid = false; - repeats = 0; - paused = true; - stream_channels = 0; - stream_srate = 0; - current_section = 0; - length = 0; - loop_restart_time = 0; -} - -AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { - - _clear_stream(); -} - -RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress) { - if (r_error) - *r_error = OK; - - AudioStreamOGGVorbis *ogg_stream = memnew(AudioStreamOGGVorbis); - ogg_stream->set_file(p_path); - return Ref<AudioStreamOGGVorbis>(ogg_stream); -} - -void ResourceFormatLoaderAudioStreamOGGVorbis::get_recognized_extensions(List<String> *p_extensions) const { - - p_extensions->push_back("ogg"); -} -String ResourceFormatLoaderAudioStreamOGGVorbis::get_resource_type(const String &p_path) const { - - if (p_path.get_extension().to_lower() == "ogg") - return "AudioStreamOGGVorbis"; - return ""; -} - -bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String &p_type) const { - return (p_type == "AudioStream" || p_type == "AudioStreamOGG" || p_type == "AudioStreamOGGVorbis"); -} diff --git a/modules/vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h deleted file mode 100644 index db621f88d2..0000000000 --- a/modules/vorbis/audio_stream_ogg_vorbis.h +++ /dev/null @@ -1,137 +0,0 @@ -/*************************************************************************/ -/* audio_stream_ogg_vorbis.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 AUDIO_STREAM_OGG_VORBIS_H -#define AUDIO_STREAM_OGG_VORBIS_H - -#include "core/io/resource_loader.h" -#include "core/os/file_access.h" -#include "core/os/thread_safe.h" -#include "scene/resources/audio_stream.h" - -#include <vorbis/vorbisfile.h> - -class AudioStreamPlaybackOGGVorbis : public AudioStreamPlayback { - - GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlayback); - - enum { - MIN_MIX = 1024 - }; - - FileAccess *f; - - ov_callbacks _ov_callbacks; - float length; - static size_t _ov_read_func(void *p_dst, size_t p_data, size_t p_count, void *_f); - static int _ov_seek_func(void *_f, ogg_int64_t offs, int whence); - static int _ov_close_func(void *_f); - static long _ov_tell_func(void *_f); - - String file; - int64_t frames_mixed; - - bool stream_loaded; - volatile bool playing; - OggVorbis_File vf; - int stream_channels; - int stream_srate; - int current_section; - - bool paused; - bool loops; - int repeats; - - Error _load_stream(); - void _clear_stream(); - void _close_file(); - - bool stream_valid; - float loop_restart_time; - -public: - Error set_file(const String &p_file); - - virtual void play(float p_from = 0); - virtual void stop(); - virtual bool is_playing() const; - - virtual void set_loop_restart_time(float p_time) { loop_restart_time = p_time; } - - virtual void set_paused(bool p_paused); - virtual bool is_paused() const; - - virtual void set_loop(bool p_enable); - virtual bool has_loop() const; - - virtual float get_length() const; - - virtual String get_stream_name() const; - - virtual int get_loop_count() const; - - virtual float get_playback_position() const; - virtual void seek(float p_time); - - virtual int get_channels() const { return stream_channels; } - virtual int get_mix_rate() const { return stream_srate; } - - virtual int get_minimum_buffer_size() const { return 0; } - virtual int mix(int16_t *p_buffer, int p_frames); - - AudioStreamPlaybackOGGVorbis(); - ~AudioStreamPlaybackOGGVorbis(); -}; - -class AudioStreamOGGVorbis : public AudioStream { - - GDCLASS(AudioStreamOGGVorbis, AudioStream); - - String file; - -public: - Ref<AudioStreamPlayback> instance_playback() { - Ref<AudioStreamPlaybackOGGVorbis> pb = memnew(AudioStreamPlaybackOGGVorbis); - pb->set_file(file); - return pb; - } - - void set_file(const String &p_file) { file = p_file; } -}; - -class ResourceFormatLoaderAudioStreamOGGVorbis : public ResourceFormatLoader { -public: - virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL, bool p_use_sub_threads = false, float *r_progress = nullptr); - virtual void get_recognized_extensions(List<String> *p_extensions) const; - virtual bool handles_type(const String &p_type) const; - virtual String get_resource_type(const String &p_path) const; -}; - -#endif // AUDIO_STREAM_OGG_H diff --git a/modules/vorbis/register_types.cpp b/modules/vorbis/register_types.cpp index de055551ad..8874b3887b 100644 --- a/modules/vorbis/register_types.cpp +++ b/modules/vorbis/register_types.cpp @@ -30,19 +30,8 @@ #include "register_types.h" -#include "audio_stream_ogg_vorbis.h" +// Dummy module as libvorbis is needed by other modules (theora ...) -static Ref<ResourceFormatLoaderAudioStreamOGGVorbis> vorbis_stream_loader; +void register_vorbis_types() {} -void register_vorbis_types() { - - vorbis_stream_loader.instance(); - ResourceLoader::add_resource_format_loader(vorbis_stream_loader); - ClassDB::register_class<AudioStreamOGGVorbis>(); -} - -void unregister_vorbis_types() { - - ResourceLoader::remove_resource_format_loader(vorbis_stream_loader); - vorbis_stream_loader.unref(); -} +void unregister_vorbis_types() {} diff --git a/modules/vorbis/stub/register_types.cpp b/modules/vorbis/stub/register_types.cpp deleted file mode 100644 index 8874b3887b..0000000000 --- a/modules/vorbis/stub/register_types.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/*************************************************************************/ -/* register_types.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 "register_types.h" - -// Dummy module as libvorbis is needed by other modules (theora ...) - -void register_vorbis_types() {} - -void unregister_vorbis_types() {} diff --git a/modules/vorbis/stub/register_types.h b/modules/vorbis/stub/register_types.h deleted file mode 100644 index 83d4904a87..0000000000 --- a/modules/vorbis/stub/register_types.h +++ /dev/null @@ -1,32 +0,0 @@ -/*************************************************************************/ -/* register_types.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. */ -/*************************************************************************/ - -void register_vorbis_types(); -void unregister_vorbis_types(); diff --git a/platform/android/SCsub b/platform/android/SCsub index 46f0703a65..5ca5ce548c 100644 --- a/platform/android/SCsub +++ b/platform/android/SCsub @@ -1,8 +1,5 @@ #!/usr/bin/env python -from detect import get_ndk_version -from distutils.version import LooseVersion - Import('env') android_files = [ diff --git a/platform/android/detect.py b/platform/android/detect.py index 8f74ae0ef0..ff3ca0706c 100644 --- a/platform/android/detect.py +++ b/platform/android/detect.py @@ -164,7 +164,6 @@ def configure(env): env.Tool('gcc') env.use_windows_spawn_fix() - mt_link = True if (sys.platform.startswith("linux")): host_subpath = "linux-x86_64" elif (sys.platform.startswith("darwin")): @@ -173,12 +172,8 @@ def configure(env): if (platform.machine().endswith('64')): host_subpath = "windows-x86_64" else: - mt_link = False host_subpath = "windows" - if env["android_arch"] == "arm64v8": - mt_link = False - compiler_path = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/" + host_subpath + "/bin" gcc_toolchain_path = env["ANDROID_NDK_ROOT"] + "/toolchains/" + target_subpath + "/prebuilt/" + host_subpath tools_path = gcc_toolchain_path + "/" + abi_subpath + "/bin" diff --git a/platform/android/java/lib/src/org/godotengine/godot/Godot.java b/platform/android/java/lib/src/org/godotengine/godot/Godot.java index 7db4aa6597..4e605f9950 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/Godot.java +++ b/platform/android/java/lib/src/org/godotengine/godot/Godot.java @@ -95,7 +95,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Locale; import org.godotengine.godot.input.GodotEditText; -import org.godotengine.godot.payments.PaymentsManager; import org.godotengine.godot.plugin.GodotPlugin; import org.godotengine.godot.plugin.GodotPluginRegistry; import org.godotengine.godot.utils.GodotNetUtils; @@ -174,21 +173,17 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe } public ResultCallback result_callback; - private PaymentsManager mPaymentsManager = null; - @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - if (requestCode == PaymentsManager.REQUEST_CODE_FOR_PURCHASE) { - mPaymentsManager.processPurchaseResponse(resultCode, data); - } else if (result_callback != null) { + if (result_callback != null) { result_callback.callback(requestCode, resultCode, data); result_callback = null; - }; + } for (GodotPlugin plugin : pluginRegistry.getAllPlugins()) { plugin.onMainActivityResult(requestCode, resultCode, data); } - }; + } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { @@ -445,8 +440,6 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe result_callback = null; - mPaymentsManager = PaymentsManager.createManager(this).initService(); - godot_initialized = true; } @@ -603,7 +596,6 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe @Override protected void onDestroy() { - if (mPaymentsManager != null) mPaymentsManager.destroy(); for (GodotPlugin plugin : pluginRegistry.getAllPlugins()) { plugin.onMainDestroy(); } @@ -938,10 +930,6 @@ public abstract class Godot extends FragmentActivity implements SensorEventListe return true; } - public PaymentsManager getPaymentsManager() { - return mPaymentsManager; - } - public boolean requestPermission(String p_name) { return PermissionsUtil.requestPermission(p_name, this); } diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/GodotPaymentInterface.java b/platform/android/java/lib/src/org/godotengine/godot/payments/GodotPaymentInterface.java deleted file mode 100644 index 6ac7338b30..0000000000 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/GodotPaymentInterface.java +++ /dev/null @@ -1,97 +0,0 @@ -/*************************************************************************/ -/* GodotPaymentInterface.java */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2019 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. */ -/*************************************************************************/ - -package org.godotengine.godot.payments; - -public interface GodotPaymentInterface { - void purchase(String sku, String transactionId); - - void consumeUnconsumedPurchases(); - - String getSignature(); - - void callbackSuccess(String ticket, String signature, String sku); - - void callbackSuccessProductMassConsumed(String ticket, String signature, String sku); - - void callbackSuccessNoUnconsumedPurchases(); - - void callbackFailConsume(String message); - - void callbackFail(String message); - - void callbackCancel(); - - void callbackAlreadyOwned(String sku); - - int getPurchaseCallbackId(); - - void setPurchaseCallbackId(int purchaseCallbackId); - - String getPurchaseValidationUrlPrefix(); - - void setPurchaseValidationUrlPrefix(String url); - - String getAccessToken(); - - void setAccessToken(String accessToken); - - void setTransactionId(String transactionId); - - String getTransactionId(); - - // request purchased items are not consumed - void requestPurchased(); - - // callback for requestPurchased() - void callbackPurchased(String receipt, String signature, String sku); - - void callbackDisconnected(); - - void callbackConnected(); - - // true if connected, false otherwise - boolean isConnected(); - - // consume item automatically after purchase. default is true. - void setAutoConsume(boolean autoConsume); - - // consume a specific item - void consume(String sku); - - // query in app item detail info - void querySkuDetails(String[] list); - - void addSkuDetail(String itemJson); - - void completeSkuDetail(); - - void errorSkuDetail(String errorMessage); -} diff --git a/platform/android/java/lib/aidl/com/android/vending/billing/IInAppBillingService.aidl b/platform/android/java/plugins/godotpayment/src/main/aidl/com/android/vending/billing/IInAppBillingService.aidl index 0f2bcae338..0f2bcae338 100644 --- a/platform/android/java/lib/aidl/com/android/vending/billing/IInAppBillingService.aidl +++ b/platform/android/java/plugins/godotpayment/src/main/aidl/com/android/vending/billing/IInAppBillingService.aidl diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/ConsumeTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ConsumeTask.java index 95cc48f536..c15bc232ce 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/ConsumeTask.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ConsumeTask.java @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -package org.godotengine.godot.payments; +package org.godotengine.godot.plugin.payment; import android.content.Context; import android.os.AsyncTask; diff --git a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java index 4a6b611c4d..c7d0a5de65 100644 --- a/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/GodotPayment.java @@ -30,6 +30,7 @@ package org.godotengine.godot.plugin.payment; +import android.content.Intent; import android.support.annotation.NonNull; import android.util.Log; import java.util.ArrayList; @@ -38,28 +39,40 @@ import java.util.List; import org.godotengine.godot.Dictionary; import org.godotengine.godot.Godot; import org.godotengine.godot.GodotLib; -import org.godotengine.godot.payments.GodotPaymentInterface; -import org.godotengine.godot.payments.PaymentsManager; import org.godotengine.godot.plugin.GodotPlugin; import org.json.JSONException; import org.json.JSONObject; -public class GodotPayment extends GodotPlugin implements GodotPaymentInterface { +public class GodotPayment extends GodotPlugin { private Integer purchaseCallbackId = 0; private String accessToken; private String purchaseValidationUrlPrefix; private String transactionId; - private PaymentsManager mPaymentManager; - private Dictionary mSkuDetails = new Dictionary(); + private final PaymentsManager mPaymentManager; + private final Dictionary mSkuDetails = new Dictionary(); public GodotPayment(Godot godot) { super(godot); - mPaymentManager = godot.getPaymentsManager(); - mPaymentManager.setBaseSingleton(this); + mPaymentManager = new PaymentsManager(godot, this); + mPaymentManager.initService(); } @Override + public void onMainActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == PaymentsManager.REQUEST_CODE_FOR_PURCHASE) { + mPaymentManager.processPurchaseResponse(resultCode, data); + } + } + + @Override + public void onMainDestroy() { + super.onMainDestroy(); + if (mPaymentManager != null) { + mPaymentManager.destroy(); + } + } + public void purchase(final String sku, final String transactionId) { runOnUiThread(new Runnable() { @Override @@ -69,7 +82,6 @@ public class GodotPayment extends GodotPlugin implements GodotPaymentInterface { }); } - @Override public void consumeUnconsumedPurchases() { runOnUiThread(new Runnable() { @Override @@ -81,89 +93,72 @@ public class GodotPayment extends GodotPlugin implements GodotPaymentInterface { private String signature; - @Override public String getSignature() { return this.signature; } - @Override public void callbackSuccess(String ticket, String signature, String sku) { GodotLib.calldeferred(purchaseCallbackId, "purchase_success", new Object[] { ticket, signature, sku }); } - @Override public void callbackSuccessProductMassConsumed(String ticket, String signature, String sku) { Log.d(this.getClass().getName(), "callbackSuccessProductMassConsumed > " + ticket + "," + signature + "," + sku); GodotLib.calldeferred(purchaseCallbackId, "consume_success", new Object[] { ticket, signature, sku }); } - @Override public void callbackSuccessNoUnconsumedPurchases() { GodotLib.calldeferred(purchaseCallbackId, "consume_not_required", new Object[] {}); } - @Override public void callbackFailConsume(String message) { GodotLib.calldeferred(purchaseCallbackId, "consume_fail", new Object[] { message }); } - @Override public void callbackFail(String message) { GodotLib.calldeferred(purchaseCallbackId, "purchase_fail", new Object[] { message }); } - @Override public void callbackCancel() { GodotLib.calldeferred(purchaseCallbackId, "purchase_cancel", new Object[] {}); } - @Override public void callbackAlreadyOwned(String sku) { GodotLib.calldeferred(purchaseCallbackId, "purchase_owned", new Object[] { sku }); } - @Override public int getPurchaseCallbackId() { return purchaseCallbackId; } - @Override public void setPurchaseCallbackId(int purchaseCallbackId) { this.purchaseCallbackId = purchaseCallbackId; } - @Override public String getPurchaseValidationUrlPrefix() { return this.purchaseValidationUrlPrefix; } - @Override public void setPurchaseValidationUrlPrefix(String url) { this.purchaseValidationUrlPrefix = url; } - @Override public String getAccessToken() { return accessToken; } - @Override public void setAccessToken(String accessToken) { this.accessToken = accessToken; } - @Override public void setTransactionId(String transactionId) { this.transactionId = transactionId; } - @Override public String getTransactionId() { return this.transactionId; } // request purchased items are not consumed - @Override public void requestPurchased() { runOnUiThread(new Runnable() { @Override @@ -174,41 +169,34 @@ public class GodotPayment extends GodotPlugin implements GodotPaymentInterface { } // callback for requestPurchased() - @Override public void callbackPurchased(String receipt, String signature, String sku) { GodotLib.calldeferred(purchaseCallbackId, "has_purchased", new Object[] { receipt, signature, sku }); } - @Override public void callbackDisconnected() { GodotLib.calldeferred(purchaseCallbackId, "iap_disconnected", new Object[] {}); } - @Override public void callbackConnected() { GodotLib.calldeferred(purchaseCallbackId, "iap_connected", new Object[] {}); } // true if connected, false otherwise - @Override public boolean isConnected() { return mPaymentManager.isConnected(); } // consume item automatically after purchase. default is true. - @Override public void setAutoConsume(boolean autoConsume) { mPaymentManager.setAutoConsume(autoConsume); } // consume a specific item - @Override public void consume(String sku) { mPaymentManager.consume(sku); } // query in app item detail info - @Override public void querySkuDetails(String[] list) { List<String> nKeys = Arrays.asList(list); List<String> cKeys = Arrays.asList(mSkuDetails.get_keys()); @@ -225,7 +213,6 @@ public class GodotPayment extends GodotPlugin implements GodotPaymentInterface { } } - @Override public void addSkuDetail(String itemJson) { JSONObject o = null; try { @@ -244,12 +231,10 @@ public class GodotPayment extends GodotPlugin implements GodotPaymentInterface { } } - @Override public void completeSkuDetail() { GodotLib.calldeferred(purchaseCallbackId, "sku_details_complete", new Object[] { mSkuDetails }); } - @Override public void errorSkuDetail(String errorMessage) { GodotLib.calldeferred(purchaseCallbackId, "sku_details_error", new Object[] { errorMessage }); } @@ -263,6 +248,8 @@ public class GodotPayment extends GodotPlugin implements GodotPaymentInterface { @NonNull @Override public List<String> getPluginMethods() { - return Arrays.asList("purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", "setAutoConsume", "consume", "querySkuDetails", "isConnected"); + return Arrays.asList("purchase", "setPurchaseCallbackId", "setPurchaseValidationUrlPrefix", + "setTransactionId", "getSignature", "consumeUnconsumedPurchases", "requestPurchased", + "setAutoConsume", "consume", "querySkuDetails", "isConnected"); } } diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/HandlePurchaseTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/HandlePurchaseTask.java index 23d693cc8c..fe5685288b 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/HandlePurchaseTask.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/HandlePurchaseTask.java @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -package org.godotengine.godot.payments; +package org.godotengine.godot.plugin.payment; import android.app.Activity; import android.content.Intent; diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsCache.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsCache.java index 84a7eda6e0..d5919e3d9d 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsCache.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsCache.java @@ -28,11 +28,10 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -package org.godotengine.godot.payments; +package org.godotengine.godot.plugin.payment; import android.content.Context; import android.content.SharedPreferences; -import android.util.Log; public class PaymentsCache { diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsManager.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsManager.java index 9bf6650f84..bded1f452f 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/PaymentsManager.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PaymentsManager.java @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -package org.godotengine.godot.payments; +package org.godotengine.godot.plugin.payment; import android.app.Activity; import android.content.ComponentName; @@ -52,20 +52,13 @@ public class PaymentsManager { public static final int REQUEST_CODE_FOR_PURCHASE = 0x1001; private static boolean auto_consume = true; - private Activity activity; + private final Activity activity; + private final GodotPayment godotPayment; IInAppBillingService mService; - public void setActivity(Activity activity) { - this.activity = activity; - } - - public static PaymentsManager createManager(Activity activity) { - PaymentsManager manager = new PaymentsManager(activity); - return manager; - } - - private PaymentsManager(Activity activity) { + PaymentsManager(Activity activity, GodotPayment godotPayment) { this.activity = activity; + this.godotPayment = godotPayment; } public PaymentsManager initService() { @@ -409,10 +402,4 @@ public class PaymentsManager { })) .start(); } - - private GodotPaymentInterface godotPayment; - - public void setBaseSingleton(GodotPaymentInterface godotPaymentInterface) { - this.godotPayment = godotPaymentInterface; - } } diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/PurchaseTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PurchaseTask.java index 09c9349124..eecd1d2151 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/PurchaseTask.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/PurchaseTask.java @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -package org.godotengine.godot.payments; +package org.godotengine.godot.plugin.payment; import android.app.Activity; import android.app.PendingIntent; diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ReleaseAllConsumablesTask.java index a101780511..b7bd638feb 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/ReleaseAllConsumablesTask.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ReleaseAllConsumablesTask.java @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -package org.godotengine.godot.payments; +package org.godotengine.godot.plugin.payment; import android.content.Context; import android.os.AsyncTask; diff --git a/platform/android/java/lib/src/org/godotengine/godot/payments/ValidateTask.java b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ValidateTask.java index 10c314aecf..179cc08ed1 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/payments/ValidateTask.java +++ b/platform/android/java/plugins/godotpayment/src/main/java/org/godotengine/godot/plugin/payment/ValidateTask.java @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -package org.godotengine.godot.payments; +package org.godotengine.godot.plugin.payment; import android.app.Activity; import android.app.ProgressDialog; @@ -42,7 +42,7 @@ import org.json.JSONObject; abstract public class ValidateTask { private Activity context; - private GodotPaymentInterface godotPayments; + private GodotPayment godotPayments; private ProgressDialog dialog; private String mSku; @@ -79,7 +79,7 @@ abstract public class ValidateTask { } } - public ValidateTask(Activity context, GodotPaymentInterface godotPayments) { + public ValidateTask(Activity context, GodotPayment godotPayments) { this.context = context; this.godotPayments = godotPayments; } diff --git a/platform/windows/detect.py b/platform/windows/detect.py index 3ab0d38a6a..cc859c0339 100644 --- a/platform/windows/detect.py +++ b/platform/windows/detect.py @@ -1,6 +1,9 @@ import methods import os +# To match other platforms +STACK_SIZE = 8388608 + def is_active(): return True @@ -259,6 +262,8 @@ def configure_msvc(env, manual_msvc_config): env['BUILDERS']['ProgramOriginal'] = env['BUILDERS']['Program'] env['BUILDERS']['Program'] = methods.precious_program + env.AppendUnique(LINKFLAGS=['/STACK:' + str(STACK_SIZE)]) + def configure_mingw(env): # Workaround for MinGW. See: # http://www.scons.org/wiki/LongCmdLinesOnWin32 @@ -351,6 +356,7 @@ def configure_mingw(env): env.Append(CCFLAGS=['-flto']) env.Append(LINKFLAGS=['-flto']) + env.Append(LINKFLAGS=['-Wl,--stack,' + str(STACK_SIZE)]) ## Compile flags diff --git a/scene/2d/visibility_notifier_2d.cpp b/scene/2d/visibility_notifier_2d.cpp index 366de28386..54511bbe1b 100644 --- a/scene/2d/visibility_notifier_2d.cpp +++ b/scene/2d/visibility_notifier_2d.cpp @@ -188,8 +188,7 @@ void VisibilityEnabler2D::_find_nodes(Node *p_node) { bool add = false; Variant meta; - if (enabler[ENABLER_FREEZE_BODIES]) { - + { RigidBody2D *rb2d = Object::cast_to<RigidBody2D>(p_node); if (rb2d && ((rb2d->get_mode() == RigidBody2D::MODE_CHARACTER || rb2d->get_mode() == RigidBody2D::MODE_RIGID))) { @@ -198,24 +197,21 @@ void VisibilityEnabler2D::_find_nodes(Node *p_node) { } } - if (enabler[ENABLER_PAUSE_ANIMATIONS]) { - + { AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node); if (ap) { add = true; } } - if (enabler[ENABLER_PAUSE_ANIMATED_SPRITES]) { - + { AnimatedSprite *as = Object::cast_to<AnimatedSprite>(p_node); if (as) { add = true; } } - if (enabler[ENABLER_PAUSE_PARTICLES]) { - + { Particles2D *ps = Object::cast_to<Particles2D>(p_node); if (ps) { add = true; @@ -278,7 +274,7 @@ void VisibilityEnabler2D::_change_node_state(Node *p_node, bool p_enabled) { ERR_FAIL_COND(!nodes.has(p_node)); - { + if (enabler[ENABLER_FREEZE_BODIES]) { RigidBody2D *rb = Object::cast_to<RigidBody2D>(p_node); if (rb) { @@ -286,7 +282,7 @@ void VisibilityEnabler2D::_change_node_state(Node *p_node, bool p_enabled) { } } - { + if (enabler[ENABLER_PAUSE_ANIMATIONS]) { AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node); if (ap) { @@ -294,7 +290,8 @@ void VisibilityEnabler2D::_change_node_state(Node *p_node, bool p_enabled) { ap->set_active(p_enabled); } } - { + + if (enabler[ENABLER_PAUSE_ANIMATED_SPRITES]) { AnimatedSprite *as = Object::cast_to<AnimatedSprite>(p_node); if (as) { @@ -306,7 +303,7 @@ void VisibilityEnabler2D::_change_node_state(Node *p_node, bool p_enabled) { } } - { + if (enabler[ENABLER_PAUSE_PARTICLES]) { Particles2D *ps = Object::cast_to<Particles2D>(p_node); if (ps) { diff --git a/scene/3d/visibility_notifier.cpp b/scene/3d/visibility_notifier.cpp index 986607f18d..5bc568bd5d 100644 --- a/scene/3d/visibility_notifier.cpp +++ b/scene/3d/visibility_notifier.cpp @@ -150,8 +150,7 @@ void VisibilityEnabler::_find_nodes(Node *p_node) { bool add = false; Variant meta; - if (enabler[ENABLER_FREEZE_BODIES]) { - + { RigidBody *rb = Object::cast_to<RigidBody>(p_node); if (rb && ((rb->get_mode() == RigidBody::MODE_CHARACTER || rb->get_mode() == RigidBody::MODE_RIGID))) { @@ -160,8 +159,7 @@ void VisibilityEnabler::_find_nodes(Node *p_node) { } } - if (enabler[ENABLER_PAUSE_ANIMATIONS]) { - + { AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node); if (ap) { add = true; @@ -219,14 +217,14 @@ void VisibilityEnabler::_change_node_state(Node *p_node, bool p_enabled) { ERR_FAIL_COND(!nodes.has(p_node)); - { + if (enabler[ENABLER_FREEZE_BODIES]) { RigidBody *rb = Object::cast_to<RigidBody>(p_node); if (rb) rb->set_sleeping(!p_enabled); } - { + if (enabler[ENABLER_PAUSE_ANIMATIONS]) { AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node); if (ap) { diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index dfd55e2577..8ef3bdd04e 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -2948,12 +2948,14 @@ Control *Viewport::get_modal_stack_top() const { } String Viewport::get_configuration_warning() const { - /*if (get_parent() && !Object::cast_to<Control>(get_parent()) && !render_target) { return TTR("This viewport is not set as render target. If you intend for it to display its contents directly to the screen, make it a child of a Control so it can obtain a size. Otherwise, make it a RenderTarget and assign its internal texture to some node for display."); }*/ + if (size.x == 0 || size.y == 0) { + return TTR("Viewport size must be greater than 0 to render anything."); + } return String(); } diff --git a/servers/visual/shader_language.cpp b/servers/visual/shader_language.cpp index 98f1b2e460..e73f8b8fc4 100644 --- a/servers/visual/shader_language.cpp +++ b/servers/visual/shader_language.cpp @@ -2114,7 +2114,7 @@ const ShaderLanguage::BuiltinFuncOutArgs ShaderLanguage::builtin_func_out_args[] { NULL, 0 } }; -bool ShaderLanguage::_validate_function_call(BlockNode *p_block, OperatorNode *p_func, DataType *r_ret_type, StringName *r_ret_type_str) { +bool ShaderLanguage::_validate_function_call(BlockNode *p_block, const Map<StringName, BuiltInInfo> &p_builtin_types, OperatorNode *p_func, DataType *r_ret_type, StringName *r_ret_type_str) { ERR_FAIL_COND_V(p_func->op != OP_CALL && p_func->op != OP_CONSTRUCT, false); @@ -2185,16 +2185,68 @@ bool ShaderLanguage::_validate_function_call(BlockNode *p_block, OperatorNode *p if (arg_idx < argcount) { - if (p_func->arguments[arg_idx + 1]->type != Node::TYPE_VARIABLE) { - _set_error("Argument " + itos(arg_idx + 1) + " of function '" + String(name) + "' is not a variable"); + if (p_func->arguments[arg_idx + 1]->type != Node::TYPE_VARIABLE && p_func->arguments[arg_idx + 1]->type != Node::TYPE_MEMBER && p_func->arguments[arg_idx + 1]->type != Node::TYPE_ARRAY) { + _set_error("Argument " + itos(arg_idx + 1) + " of function '" + String(name) + "' is not a variable, array or member."); return false; } - StringName var_name = static_cast<const VariableNode *>(p_func->arguments[arg_idx + 1])->name; + if (p_func->arguments[arg_idx + 1]->type == Node::TYPE_ARRAY) { + ArrayNode *mn = static_cast<ArrayNode *>(p_func->arguments[arg_idx + 1]); + if (mn->is_const) { + fail = true; + } + } else if (p_func->arguments[arg_idx + 1]->type == Node::TYPE_MEMBER) { + MemberNode *mn = static_cast<MemberNode *>(p_func->arguments[arg_idx + 1]); + if (mn->basetype_const) { + fail = true; + } + } else { // TYPE_VARIABLE + VariableNode *vn = static_cast<VariableNode *>(p_func->arguments[arg_idx + 1]); + if (vn->is_const) { + fail = true; + } else { + StringName varname = vn->name; + if (shader->uniforms.has(varname)) { + fail = true; + } else { + if (p_builtin_types.has(varname)) { + BuiltInInfo info = p_builtin_types[varname]; + if (info.constant) { + fail = true; + } + } + } + } + } + if (fail) { + _set_error(vformat("Constant value cannot be passed for '%s' parameter!", "out")); + return false; + } + + StringName var_name; + if (p_func->arguments[arg_idx + 1]->type == Node::TYPE_ARRAY) { + var_name = static_cast<const ArrayNode *>(p_func->arguments[arg_idx + 1])->name; + } else if (p_func->arguments[arg_idx + 1]->type == Node::TYPE_MEMBER) { + Node *n = static_cast<const MemberNode *>(p_func->arguments[arg_idx + 1])->owner; + while (n->type == Node::TYPE_MEMBER) { + n = static_cast<const MemberNode *>(n)->owner; + } + if (n->type != Node::TYPE_VARIABLE && n->type != Node::TYPE_ARRAY) { + _set_error("Argument " + itos(arg_idx + 1) + " of function '" + String(name) + "' is not a variable, array or member."); + return false; + } + if (n->type == Node::TYPE_VARIABLE) { + var_name = static_cast<const VariableNode *>(n)->name; + } else { // TYPE_ARRAY + var_name = static_cast<const ArrayNode *>(n)->name; + } + } else { // TYPE_VARIABLE + var_name = static_cast<const VariableNode *>(p_func->arguments[arg_idx + 1])->name; + } const BlockNode *b = p_block; bool valid = false; while (b) { - if (b->variables.has(var_name)) { + if (b->variables.has(var_name) || p_builtin_types.has(var_name)) { valid = true; break; } @@ -2210,7 +2262,7 @@ bool ShaderLanguage::_validate_function_call(BlockNode *p_block, OperatorNode *p } if (!valid) { - _set_error("Argument " + itos(arg_idx + 1) + " of function '" + String(name) + "' can only take a local variable"); + _set_error("Argument " + itos(arg_idx + 1) + " of function '" + String(name) + "' can only take a local variable, array or member."); return false; } } @@ -3197,7 +3249,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons if (!ok) return NULL; - if (!_validate_function_call(p_block, func, &func->return_cache, &func->struct_name)) { + if (!_validate_function_call(p_block, p_builtin_types, func, &func->return_cache, &func->struct_name)) { _set_error("No matching constructor found for: '" + String(funcname->name) + "'"); return NULL; } @@ -3461,7 +3513,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons if (!ok) return NULL; - if (!_validate_function_call(p_block, func, &func->return_cache, &func->struct_name)) { + if (!_validate_function_call(p_block, p_builtin_types, func, &func->return_cache, &func->struct_name)) { _set_error("No matching function found for: '" + String(funcname->name) + "'"); return NULL; } @@ -6753,6 +6805,14 @@ Error ShaderLanguage::complete(const String &p_code, const Map<StringName, Funct calltip += CharType(0xFFFF); } + if (shader->functions[i].function->arguments[j].qualifier != ArgumentQualifier::ARGUMENT_QUALIFIER_IN) { + if (shader->functions[i].function->arguments[j].qualifier == ArgumentQualifier::ARGUMENT_QUALIFIER_OUT) { + calltip += "out "; + } else { // ArgumentQualifier::ARGUMENT_QUALIFIER_INOUT + calltip += "inout "; + } + } + calltip += get_datatype_name(shader->functions[i].function->arguments[j].type); calltip += " "; calltip += shader->functions[i].function->arguments[j].name; @@ -6783,6 +6843,16 @@ Error ShaderLanguage::complete(const String &p_code, const Map<StringName, Funct continue; } + int idx2 = 0; + int out_arg = -1; + while (builtin_func_out_args[idx2].name != nullptr) { + if (builtin_func_out_args[idx2].name == builtin_func_defs[idx].name) { + out_arg = builtin_func_out_args[idx2].argument; + break; + } + idx2++; + } + if (completion_function == builtin_func_defs[idx].name) { if (builtin_func_defs[idx].tag != completion_class) { @@ -6813,6 +6883,10 @@ Error ShaderLanguage::complete(const String &p_code, const Map<StringName, Funct calltip += CharType(0xFFFF); } + if (out_arg >= 0 && i == out_arg) { + calltip += "out "; + } + calltip += get_datatype_name(builtin_func_defs[idx].args[i]); if (i == completion_argument) { diff --git a/servers/visual/shader_language.h b/servers/visual/shader_language.h index f8391dc273..239805a18e 100644 --- a/servers/visual/shader_language.h +++ b/servers/visual/shader_language.h @@ -859,7 +859,7 @@ private: Error _validate_datatype(DataType p_type); bool _compare_datatypes_in_nodes(Node *a, Node *b) const; - bool _validate_function_call(BlockNode *p_block, OperatorNode *p_func, DataType *r_ret_type, StringName *r_ret_type_str); + bool _validate_function_call(BlockNode *p_block, const Map<StringName, BuiltInInfo> &p_builtin_types, OperatorNode *p_func, DataType *r_ret_type, StringName *r_ret_type_str); bool _parse_function_arguments(BlockNode *p_block, const Map<StringName, BuiltInInfo> &p_builtin_types, OperatorNode *p_func, int *r_complete_arg = NULL); bool _propagate_function_call_sampler_uniform_settings(StringName p_name, int p_argument, TextureFilter p_filter, TextureRepeat p_repeat); bool _propagate_function_call_sampler_builtin_reference(StringName p_name, int p_argument, const StringName &p_builtin); |