diff options
Diffstat (limited to 'modules')
105 files changed, 1069 insertions, 813 deletions
diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp index ae03abca50..cc21ed28e8 100644 --- a/modules/bmp/image_loader_bmp.cpp +++ b/modules/bmp/image_loader_bmp.cpp @@ -200,7 +200,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, return err; } -Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { bmp_header_s bmp_header; Error err = ERR_INVALID_DATA; diff --git a/modules/bmp/image_loader_bmp.h b/modules/bmp/image_loader_bmp.h index cf8346ecad..0ca54de1dc 100644 --- a/modules/bmp/image_loader_bmp.h +++ b/modules/bmp/image_loader_bmp.h @@ -83,7 +83,7 @@ protected: const bmp_header_s &p_header); public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderBMP(); }; diff --git a/modules/bmp/register_types.cpp b/modules/bmp/register_types.cpp index 7c4a2085b2..67858e9d46 100644 --- a/modules/bmp/register_types.cpp +++ b/modules/bmp/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_bmp.h" -static ImageLoaderBMP *image_loader_bmp = nullptr; +static Ref<ImageLoaderBMP> image_loader_bmp; void initialize_bmp_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_bmp = memnew(ImageLoaderBMP); + image_loader_bmp.instantiate(); ImageLoader::add_image_format_loader(image_loader_bmp); } @@ -48,5 +48,6 @@ void uninitialize_bmp_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_bmp); + ImageLoader::remove_image_format_loader(image_loader_bmp); + image_loader_bmp.unref(); } diff --git a/modules/gdscript/doc_classes/@GDScript.xml b/modules/gdscript/doc_classes/@GDScript.xml index 4a38caea52..6cf8c1a30e 100644 --- a/modules/gdscript/doc_classes/@GDScript.xml +++ b/modules/gdscript/doc_classes/@GDScript.xml @@ -35,14 +35,14 @@ <description> Asserts that the [code]condition[/code] is [code]true[/code]. If the [code]condition[/code] is [code]false[/code], an error is generated. When running from the editor, the running project will also be paused until you resume it. This can be used as a stronger form of [method @GlobalScope.push_error] for reporting errors to project developers or add-on users. [b]Note:[/b] For performance reasons, the code inside [method assert] is only executed in debug builds or when running the project from the editor. Don't include code that has side effects in an [method assert] call. Otherwise, the project will behave differently when exported in release mode. - The optional [code]message[/code] argument, if given, is shown in addition to the generic "Assertion failed" message. You can use this to provide additional details about why the assertion failed. + The optional [code]message[/code] argument, if given, is shown in addition to the generic "Assertion failed" message. It must be a static string, so format strings can't be used. You can use this to provide additional details about why the assertion failed. [codeblock] # Imagine we always want speed to be between 0 and 20. var speed = -10 assert(speed < 20) # True, the program will continue assert(speed >= 0) # False, the program will stop assert(speed >= 0 and speed < 20) # You can also combine the two conditional statements in one check - assert(speed < 20, "speed = %f, but the speed limit is 20" % speed) # Show a message with clarifying details + assert(speed < 20, "the speed limit is 20") # Show a message [/codeblock] </description> </method> @@ -555,7 +555,7 @@ <annotation name="@onready"> <return type="void" /> <description> - Mark the following property as assigned on [Node]'s ready state change. Values for these properties are no assigned immediately upon the node's creation, and instead are computed and stored right before [method Node._ready]. + Mark the following property as assigned on [Node]'s ready state change. Values for these properties are not assigned immediately upon the node's creation, and instead are computed and stored right before [method Node._ready]. [codeblock] @onready var character_name: Label = $Label [/codeblock] diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 10babad378..1cff2181af 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -1077,10 +1077,12 @@ Error GDScript::load_source_code(const String &p_path) { } source = s; + path = p_path; #ifdef TOOLS_ENABLED source_changed_cache = true; -#endif - path = p_path; + set_edited(false); + set_last_modified_time(FileAccess::get_modified_time(path)); +#endif // TOOLS_ENABLED return OK; } diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index e37ac1dc3b..32d9aec84f 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -484,12 +484,23 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type if (parser->script_path == ScriptServer::get_global_class_path(first)) { result = parser->head->get_datatype(); } else { - Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(first)); - if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) { - push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); - return GDScriptParser::DataType(); + String path = ScriptServer::get_global_class_path(first); + String ext = path.get_extension(); + if (ext == GDScriptLanguage::get_singleton()->get_extension()) { + Ref<GDScriptParserRef> ref = get_parser_for(path); + if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) { + push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); + return GDScriptParser::DataType(); + } + result = ref->get_parser()->head->get_datatype(); + } else { + result.kind = GDScriptParser::DataType::SCRIPT; + result.native_type = ScriptServer::get_global_class_native_base(first); + result.script_type = ResourceLoader::load(path, "Script"); + result.script_path = path; + result.is_constant = true; + result.is_meta_type = false; } - result = ref->get_parser()->head->get_datatype(); } } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) { const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first); @@ -540,12 +551,13 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type result = ref->get_parser()->head->get_datatype(); result.is_meta_type = false; } else { - Ref<GDScript> script = member.constant->initializer->reduced_value; + Ref<Script> script = member.constant->initializer->reduced_value; result.kind = GDScriptParser::DataType::SCRIPT; result.builtin_type = Variant::OBJECT; result.script_type = script; result.script_path = script->get_path(); result.native_type = script->get_instance_base_type(); + result.is_meta_type = false; } break; } @@ -2676,31 +2688,45 @@ void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) { GDScriptParser::DataType type; - Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name)); - if (ref.is_null()) { - push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source); - type.type_source = GDScriptParser::DataType::UNDETECTED; - type.kind = GDScriptParser::DataType::VARIANT; + String path = ScriptServer::get_global_class_path(p_class_name); + String ext = path.get_extension(); + if (ext == GDScriptLanguage::get_singleton()->get_extension()) { + Ref<GDScriptParserRef> ref = get_parser_for(path); + if (ref.is_null()) { + push_error(vformat(R"(Could not find script for class "%s".)", p_class_name), p_source); + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } + + Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); + if (err) { + push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source); + type.type_source = GDScriptParser::DataType::UNDETECTED; + type.kind = GDScriptParser::DataType::VARIANT; + return type; + } + + type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + type.kind = GDScriptParser::DataType::CLASS; + type.builtin_type = Variant::OBJECT; + type.native_type = ScriptServer::get_global_class_native_base(p_class_name); + type.class_type = ref->get_parser()->head; + type.script_path = ref->get_parser()->script_path; + type.is_constant = true; + type.is_meta_type = true; return type; - } - - Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED); - if (err) { - push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source); - type.type_source = GDScriptParser::DataType::UNDETECTED; - type.kind = GDScriptParser::DataType::VARIANT; + } else { + type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; + type.kind = GDScriptParser::DataType::SCRIPT; + type.builtin_type = Variant::OBJECT; + type.native_type = ScriptServer::get_global_class_native_base(p_class_name); + type.script_type = ResourceLoader::load(path, "Script"); + type.script_path = path; + type.is_constant = true; + type.is_meta_type = true; return type; } - - type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; - type.kind = GDScriptParser::DataType::CLASS; - type.builtin_type = Variant::OBJECT; - type.native_type = ScriptServer::get_global_class_native_base(p_class_name); - type.class_type = ref->get_parser()->head; - type.script_path = ref->get_parser()->script_path; - type.is_constant = true; - type.is_meta_type = true; - return type; } void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) { @@ -3189,7 +3215,7 @@ void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) { p_preload->resolved_path = parser->script_path.get_base_dir().path_join(p_preload->resolved_path); } p_preload->resolved_path = p_preload->resolved_path.simplify_path(); - if (!FileAccess::exists(p_preload->resolved_path)) { + if (!ResourceLoader::exists(p_preload->resolved_path)) { push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path); } else { // TODO: Don't load if validating: use completion cache. @@ -3808,7 +3834,7 @@ bool GDScriptAnalyzer::get_function_signature(GDScriptParser::Node *p_source, bo Ref<Script> base_script = p_base_type.script_type; - while (base_script.is_valid() && base_script->is_valid()) { + while (base_script.is_valid() && base_script->has_method(function_name)) { MethodInfo info = base_script->get_method_info(function_name); if (!(info == MethodInfo())) { diff --git a/modules/gdscript/gdscript_cache.cpp b/modules/gdscript/gdscript_cache.cpp index 48d5fbc569..c25f5b58d5 100644 --- a/modules/gdscript/gdscript_cache.cpp +++ b/modules/gdscript/gdscript_cache.cpp @@ -146,9 +146,7 @@ String GDScriptCache::get_source_code(const String &p_path) { Vector<uint8_t> source_file; Error err; Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); - if (err) { - ERR_FAIL_COND_V(err, ""); - } + ERR_FAIL_COND_V(err, ""); uint64_t len = f->get_length(); source_file.resize(len + 1); diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 888cd782fb..d8a06a8663 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -3758,6 +3758,33 @@ bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node return false; } break; + case GDScriptParser::DataType::CLASS: + // Can assume type is a global GDScript class. + if (!ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) { + push_error(R"(Exported script type must extend Resource.)"); + return false; + } + variable->export_info.type = Variant::OBJECT; + variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE; + variable->export_info.hint_string = export_type.class_type->identifier->name; + break; + case GDScriptParser::DataType::SCRIPT: { + StringName class_name; + if (export_type.script_type != nullptr && export_type.script_type.is_valid()) { + class_name = export_type.script_type->get_language()->get_global_class_name(export_type.script_type->get_path()); + } + if (class_name == StringName()) { + Ref<Script> script = ResourceLoader::load(export_type.script_path, SNAME("Script")); + if (script.is_valid()) { + class_name = script->get_language()->get_global_class_name(export_type.script_path); + } + } + if (class_name != StringName() && ClassDB::is_parent_class(ScriptServer::get_global_class_native_base(class_name), SNAME("Resource"))) { + variable->export_info.type = Variant::OBJECT; + variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE; + variable->export_info.hint_string = class_name; + } + } break; case GDScriptParser::DataType::ENUM: { variable->export_info.type = Variant::INT; variable->export_info.hint = PROPERTY_HINT_ENUM; diff --git a/modules/gltf/SCsub b/modules/gltf/SCsub index 71f3ba58d9..5f111165fd 100644 --- a/modules/gltf/SCsub +++ b/modules/gltf/SCsub @@ -7,7 +7,7 @@ env_gltf = env_modules.Clone() # Godot source files env_gltf.add_source_files(env.modules_sources, "*.cpp") -env_gltf.add_source_files(env.modules_sources, "extensions/*.cpp") env_gltf.add_source_files(env.modules_sources, "structures/*.cpp") +SConscript("extensions/SCsub") if env["tools"]: env_gltf.add_source_files(env.modules_sources, "editor/*.cpp") diff --git a/modules/gltf/doc_classes/GLTFDocumentExtension.xml b/modules/gltf/doc_classes/GLTFDocumentExtension.xml index d2a9022445..936794976d 100644 --- a/modules/gltf/doc_classes/GLTFDocumentExtension.xml +++ b/modules/gltf/doc_classes/GLTFDocumentExtension.xml @@ -1,8 +1,10 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFDocumentExtension" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + [GLTFDocument] extension class. </brief_description> <description> + Extends the functionality of the [GLTFDocument] class by allowing you to run arbitrary code at various stages of GLTF import or export. </description> <tutorials> </tutorials> @@ -28,6 +30,12 @@ <description> </description> </method> + <method name="_get_supported_extensions" qualifiers="virtual"> + <return type="PackedStringArray" /> + <description> + Returns an array of the GLTF extensions supported by this GLTFDocumentExtension class. This is used to validate if a GLTF file with required extensions can be loaded. + </description> + </method> <method name="_import_node" qualifiers="virtual"> <return type="int" /> <param index="0" name="state" type="GLTFState" /> diff --git a/modules/gltf/doc_classes/GLTFNode.xml b/modules/gltf/doc_classes/GLTFNode.xml index e933e6046a..4d1aa89ac9 100644 --- a/modules/gltf/doc_classes/GLTFNode.xml +++ b/modules/gltf/doc_classes/GLTFNode.xml @@ -1,10 +1,13 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GLTFNode" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd"> <brief_description> + GLTF node class. </brief_description> <description> + Represents a GLTF node. GLTF nodes may have names, transforms, children (other GLTF nodes), and more specialized properties (represented by their own classes). </description> <tutorials> + <link title="GLTF scene and node spec">https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_004_ScenesNodes.md"</link> </tutorials> <members> <member name="camera" type="int" setter="set_camera" getter="get_camera" default="-1"> diff --git a/modules/gltf/doc_classes/GLTFState.xml b/modules/gltf/doc_classes/GLTFState.xml index 1dbd89aed8..6c2f488c1c 100644 --- a/modules/gltf/doc_classes/GLTFState.xml +++ b/modules/gltf/doc_classes/GLTFState.xml @@ -7,6 +7,14 @@ <tutorials> </tutorials> <methods> + <method name="add_used_extension"> + <return type="void" /> + <param index="0" name="extension_name" type="String" /> + <param index="1" name="required" type="bool" /> + <description> + Appends an extension to the list of extensions used by this GLTF file during serialization. If [param required] is true, the extension will also be added to the list of required extensions. Do not run this in [method GLTFDocumentExtension._export_post], as that stage is too late to add extensions. The final list is sorted alphabetically. + </description> + </method> <method name="get_accessors"> <return type="GLTFAccessor[]" /> <description> diff --git a/modules/gltf/extensions/SCsub b/modules/gltf/extensions/SCsub new file mode 100644 index 0000000000..ad214bb79c --- /dev/null +++ b/modules/gltf/extensions/SCsub @@ -0,0 +1,9 @@ +#!/usr/bin/env python + +Import("env") +Import("env_modules") + +env_gltf = env_modules.Clone() + +# Godot source files +env_gltf.add_source_files(env.modules_sources, "*.cpp") diff --git a/modules/gltf/gltf_defines.h b/modules/gltf/gltf_defines.h index c20c87f798..9ee2397968 100644 --- a/modules/gltf/gltf_defines.h +++ b/modules/gltf/gltf_defines.h @@ -66,9 +66,9 @@ using GLTFBufferIndex = int; using GLTFBufferViewIndex = int; using GLTFCameraIndex = int; using GLTFImageIndex = int; +using GLTFLightIndex = int; using GLTFMaterialIndex = int; using GLTFMeshIndex = int; -using GLTFLightIndex = int; using GLTFNodeIndex = int; using GLTFSkeletonIndex = int; using GLTFSkinIndex = int; diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index 6cb398b5f8..8d2e37be3a 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -191,14 +191,14 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return Error::FAILED; } - /* STEP SERIALIZE SCENE */ + /* STEP SERIALIZE LIGHTS */ err = _serialize_lights(state); if (err != OK) { return Error::FAILED; } /* STEP SERIALIZE EXTENSIONS */ - err = _serialize_extensions(state); + err = _serialize_gltf_extensions(state); if (err != OK) { return Error::FAILED; } @@ -219,9 +219,9 @@ Error GLTFDocument::_serialize(Ref<GLTFState> state, const String &p_path) { return OK; } -Error GLTFDocument::_serialize_extensions(Ref<GLTFState> state) const { - Array extensions_used; - Array extensions_required; +Error GLTFDocument::_serialize_gltf_extensions(Ref<GLTFState> state) const { + Vector<String> extensions_used = state->extensions_used; + Vector<String> extensions_required = state->extensions_required; if (!state->lights.is_empty()) { extensions_used.push_back("KHR_lights_punctual"); } @@ -230,9 +230,11 @@ Error GLTFDocument::_serialize_extensions(Ref<GLTFState> state) const { extensions_required.push_back("KHR_texture_transform"); } if (!extensions_used.is_empty()) { + extensions_used.sort(); state->json["extensionsUsed"] = extensions_used; } if (!extensions_required.is_empty()) { + extensions_required.sort(); state->json["extensionsRequired"] = extensions_required; } return OK; @@ -401,47 +403,47 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { Array nodes; for (int i = 0; i < state->nodes.size(); i++) { Dictionary node; - Ref<GLTFNode> n = state->nodes[i]; + Ref<GLTFNode> gltf_node = state->nodes[i]; Dictionary extensions; node["extensions"] = extensions; - if (!n->get_name().is_empty()) { - node["name"] = n->get_name(); + if (!gltf_node->get_name().is_empty()) { + node["name"] = gltf_node->get_name(); } - if (n->camera != -1) { - node["camera"] = n->camera; + if (gltf_node->camera != -1) { + node["camera"] = gltf_node->camera; } - if (n->light != -1) { + if (gltf_node->light != -1) { Dictionary lights_punctual; extensions["KHR_lights_punctual"] = lights_punctual; - lights_punctual["light"] = n->light; + lights_punctual["light"] = gltf_node->light; } - if (n->mesh != -1) { - node["mesh"] = n->mesh; + if (gltf_node->mesh != -1) { + node["mesh"] = gltf_node->mesh; } - if (n->skin != -1) { - node["skin"] = n->skin; + if (gltf_node->skin != -1) { + node["skin"] = gltf_node->skin; } - if (n->skeleton != -1 && n->skin < 0) { + if (gltf_node->skeleton != -1 && gltf_node->skin < 0) { } - if (n->xform != Transform3D()) { - node["matrix"] = _xform_to_array(n->xform); + if (gltf_node->xform != Transform3D()) { + node["matrix"] = _xform_to_array(gltf_node->xform); } - if (!n->rotation.is_equal_approx(Quaternion())) { - node["rotation"] = _quaternion_to_array(n->rotation); + if (!gltf_node->rotation.is_equal_approx(Quaternion())) { + node["rotation"] = _quaternion_to_array(gltf_node->rotation); } - if (!n->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) { - node["scale"] = _vec3_to_arr(n->scale); + if (!gltf_node->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) { + node["scale"] = _vec3_to_arr(gltf_node->scale); } - if (!n->position.is_zero_approx()) { - node["translation"] = _vec3_to_arr(n->position); + if (!gltf_node->position.is_zero_approx()) { + node["translation"] = _vec3_to_arr(gltf_node->position); } - if (n->children.size()) { + if (gltf_node->children.size()) { Array children; - for (int j = 0; j < n->children.size(); j++) { - children.push_back(n->children[j]); + for (int j = 0; j < gltf_node->children.size(); j++) { + children.push_back(gltf_node->children[j]); } node["children"] = children; } @@ -450,7 +452,7 @@ Error GLTFDocument::_serialize_nodes(Ref<GLTFState> state) { Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; ERR_CONTINUE(ext.is_null()); ERR_CONTINUE(!state->scene_nodes.find(i)); - Error err = ext->export_node(state, n, state->json, state->scene_nodes[i]); + Error err = ext->export_node(state, gltf_node, node, state->scene_nodes[i]); ERR_CONTINUE(err != OK); } @@ -2673,7 +2675,7 @@ Error GLTFDocument::_parse_meshes(Ref<GLTFState> state) { } else if (a.has("JOINTS_0") && a.has("JOINTS_1")) { PackedInt32Array joints_0 = _decode_accessor_as_ints(state, a["JOINTS_0"], true); PackedInt32Array joints_1 = _decode_accessor_as_ints(state, a["JOINTS_1"], true); - ERR_FAIL_COND_V(joints_0.size() != joints_0.size(), ERR_INVALID_DATA); + ERR_FAIL_COND_V(joints_0.size() != joints_1.size(), ERR_INVALID_DATA); int32_t weight_8_count = JOINT_GROUP_SIZE * 2; Vector<int> joints; joints.resize(vertex_num * weight_8_count); @@ -5046,7 +5048,7 @@ ImporterMeshInstance3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> sta return mi; } -Node3D *GLTFDocument::_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index) { +Light3D *GLTFDocument::_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index) { Ref<GLTFNode> gltf_node = state->nodes[node_index]; ERR_FAIL_INDEX_V(gltf_node->light, state->lights.size(), nullptr); @@ -5102,6 +5104,7 @@ Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> state, const GLTFNodeInde return spatial; } + void GLTFDocument::_convert_scene_node(Ref<GLTFState> state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) { bool retflag = true; _check_visibility(p_current, retflag); @@ -6916,12 +6919,32 @@ Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> r_state, uint Error GLTFDocument::_parse_gltf_extensions(Ref<GLTFState> state) { ERR_FAIL_NULL_V(state, ERR_PARSE_ERROR); - if (state->json.has("extensionsRequired") && state->json["extensionsRequired"].get_type() == Variant::ARRAY) { - Array extensions_required = state->json["extensionsRequired"]; - if (extensions_required.find("KHR_draco_mesh_compression") != -1) { - ERR_PRINT("glTF2 extension KHR_draco_mesh_compression is not supported."); - return ERR_UNAVAILABLE; + if (state->json.has("extensionsUsed")) { + Vector<String> ext_array = state->json["extensionsUsed"]; + state->extensions_used = ext_array; + } + if (state->json.has("extensionsRequired")) { + Vector<String> ext_array = state->json["extensionsRequired"]; + state->extensions_required = ext_array; + } + HashSet<String> supported_extensions; + supported_extensions.insert("KHR_lights_punctual"); + supported_extensions.insert("KHR_materials_pbrSpecularGlossiness"); + supported_extensions.insert("KHR_texture_transform"); + for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) { + Ref<GLTFDocumentExtension> ext = document_extensions[ext_i]; + ERR_CONTINUE(ext.is_null()); + Vector<String> ext_supported_extensions = ext->get_supported_extensions(); + for (int i = 0; i < ext_supported_extensions.size(); ++i) { + supported_extensions.insert(ext_supported_extensions[i]); } } - return OK; + Error ret = Error::OK; + for (int i = 0; i < state->extensions_required.size(); i++) { + if (!supported_extensions.has(state->extensions_required[i])) { + ERR_PRINT("GLTF: Can't import file '" + state->filename + "', required extension '" + String(state->extensions_required[i]) + "' is not supported. Are you missing a GLTFDocumentExtension plugin?"); + ret = ERR_UNAVAILABLE; + } + } + return ret; } diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h index 36a2f94a4e..750d3d403e 100644 --- a/modules/gltf/gltf_document.h +++ b/modules/gltf/gltf_document.h @@ -188,7 +188,7 @@ private: const GLTFNodeIndex bone_index); ImporterMeshInstance3D *_generate_mesh_instance(Ref<GLTFState> state, const GLTFNodeIndex node_index); Camera3D *_generate_camera(Ref<GLTFState> state, const GLTFNodeIndex node_index); - Node3D *_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index); + Light3D *_generate_light(Ref<GLTFState> state, const GLTFNodeIndex node_index); Node3D *_generate_spatial(Ref<GLTFState> state, const GLTFNodeIndex node_index); void _assign_scene_names(Ref<GLTFState> state); template <class T> @@ -265,7 +265,7 @@ private: Dictionary _serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material); Error _serialize_version(Ref<GLTFState> state); Error _serialize_file(Ref<GLTFState> state, const String p_path); - Error _serialize_extensions(Ref<GLTFState> state) const; + Error _serialize_gltf_extensions(Ref<GLTFState> state) const; public: // https://www.itu.int/rec/R-REC-BT.601 diff --git a/modules/gltf/gltf_document_extension.cpp b/modules/gltf/gltf_document_extension.cpp index d0bd7651e0..3b952f8246 100644 --- a/modules/gltf/gltf_document_extension.cpp +++ b/modules/gltf/gltf_document_extension.cpp @@ -31,6 +31,7 @@ #include "gltf_document_extension.h" void GLTFDocumentExtension::_bind_methods() { + GDVIRTUAL_BIND(_get_supported_extensions); GDVIRTUAL_BIND(_import_preflight, "state"); GDVIRTUAL_BIND(_import_post_parse, "state"); GDVIRTUAL_BIND(_import_node, "state", "gltf_node", "json", "node"); @@ -40,6 +41,12 @@ void GLTFDocumentExtension::_bind_methods() { GDVIRTUAL_BIND(_export_post, "state"); } +Vector<String> GLTFDocumentExtension::get_supported_extensions() { + Vector<String> ret; + GDVIRTUAL_CALL(_get_supported_extensions, ret); + return ret; +} + Error GLTFDocumentExtension::import_post(Ref<GLTFState> p_state, Node *p_root) { ERR_FAIL_NULL_V(p_root, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(p_state, ERR_INVALID_PARAMETER); diff --git a/modules/gltf/gltf_document_extension.h b/modules/gltf/gltf_document_extension.h index 0ef9109584..d4bb3993dc 100644 --- a/modules/gltf/gltf_document_extension.h +++ b/modules/gltf/gltf_document_extension.h @@ -41,6 +41,7 @@ protected: static void _bind_methods(); public: + virtual Vector<String> get_supported_extensions(); virtual Error import_preflight(Ref<GLTFState> p_state); virtual Error import_post_parse(Ref<GLTFState> p_state); virtual Error export_post(Ref<GLTFState> p_state); @@ -48,6 +49,7 @@ public: virtual Error export_preflight(Node *p_state); virtual Error import_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_json, Node *p_node); virtual Error export_node(Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node, Dictionary &r_json, Node *p_node); + GDVIRTUAL0R(Vector<String>, _get_supported_extensions); GDVIRTUAL1R(int, _import_preflight, Ref<GLTFState>); GDVIRTUAL1R(int, _import_post_parse, Ref<GLTFState>); GDVIRTUAL4R(int, _import_node, Ref<GLTFState>, Ref<GLTFNode>, Dictionary, Node *); diff --git a/modules/gltf/gltf_state.cpp b/modules/gltf/gltf_state.cpp index 85bac446cc..a23fb39503 100644 --- a/modules/gltf/gltf_state.cpp +++ b/modules/gltf/gltf_state.cpp @@ -31,6 +31,7 @@ #include "gltf_state.h" void GLTFState::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_used_extension", "extension_name", "required"), &GLTFState::add_used_extension); ClassDB::bind_method(D_METHOD("get_json"), &GLTFState::get_json); ClassDB::bind_method(D_METHOD("set_json", "json"), &GLTFState::set_json); ClassDB::bind_method(D_METHOD("get_major_version"), &GLTFState::get_major_version); @@ -112,6 +113,17 @@ void GLTFState::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "animations", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_EDITOR), "set_animations", "get_animations"); // Vector<Ref<GLTFAnimation>> } +void GLTFState::add_used_extension(const String &p_extension_name, bool p_required) { + if (!extensions_used.has(p_extension_name)) { + extensions_used.push_back(p_extension_name); + } + if (p_required) { + if (!extensions_required.has(p_extension_name)) { + extensions_required.push_back(p_extension_name); + } + } +} + Dictionary GLTFState::get_json() { return json; } diff --git a/modules/gltf/gltf_state.h b/modules/gltf/gltf_state.h index 6b2d1ca228..791431f376 100644 --- a/modules/gltf/gltf_state.h +++ b/modules/gltf/gltf_state.h @@ -78,6 +78,8 @@ class GLTFState : public Resource { Vector<int> root_nodes; Vector<Ref<GLTFTexture>> textures; Vector<Ref<Texture2D>> images; + Vector<String> extensions_used; + Vector<String> extensions_required; Vector<Ref<GLTFSkin>> skins; Vector<Ref<GLTFCamera>> cameras; @@ -97,6 +99,8 @@ protected: static void _bind_methods(); public: + void add_used_extension(const String &p_extension, bool p_required = false); + Dictionary get_json(); void set_json(Dictionary p_json); diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp index dbbccc9bcc..6e7f7d6fed 100644 --- a/modules/gltf/register_types.cpp +++ b/modules/gltf/register_types.cpp @@ -142,6 +142,11 @@ void initialize_gltf_module(ModuleInitializationLevel p_level) { GLOBAL_DEF_RST("filesystem/import/fbx/enabled", true); GDREGISTER_CLASS(EditorSceneFormatImporterBlend); GDREGISTER_CLASS(EditorSceneFormatImporterFBX); + // Can't (a priori) run external app on these platforms. + GLOBAL_DEF_RST("filesystem/import/blender/enabled.android", false); + GLOBAL_DEF_RST("filesystem/import/blender/enabled.web", false); + GLOBAL_DEF_RST("filesystem/import/fbx/enabled.android", false); + GLOBAL_DEF_RST("filesystem/import/fbx/enabled.web", false); ClassDB::set_current_api(prev_api); EditorNode::add_init_callback(_editor_init); diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml index 5548006834..ed6cb8656a 100644 --- a/modules/gridmap/doc_classes/GridMap.xml +++ b/modules/gridmap/doc_classes/GridMap.xml @@ -94,6 +94,13 @@ Returns whether or not the specified layer of the [member navigation_layers] bitmask is enabled, given a [code]layer_number[/code] between 1 and 32. </description> </method> + <method name="get_navigation_map" qualifiers="const"> + <return type="RID" /> + <description> + Returns the [RID] of the navigation map this GridMap node uses for its cell baked navigation meshes. + This function returns always the map set on the GridMap node and not the map on the NavigationServer. If the map is changed directly with the NavigationServer API the GridMap node will not be aware of the map change. + </description> + </method> <method name="get_orthogonal_index_from_basis" qualifiers="const"> <return type="int" /> <param index="0" name="basis" type="Basis" /> @@ -176,6 +183,13 @@ Based on [code]value[/code], enables or disables the specified layer in the [member navigation_layers] bitmask, given a [code]layer_number[/code] between 1 and 32. </description> </method> + <method name="set_navigation_map"> + <return type="void" /> + <param index="0" name="navigation_map" type="RID" /> + <description> + Sets the [RID] of the navigation map this GridMap node should use for its cell baked navigation meshes. + </description> + </method> </methods> <members> <member name="bake_navigation" type="bool" setter="set_bake_navigation" getter="is_baking_navigation" default="false"> diff --git a/modules/gridmap/editor/grid_map_editor_plugin.cpp b/modules/gridmap/editor/grid_map_editor_plugin.cpp index 17f9832096..b5afd8507d 100644 --- a/modules/gridmap/editor/grid_map_editor_plugin.cpp +++ b/modules/gridmap/editor/grid_map_editor_plugin.cpp @@ -603,13 +603,13 @@ EditorPlugin::AfterGUIInput GridMapEditor::forward_spatial_input_event(Camera3D Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid()) { - if (mb->get_button_index() == MouseButton::WHEEL_UP && (mb->is_command_pressed() || mb->is_shift_pressed())) { + if (mb->get_button_index() == MouseButton::WHEEL_UP && (mb->is_command_or_control_pressed() || mb->is_shift_pressed())) { if (mb->is_pressed()) { floor->set_value(floor->get_value() + mb->get_factor()); } return EditorPlugin::AFTER_GUI_INPUT_STOP; // Eaten. - } else if (mb->get_button_index() == MouseButton::WHEEL_DOWN && (mb->is_command_pressed() || mb->is_shift_pressed())) { + } else if (mb->get_button_index() == MouseButton::WHEEL_DOWN && (mb->is_command_or_control_pressed() || mb->is_shift_pressed())) { if (mb->is_pressed()) { floor->set_value(floor->get_value() - mb->get_factor()); } @@ -629,7 +629,7 @@ EditorPlugin::AfterGUIInput GridMapEditor::forward_spatial_input_event(Camera3D } else if (mb->is_shift_pressed() && can_edit) { input_action = INPUT_SELECT; last_selection = selection; - } else if (mb->is_command_pressed() && can_edit) { + } else if (mb->is_command_or_control_pressed() && can_edit) { input_action = INPUT_PICK; } else { input_action = INPUT_PAINT; @@ -746,7 +746,7 @@ EditorPlugin::AfterGUIInput GridMapEditor::forward_spatial_input_event(Camera3D Ref<InputEventPanGesture> pan_gesture = p_event; if (pan_gesture.is_valid()) { - if (pan_gesture->is_alt_pressed() && (pan_gesture->is_command_pressed() || pan_gesture->is_shift_pressed())) { + if (pan_gesture->is_alt_pressed() && (pan_gesture->is_command_or_control_pressed() || pan_gesture->is_shift_pressed())) { const real_t delta = pan_gesture->get_delta().y * 0.5; accumulated_floor_delta += delta; int step = 0; @@ -807,7 +807,7 @@ void GridMapEditor::_mesh_library_palette_input(const Ref<InputEvent> &p_ie) { const Ref<InputEventMouseButton> mb = p_ie; // Zoom in/out using Ctrl + mouse wheel - if (mb.is_valid() && mb->is_pressed() && mb->is_command_pressed()) { + if (mb.is_valid() && mb->is_pressed() && mb->is_command_or_control_pressed()) { if (mb->is_pressed() && mb->get_button_index() == MouseButton::WHEEL_UP) { size_slider->set_value(size_slider->get_value() + 0.2); } diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index ac0755cf68..466a2efd21 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -226,6 +226,27 @@ bool GridMap::is_baking_navigation() { return bake_navigation; } +void GridMap::set_navigation_map(RID p_navigation_map) { + map_override = p_navigation_map; + for (const KeyValue<OctantKey, Octant *> &E : octant_map) { + Octant &g = *octant_map[E.key]; + for (KeyValue<IndexKey, Octant::NavMesh> &F : g.navmesh_ids) { + if (F.value.region.is_valid()) { + NavigationServer3D::get_singleton()->region_set_map(F.value.region, map_override); + } + } + } +} + +RID GridMap::get_navigation_map() const { + if (map_override.is_valid()) { + return map_override; + } else if (is_inside_tree()) { + return get_world_3d()->get_navigation_map(); + } + return RID(); +} + void GridMap::set_navigation_layers(uint32_t p_navigation_layers) { navigation_layers = p_navigation_layers; _recreate_octant_data(); @@ -639,10 +660,15 @@ bool GridMap::_octant_update(const OctantKey &p_key) { NavigationServer3D::get_singleton()->region_set_navmesh(region, navmesh); NavigationServer3D::get_singleton()->region_set_transform(region, get_global_transform() * nm.xform); if (is_inside_tree()) { - NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); + if (map_override.is_valid()) { + NavigationServer3D::get_singleton()->region_set_map(region, map_override); + } else { + NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); + } } nm.region = region; +#ifdef DEBUG_ENABLED // add navigation debugmesh visual instances if debug is enabled SceneTree *st = SceneTree::get_singleton(); if (st && st->is_debugging_navigation_hint()) { @@ -650,15 +676,14 @@ bool GridMap::_octant_update(const OctantKey &p_key) { RID navmesh_debug_rid = navmesh->get_debug_mesh()->get_rid(); nm.navmesh_debug_instance = RS::get_singleton()->instance_create(); RS::get_singleton()->instance_set_base(nm.navmesh_debug_instance, navmesh_debug_rid); - RS::get_singleton()->mesh_surface_set_material(navmesh_debug_rid, 0, st->get_debug_navigation_material()->get_rid()); } if (is_inside_tree()) { RS::get_singleton()->instance_set_scenario(nm.navmesh_debug_instance, get_world_3d()->get_scenario()); RS::get_singleton()->instance_set_transform(nm.navmesh_debug_instance, get_global_transform() * nm.xform); } } +#endif // DEBUG_ENABLED } - g.navmesh_ids[E] = nm; } } @@ -757,7 +782,11 @@ void GridMap::_octant_enter_world(const OctantKey &p_key) { NavigationServer3D::get_singleton()->region_set_navigation_layers(region, navigation_layers); NavigationServer3D::get_singleton()->region_set_navmesh(region, nm); NavigationServer3D::get_singleton()->region_set_transform(region, get_global_transform() * F.value.xform); - NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); + if (map_override.is_valid()) { + NavigationServer3D::get_singleton()->region_set_map(region, map_override); + } else { + NavigationServer3D::get_singleton()->region_set_map(region, get_world_3d()->get_navigation_map()); + } F.value.region = region; } @@ -1022,6 +1051,9 @@ void GridMap::_bind_methods() { ClassDB::bind_method(D_METHOD("set_bake_navigation", "bake_navigation"), &GridMap::set_bake_navigation); ClassDB::bind_method(D_METHOD("is_baking_navigation"), &GridMap::is_baking_navigation); + ClassDB::bind_method(D_METHOD("set_navigation_map", "navigation_map"), &GridMap::set_navigation_map); + ClassDB::bind_method(D_METHOD("get_navigation_map"), &GridMap::get_navigation_map); + ClassDB::bind_method(D_METHOD("set_navigation_layers", "layers"), &GridMap::set_navigation_layers); ClassDB::bind_method(D_METHOD("get_navigation_layers"), &GridMap::get_navigation_layers); diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h index 4a4e970fd3..6a53457d25 100644 --- a/modules/gridmap/grid_map.h +++ b/modules/gridmap/grid_map.h @@ -152,6 +152,7 @@ class GridMap : public Node3D { uint32_t collision_mask = 1; Ref<PhysicsMaterial> physics_material; bool bake_navigation = false; + RID map_override; uint32_t navigation_layers = 1; Transform3D last_transform; @@ -247,6 +248,9 @@ public: void set_bake_navigation(bool p_bake_navigation); bool is_baking_navigation(); + void set_navigation_map(RID p_navigation_map); + RID get_navigation_map() const; + void set_navigation_layers(uint32_t p_navigation_layers); uint32_t get_navigation_layers() const; diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp index e7c6fe592d..6f0bc16a26 100644 --- a/modules/hdr/image_loader_hdr.cpp +++ b/modules/hdr/image_loader_hdr.cpp @@ -33,7 +33,7 @@ #include "core/os/os.h" #include "core/string/print_string.h" -Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { String header = f->get_token(); ERR_FAIL_COND_V_MSG(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED, "Unsupported header information in HDR: " + header + "."); diff --git a/modules/hdr/image_loader_hdr.h b/modules/hdr/image_loader_hdr.h index 1bff05129b..5f817f0ba8 100644 --- a/modules/hdr/image_loader_hdr.h +++ b/modules/hdr/image_loader_hdr.h @@ -35,7 +35,7 @@ class ImageLoaderHDR : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderHDR(); }; diff --git a/modules/hdr/register_types.cpp b/modules/hdr/register_types.cpp index b988bf4587..18b1a73f1c 100644 --- a/modules/hdr/register_types.cpp +++ b/modules/hdr/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_hdr.h" -static ImageLoaderHDR *image_loader_hdr = nullptr; +static Ref<ImageLoaderHDR> image_loader_hdr; void initialize_hdr_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_hdr = memnew(ImageLoaderHDR); + image_loader_hdr.instantiate(); ImageLoader::add_image_format_loader(image_loader_hdr); } @@ -48,5 +48,6 @@ void uninitialize_hdr_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_hdr); + ImageLoader::remove_image_format_loader(image_loader_hdr); + image_loader_hdr.unref(); } diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index 3e138bf633..ce20ac9060 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -104,7 +104,7 @@ Error jpeg_load_image_from_buffer(Image *p_image, const uint8_t *p_buffer, int p return OK; } -Error ImageLoaderJPG::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderJPG::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); diff --git a/modules/jpg/image_loader_jpegd.h b/modules/jpg/image_loader_jpegd.h index caa0461d05..f63db51521 100644 --- a/modules/jpg/image_loader_jpegd.h +++ b/modules/jpg/image_loader_jpegd.h @@ -35,7 +35,7 @@ class ImageLoaderJPG : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderJPG(); }; diff --git a/modules/jpg/register_types.cpp b/modules/jpg/register_types.cpp index b8b48a550f..7da216bbe2 100644 --- a/modules/jpg/register_types.cpp +++ b/modules/jpg/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_jpegd.h" -static ImageLoaderJPG *image_loader_jpg = nullptr; +static Ref<ImageLoaderJPG> image_loader_jpg; void initialize_jpg_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_jpg = memnew(ImageLoaderJPG); + image_loader_jpg.instantiate(); ImageLoader::add_image_format_loader(image_loader_jpg); } @@ -48,5 +48,6 @@ void uninitialize_jpg_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_jpg); + ImageLoader::remove_image_format_loader(image_loader_jpg); + image_loader_jpg.unref(); } diff --git a/modules/mbedtls/crypto_mbedtls.h b/modules/mbedtls/crypto_mbedtls.h index 5ba7e9cbf6..f129ef6f11 100644 --- a/modules/mbedtls/crypto_mbedtls.h +++ b/modules/mbedtls/crypto_mbedtls.h @@ -39,7 +39,7 @@ #include <mbedtls/ssl.h> class CryptoMbedTLS; -class SSLContextMbedTLS; +class TLSContextMbedTLS; class CryptoKeyMbedTLS : public CryptoKey { private: mbedtls_pk_context pkey; @@ -69,7 +69,7 @@ public: _FORCE_INLINE_ void unlock() { locks--; } friend class CryptoMbedTLS; - friend class SSLContextMbedTLS; + friend class TLSContextMbedTLS; }; class X509CertificateMbedTLS : public X509Certificate { @@ -98,7 +98,7 @@ public: _FORCE_INLINE_ void unlock() { locks--; } friend class CryptoMbedTLS; - friend class SSLContextMbedTLS; + friend class TLSContextMbedTLS; }; class HMACContextMbedTLS : public HMACContext { diff --git a/modules/mbedtls/dtls_server_mbedtls.h b/modules/mbedtls/dtls_server_mbedtls.h index a6626c9f65..0c9f10b5ed 100644 --- a/modules/mbedtls/dtls_server_mbedtls.h +++ b/modules/mbedtls/dtls_server_mbedtls.h @@ -32,7 +32,7 @@ #define DTLS_SERVER_MBEDTLS_H #include "core/io/dtls_server.h" -#include "ssl_context_mbedtls.h" +#include "tls_context_mbedtls.h" class DTLSServerMbedTLS : public DTLSServer { private: diff --git a/modules/mbedtls/packet_peer_mbed_dtls.cpp b/modules/mbedtls/packet_peer_mbed_dtls.cpp index 78a06ff4a1..e84d95773d 100644 --- a/modules/mbedtls/packet_peer_mbed_dtls.cpp +++ b/modules/mbedtls/packet_peer_mbed_dtls.cpp @@ -79,7 +79,7 @@ int PacketPeerMbedDTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { } void PacketPeerMbedDTLS::_cleanup() { - ssl_ctx->clear(); + tls_ctx->clear(); base = Ref<PacketPeer>(); status = STATUS_DISCONNECTED; } @@ -91,16 +91,16 @@ int PacketPeerMbedDTLS::_set_cookie() { uint16_t port = base->get_packet_port(); memcpy(client_id, addr.get_ipv6(), 16); memcpy(&client_id[16], (uint8_t *)&port, 2); - return mbedtls_ssl_set_client_transport_id(ssl_ctx->get_context(), client_id, 18); + return mbedtls_ssl_set_client_transport_id(tls_ctx->get_context(), client_id, 18); } Error PacketPeerMbedDTLS::_do_handshake() { int ret = 0; - while ((ret = mbedtls_ssl_handshake(ssl_ctx->get_context())) != 0) { + while ((ret = mbedtls_ssl_handshake(tls_ctx->get_context())) != 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { if (ret != MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) { ERR_PRINT("TLS handshake error: " + itos(ret)); - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); } _cleanup(); status = STATUS_ERROR; @@ -121,12 +121,12 @@ Error PacketPeerMbedDTLS::connect_to_peer(Ref<PacketPeerUDP> p_base, bool p_vali int ret = 0; int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE; - Error err = ssl_ctx->init_client(MBEDTLS_SSL_TRANSPORT_DATAGRAM, authmode, p_ca_certs); + Error err = tls_ctx->init_client(MBEDTLS_SSL_TRANSPORT_DATAGRAM, authmode, p_ca_certs); ERR_FAIL_COND_V(err != OK, err); - mbedtls_ssl_set_hostname(ssl_ctx->get_context(), p_for_hostname.utf8().get_data()); - mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, nullptr); - mbedtls_ssl_set_timer_cb(ssl_ctx->get_context(), &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); + mbedtls_ssl_set_hostname(tls_ctx->get_context(), p_for_hostname.utf8().get_data()); + mbedtls_ssl_set_bio(tls_ctx->get_context(), this, bio_send, bio_recv, nullptr); + mbedtls_ssl_set_timer_cb(tls_ctx->get_context(), &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); status = STATUS_HANDSHAKING; @@ -139,13 +139,13 @@ Error PacketPeerMbedDTLS::connect_to_peer(Ref<PacketPeerUDP> p_base, bool p_vali } Error PacketPeerMbedDTLS::accept_peer(Ref<PacketPeerUDP> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain, Ref<CookieContextMbedTLS> p_cookies) { - Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert, p_cookies); + Error err = tls_ctx->init_server(MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert, p_cookies); ERR_FAIL_COND_V(err != OK, err); base = p_base; base->set_blocking_mode(false); - mbedtls_ssl_session_reset(ssl_ctx->get_context()); + mbedtls_ssl_session_reset(tls_ctx->get_context()); int ret = _set_cookie(); if (ret != 0) { @@ -153,8 +153,8 @@ Error PacketPeerMbedDTLS::accept_peer(Ref<PacketPeerUDP> p_base, Ref<CryptoKey> ERR_FAIL_V_MSG(FAILED, "Error setting DTLS client cookie"); } - mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, nullptr); - mbedtls_ssl_set_timer_cb(ssl_ctx->get_context(), &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); + mbedtls_ssl_set_bio(tls_ctx->get_context(), this, bio_send, bio_recv, nullptr); + mbedtls_ssl_set_timer_cb(tls_ctx->get_context(), &timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay); status = STATUS_HANDSHAKING; @@ -173,11 +173,11 @@ Error PacketPeerMbedDTLS::put_packet(const uint8_t *p_buffer, int p_bytes) { return OK; } - int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_buffer, p_bytes); + int ret = mbedtls_ssl_write(tls_ctx->get_context(), p_buffer, p_bytes); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { ret = 0; // non blocking io } else if (ret <= 0) { - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); _cleanup(); return ERR_CONNECTION_ERROR; } @@ -190,7 +190,7 @@ Error PacketPeerMbedDTLS::get_packet(const uint8_t **r_buffer, int &r_bytes) { r_bytes = 0; - int ret = mbedtls_ssl_read(ssl_ctx->get_context(), packet_buffer, PACKET_BUFFER_SIZE); + int ret = mbedtls_ssl_read(tls_ctx->get_context(), packet_buffer, PACKET_BUFFER_SIZE); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { ret = 0; // non blocking io } else if (ret <= 0) { @@ -200,7 +200,7 @@ Error PacketPeerMbedDTLS::get_packet(const uint8_t **r_buffer, int &r_bytes) { } else { _cleanup(); status = STATUS_ERROR; - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); } return ERR_CONNECTION_ERROR; } @@ -220,7 +220,7 @@ void PacketPeerMbedDTLS::poll() { ERR_FAIL_COND(!base.is_valid()); - int ret = mbedtls_ssl_read(ssl_ctx->get_context(), nullptr, 0); + int ret = mbedtls_ssl_read(tls_ctx->get_context(), nullptr, 0); if (ret < 0 && ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { @@ -229,7 +229,7 @@ void PacketPeerMbedDTLS::poll() { } else { _cleanup(); status = STATUS_ERROR; - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); } } } @@ -237,7 +237,7 @@ void PacketPeerMbedDTLS::poll() { int PacketPeerMbedDTLS::get_available_packet_count() const { ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0); - return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl)) > 0 ? 1 : 0; + return mbedtls_ssl_get_bytes_avail(&(tls_ctx->tls)) > 0 ? 1 : 0; } int PacketPeerMbedDTLS::get_max_packet_size() const { @@ -245,7 +245,7 @@ int PacketPeerMbedDTLS::get_max_packet_size() const { } PacketPeerMbedDTLS::PacketPeerMbedDTLS() { - ssl_ctx.instantiate(); + tls_ctx.instantiate(); } PacketPeerMbedDTLS::~PacketPeerMbedDTLS() { @@ -261,7 +261,7 @@ void PacketPeerMbedDTLS::disconnect_from_peer() { int ret = 0; // Send SSL close notification, blocking, but ignore other errors. do { - ret = mbedtls_ssl_close_notify(ssl_ctx->get_context()); + ret = mbedtls_ssl_close_notify(tls_ctx->get_context()); } while (ret == MBEDTLS_ERR_SSL_WANT_WRITE); } diff --git a/modules/mbedtls/packet_peer_mbed_dtls.h b/modules/mbedtls/packet_peer_mbed_dtls.h index 5f2f42cd30..cc79057d67 100644 --- a/modules/mbedtls/packet_peer_mbed_dtls.h +++ b/modules/mbedtls/packet_peer_mbed_dtls.h @@ -32,7 +32,7 @@ #define PACKET_PEER_MBED_DTLS_H #include "core/io/packet_peer_dtls.h" -#include "ssl_context_mbedtls.h" +#include "tls_context_mbedtls.h" #include <mbedtls/timing.h> @@ -56,7 +56,7 @@ private: void _cleanup(); protected: - Ref<SSLContextMbedTLS> ssl_ctx; + Ref<TLSContextMbedTLS> tls_ctx; mbedtls_timing_delay_context timer; Error _do_handshake(); diff --git a/modules/mbedtls/register_types.cpp b/modules/mbedtls/register_types.cpp index 2d4a18b3fc..675091b617 100644 --- a/modules/mbedtls/register_types.cpp +++ b/modules/mbedtls/register_types.cpp @@ -45,7 +45,7 @@ void initialize_mbedtls_module(ModuleInitializationLevel p_level) { } CryptoMbedTLS::initialize_crypto(); - StreamPeerMbedTLS::initialize_ssl(); + StreamPeerMbedTLS::initialize_tls(); PacketPeerMbedDTLS::initialize_dtls(); DTLSServerMbedTLS::initialize(); } @@ -57,6 +57,6 @@ void uninitialize_mbedtls_module(ModuleInitializationLevel p_level) { DTLSServerMbedTLS::finalize(); PacketPeerMbedDTLS::finalize_dtls(); - StreamPeerMbedTLS::finalize_ssl(); + StreamPeerMbedTLS::finalize_tls(); CryptoMbedTLS::finalize_crypto(); } diff --git a/modules/mbedtls/stream_peer_mbedtls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp index 0bf4ca7032..a97c6bd916 100644 --- a/modules/mbedtls/stream_peer_mbedtls.cpp +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -74,18 +74,18 @@ int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { } void StreamPeerMbedTLS::_cleanup() { - ssl_ctx->clear(); + tls_ctx->clear(); base = Ref<StreamPeer>(); status = STATUS_DISCONNECTED; } Error StreamPeerMbedTLS::_do_handshake() { int ret = 0; - while ((ret = mbedtls_ssl_handshake(ssl_ctx->get_context())) != 0) { + while ((ret = mbedtls_ssl_handshake(tls_ctx->get_context())) != 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { // An error occurred. ERR_PRINT("TLS handshake error: " + itos(ret)); - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); status = STATUS_ERROR; return FAILED; @@ -108,11 +108,11 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida base = p_base; int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE; - Error err = ssl_ctx->init_client(MBEDTLS_SSL_TRANSPORT_STREAM, authmode, p_ca_certs); + Error err = tls_ctx->init_client(MBEDTLS_SSL_TRANSPORT_STREAM, authmode, p_ca_certs); ERR_FAIL_COND_V(err != OK, err); - mbedtls_ssl_set_hostname(ssl_ctx->get_context(), p_for_hostname.utf8().get_data()); - mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, nullptr); + mbedtls_ssl_set_hostname(tls_ctx->get_context(), p_for_hostname.utf8().get_data()); + mbedtls_ssl_set_bio(tls_ctx->get_context(), this, bio_send, bio_recv, nullptr); status = STATUS_HANDSHAKING; @@ -127,12 +127,12 @@ Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base, Ref<CryptoKey> p_key, Ref<X509Certificate> p_cert, Ref<X509Certificate> p_ca_chain) { ERR_FAIL_COND_V(p_base.is_null(), ERR_INVALID_PARAMETER); - Error err = ssl_ctx->init_server(MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert); + Error err = tls_ctx->init_server(MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_VERIFY_NONE, p_key, p_cert); ERR_FAIL_COND_V(err != OK, err); base = p_base; - mbedtls_ssl_set_bio(ssl_ctx->get_context(), this, bio_send, bio_recv, nullptr); + mbedtls_ssl_set_bio(tls_ctx->get_context(), this, bio_send, bio_recv, nullptr); status = STATUS_HANDSHAKING; @@ -173,7 +173,7 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in return OK; } - int ret = mbedtls_ssl_write(ssl_ctx->get_context(), p_data, p_bytes); + int ret = mbedtls_ssl_write(tls_ctx->get_context(), p_data, p_bytes); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { // Non blocking IO ret = 0; @@ -182,7 +182,7 @@ Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, in disconnect_from_stream(); return ERR_FILE_EOF; } else if (ret <= 0) { - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); return ERR_CONNECTION_ERROR; } @@ -216,7 +216,7 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r r_received = 0; - int ret = mbedtls_ssl_read(ssl_ctx->get_context(), p_buffer, p_bytes); + int ret = mbedtls_ssl_read(tls_ctx->get_context(), p_buffer, p_bytes); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { ret = 0; // non blocking io } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { @@ -224,7 +224,7 @@ Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r disconnect_from_stream(); return ERR_FILE_EOF; } else if (ret <= 0) { - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); return ERR_CONNECTION_ERROR; } @@ -245,7 +245,7 @@ void StreamPeerMbedTLS::poll() { // We could pass nullptr as second parameter, but some behaviour sanitizers don't seem to like that. // Passing a 1 byte buffer to workaround it. uint8_t byte; - int ret = mbedtls_ssl_read(ssl_ctx->get_context(), &byte, 0); + int ret = mbedtls_ssl_read(tls_ctx->get_context(), &byte, 0); if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) { // Nothing to read/write (non blocking IO) @@ -254,7 +254,7 @@ void StreamPeerMbedTLS::poll() { disconnect_from_stream(); return; } else if (ret < 0) { - SSLContextMbedTLS::print_mbedtls_error(ret); + TLSContextMbedTLS::print_mbedtls_error(ret); disconnect_from_stream(); return; } @@ -269,11 +269,11 @@ void StreamPeerMbedTLS::poll() { int StreamPeerMbedTLS::get_available_bytes() const { ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0); - return mbedtls_ssl_get_bytes_avail(&(ssl_ctx->ssl)); + return mbedtls_ssl_get_bytes_avail(&(tls_ctx->tls)); } StreamPeerMbedTLS::StreamPeerMbedTLS() { - ssl_ctx.instantiate(); + tls_ctx.instantiate(); } StreamPeerMbedTLS::~StreamPeerMbedTLS() { @@ -288,7 +288,7 @@ void StreamPeerMbedTLS::disconnect_from_stream() { Ref<StreamPeerTCP> tcp = base; if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) { // We are still connected on the socket, try to send close notify. - mbedtls_ssl_close_notify(ssl_ctx->get_context()); + mbedtls_ssl_close_notify(tls_ctx->get_context()); } _cleanup(); @@ -306,12 +306,12 @@ StreamPeerTLS *StreamPeerMbedTLS::_create_func() { return memnew(StreamPeerMbedTLS); } -void StreamPeerMbedTLS::initialize_ssl() { +void StreamPeerMbedTLS::initialize_tls() { _create = _create_func; available = true; } -void StreamPeerMbedTLS::finalize_ssl() { +void StreamPeerMbedTLS::finalize_tls() { available = false; _create = nullptr; } diff --git a/modules/mbedtls/stream_peer_mbedtls.h b/modules/mbedtls/stream_peer_mbedtls.h index 12d06d05ed..9219269539 100644 --- a/modules/mbedtls/stream_peer_mbedtls.h +++ b/modules/mbedtls/stream_peer_mbedtls.h @@ -32,7 +32,7 @@ #define STREAM_PEER_MBEDTLS_H #include "core/io/stream_peer_tls.h" -#include "ssl_context_mbedtls.h" +#include "tls_context_mbedtls.h" class StreamPeerMbedTLS : public StreamPeerTLS { private: @@ -48,7 +48,7 @@ private: void _cleanup(); protected: - Ref<SSLContextMbedTLS> ssl_ctx; + Ref<TLSContextMbedTLS> tls_ctx; Error _do_handshake(); @@ -69,8 +69,8 @@ public: virtual int get_available_bytes() const; - static void initialize_ssl(); - static void finalize_ssl(); + static void initialize_tls(); + static void finalize_tls(); StreamPeerMbedTLS(); ~StreamPeerMbedTLS(); diff --git a/modules/mbedtls/ssl_context_mbedtls.cpp b/modules/mbedtls/tls_context_mbedtls.cpp index e2dad074cc..1ae7bc0436 100644 --- a/modules/mbedtls/ssl_context_mbedtls.cpp +++ b/modules/mbedtls/tls_context_mbedtls.cpp @@ -1,5 +1,5 @@ /*************************************************************************/ -/* ssl_context_mbedtls.cpp */ +/* tls_context_mbedtls.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,7 +28,7 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#include "ssl_context_mbedtls.h" +#include "tls_context_mbedtls.h" static void my_debug(void *ctx, int level, const char *file, int line, @@ -37,7 +37,7 @@ static void my_debug(void *ctx, int level, fflush(stdout); } -void SSLContextMbedTLS::print_mbedtls_error(int p_ret) { +void TLSContextMbedTLS::print_mbedtls_error(int p_ret) { printf("mbedtls error: returned -0x%x\n\n", -p_ret); fflush(stdout); } @@ -82,12 +82,12 @@ CookieContextMbedTLS::~CookieContextMbedTLS() { clear(); } -/// SSLContextMbedTLS +/// TLSContextMbedTLS -Error SSLContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) { +Error TLSContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) { ERR_FAIL_COND_V_MSG(inited, ERR_ALREADY_IN_USE, "This SSL context is already active"); - mbedtls_ssl_init(&ssl); + mbedtls_ssl_init(&tls); mbedtls_ssl_config_init(&conf); mbedtls_ctr_drbg_init(&ctr_drbg); mbedtls_entropy_init(&entropy); @@ -110,7 +110,7 @@ Error SSLContextMbedTLS::_setup(int p_endpoint, int p_transport, int p_authmode) return OK; } -Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert, Ref<CookieContextMbedTLS> p_cookies) { +Error TLSContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<CryptoKeyMbedTLS> p_pkey, Ref<X509CertificateMbedTLS> p_cert, Ref<CookieContextMbedTLS> p_cookies) { ERR_FAIL_COND_V(!p_pkey.is_valid(), ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(!p_cert.is_valid(), ERR_INVALID_PARAMETER); @@ -146,11 +146,11 @@ Error SSLContextMbedTLS::init_server(int p_transport, int p_authmode, Ref<Crypto cookies = p_cookies; mbedtls_ssl_conf_dtls_cookies(&conf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &(cookies->cookie_ctx)); } - mbedtls_ssl_setup(&ssl, &conf); + mbedtls_ssl_setup(&tls, &conf); return OK; } -Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas) { +Error TLSContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509CertificateMbedTLS> p_valid_cas) { Error err = _setup(MBEDTLS_SSL_IS_CLIENT, p_transport, p_authmode); ERR_FAIL_COND_V(err != OK, err); @@ -172,15 +172,15 @@ Error SSLContextMbedTLS::init_client(int p_transport, int p_authmode, Ref<X509Ce // Set valid CAs mbedtls_ssl_conf_ca_chain(&conf, &(cas->cert), nullptr); - mbedtls_ssl_setup(&ssl, &conf); + mbedtls_ssl_setup(&tls, &conf); return OK; } -void SSLContextMbedTLS::clear() { +void TLSContextMbedTLS::clear() { if (!inited) { return; } - mbedtls_ssl_free(&ssl); + mbedtls_ssl_free(&tls); mbedtls_ssl_config_free(&conf); mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); @@ -198,14 +198,14 @@ void SSLContextMbedTLS::clear() { inited = false; } -mbedtls_ssl_context *SSLContextMbedTLS::get_context() { +mbedtls_ssl_context *TLSContextMbedTLS::get_context() { ERR_FAIL_COND_V(!inited, nullptr); - return &ssl; + return &tls; } -SSLContextMbedTLS::SSLContextMbedTLS() { +TLSContextMbedTLS::TLSContextMbedTLS() { } -SSLContextMbedTLS::~SSLContextMbedTLS() { +TLSContextMbedTLS::~TLSContextMbedTLS() { clear(); } diff --git a/modules/mbedtls/ssl_context_mbedtls.h b/modules/mbedtls/tls_context_mbedtls.h index 5883388311..5e7b3dc46e 100644 --- a/modules/mbedtls/ssl_context_mbedtls.h +++ b/modules/mbedtls/tls_context_mbedtls.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* ssl_context_mbedtls.h */ +/* tls_context_mbedtls.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef SSL_CONTEXT_MBEDTLS_H -#define SSL_CONTEXT_MBEDTLS_H +#ifndef TLS_CONTEXT_MBEDTLS_H +#define TLS_CONTEXT_MBEDTLS_H #include "crypto_mbedtls.h" @@ -44,10 +44,10 @@ #include <mbedtls/ssl.h> #include <mbedtls/ssl_cookie.h> -class SSLContextMbedTLS; +class TLSContextMbedTLS; class CookieContextMbedTLS : public RefCounted { - friend class SSLContextMbedTLS; + friend class TLSContextMbedTLS; protected: bool inited = false; @@ -63,7 +63,7 @@ public: ~CookieContextMbedTLS(); }; -class SSLContextMbedTLS : public RefCounted { +class TLSContextMbedTLS : public RefCounted { protected: bool inited = false; @@ -73,7 +73,7 @@ public: Ref<X509CertificateMbedTLS> certs; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; - mbedtls_ssl_context ssl; + mbedtls_ssl_context tls; mbedtls_ssl_config conf; Ref<CookieContextMbedTLS> cookies; @@ -86,8 +86,8 @@ public: mbedtls_ssl_context *get_context(); - SSLContextMbedTLS(); - ~SSLContextMbedTLS(); + TLSContextMbedTLS(); + ~TLSContextMbedTLS(); }; -#endif // SSL_CONTEXT_MBEDTLS_H +#endif // TLS_CONTEXT_MBEDTLS_H diff --git a/modules/mono/build_scripts/build_assemblies.py b/modules/mono/build_scripts/build_assemblies.py index 6f66ce9efa..d78a9c7db8 100755 --- a/modules/mono/build_scripts/build_assemblies.py +++ b/modules/mono/build_scripts/build_assemblies.py @@ -315,6 +315,8 @@ def main(): output_dir = os.path.abspath(args.godot_output_dir) + push_nupkgs_local = os.path.abspath(args.push_nupkgs_local) if args.push_nupkgs_local else None + msbuild_tool = find_any_msbuild_tool(args.mono_prefix) if msbuild_tool is None: @@ -327,7 +329,7 @@ def main(): output_dir, args.godot_platform, args.dev_debug, - args.push_nupkgs_local, + push_nupkgs_local, args.float, ) sys.exit(exit_code) diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 990a95821e..8fd3626a20 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -2035,6 +2035,52 @@ void CSharpScript::_update_exports_values(HashMap<StringName, Variant> &values, } #endif +void GD_CLR_STDCALL CSharpScript::_add_property_info_list_callback(CSharpScript *p_script, const String *p_current_class_name, void *p_props, int32_t p_count) { + GDMonoCache::godotsharp_property_info *props = (GDMonoCache::godotsharp_property_info *)p_props; + +#ifdef TOOLS_ENABLED + p_script->exported_members_cache.push_back(PropertyInfo( + Variant::NIL, *p_current_class_name, PROPERTY_HINT_NONE, + p_script->get_path(), PROPERTY_USAGE_CATEGORY)); +#endif + + for (int i = 0; i < p_count; i++) { + const GDMonoCache::godotsharp_property_info &prop = props[i]; + + StringName name = *reinterpret_cast<const StringName *>(&prop.name); + String hint_string = *reinterpret_cast<const String *>(&prop.hint_string); + + PropertyInfo pinfo(prop.type, name, prop.hint, hint_string, prop.usage); + + p_script->member_info[name] = pinfo; + + if (prop.exported) { +#ifdef TOOLS_ENABLED + p_script->exported_members_cache.push_back(pinfo); +#endif + +#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED) + p_script->exported_members_names.insert(name); +#endif + } + } +} + +#ifdef TOOLS_ENABLED +void GD_CLR_STDCALL CSharpScript::_add_property_default_values_callback(CSharpScript *p_script, void *p_def_vals, int32_t p_count) { + GDMonoCache::godotsharp_property_def_val_pair *def_vals = (GDMonoCache::godotsharp_property_def_val_pair *)p_def_vals; + + for (int i = 0; i < p_count; i++) { + const GDMonoCache::godotsharp_property_def_val_pair &def_val_pair = def_vals[i]; + + StringName name = *reinterpret_cast<const StringName *>(&def_val_pair.name); + Variant value = *reinterpret_cast<const Variant *>(&def_val_pair.value); + + p_script->exported_members_defval_cache[name] = value; + } +} +#endif + bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_update) { #ifdef TOOLS_ENABLED bool is_editor = Engine::get_singleton()->is_editor_hint(); @@ -2066,49 +2112,10 @@ bool CSharpScript::_update_exports(PlaceHolderScriptInstance *p_instance_to_upda #endif if (GDMonoCache::godot_api_cache_updated) { - GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyInfoList(this, - [](CSharpScript *p_script, const String *p_current_class_name, GDMonoCache::godotsharp_property_info *p_props, int32_t p_count) { -#ifdef TOOLS_ENABLED - p_script->exported_members_cache.push_back(PropertyInfo( - Variant::NIL, *p_current_class_name, PROPERTY_HINT_NONE, - p_script->get_path(), PROPERTY_USAGE_CATEGORY)); -#endif - - for (int i = 0; i < p_count; i++) { - const GDMonoCache::godotsharp_property_info &prop = p_props[i]; - - StringName name = *reinterpret_cast<const StringName *>(&prop.name); - String hint_string = *reinterpret_cast<const String *>(&prop.hint_string); - - PropertyInfo pinfo(prop.type, name, prop.hint, hint_string, prop.usage); - - p_script->member_info[name] = pinfo; - - if (prop.exported) { + GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyInfoList(this, &_add_property_info_list_callback); #ifdef TOOLS_ENABLED - p_script->exported_members_cache.push_back(pinfo); -#endif - -#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED) - p_script->exported_members_names.insert(name); -#endif - } - } - }); - -#ifdef TOOLS_ENABLED - GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyDefaultValues(this, - [](CSharpScript *p_script, GDMonoCache::godotsharp_property_def_val_pair *p_def_vals, int32_t p_count) { - for (int i = 0; i < p_count; i++) { - const GDMonoCache::godotsharp_property_def_val_pair &def_val_pair = p_def_vals[i]; - - StringName name = *reinterpret_cast<const StringName *>(&def_val_pair.name); - Variant value = *reinterpret_cast<const Variant *>(&def_val_pair.value); - - p_script->exported_members_defval_cache[name] = value; - } - }); + GDMonoCache::managed_callbacks.ScriptManagerBridge_GetPropertyDefaultValues(this, &_add_property_default_values_callback); #endif } } diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index f2844a051d..d469c28d4a 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -133,6 +133,10 @@ class CSharpScript : public Script { void _clear(); + static void GD_CLR_STDCALL _add_property_info_list_callback(CSharpScript *p_script, const String *p_current_class_name, void *p_props, int32_t p_count); +#ifdef TOOLS_ENABLED + static void GD_CLR_STDCALL _add_property_default_values_callback(CSharpScript *p_script, void *p_def_vals, int32_t p_count); +#endif bool _update_exports(PlaceHolderScriptInstance *p_instance_to_update = nullptr); CSharpInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_is_ref_counted, Callable::CallError &r_error); diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets index bff9760b32..859ea52c93 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.NET.Sdk/Sdk/Sdk.targets @@ -17,7 +17,7 @@ <!-- C# source generators --> <ItemGroup Condition=" '$(DisableImplicitGodotGeneratorReferences)' != 'true' "> - <PackageReference Include="Godot.SourceGenerators" Version="$(PackageFloatingVersion_Godot)" /> + <PackageReference Include="Godot.SourceGenerators" Version="$(PackageVersion_Godot_SourceGenerators)" /> </ItemGroup> <!-- Godot API references --> diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs index efdd50098e..f31ded4d77 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/MarshalUtils.cs @@ -156,6 +156,10 @@ namespace Godot.SourceGenerators else if (typeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; + + if (arrayType.Rank != 1) + return null; + var elementType = arrayType.ElementType; switch (elementType.SpecialType) @@ -177,8 +181,8 @@ namespace Godot.SourceGenerators if (elementType.SimpleDerivesFrom(typeCache.GodotObjectType)) return MarshalType.GodotObjectOrDerivedArray; - if (elementType.ContainingAssembly.Name == "GodotSharp" && - elementType.ContainingNamespace.Name == "Godot") + if (elementType.ContainingAssembly?.Name == "GodotSharp" && + elementType.ContainingNamespace?.Name == "Godot") { switch (elementType) { diff --git a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs index 1df41a905b..eeda1042ca 100644 --- a/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs +++ b/modules/mono/editor/Godot.NET.Sdk/Godot.SourceGenerators/ScriptSignalsGenerator.cs @@ -235,6 +235,8 @@ namespace Godot.SourceGenerators .Append(signalName) .Append(";\n"); + source.Append($" /// <inheritdoc cref=\"{signalDelegate.DelegateSymbol.FullQualifiedName()}\"/>\n"); + source.Append(" public event ") .Append(signalDelegate.DelegateSymbol.FullQualifiedName()) .Append(" ") diff --git a/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets index 4baae77b34..37bd4a0be0 100644 --- a/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets +++ b/modules/mono/editor/GodotTools/GodotTools.Shared/GenerateGodotNupkgsVersions.targets @@ -21,10 +21,13 @@ Outputs="$(GeneratedGodotNupkgsVersionsFile)"> <PropertyGroup> <GenerateGodotNupkgsVersionsCode><![CDATA[ -namespace $(RootNamespace) { - public class GeneratedGodotNupkgsVersions { +namespace $(RootNamespace) +{ + public class GeneratedGodotNupkgsVersions + { public const string GodotNETSdk = "$(PackageVersion_Godot_NET_Sdk)"%3b public const string GodotSourceGenerators = "$(PackageVersion_Godot_SourceGenerators)"%3b + public const string GodotSharp = "$(PackageVersion_GodotSharp)"%3b } } ]]></GenerateGodotNupkgsVersionsCode> diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs index ad4fce8daa..4d40724a83 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/BuildOutputView.cs @@ -69,51 +69,41 @@ namespace GodotTools.Build private void LoadIssuesFromFile(string csvFile) { - using (var file = new Godot.File()) + using var file = FileAccess.Open(csvFile, FileAccess.ModeFlags.Read); + + if (file == null) + return; + + while (!file.EofReached()) { - try - { - Error openError = file.Open(csvFile, Godot.File.ModeFlags.Read); + string[] csvColumns = file.GetCsvLine(); - if (openError != Error.Ok) - return; + if (csvColumns.Length == 1 && string.IsNullOrEmpty(csvColumns[0])) + return; - while (!file.EofReached()) - { - string[] csvColumns = file.GetCsvLine(); - - if (csvColumns.Length == 1 && string.IsNullOrEmpty(csvColumns[0])) - return; - - if (csvColumns.Length != 7) - { - GD.PushError($"Expected 7 columns, got {csvColumns.Length}"); - continue; - } - - var issue = new BuildIssue - { - Warning = csvColumns[0] == "warning", - File = csvColumns[1], - Line = int.Parse(csvColumns[2]), - Column = int.Parse(csvColumns[3]), - Code = csvColumns[4], - Message = csvColumns[5], - ProjectFile = csvColumns[6] - }; - - if (issue.Warning) - WarningCount += 1; - else - ErrorCount += 1; - - _issues.Add(issue); - } - } - finally + if (csvColumns.Length != 7) { - file.Close(); // Disposing it is not enough. We need to call Close() + GD.PushError($"Expected 7 columns, got {csvColumns.Length}"); + continue; } + + var issue = new BuildIssue + { + Warning = csvColumns[0] == "warning", + File = csvColumns[1], + Line = int.Parse(csvColumns[2]), + Column = int.Parse(csvColumns[3]), + Code = csvColumns[4], + Message = csvColumns[5], + ProjectFile = csvColumns[6] + }; + + if (issue.Warning) + WarningCount += 1; + else + ErrorCount += 1; + + _issues.Add(issue); } } diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs b/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs index 7bce53308c..b437c7e742 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/DotNetFinder.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Runtime.InteropServices; using JetBrains.Annotations; using OS = GodotTools.Utils.OS; @@ -16,6 +17,23 @@ namespace GodotTools.Build // In the future, this method may do more than just search in PATH. We could look in // known locations or use Godot's linked nethost to search from the hostfxr location. + if (OS.IsMacOS) + { + if (RuntimeInformation.OSArchitecture == Architecture.X64) + { + string dotnet_x64 = "/usr/local/share/dotnet/x64/dotnet"; // Look for x64 version, when running under Rosetta 2. + if (File.Exists(dotnet_x64)) + { + return dotnet_x64; + } + } + string dotnet = "/usr/local/share/dotnet/dotnet"; // Look for native version. + if (File.Exists(dotnet)) + { + return dotnet; + } + } + return OS.PathWhich("dotnet"); } diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs index 4041026426..237ac85267 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/MSBuildPanel.cs @@ -122,7 +122,7 @@ namespace GodotTools.Build { base._Ready(); - CustomMinimumSize = new Vector2(0, 228) * EditorScale; + CustomMinimumSize = new Vector2i(0, (int)(228 * EditorScale)); SizeFlagsVertical = (int)SizeFlags.ExpandFill; var toolBarHBox = new HBoxContainer { SizeFlagsHorizontal = (int)SizeFlags.ExpandFill }; diff --git a/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs index d2e0e128b5..fe309b8102 100644 --- a/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs +++ b/modules/mono/editor/GodotTools/GodotTools/Build/NuGetUtils.cs @@ -22,71 +22,13 @@ namespace GodotTools.Build public static string GodotFallbackFolderPath => Path.Combine(GodotSharpDirs.MonoUserDir, "GodotNuGetFallbackFolder"); - private static void AddFallbackFolderToNuGetConfig(string nuGetConfigPath, string name, string path) - { - var xmlDoc = new XmlDocument(); - xmlDoc.Load(nuGetConfigPath); - - const string nuGetConfigRootName = "configuration"; - - var rootNode = xmlDoc.DocumentElement; - - if (rootNode == null) - { - // No root node, create it - rootNode = xmlDoc.CreateElement(nuGetConfigRootName); - xmlDoc.AppendChild(rootNode); - - // Since this can be considered pretty much a new NuGet.Config, add the default nuget.org source as well - XmlElement nugetOrgSourceEntry = xmlDoc.CreateElement("add"); - nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("key")).Value = "nuget.org"; - nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value = - "https://api.nuget.org/v3/index.json"; - nugetOrgSourceEntry.Attributes.Append(xmlDoc.CreateAttribute("protocolVersion")).Value = "3"; - rootNode.AppendChild(xmlDoc.CreateElement("packageSources")).AppendChild(nugetOrgSourceEntry); - } - else - { - // Check that the root node is the expected one - if (rootNode.Name != nuGetConfigRootName) - throw new FormatException("Invalid root Xml node for NuGet.Config. " + - $"Expected '{nuGetConfigRootName}' got '{rootNode.Name}'."); - } - - var fallbackFoldersNode = rootNode["fallbackPackageFolders"] ?? - rootNode.AppendChild(xmlDoc.CreateElement("fallbackPackageFolders")); - - // Check if it already has our fallback package folder - for (var xmlNode = fallbackFoldersNode.FirstChild; xmlNode != null; xmlNode = xmlNode.NextSibling) - { - if (xmlNode.NodeType != XmlNodeType.Element) - continue; - - var xmlElement = (XmlElement)xmlNode; - if (xmlElement.Name == "add" && - xmlElement.Attributes["key"]?.Value == name && - xmlElement.Attributes["value"]?.Value == path) - { - return; - } - } - - XmlElement newEntry = xmlDoc.CreateElement("add"); - newEntry.Attributes.Append(xmlDoc.CreateAttribute("key")).Value = name; - newEntry.Attributes.Append(xmlDoc.CreateAttribute("value")).Value = path; - - fallbackFoldersNode.AppendChild(newEntry); - - xmlDoc.Save(nuGetConfigPath); - } - /// <summary> - /// Returns all the paths where the user NuGet.Config files can be found. + /// Returns all the paths where the Godot.Offline.Config files can be found. /// Does not determine whether the returned files exist or not. /// </summary> - private static string[] GetAllUserNuGetConfigFilePaths() + private static string[] GetAllGodotNuGetConfigFilePaths() { - // Where to find 'NuGet/NuGet.Config': + // Where to find 'NuGet/config/Godot.Offline.Config': // // - Mono/.NETFramework (standalone NuGet): // Uses Environment.SpecialFolder.ApplicationData @@ -98,10 +40,12 @@ namespace GodotTools.Build string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + const string configFileName = "Godot.Offline.Config"; + if (Utils.OS.IsWindows) { // %APPDATA% for both - return new[] { Path.Combine(applicationData, "NuGet", "NuGet.Config") }; + return new[] { Path.Combine(applicationData, "NuGet", "config", configFileName) }; } var paths = new string[2]; @@ -111,20 +55,20 @@ namespace GodotTools.Build string dotnetCliHome = Environment.GetEnvironmentVariable("DOTNET_CLI_HOME"); if (!string.IsNullOrEmpty(dotnetCliHome)) { - paths[0] = Path.Combine(dotnetCliHome, ".nuget", "NuGet", "NuGet.Config"); + paths[0] = Path.Combine(dotnetCliHome, ".nuget", "NuGet", "config", configFileName); } else { string home = Environment.GetEnvironmentVariable("HOME"); if (string.IsNullOrEmpty(home)) throw new InvalidOperationException("Required environment variable 'HOME' is not set."); - paths[0] = Path.Combine(home, ".nuget", "NuGet", "NuGet.Config"); + paths[0] = Path.Combine(home, ".nuget", "NuGet", "config", configFileName); } // Mono/.NETFramework (standalone NuGet) // ApplicationData is $HOME/.config on Linux/macOS - paths[1] = Path.Combine(applicationData, "NuGet", "NuGet.Config"); + paths[1] = Path.Combine(applicationData, "NuGet", "config", configFileName); return paths; } @@ -141,28 +85,26 @@ namespace GodotTools.Build // The nuspec is not lower case inside the nupkg but must be made lower case when extracted. /// <summary> - /// Adds the specified fallback folder to the user NuGet.Config files, + /// Adds the specified fallback folder to the Godot.Offline.Config files, /// for both standalone NuGet (Mono/.NETFramework) and dotnet CLI NuGet. /// </summary> - public static void AddFallbackFolderToUserNuGetConfigs(string name, string path) + public static void AddFallbackFolderToGodotNuGetConfigs(string name, string path) { - foreach (string nuGetConfigPath in GetAllUserNuGetConfigFilePaths()) + // Make sure the fallback folder exists to avoid error: + // MSB4018: The "ResolvePackageAssets" task failed unexpectedly. + System.IO.Directory.CreateDirectory(path); + + foreach (string nuGetConfigPath in GetAllGodotNuGetConfigFilePaths()) { - if (!System.IO.File.Exists(nuGetConfigPath)) - { - // It doesn't exist, so we create a default one - const string defaultConfig = @"<?xml version=""1.0"" encoding=""utf-8""?> + string defaultConfig = @$"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> - <packageSources> - <add key=""nuget.org"" value=""https://api.nuget.org/v3/index.json"" protocolVersion=""3"" /> - </packageSources> + <fallbackPackageFolders> + <add key=""{name}"" value=""{path}"" /> + </fallbackPackageFolders> </configuration> "; - System.IO.Directory.CreateDirectory(Path.GetDirectoryName(nuGetConfigPath)); - System.IO.File.WriteAllText(nuGetConfigPath, defaultConfig, Encoding.UTF8); // UTF-8 with BOM - } - - AddFallbackFolderToNuGetConfig(nuGetConfigPath, name, path); + System.IO.Directory.CreateDirectory(Path.GetDirectoryName(nuGetConfigPath)); + System.IO.File.WriteAllText(nuGetConfigPath, defaultConfig, Encoding.UTF8); // UTF-8 with BOM } } @@ -189,6 +131,7 @@ namespace GodotTools.Build string destDir = Path.Combine(fallbackFolder, packageIdLower, packageVersionLower); string nupkgDestPath = Path.Combine(destDir, $"{packageIdLower}.{packageVersionLower}.nupkg"); string nupkgSha512DestPath = Path.Combine(destDir, $"{packageIdLower}.{packageVersionLower}.nupkg.sha512"); + string nupkgMetadataDestPath = Path.Combine(destDir, ".nupkg.metadata"); if (File.Exists(nupkgDestPath) && File.Exists(nupkgSha512DestPath)) return; // Already added (for speed we don't check if every file is properly extracted) @@ -197,12 +140,18 @@ namespace GodotTools.Build // Generate .nupkg.sha512 file - using (var alg = SHA512.Create()) - { - alg.ComputeHash(File.ReadAllBytes(nupkgPath)); - string base64Hash = Convert.ToBase64String(alg.Hash); - File.WriteAllText(nupkgSha512DestPath, base64Hash); - } + byte[] hash = SHA512.HashData(File.ReadAllBytes(nupkgPath)); + string base64Hash = Convert.ToBase64String(hash); + File.WriteAllText(nupkgSha512DestPath, base64Hash); + + // Generate .nupkg.metadata file + // Spec: https://github.com/NuGet/Home/wiki/Nupkg-Metadata-File + + File.WriteAllText(nupkgMetadataDestPath, @$"{{ + ""version"": 2, + ""contentHash"": ""{base64Hash}"", + ""source"": null +}}"); // Extract nupkg ExtractNupkg(destDir, nupkgPath, packageId, packageVersion); @@ -251,7 +200,7 @@ namespace GodotTools.Build entryFullName.EndsWith(".nupkg.sha512", StringComparison.OrdinalIgnoreCase) || entryFullName.EndsWith(".nupkg.metadata", StringComparison.OrdinalIgnoreCase) || // Nuspec at root level. We already extracted it previously but in lower case. - entryFullName.IndexOf('/') == -1 && entryFullName.EndsWith(".nuspec")) + !entryFullName.Contains('/') && entryFullName.EndsWith(".nuspec")) { continue; } @@ -297,6 +246,8 @@ namespace GodotTools.Build { ("Godot.NET.Sdk", GeneratedGodotNupkgsVersions.GodotNETSdk), ("Godot.SourceGenerators", GeneratedGodotNupkgsVersions.GodotSourceGenerators), + ("GodotSharp", GeneratedGodotNupkgsVersions.GodotSharp), + ("GodotSharpEditor", GeneratedGodotNupkgsVersions.GodotSharp), }; } } diff --git a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs index 1cfaea3ec9..89364d1c02 100644 --- a/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs +++ b/modules/mono/editor/GodotTools/GodotTools/GodotSharpEditor.cs @@ -123,7 +123,7 @@ namespace GodotTools try { string fallbackFolder = NuGetUtils.GodotFallbackFolderPath; - NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, + NuGetUtils.AddFallbackFolderToGodotNuGetConfigs(NuGetUtils.GodotFallbackFolderName, fallbackFolder); NuGetUtils.AddBundledPackagesToFallbackFolder(fallbackFolder); } @@ -497,7 +497,7 @@ namespace GodotTools try { // At startup we make sure NuGet.Config files have our Godot NuGet fallback folder included - NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, + NuGetUtils.AddFallbackFolderToGodotNuGetConfigs(NuGetUtils.GodotFallbackFolderName, NuGetUtils.GodotFallbackFolderPath); } catch (Exception e) diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index c27bb959fe..95a44d3b7e 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -2229,6 +2229,35 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf // Generate signal { + p_output.append(MEMBER_BEGIN "/// <summary>\n"); + p_output.append(INDENT1 "/// "); + p_output.append("Represents the method that handles the "); + p_output.append("<see cref=\"" BINDINGS_NAMESPACE "." + p_itype.proxy_name + "." + p_isignal.proxy_name + "\"/>"); + p_output.append(" event of a "); + p_output.append("<see cref=\"" BINDINGS_NAMESPACE "." + p_itype.proxy_name + "\"/>"); + p_output.append(" class.\n"); + p_output.append(INDENT1 "/// </summary>"); + + if (p_isignal.is_deprecated) { + if (p_isignal.deprecation_message.is_empty()) { + WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + p_isignal.proxy_name + "'."); + } + + p_output.append(MEMBER_BEGIN "[Obsolete(\""); + p_output.append(p_isignal.deprecation_message); + p_output.append("\")]"); + } + + String delegate_name = p_isignal.proxy_name; + delegate_name += "EventHandler"; // Delegate name is [SignalName]EventHandler + + // Generate delegate + p_output.append(MEMBER_BEGIN "public delegate void "); + p_output.append(delegate_name); + p_output.append("("); + p_output.append(arguments_sig); + p_output.append(");\n"); + if (p_isignal.method_doc && p_isignal.method_doc->description.size()) { String xml_summary = bbcode_to_xml(fix_doc_description(p_isignal.method_doc->description), &p_itype); Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>(); @@ -2247,25 +2276,11 @@ Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterf } if (p_isignal.is_deprecated) { - if (p_isignal.deprecation_message.is_empty()) { - WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + p_isignal.proxy_name + "'."); - } - p_output.append(MEMBER_BEGIN "[Obsolete(\""); p_output.append(p_isignal.deprecation_message); p_output.append("\")]"); } - String delegate_name = p_isignal.proxy_name; - delegate_name += "EventHandler"; // Delegate name is [SignalName]EventHandler - - // Generate delegate - p_output.append(MEMBER_BEGIN "public delegate void "); - p_output.append(delegate_name); - p_output.append("("); - p_output.append(arguments_sig); - p_output.append(");\n"); - // TODO: // Could we assume the StringName instance of signal name will never be freed (it's stored in ClassDB) before the managed world is unloaded? // If so, we could store the pointer we get from `data_unique_pointer()` instead of allocating StringName here. diff --git a/modules/mono/editor/editor_internal_calls.cpp b/modules/mono/editor/editor_internal_calls.cpp index 6f42ad6916..91392c8f79 100644 --- a/modules/mono/editor/editor_internal_calls.cpp +++ b/modules/mono/editor/editor_internal_calls.cpp @@ -152,7 +152,7 @@ bool godot_icall_Internal_ScriptEditorEdit(Resource *p_resource, int32_t p_line, } void godot_icall_Internal_EditorNodeShowScriptScreen() { - EditorNode::get_singleton()->call("_editor_select", EditorNode::EDITOR_SCRIPT); + EditorNode::get_singleton()->editor_select(EditorNode::EDITOR_SCRIPT); } void godot_icall_Internal_EditorRunPlay() { diff --git a/modules/mono/editor/hostfxr_resolver.cpp b/modules/mono/editor/hostfxr_resolver.cpp index bdc8fac8b5..ea5978b2cd 100644 --- a/modules/mono/editor/hostfxr_resolver.cpp +++ b/modules/mono/editor/hostfxr_resolver.cpp @@ -82,7 +82,7 @@ namespace { String get_hostfxr_file_name() { #if defined(WINDOWS_ENABLED) || defined(UWP_ENABLED) return "hostfxr.dll"; -#elif defined(OSX_ENABLED) || defined(IOS_ENABLED) +#elif defined(MACOS_ENABLED) || defined(IOS_ENABLED) return "libhostfxr.dylib"; #else return "libhostfxr.so"; @@ -197,7 +197,7 @@ bool get_default_installation_dir(String &r_dotnet_root) { r_dotnet_root = path::join(program_files_dir, "dotnet"); return true; -#elif defined(TARGET_OSX) +#elif defined(MACOS_ENABLED) r_dotnet_root = "/usr/local/share/dotnet"; #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) diff --git a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs index 44f951e314..d77baab24b 100644 --- a/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs +++ b/modules/mono/glue/GodotSharp/GodotSharp/Core/StringExtensions.cs @@ -1245,12 +1245,12 @@ namespace Godot /// <summary> /// If the string is a path, this concatenates <paramref name="file"/> /// at the end of the string as a subpath. - /// E.g. <c>"this/is".PlusFile("path") == "this/is/path"</c>. + /// E.g. <c>"this/is".PathJoin("path") == "this/is/path"</c>. /// </summary> /// <param name="instance">The path that will be concatenated.</param> /// <param name="file">File name to concatenate with the path.</param> /// <returns>The concatenated path with the given file name.</returns> - public static string PlusFile(this string instance, string file) + public static string PathJoin(this string instance, string file) { if (instance.Length > 0 && instance[instance.Length - 1] == '/') return instance + file; diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h index 43811a4325..21252a5dca 100644 --- a/modules/mono/mono_gd/gd_mono.h +++ b/modules/mono/mono_gd/gd_mono.h @@ -35,11 +35,13 @@ #include "../godotsharp_defs.h" +#ifndef GD_CLR_STDCALL #ifdef WIN32 #define GD_CLR_STDCALL __stdcall #else #define GD_CLR_STDCALL #endif +#endif namespace gdmono { @@ -56,8 +58,6 @@ struct PluginCallbacks { } // namespace gdmono -#undef GD_CLR_STDCALL - class GDMono { bool runtime_initialized; bool finalizing_scripts_domain; diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index ca3a6c95a7..13b599fe55 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -47,11 +47,13 @@ class CSharpScript; namespace GDMonoCache { +#ifndef GD_CLR_STDCALL #ifdef WIN32 #define GD_CLR_STDCALL __stdcall #else #define GD_CLR_STDCALL #endif +#endif struct godotsharp_property_info { godot_string_name name; // Not owned @@ -68,8 +70,8 @@ struct godotsharp_property_def_val_pair { }; struct ManagedCallbacks { - using Callback_ScriptManagerBridge_GetPropertyInfoList_Add = void(GD_CLR_STDCALL *)(CSharpScript *p_script, const String *, godotsharp_property_info *p_props, int32_t p_count); - using Callback_ScriptManagerBridge_GetPropertyDefaultValues_Add = void(GD_CLR_STDCALL *)(CSharpScript *p_script, godotsharp_property_def_val_pair *p_def_vals, int32_t p_count); + using Callback_ScriptManagerBridge_GetPropertyInfoList_Add = void(GD_CLR_STDCALL *)(CSharpScript *p_script, const String *, void *p_props, int32_t p_count); + using Callback_ScriptManagerBridge_GetPropertyDefaultValues_Add = void(GD_CLR_STDCALL *)(CSharpScript *p_script, void *p_def_vals, int32_t p_count); using FuncSignalAwaiter_SignalCallback = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Variant **, int32_t, bool *); using FuncDelegateUtils_InvokeWithVariantArgs = void(GD_CLR_STDCALL *)(GCHandleIntPtr, const Variant **, uint32_t, const Variant *); @@ -145,6 +147,4 @@ void update_godot_api_cache(const ManagedCallbacks &p_managed_callbacks); } // namespace GDMonoCache -#undef GD_CLR_STDCALL - #endif // GD_MONO_CACHE_H diff --git a/modules/multiplayer/multiplayer_spawner.cpp b/modules/multiplayer/multiplayer_spawner.cpp index 6f60318b3b..9d28feef09 100644 --- a/modules/multiplayer/multiplayer_spawner.cpp +++ b/modules/multiplayer/multiplayer_spawner.cpp @@ -86,23 +86,41 @@ void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const { } } #endif + +PackedStringArray MultiplayerSpawner::get_configuration_warnings() const { + PackedStringArray warnings = Node::get_configuration_warnings(); + + if (spawn_path.is_empty() || !has_node(spawn_path)) { + warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes.")); + } + bool has_scenes = get_spawnable_scene_count() > 0; + // Can't check if method is overriden in placeholder scripts. + bool has_placeholder_script = get_script_instance() && get_script_instance()->is_placeholder(); + if (!has_scenes && !GDVIRTUAL_IS_OVERRIDDEN(_spawn_custom) && !has_placeholder_script) { + warnings.push_back(RTR("A list of PackedScenes must be set in the \"Auto Spawn List\" property in order for MultiplayerSpawner to automatically spawn them remotely when added as child of \"spawn_path\".")); + warnings.push_back(RTR("Alternatively, a Script implementing the function \"_spawn_custom\" must be set for this MultiplayerSpawner, and \"spawn\" must be called explicitly in code.")); + } + return warnings; +} + void MultiplayerSpawner::add_spawnable_scene(const String &p_path) { SpawnableScene sc; sc.path = p_path; if (Engine::get_singleton()->is_editor_hint()) { ERR_FAIL_COND(!FileAccess::exists(p_path)); - } else { - sc.cache = ResourceLoader::load(p_path); - ERR_FAIL_COND_MSG(sc.cache.is_null(), "Invalid spawnable scene: " + p_path); } spawnable_scenes.push_back(sc); } + int MultiplayerSpawner::get_spawnable_scene_count() const { return spawnable_scenes.size(); } + String MultiplayerSpawner::get_spawnable_scene(int p_idx) const { + ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), ""); return spawnable_scenes[p_idx].path; } + void MultiplayerSpawner::clear_spawnable_scenes() { spawnable_scenes.clear(); } @@ -270,9 +288,12 @@ const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const Node *MultiplayerSpawner::instantiate_scene(int p_id) { ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!"); ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr); - Ref<PackedScene> scene = spawnable_scenes[p_id].cache; - ERR_FAIL_COND_V(scene.is_null(), nullptr); - return scene->instantiate(); + SpawnableScene &sc = spawnable_scenes[p_id]; + if (sc.cache.is_null()) { + sc.cache = ResourceLoader::load(sc.path); + } + ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path); + return sc.cache->instantiate(); } Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) { diff --git a/modules/multiplayer/multiplayer_spawner.h b/modules/multiplayer/multiplayer_spawner.h index fc3befc2d4..587c99efd1 100644 --- a/modules/multiplayer/multiplayer_spawner.h +++ b/modules/multiplayer/multiplayer_spawner.h @@ -91,6 +91,8 @@ protected: void _get_property_list(List<PropertyInfo> *p_list) const; #endif public: + PackedStringArray get_configuration_warnings() const override; + Node *get_spawn_node() const { return spawn_node.is_valid() ? Object::cast_to<Node>(ObjectDB::get_instance(spawn_node)) : nullptr; } diff --git a/modules/multiplayer/multiplayer_synchronizer.cpp b/modules/multiplayer/multiplayer_synchronizer.cpp index eee1495c14..2c3ebccaeb 100644 --- a/modules/multiplayer/multiplayer_synchronizer.cpp +++ b/modules/multiplayer/multiplayer_synchronizer.cpp @@ -94,6 +94,16 @@ void MultiplayerSynchronizer::_update_process() { } } +PackedStringArray MultiplayerSynchronizer::get_configuration_warnings() const { + PackedStringArray warnings = Node::get_configuration_warnings(); + + if (root_path.is_empty() || !has_node(root_path)) { + warnings.push_back(RTR("A valid NodePath must be set in the \"Root Path\" property in order for MultiplayerSynchronizer to be able to synchronize properties.")); + } + + return warnings; +} + Error MultiplayerSynchronizer::get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs) { ERR_FAIL_COND_V(!p_obj, ERR_INVALID_PARAMETER); r_variant.resize(p_properties.size()); diff --git a/modules/multiplayer/multiplayer_synchronizer.h b/modules/multiplayer/multiplayer_synchronizer.h index e84d41db86..f10a95a1d4 100644 --- a/modules/multiplayer/multiplayer_synchronizer.h +++ b/modules/multiplayer/multiplayer_synchronizer.h @@ -66,6 +66,8 @@ public: static Error get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs); static Error set_state(const List<NodePath> &p_properties, Object *p_obj, const Vector<Variant> &p_state); + PackedStringArray get_configuration_warnings() const override; + void set_replication_interval(double p_interval); double get_replication_interval() const; uint64_t get_replication_interval_msec() const; diff --git a/modules/navigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp index cfb8e0cd42..f989fc45a5 100644 --- a/modules/navigation/navigation_mesh_generator.cpp +++ b/modules/navigation/navigation_mesh_generator.cpp @@ -209,6 +209,9 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans for (uint32_t shape_owner : shape_owners) { const int shape_count = static_body->shape_owner_get_shape_count(shape_owner); for (int i = 0; i < shape_count; i++) { + if (static_body->is_shape_owner_disabled(i)) { + continue; + } Ref<Shape3D> s = static_body->shape_owner_get_shape(shape_owner, i); if (s.is_null()) { continue; diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp index 92d074cb75..94095eb61c 100644 --- a/modules/openxr/openxr_api.cpp +++ b/modules/openxr/openxr_api.cpp @@ -1557,7 +1557,7 @@ void OpenXRAPI::end_frame() { XrCompositionLayerProjection projection_layer = { XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type nullptr, // next - layers_list.size() > 1 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags + layers_list.size() > 0 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags play_space, // space view_count, // viewCount projection_views, // views diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp index 5f839bd979..f43f2784c7 100644 --- a/modules/svg/image_loader_svg.cpp +++ b/modules/svg/image_loader_svg.cpp @@ -35,6 +35,12 @@ #include <thorvg.h> +HashMap<Color, Color> ImageLoaderSVG::forced_color_map = HashMap<Color, Color>(); + +void ImageLoaderSVG::set_forced_color_map(const HashMap<Color, Color> &p_color_map) { + forced_color_map = p_color_map; +} + void ImageLoaderSVG::_replace_color_property(const HashMap<Color, Color> &p_color_map, const String &p_prefix, String &r_string) { // Replace colors in the SVG based on what is passed in `p_color_map`. // Used to change the colors of editor icons based on the used theme. @@ -136,9 +142,15 @@ void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const p_extensions->push_back("svg"); } -Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, uint32_t p_flags, float p_scale) { +Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { String svg = p_fileaccess->get_as_utf8_string(); - create_image_from_string(p_image, svg, p_scale, false, HashMap<Color, Color>()); + + if (p_flags & FLAG_CONVERT_COLORS) { + create_image_from_string(p_image, svg, p_scale, false, forced_color_map); + } else { + create_image_from_string(p_image, svg, p_scale, false, HashMap<Color, Color>()); + } + ERR_FAIL_COND_V(p_image->is_empty(), FAILED); if (p_flags & FLAG_FORCE_LINEAR) { p_image->srgb_to_linear(); diff --git a/modules/svg/image_loader_svg.h b/modules/svg/image_loader_svg.h index fc89b63edb..b0b0963c15 100644 --- a/modules/svg/image_loader_svg.h +++ b/modules/svg/image_loader_svg.h @@ -34,12 +34,16 @@ #include "core/io/image_loader.h" class ImageLoaderSVG : public ImageFormatLoader { + static HashMap<Color, Color> forced_color_map; + void _replace_color_property(const HashMap<Color, Color> &p_color_map, const String &p_prefix, String &r_string); public: + static void set_forced_color_map(const HashMap<Color, Color> &p_color_map); + void create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, const HashMap<Color, Color> &p_color_map); - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, uint32_t p_flags, float p_scale) override; + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) override; virtual void get_recognized_extensions(List<String> *p_extensions) const override; }; diff --git a/modules/svg/register_types.cpp b/modules/svg/register_types.cpp index 5b4d1d31ca..323b1d652a 100644 --- a/modules/svg/register_types.cpp +++ b/modules/svg/register_types.cpp @@ -34,7 +34,7 @@ #include <thorvg.h> -static ImageLoaderSVG *image_loader_svg = nullptr; +static Ref<ImageLoaderSVG> image_loader_svg; void initialize_svg_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { @@ -45,7 +45,8 @@ void initialize_svg_module(ModuleInitializationLevel p_level) { if (tvg::Initializer::init(tvgEngine, 1) != tvg::Result::Success) { return; } - image_loader_svg = memnew(ImageLoaderSVG); + + image_loader_svg.instantiate(); ImageLoader::add_image_format_loader(image_loader_svg); } @@ -54,9 +55,12 @@ void uninitialize_svg_module(ModuleInitializationLevel p_level) { return; } - if (!image_loader_svg) { + if (image_loader_svg.is_null()) { + // It failed to initialize so it was not added. return; } - memdelete(image_loader_svg); + + ImageLoader::remove_image_format_loader(image_loader_svg); + image_loader_svg.unref(); tvg::Initializer::term(tvg::CanvasEngine::Sw); } diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp index 7aebeafe70..b0f414f7f0 100644 --- a/modules/text_server_adv/text_server_adv.cpp +++ b/modules/text_server_adv/text_server_adv.cpp @@ -45,7 +45,6 @@ using namespace godot; // Headers for building as built-in module. #include "core/config/project_settings.h" -#include "core/core_bind.h" #include "core/error/error_macros.h" #include "core/object/worker_thread_pool.h" #include "core/string/print_string.h" @@ -53,8 +52,6 @@ using namespace godot; #include "modules/modules_enabled.gen.h" // For freetype, msdfgen. -using namespace core_bind; - #endif // Built-in ICU data. @@ -408,13 +405,12 @@ bool TextServerAdvanced::load_support_data(const String &p_filename) { if (!icu_data_loaded) { String filename = (p_filename.is_empty()) ? String("res://") + _MKSTR(ICU_DATA_NAME) : p_filename; - Ref<File> f; - f.instantiate(); - if (f->open(filename, File::READ) != OK) { + Ref<FileAccess> f = FileAccess::open(filename, FileAccess::READ); + if (f.is_null()) { return false; } uint64_t len = f->get_length(); - PackedByteArray icu_data = f->get_buffer(len); + PackedByteArray icu_data = f->_get_buffer(len); UErrorCode err = U_ZERO_ERROR; udata_setCommonData(icu_data.ptr(), &err); @@ -455,16 +451,15 @@ bool TextServerAdvanced::save_support_data(const String &p_filename) const { // Store data to the res file if it's available. - Ref<File> f; - f.instantiate(); - if (f->open(p_filename, File::WRITE) != OK) { + Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::WRITE); + if (f.is_null()) { return false; } PackedByteArray icu_data; icu_data.resize(U_ICUDATA_SIZE); memcpy(icu_data.ptrw(), U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE); - f->store_buffer(icu_data); + f->_store_buffer(icu_data); return true; #else @@ -1940,12 +1935,12 @@ int64_t TextServerAdvanced::font_get_face_count(const RID &p_font_rid) const { fargs.flags = FT_OPEN_MEMORY; fargs.stream = &stream; - FT_Face tmp_face; + FT_Face tmp_face = nullptr; error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face); if (error == 0) { face_count = tmp_face->num_faces; + FT_Done_Face(tmp_face); } - FT_Done_Face(tmp_face); #endif } diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp index 4d599dbcb5..23662bf2c4 100644 --- a/modules/text_server_fb/text_server_fb.cpp +++ b/modules/text_server_fb/text_server_fb.cpp @@ -1039,12 +1039,12 @@ int64_t TextServerFallback::font_get_face_count(const RID &p_font_rid) const { fargs.flags = FT_OPEN_MEMORY; fargs.stream = &stream; - FT_Face tmp_face; + FT_Face tmp_face = nullptr; error = FT_Open_Face(ft_library, &fargs, -1, &tmp_face); if (error == 0) { face_count = tmp_face->num_faces; + FT_Done_Face(tmp_face); } - FT_Done_Face(tmp_face); #endif } diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp index 16d9bf7b93..00ba32eae1 100644 --- a/modules/tga/image_loader_tga.cpp +++ b/modules/tga/image_loader_tga.cpp @@ -230,7 +230,7 @@ Error ImageLoaderTGA::convert_to_image(Ref<Image> p_image, const uint8_t *p_buff return OK; } -Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); diff --git a/modules/tga/image_loader_tga.h b/modules/tga/image_loader_tga.h index d95c5ff30b..b257ed110d 100644 --- a/modules/tga/image_loader_tga.h +++ b/modules/tga/image_loader_tga.h @@ -73,7 +73,7 @@ class ImageLoaderTGA : public ImageFormatLoader { static Error convert_to_image(Ref<Image> p_image, const uint8_t *p_buffer, const tga_header_s &p_header, const uint8_t *p_palette, const bool p_is_monochrome, size_t p_input_size); public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderTGA(); }; diff --git a/modules/tga/register_types.cpp b/modules/tga/register_types.cpp index 520ed5f799..3a9d2324e7 100644 --- a/modules/tga/register_types.cpp +++ b/modules/tga/register_types.cpp @@ -32,14 +32,14 @@ #include "image_loader_tga.h" -static ImageLoaderTGA *image_loader_tga = nullptr; +static Ref<ImageLoaderTGA> image_loader_tga; void initialize_tga_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_tga = memnew(ImageLoaderTGA); + image_loader_tga.instantiate(); ImageLoader::add_image_format_loader(image_loader_tga); } @@ -48,5 +48,6 @@ void uninitialize_tga_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_tga); + ImageLoader::remove_image_format_loader(image_loader_tga); + image_loader_tga.unref(); } diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp index 6f61251f9b..5c43bfc8b7 100644 --- a/modules/tinyexr/image_loader_tinyexr.cpp +++ b/modules/tinyexr/image_loader_tinyexr.cpp @@ -37,7 +37,7 @@ #include "thirdparty/tinyexr/tinyexr.h" -Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); diff --git a/modules/tinyexr/image_loader_tinyexr.h b/modules/tinyexr/image_loader_tinyexr.h index 8da2a0d4af..ab34a59da5 100644 --- a/modules/tinyexr/image_loader_tinyexr.h +++ b/modules/tinyexr/image_loader_tinyexr.h @@ -35,7 +35,7 @@ class ImageLoaderTinyEXR : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderTinyEXR(); }; diff --git a/modules/tinyexr/register_types.cpp b/modules/tinyexr/register_types.cpp index c5897f37c3..b1a9f18e3b 100644 --- a/modules/tinyexr/register_types.cpp +++ b/modules/tinyexr/register_types.cpp @@ -33,14 +33,14 @@ #include "image_loader_tinyexr.h" #include "image_saver_tinyexr.h" -static ImageLoaderTinyEXR *image_loader_tinyexr = nullptr; +static Ref<ImageLoaderTinyEXR> image_loader_tinyexr; void initialize_tinyexr_module(ModuleInitializationLevel p_level) { if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE) { return; } - image_loader_tinyexr = memnew(ImageLoaderTinyEXR); + image_loader_tinyexr.instantiate(); ImageLoader::add_image_format_loader(image_loader_tinyexr); Image::save_exr_func = save_exr; @@ -52,7 +52,8 @@ void uninitialize_tinyexr_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_tinyexr); + ImageLoader::remove_image_format_loader(image_loader_tinyexr); + image_loader_tinyexr.unref(); Image::save_exr_func = nullptr; } diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp index 705ab508ab..dd387db554 100644 --- a/modules/webp/image_loader_webp.cpp +++ b/modules/webp/image_loader_webp.cpp @@ -48,7 +48,7 @@ static Ref<Image> _webp_mem_loader_func(const uint8_t *p_png, int p_size) { return img; } -Error ImageLoaderWebP::load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale) { +Error ImageLoaderWebP::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale) { Vector<uint8_t> src_image; uint64_t src_image_len = f->get_length(); ERR_FAIL_COND_V(src_image_len == 0, ERR_FILE_CORRUPT); diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h index d868ae3f7f..0522e4ef91 100644 --- a/modules/webp/image_loader_webp.h +++ b/modules/webp/image_loader_webp.h @@ -35,7 +35,7 @@ class ImageLoaderWebP : public ImageFormatLoader { public: - virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, uint32_t p_flags, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField<ImageFormatLoader::LoaderFlags> p_flags, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderWebP(); }; diff --git a/modules/webp/register_types.cpp b/modules/webp/register_types.cpp index 29f633743e..e523f43cfe 100644 --- a/modules/webp/register_types.cpp +++ b/modules/webp/register_types.cpp @@ -33,7 +33,7 @@ #include "image_loader_webp.h" #include "resource_saver_webp.h" -static ImageLoaderWebP *image_loader_webp = nullptr; +static Ref<ImageLoaderWebP> image_loader_webp; static Ref<ResourceSaverWebP> resource_saver_webp; void initialize_webp_module(ModuleInitializationLevel p_level) { @@ -41,9 +41,10 @@ void initialize_webp_module(ModuleInitializationLevel p_level) { return; } - image_loader_webp = memnew(ImageLoaderWebP); - resource_saver_webp.instantiate(); + image_loader_webp.instantiate(); ImageLoader::add_image_format_loader(image_loader_webp); + + resource_saver_webp.instantiate(); ResourceSaver::add_resource_format_saver(resource_saver_webp); } @@ -52,7 +53,9 @@ void uninitialize_webp_module(ModuleInitializationLevel p_level) { return; } - memdelete(image_loader_webp); + ImageLoader::remove_image_format_loader(image_loader_webp); + image_loader_webp.unref(); + ResourceSaver::remove_resource_format_saver(resource_saver_webp); resource_saver_webp.unref(); } diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml index e99aeb4f51..4ecc71ddbb 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnection.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnection.xml @@ -67,6 +67,18 @@ Returns the connection state. See [enum ConnectionState]. </description> </method> + <method name="get_gathering_state" qualifiers="const"> + <return type="int" enum="WebRTCPeerConnection.GatheringState" /> + <description> + Returns the ICE [enum GatheringState] of the connection. This lets you detect, for example, when collection of ICE candidates has finished. + </description> + </method> + <method name="get_signaling_state" qualifiers="const"> + <return type="int" enum="WebRTCPeerConnection.SignalingState" /> + <description> + Returns the [enum SignalingState] on the local end of the connection while connecting or reconnecting to another peer. + </description> + </method> <method name="initialize"> <return type="int" enum="Error" /> <param index="0" name="configuration" type="Dictionary" default="{}" /> @@ -165,5 +177,32 @@ <constant name="STATE_CLOSED" value="5" enum="ConnectionState"> The peer connection is closed (after calling [method close] for example). </constant> + <constant name="GATHERING_STATE_NEW" value="0" enum="GatheringState"> + The peer connection was just created and hasn't done any networking yet. + </constant> + <constant name="GATHERING_STATE_GATHERING" value="1" enum="GatheringState"> + The ICE agent is in the process of gathering candidates for the connection. + </constant> + <constant name="GATHERING_STATE_COMPLETE" value="2" enum="GatheringState"> + The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to gathering to gather those candidates. + </constant> + <constant name="SIGNALING_STATE_STABLE" value="0" enum="SignalingState"> + There is no ongoing exchange of offer and answer underway. This may mean that the [WebRTCPeerConnection] is new ([constant STATE_NEW]) or that negotiation is complete and a connection has been established ([constant STATE_CONNECTED]). + </constant> + <constant name="SIGNALING_STATE_HAVE_LOCAL_OFFER" value="1" enum="SignalingState"> + The local peer has called [method set_local_description], passing in SDP representing an offer (usually created by calling [method create_offer]), and the offer has been applied successfully. + </constant> + <constant name="SIGNALING_STATE_HAVE_REMOTE_OFFER" value="2" enum="SignalingState"> + The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling [method set_remote_description]. + </constant> + <constant name="SIGNALING_STATE_HAVE_LOCAL_PRANSWER" value="3" enum="SignalingState"> + The offer sent by the remote peer has been applied and an answer has been created and applied by calling [method set_local_description]. This provisional answer describes the supported media formats and so forth, but may not have a complete set of ICE candidates included. Further candidates will be delivered separately later. + </constant> + <constant name="SIGNALING_STATE_HAVE_REMOTE_PRANSWER" value="4" enum="SignalingState"> + A provisional answer has been received and successfully applied in response to an offer previously sent and established by calling [method set_local_description]. + </constant> + <constant name="SIGNALING_STATE_CLOSED" value="5" enum="SignalingState"> + The [WebRTCPeerConnection] has been closed. + </constant> </constants> </class> diff --git a/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml b/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml index 3c4bf18a76..474d2f6a89 100644 --- a/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml +++ b/modules/webrtc/doc_classes/WebRTCPeerConnectionExtension.xml @@ -37,6 +37,16 @@ <description> </description> </method> + <method name="_get_gathering_state" qualifiers="virtual const"> + <return type="int" enum="WebRTCPeerConnection.GatheringState" /> + <description> + </description> + </method> + <method name="_get_signaling_state" qualifiers="virtual const"> + <return type="int" enum="WebRTCPeerConnection.SignalingState" /> + <description> + </description> + </method> <method name="_initialize" qualifiers="virtual"> <return type="int" enum="Error" /> <param index="0" name="p_config" type="Dictionary" /> diff --git a/modules/webrtc/library_godot_webrtc.js b/modules/webrtc/library_godot_webrtc.js index e57e4299e0..e6604eecd7 100644 --- a/modules/webrtc/library_godot_webrtc.js +++ b/modules/webrtc/library_godot_webrtc.js @@ -220,64 +220,123 @@ mergeInto(LibraryManager.library, GodotRTCDataChannel); const GodotRTCPeerConnection = { $GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotRuntime', '$GodotRTCDataChannel'], $GodotRTCPeerConnection: { - onstatechange: function (p_id, p_conn, callback, event) { - const ref = IDHandler.get(p_id); - if (!ref) { - return; - } - let state; - switch (p_conn.iceConnectionState) { - case 'new': - state = 0; - break; - case 'checking': - state = 1; - break; - case 'connected': - case 'completed': - state = 2; - break; - case 'disconnected': - state = 3; - break; - case 'failed': - state = 4; - break; - case 'closed': - default: - state = 5; - break; - } - callback(state); + // Enums + ConnectionState: { + 'new': 0, + 'connecting': 1, + 'connected': 2, + 'disconnected': 3, + 'failed': 4, + 'closed': 5, }, - onicecandidate: function (p_id, callback, event) { - const ref = IDHandler.get(p_id); - if (!ref || !event.candidate) { - return; + ConnectionStateCompat: { + // Using values from IceConnectionState for browsers that do not support ConnectionState (notably Firefox). + 'new': 0, + 'checking': 1, + 'connected': 2, + 'completed': 2, + 'disconnected': 3, + 'failed': 4, + 'closed': 5, + }, + + IceGatheringState: { + 'new': 0, + 'gathering': 1, + 'complete': 2, + }, + + SignalingState: { + 'stable': 0, + 'have-local-offer': 1, + 'have-remote-offer': 2, + 'have-local-pranswer': 3, + 'have-remote-pranswer': 4, + 'closed': 5, + }, + + // Callbacks + create: function (config, onConnectionChange, onSignalingChange, onIceGatheringChange, onIceCandidate, onDataChannel) { + let conn = null; + try { + conn = new RTCPeerConnection(config); + } catch (e) { + GodotRuntime.error(e); + return 0; } - const c = event.candidate; - const candidate_str = GodotRuntime.allocString(c.candidate); - const mid_str = GodotRuntime.allocString(c.sdpMid); - callback(mid_str, c.sdpMLineIndex, candidate_str); - GodotRuntime.free(candidate_str); - GodotRuntime.free(mid_str); + const id = IDHandler.add(conn); + + if ('connectionState' in conn && conn['connectionState'] !== undefined) { + // Use "connectionState" if supported + conn.onconnectionstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onConnectionChange(GodotRTCPeerConnection.ConnectionState[conn.connectionState] || 0); + }; + } else { + // Fall back to using "iceConnectionState" when "connectionState" is not supported (notably Firefox). + conn.oniceconnectionstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onConnectionChange(GodotRTCPeerConnection.ConnectionStateCompat[conn.iceConnectionState] || 0); + }; + } + conn.onicegatheringstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onIceGatheringChange(GodotRTCPeerConnection.IceGatheringState[conn.iceGatheringState] || 0); + }; + conn.onsignalingstatechange = function (event) { + if (!IDHandler.get(id)) { + return; + } + onSignalingChange(GodotRTCPeerConnection.SignalingState[conn.signalingState] || 0); + }; + conn.onicecandidate = function (event) { + if (!IDHandler.get(id)) { + return; + } + const c = event.candidate; + if (!c || !c.candidate) { + return; + } + const candidate_str = GodotRuntime.allocString(c.candidate); + const mid_str = GodotRuntime.allocString(c.sdpMid); + onIceCandidate(mid_str, c.sdpMLineIndex, candidate_str); + GodotRuntime.free(candidate_str); + GodotRuntime.free(mid_str); + }; + conn.ondatachannel = function (event) { + if (!IDHandler.get(id)) { + return; + } + const cid = IDHandler.add(event.channel); + onDataChannel(cid); + }; + return id; }, - ondatachannel: function (p_id, callback, event) { - const ref = IDHandler.get(p_id); - if (!ref) { + destroy: function (p_id) { + const conn = IDHandler.get(p_id); + if (!conn) { return; } - - const cid = IDHandler.add(event.channel); - callback(cid); + conn.onconnectionstatechange = null; + conn.oniceconnectionstatechange = null; + conn.onicegatheringstatechange = null; + conn.onsignalingstatechange = null; + conn.onicecandidate = null; + conn.ondatachannel = null; + IDHandler.remove(p_id); }, onsession: function (p_id, callback, session) { - const ref = IDHandler.get(p_id); - if (!ref) { + if (!IDHandler.get(p_id)) { return; } const type_str = GodotRuntime.allocString(session.type); @@ -297,27 +356,19 @@ const GodotRTCPeerConnection = { }, }, - godot_js_rtc_pc_create__sig: 'iiiiii', - godot_js_rtc_pc_create: function (p_config, p_ref, p_on_state_change, p_on_candidate, p_on_datachannel) { - const onstatechange = GodotRuntime.get_func(p_on_state_change).bind(null, p_ref); - const oncandidate = GodotRuntime.get_func(p_on_candidate).bind(null, p_ref); - const ondatachannel = GodotRuntime.get_func(p_on_datachannel).bind(null, p_ref); - - const config = JSON.parse(GodotRuntime.parseString(p_config)); - let conn = null; - try { - conn = new RTCPeerConnection(config); - } catch (e) { - GodotRuntime.error(e); - return 0; - } - - const base = GodotRTCPeerConnection; - const id = IDHandler.add(conn); - conn.oniceconnectionstatechange = base.onstatechange.bind(null, id, conn, onstatechange); - conn.onicecandidate = base.onicecandidate.bind(null, id, oncandidate); - conn.ondatachannel = base.ondatachannel.bind(null, id, ondatachannel); - return id; + godot_js_rtc_pc_create__sig: 'iiiiiiii', + godot_js_rtc_pc_create: function (p_config, p_ref, p_on_connection_state_change, p_on_ice_gathering_state_change, p_on_signaling_state_change, p_on_ice_candidate, p_on_datachannel) { + const wrap = function (p_func) { + return GodotRuntime.get_func(p_func).bind(null, p_ref); + }; + return GodotRTCPeerConnection.create( + JSON.parse(GodotRuntime.parseString(p_config)), + wrap(p_on_connection_state_change), + wrap(p_on_signaling_state_change), + wrap(p_on_ice_gathering_state_change), + wrap(p_on_ice_candidate), + wrap(p_on_datachannel) + ); }, godot_js_rtc_pc_close__sig: 'vi', @@ -331,14 +382,7 @@ const GodotRTCPeerConnection = { godot_js_rtc_pc_destroy__sig: 'vi', godot_js_rtc_pc_destroy: function (p_id) { - const ref = IDHandler.get(p_id); - if (!ref) { - return; - } - ref.oniceconnectionstatechange = null; - ref.onicecandidate = null; - ref.ondatachannel = null; - IDHandler.remove(p_id); + GodotRTCPeerConnection.destroy(p_id); }, godot_js_rtc_pc_offer_create__sig: 'viiii', diff --git a/modules/webrtc/webrtc_peer_connection.cpp b/modules/webrtc/webrtc_peer_connection.cpp index d885b9262b..5aa891d35c 100644 --- a/modules/webrtc/webrtc_peer_connection.cpp +++ b/modules/webrtc/webrtc_peer_connection.cpp @@ -69,6 +69,8 @@ void WebRTCPeerConnection::_bind_methods() { ClassDB::bind_method(D_METHOD("close"), &WebRTCPeerConnection::close); ClassDB::bind_method(D_METHOD("get_connection_state"), &WebRTCPeerConnection::get_connection_state); + ClassDB::bind_method(D_METHOD("get_gathering_state"), &WebRTCPeerConnection::get_gathering_state); + ClassDB::bind_method(D_METHOD("get_signaling_state"), &WebRTCPeerConnection::get_signaling_state); ADD_SIGNAL(MethodInfo("session_description_created", PropertyInfo(Variant::STRING, "type"), PropertyInfo(Variant::STRING, "sdp"))); ADD_SIGNAL(MethodInfo("ice_candidate_created", PropertyInfo(Variant::STRING, "media"), PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::STRING, "name"))); @@ -80,6 +82,17 @@ void WebRTCPeerConnection::_bind_methods() { BIND_ENUM_CONSTANT(STATE_DISCONNECTED); BIND_ENUM_CONSTANT(STATE_FAILED); BIND_ENUM_CONSTANT(STATE_CLOSED); + + BIND_ENUM_CONSTANT(GATHERING_STATE_NEW); + BIND_ENUM_CONSTANT(GATHERING_STATE_GATHERING); + BIND_ENUM_CONSTANT(GATHERING_STATE_COMPLETE); + + BIND_ENUM_CONSTANT(SIGNALING_STATE_STABLE); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_LOCAL_OFFER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_REMOTE_OFFER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_LOCAL_PRANSWER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_HAVE_REMOTE_PRANSWER); + BIND_ENUM_CONSTANT(SIGNALING_STATE_CLOSED); } WebRTCPeerConnection::WebRTCPeerConnection() { diff --git a/modules/webrtc/webrtc_peer_connection.h b/modules/webrtc/webrtc_peer_connection.h index 122ea3d00f..76f29f9d68 100644 --- a/modules/webrtc/webrtc_peer_connection.h +++ b/modules/webrtc/webrtc_peer_connection.h @@ -47,6 +47,21 @@ public: STATE_CLOSED }; + enum GatheringState { + GATHERING_STATE_NEW, + GATHERING_STATE_GATHERING, + GATHERING_STATE_COMPLETE, + }; + + enum SignalingState { + SIGNALING_STATE_STABLE, + SIGNALING_STATE_HAVE_LOCAL_OFFER, + SIGNALING_STATE_HAVE_REMOTE_OFFER, + SIGNALING_STATE_HAVE_LOCAL_PRANSWER, + SIGNALING_STATE_HAVE_REMOTE_PRANSWER, + SIGNALING_STATE_CLOSED, + }; + private: static StringName default_extension; @@ -57,6 +72,8 @@ public: static void set_default_extension(const StringName &p_name); virtual ConnectionState get_connection_state() const = 0; + virtual GatheringState get_gathering_state() const = 0; + virtual SignalingState get_signaling_state() const = 0; virtual Error initialize(Dictionary p_config = Dictionary()) = 0; virtual Ref<WebRTCDataChannel> create_data_channel(String p_label, Dictionary p_options = Dictionary()) = 0; @@ -74,5 +91,7 @@ public: }; VARIANT_ENUM_CAST(WebRTCPeerConnection::ConnectionState); +VARIANT_ENUM_CAST(WebRTCPeerConnection::GatheringState); +VARIANT_ENUM_CAST(WebRTCPeerConnection::SignalingState); #endif // WEBRTC_PEER_CONNECTION_H diff --git a/modules/webrtc/webrtc_peer_connection_extension.cpp b/modules/webrtc/webrtc_peer_connection_extension.cpp index 54143e4b79..592a1f8a97 100644 --- a/modules/webrtc/webrtc_peer_connection_extension.cpp +++ b/modules/webrtc/webrtc_peer_connection_extension.cpp @@ -32,6 +32,8 @@ void WebRTCPeerConnectionExtension::_bind_methods() { GDVIRTUAL_BIND(_get_connection_state); + GDVIRTUAL_BIND(_get_gathering_state); + GDVIRTUAL_BIND(_get_signaling_state); GDVIRTUAL_BIND(_initialize, "p_config"); GDVIRTUAL_BIND(_create_data_channel, "p_label", "p_config"); GDVIRTUAL_BIND(_create_offer); diff --git a/modules/webrtc/webrtc_peer_connection_extension.h b/modules/webrtc/webrtc_peer_connection_extension.h index 0c324ca45f..085069debb 100644 --- a/modules/webrtc/webrtc_peer_connection_extension.h +++ b/modules/webrtc/webrtc_peer_connection_extension.h @@ -53,6 +53,8 @@ public: /** GDExtension **/ EXBIND0RC(ConnectionState, get_connection_state); + EXBIND0RC(GatheringState, get_gathering_state); + EXBIND0RC(SignalingState, get_signaling_state); EXBIND1R(Error, initialize, Dictionary); EXBIND0R(Error, create_offer); EXBIND2R(Error, set_remote_description, String, String); diff --git a/modules/webrtc/webrtc_peer_connection_js.cpp b/modules/webrtc/webrtc_peer_connection_js.cpp index f48705253b..a371312ae9 100644 --- a/modules/webrtc/webrtc_peer_connection_js.cpp +++ b/modules/webrtc/webrtc_peer_connection_js.cpp @@ -51,6 +51,16 @@ void WebRTCPeerConnectionJS::_on_connection_state_changed(void *p_obj, int p_sta peer->_conn_state = (ConnectionState)p_state; } +void WebRTCPeerConnectionJS::_on_gathering_state_changed(void *p_obj, int p_state) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); + peer->_gathering_state = (GatheringState)p_state; +} + +void WebRTCPeerConnectionJS::_on_signaling_state_changed(void *p_obj, int p_state) { + WebRTCPeerConnectionJS *peer = static_cast<WebRTCPeerConnectionJS *>(p_obj); + peer->_signaling_state = (SignalingState)p_state; +} + void WebRTCPeerConnectionJS::_on_error(void *p_obj) { ERR_PRINT("RTCPeerConnection error!"); } @@ -100,7 +110,7 @@ Error WebRTCPeerConnectionJS::initialize(Dictionary p_config) { _conn_state = STATE_NEW; String config = Variant(p_config).to_json_string(); - _js_id = godot_js_rtc_pc_create(config.utf8().get_data(), this, &_on_connection_state_changed, &_on_ice_candidate, &_on_data_channel); + _js_id = godot_js_rtc_pc_create(config.utf8().get_data(), this, &_on_connection_state_changed, &_on_gathering_state_changed, &_on_signaling_state_changed, &_on_ice_candidate, &_on_data_channel); return _js_id ? OK : FAILED; } @@ -117,14 +127,19 @@ Error WebRTCPeerConnectionJS::poll() { return OK; } +WebRTCPeerConnection::GatheringState WebRTCPeerConnectionJS::get_gathering_state() const { + return _gathering_state; +} + +WebRTCPeerConnection::SignalingState WebRTCPeerConnectionJS::get_signaling_state() const { + return _signaling_state; +} + WebRTCPeerConnection::ConnectionState WebRTCPeerConnectionJS::get_connection_state() const { return _conn_state; } WebRTCPeerConnectionJS::WebRTCPeerConnectionJS() { - _conn_state = STATE_NEW; - _js_id = 0; - Dictionary config; initialize(config); } diff --git a/modules/webrtc/webrtc_peer_connection_js.h b/modules/webrtc/webrtc_peer_connection_js.h index 50266129e4..e62ad6af28 100644 --- a/modules/webrtc/webrtc_peer_connection_js.h +++ b/modules/webrtc/webrtc_peer_connection_js.h @@ -37,11 +37,13 @@ extern "C" { typedef void (*RTCOnIceConnectionStateChange)(void *p_obj, int p_state); +typedef void (*RTCOnIceGatheringStateChange)(void *p_obj, int p_state); +typedef void (*RTCOnSignalingStateChange)(void *p_obj, int p_state); typedef void (*RTCOnIceCandidate)(void *p_obj, const char *p_mid, int p_mline_idx, const char *p_candidate); typedef void (*RTCOnDataChannel)(void *p_obj, int p_id); typedef void (*RTCOnSession)(void *p_obj, const char *p_type, const char *p_sdp); typedef void (*RTCOnError)(void *p_obj); -extern int godot_js_rtc_pc_create(const char *p_config, void *p_obj, RTCOnIceConnectionStateChange p_on_state_change, RTCOnIceCandidate p_on_candidate, RTCOnDataChannel p_on_datachannel); +extern int godot_js_rtc_pc_create(const char *p_config, void *p_obj, RTCOnIceConnectionStateChange p_on_connection_state_change, RTCOnIceGatheringStateChange p_on_gathering_state_change, RTCOnSignalingStateChange p_on_signaling_state_change, RTCOnIceCandidate p_on_candidate, RTCOnDataChannel p_on_datachannel); extern void godot_js_rtc_pc_close(int p_id); extern void godot_js_rtc_pc_destroy(int p_id); extern void godot_js_rtc_pc_offer_create(int p_id, void *p_obj, RTCOnSession p_on_session, RTCOnError p_on_error); @@ -55,10 +57,14 @@ class WebRTCPeerConnectionJS : public WebRTCPeerConnection { GDCLASS(WebRTCPeerConnectionJS, WebRTCPeerConnection); private: - int _js_id; - ConnectionState _conn_state; + int _js_id = 0; + ConnectionState _conn_state = STATE_NEW; + GatheringState _gathering_state = GATHERING_STATE_NEW; + SignalingState _signaling_state = SIGNALING_STATE_STABLE; static void _on_connection_state_changed(void *p_obj, int p_state); + static void _on_gathering_state_changed(void *p_obj, int p_state); + static void _on_signaling_state_changed(void *p_obj, int p_state); static void _on_ice_candidate(void *p_obj, const char *p_mid_name, int p_mline_idx, const char *p_candidate); static void _on_data_channel(void *p_obj, int p_channel); static void _on_session_created(void *p_obj, const char *p_type, const char *p_session); @@ -66,6 +72,8 @@ private: public: virtual ConnectionState get_connection_state() const override; + virtual GatheringState get_gathering_state() const override; + virtual SignalingState get_signaling_state() const override; virtual Error initialize(Dictionary configuration = Dictionary()) override; virtual Ref<WebRTCDataChannel> create_data_channel(String p_channel_name, Dictionary p_channel_config = Dictionary()) override; diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml index 7d73194ea9..1978d2e7c6 100644 --- a/modules/websocket/doc_classes/WebSocketClient.xml +++ b/modules/websocket/doc_classes/WebSocketClient.xml @@ -24,8 +24,8 @@ If [code]true[/code] is passed as [code]gd_mp_api[/code], the client will behave like a multiplayer peer for the [MultiplayerAPI], connections to non-Godot servers will not work, and [signal data_received] will not be emitted. If [code]false[/code] is passed instead (default), you must call [PacketPeer] functions ([code]put_packet[/code], [code]get_packet[/code], etc.) on the [WebSocketPeer] returned via [code]get_peer(1)[/code] and not on this object directly (e.g. [code]get_peer(1).put_packet(data)[/code]). You can optionally pass a list of [code]custom_headers[/code] to be added to the handshake HTTP request. - [b]Note:[/b] To avoid mixed content warnings or errors in Web, you may have to use a [code]url[/code] that starts with [code]wss://[/code] (secure) instead of [code]ws://[/code]. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's SSL certificate. Do not connect directly via the IP address for [code]wss://[/code] connections, as it won't match with the SSL certificate. - [b]Note:[/b] Specifying [code]custom_headers[/code] is not supported in Web exports due to browsers restrictions. + [b]Note:[/b] To avoid mixed content warnings or errors in Web, you may have to use a [code]url[/code] that starts with [code]wss://[/code] (secure) instead of [code]ws://[/code]. When doing so, make sure to use the fully qualified domain name that matches the one defined in the server's TLS certificate. Do not connect directly via the IP address for [code]wss://[/code] connections, as it won't match with the TLS certificate. + [b]Note:[/b] Specifying [code]custom_headers[/code] is not supported in Web exports due to browsers' restrictions. </description> </method> <method name="disconnect_from_host"> @@ -50,12 +50,12 @@ </method> </methods> <members> - <member name="trusted_ssl_certificate" type="X509Certificate" setter="set_trusted_ssl_certificate" getter="get_trusted_ssl_certificate"> - If specified, this [X509Certificate] will be the only one accepted when connecting to an SSL host. Any other certificate provided by the server will be regarded as invalid. - [b]Note:[/b] Specifying a custom [code]trusted_ssl_certificate[/code] is not supported in Web exports due to browsers restrictions. + <member name="trusted_tls_certificate" type="X509Certificate" setter="set_trusted_tls_certificate" getter="get_trusted_tls_certificate"> + If specified, this [X509Certificate] will be the only one accepted when connecting to an TLS host. Any other certificate provided by the server will be regarded as invalid. + [b]Note:[/b] Specifying a custom [code]trusted_tls_certificate[/code] is not supported in Web exports due to browsers' restrictions. </member> - <member name="verify_ssl" type="bool" setter="set_verify_ssl_enabled" getter="is_verify_ssl_enabled"> - If [code]true[/code], SSL certificate verification is enabled. + <member name="verify_tls" type="bool" setter="set_verify_tls_enabled" getter="is_verify_tls_enabled"> + If [code]true[/code], TLS certificate verification is enabled. [b]Note:[/b] You must specify the certificates to be used in the Project Settings for it to work when exported. </member> </members> diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml index 19c36700e6..07a55b73f1 100644 --- a/modules/websocket/doc_classes/WebSocketServer.xml +++ b/modules/websocket/doc_classes/WebSocketServer.xml @@ -79,16 +79,16 @@ When not set to [code]*[/code] will restrict incoming connections to the specified IP address. Setting [code]bind_ip[/code] to [code]127.0.0.1[/code] will cause the server to listen only to the local host. </member> <member name="ca_chain" type="X509Certificate" setter="set_ca_chain" getter="get_ca_chain"> - When using SSL (see [member private_key] and [member ssl_certificate]), you can set this to a valid [X509Certificate] to be provided as additional CA chain information during the SSL handshake. + When using TLS (see [member private_key] and [member tls_certificate]), you can set this to a valid [X509Certificate] to be provided as additional CA chain information during the TLS handshake. </member> <member name="handshake_timeout" type="float" setter="set_handshake_timeout" getter="get_handshake_timeout" default="3.0"> The time in seconds before a pending client (i.e. a client that has not yet finished the HTTP handshake) is considered stale and forcefully disconnected. </member> <member name="private_key" type="CryptoKey" setter="set_private_key" getter="get_private_key"> - When set to a valid [CryptoKey] (along with [member ssl_certificate]) will cause the server to require SSL instead of regular TCP (i.e. the [code]wss://[/code] protocol). + When set to a valid [CryptoKey] (along with [member tls_certificate]) will cause the server to require TLS instead of regular TCP (i.e. the [code]wss://[/code] protocol). </member> - <member name="ssl_certificate" type="X509Certificate" setter="set_ssl_certificate" getter="get_ssl_certificate"> - When set to a valid [X509Certificate] (along with [member private_key]) will cause the server to require SSL instead of regular TCP (i.e. the [code]wss://[/code] protocol). + <member name="tls_certificate" type="X509Certificate" setter="set_tls_certificate" getter="get_tls_certificate"> + When set to a valid [X509Certificate] (along with [member private_key]) will cause the server to require TLS instead of regular TCP (i.e. the [code]wss://[/code] protocol). </member> </members> <signals> diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp index 65e0703c00..933a1f43e9 100644 --- a/modules/websocket/emws_client.cpp +++ b/modules/websocket/emws_client.cpp @@ -65,7 +65,7 @@ void EMWSClient::_esws_on_close(void *obj, int code, const char *reason, int was client->_on_disconnect(was_clean != 0); } -Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { +Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { if (_js_id) { godot_js_websocket_destroy(_js_id); _js_id = 0; @@ -84,9 +84,9 @@ Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, if (p_custom_headers.size()) { WARN_PRINT_ONCE("Custom headers are not supported in Web platform."); } - if (p_ssl) { + if (p_tls) { str = "wss://"; - if (ssl_cert.is_valid()) { + if (tls_cert.is_valid()) { WARN_PRINT_ONCE("Custom SSL certificate is not supported in Web platform."); } } diff --git a/modules/websocket/emws_client.h b/modules/websocket/emws_client.h index ff63a76753..cdcec31e19 100644 --- a/modules/websocket/emws_client.h +++ b/modules/websocket/emws_client.h @@ -54,7 +54,7 @@ private: public: Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override; - Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override; + Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override; Ref<WebSocketPeer> get_peer(int p_peer_id) const override; void disconnect_from_host(int p_code = 1000, String p_reason = "") override; IPAddress get_connected_host() const override; diff --git a/modules/websocket/websocket_client.cpp b/modules/websocket/websocket_client.cpp index 2734b4b88f..0b2d5d1918 100644 --- a/modules/websocket/websocket_client.cpp +++ b/modules/websocket/websocket_client.cpp @@ -48,34 +48,34 @@ Error WebSocketClient::connect_to_url(String p_url, const Vector<String> p_proto Error err = p_url.parse_url(scheme, host, port, path); ERR_FAIL_COND_V_MSG(err != OK, err, "Invalid URL: " + p_url); - bool ssl = false; + bool tls = false; if (scheme == "wss://") { - ssl = true; + tls = true; } if (port == 0) { - port = ssl ? 443 : 80; + port = tls ? 443 : 80; } if (path.is_empty()) { path = "/"; } - return connect_to_host(host, path, port, ssl, p_protocols, p_custom_headers); + return connect_to_host(host, path, port, tls, p_protocols, p_custom_headers); } -void WebSocketClient::set_verify_ssl_enabled(bool p_verify_ssl) { - verify_ssl = p_verify_ssl; +void WebSocketClient::set_verify_tls_enabled(bool p_verify_tls) { + verify_tls = p_verify_tls; } -bool WebSocketClient::is_verify_ssl_enabled() const { - return verify_ssl; +bool WebSocketClient::is_verify_tls_enabled() const { + return verify_tls; } -Ref<X509Certificate> WebSocketClient::get_trusted_ssl_certificate() const { - return ssl_cert; +Ref<X509Certificate> WebSocketClient::get_trusted_tls_certificate() const { + return tls_cert; } -void WebSocketClient::set_trusted_ssl_certificate(Ref<X509Certificate> p_cert) { +void WebSocketClient::set_trusted_tls_certificate(Ref<X509Certificate> p_cert) { ERR_FAIL_COND(get_connection_status() != CONNECTION_DISCONNECTED); - ssl_cert = p_cert; + tls_cert = p_cert; } bool WebSocketClient::is_server() const { @@ -123,15 +123,15 @@ void WebSocketClient::_bind_methods() { ClassDB::bind_method(D_METHOD("disconnect_from_host", "code", "reason"), &WebSocketClient::disconnect_from_host, DEFVAL(1000), DEFVAL("")); ClassDB::bind_method(D_METHOD("get_connected_host"), &WebSocketClient::get_connected_host); ClassDB::bind_method(D_METHOD("get_connected_port"), &WebSocketClient::get_connected_port); - ClassDB::bind_method(D_METHOD("set_verify_ssl_enabled", "enabled"), &WebSocketClient::set_verify_ssl_enabled); - ClassDB::bind_method(D_METHOD("is_verify_ssl_enabled"), &WebSocketClient::is_verify_ssl_enabled); + ClassDB::bind_method(D_METHOD("set_verify_tls_enabled", "enabled"), &WebSocketClient::set_verify_tls_enabled); + ClassDB::bind_method(D_METHOD("is_verify_tls_enabled"), &WebSocketClient::is_verify_tls_enabled); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "verify_ssl", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_verify_ssl_enabled", "is_verify_ssl_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "verify_tls", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_verify_tls_enabled", "is_verify_tls_enabled"); - ClassDB::bind_method(D_METHOD("get_trusted_ssl_certificate"), &WebSocketClient::get_trusted_ssl_certificate); - ClassDB::bind_method(D_METHOD("set_trusted_ssl_certificate", "cert"), &WebSocketClient::set_trusted_ssl_certificate); + ClassDB::bind_method(D_METHOD("get_trusted_tls_certificate"), &WebSocketClient::get_trusted_tls_certificate); + ClassDB::bind_method(D_METHOD("set_trusted_tls_certificate", "cert"), &WebSocketClient::set_trusted_tls_certificate); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "trusted_ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_trusted_ssl_certificate", "get_trusted_ssl_certificate"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "trusted_tls_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_trusted_tls_certificate", "get_trusted_tls_certificate"); ADD_SIGNAL(MethodInfo("data_received")); ADD_SIGNAL(MethodInfo("connection_established", PropertyInfo(Variant::STRING, "protocol"))); diff --git a/modules/websocket/websocket_client.h b/modules/websocket/websocket_client.h index d6c072ae16..e747aee4e4 100644 --- a/modules/websocket/websocket_client.h +++ b/modules/websocket/websocket_client.h @@ -42,20 +42,20 @@ class WebSocketClient : public WebSocketMultiplayerPeer { protected: Ref<WebSocketPeer> _peer; - bool verify_ssl = true; - Ref<X509Certificate> ssl_cert; + bool verify_tls = true; + Ref<X509Certificate> tls_cert; static void _bind_methods(); public: Error connect_to_url(String p_url, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false, const Vector<String> p_custom_headers = Vector<String>()); - void set_verify_ssl_enabled(bool p_verify_ssl); - bool is_verify_ssl_enabled() const; - Ref<X509Certificate> get_trusted_ssl_certificate() const; - void set_trusted_ssl_certificate(Ref<X509Certificate> p_cert); + void set_verify_tls_enabled(bool p_verify_tls); + bool is_verify_tls_enabled() const; + Ref<X509Certificate> get_trusted_tls_certificate() const; + void set_trusted_tls_certificate(Ref<X509Certificate> p_cert); - virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) = 0; + virtual Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) = 0; virtual void disconnect_from_host(int p_code = 1000, String p_reason = "") = 0; virtual IPAddress get_connected_host() const = 0; virtual uint16_t get_connected_port() const = 0; diff --git a/modules/websocket/websocket_macros.h b/modules/websocket/websocket_macros.h index a01ae65c56..b03bd8f45c 100644 --- a/modules/websocket/websocket_macros.h +++ b/modules/websocket/websocket_macros.h @@ -35,34 +35,32 @@ #define DEF_PKT_SHIFT 10 #define DEF_BUF_SHIFT 16 -/* clang-format off */ -#define GDCICLASS(CNAME) \ -public:\ - static CNAME *(*_create)();\ -\ - static Ref<CNAME > create_ref() {\ -\ - if (!_create)\ - return Ref<CNAME >();\ - return Ref<CNAME >(_create());\ - }\ -\ - static CNAME *create() {\ -\ - if (!_create)\ - return nullptr;\ - return _create();\ - }\ -protected:\ +#define GDCICLASS(CNAME) \ +public: \ + static CNAME *(*_create)(); \ + \ + static Ref<CNAME> create_ref() { \ + if (!_create) \ + return Ref<CNAME>(); \ + return Ref<CNAME>(_create()); \ + } \ + \ + static CNAME *create() { \ + if (!_create) \ + return nullptr; \ + return _create(); \ + } \ + \ +protected: #define GDCINULL(CNAME) \ -CNAME *(*CNAME::_create)() = nullptr; + CNAME *(*CNAME::_create)() = nullptr; -#define GDCIIMPL(IMPNAME, CNAME) \ -public:\ - static CNAME *_create() { return memnew(IMPNAME); }\ - static void make_default() { CNAME::_create = IMPNAME::_create; }\ -protected:\ -/* clang-format on */ +#define GDCIIMPL(IMPNAME, CNAME) \ +public: \ + static CNAME *_create() { return memnew(IMPNAME); } \ + static void make_default() { CNAME::_create = IMPNAME::_create; } \ + \ +protected: #endif // WEBSOCKET_MACROS_H diff --git a/modules/websocket/websocket_server.cpp b/modules/websocket/websocket_server.cpp index b7851b02c4..25a6e420fc 100644 --- a/modules/websocket/websocket_server.cpp +++ b/modules/websocket/websocket_server.cpp @@ -58,9 +58,9 @@ void WebSocketServer::_bind_methods() { ClassDB::bind_method(D_METHOD("set_private_key", "key"), &WebSocketServer::set_private_key); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "private_key", PROPERTY_HINT_RESOURCE_TYPE, "CryptoKey", PROPERTY_USAGE_NONE), "set_private_key", "get_private_key"); - ClassDB::bind_method(D_METHOD("get_ssl_certificate"), &WebSocketServer::get_ssl_certificate); - ClassDB::bind_method(D_METHOD("set_ssl_certificate", "cert"), &WebSocketServer::set_ssl_certificate); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "ssl_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_ssl_certificate", "get_ssl_certificate"); + ClassDB::bind_method(D_METHOD("get_tls_certificate"), &WebSocketServer::get_tls_certificate); + ClassDB::bind_method(D_METHOD("set_tls_certificate", "cert"), &WebSocketServer::set_tls_certificate); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tls_certificate", PROPERTY_HINT_RESOURCE_TYPE, "X509Certificate", PROPERTY_USAGE_NONE), "set_tls_certificate", "get_tls_certificate"); ClassDB::bind_method(D_METHOD("get_ca_chain"), &WebSocketServer::get_ca_chain); ClassDB::bind_method(D_METHOD("set_ca_chain", "ca_chain"), &WebSocketServer::set_ca_chain); @@ -95,13 +95,13 @@ void WebSocketServer::set_private_key(Ref<CryptoKey> p_key) { private_key = p_key; } -Ref<X509Certificate> WebSocketServer::get_ssl_certificate() const { - return ssl_cert; +Ref<X509Certificate> WebSocketServer::get_tls_certificate() const { + return tls_cert; } -void WebSocketServer::set_ssl_certificate(Ref<X509Certificate> p_cert) { +void WebSocketServer::set_tls_certificate(Ref<X509Certificate> p_cert) { ERR_FAIL_COND(is_listening()); - ssl_cert = p_cert; + tls_cert = p_cert; } Ref<X509Certificate> WebSocketServer::get_ca_chain() const { diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h index ac04c4e57e..de23ee884d 100644 --- a/modules/websocket/websocket_server.h +++ b/modules/websocket/websocket_server.h @@ -46,7 +46,7 @@ protected: static void _bind_methods(); Ref<CryptoKey> private_key; - Ref<X509Certificate> ssl_cert; + Ref<X509Certificate> tls_cert; Ref<X509Certificate> ca_chain; uint32_t handshake_timeout = 3000; @@ -74,8 +74,8 @@ public: Ref<CryptoKey> get_private_key() const; void set_private_key(Ref<CryptoKey> p_key); - Ref<X509Certificate> get_ssl_certificate() const; - void set_ssl_certificate(Ref<X509Certificate> p_cert); + Ref<X509Certificate> get_tls_certificate() const; + void set_tls_certificate(Ref<X509Certificate> p_cert); Ref<X509Certificate> get_ca_chain() const; void set_ca_chain(Ref<X509Certificate> p_ca_chain); diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp index 290108706b..50ef53e267 100644 --- a/modules/websocket/wsl_client.cpp +++ b/modules/websocket/wsl_client.cpp @@ -161,7 +161,7 @@ bool WSLClient::_verify_headers(String &r_protocol) { return true; } -Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { +Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocols, const Vector<String> p_custom_headers) { ERR_FAIL_COND_V(_connection.is_valid(), ERR_ALREADY_IN_USE); ERR_FAIL_COND_V(p_path.is_empty(), ERR_INVALID_PARAMETER); @@ -196,7 +196,7 @@ Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, return err; } _connection = _tcp; - _use_ssl = p_ssl; + _use_tls = p_tls; _host = p_host; _port = p_port; // Strip edges from protocols. @@ -209,7 +209,7 @@ Error WSLClient::connect_to_host(String p_host, String p_path, uint16_t p_port, _key = WSLPeer::generate_key(); String request = "GET " + p_path + " HTTP/1.1\r\n"; String port = ""; - if ((p_port != 80 && !p_ssl) || (p_port != 443 && p_ssl)) { + if ((p_port != 80 && !p_tls) || (p_port != 443 && p_tls)) { port = ":" + itos(p_port); } request += "Host: " + p_host + port + "\r\n"; @@ -288,27 +288,27 @@ void WSLClient::poll() { break; case StreamPeerTCP::STATUS_CONNECTED: { _ip_candidates.clear(); - Ref<StreamPeerTLS> ssl; - if (_use_ssl) { + Ref<StreamPeerTLS> tls; + if (_use_tls) { if (_connection == _tcp) { // Start SSL handshake - ssl = Ref<StreamPeerTLS>(StreamPeerTLS::create()); - ERR_FAIL_COND_MSG(ssl.is_null(), "SSL is not available in this build."); - ssl->set_blocking_handshake_enabled(false); - if (ssl->connect_to_stream(_tcp, verify_ssl, _host, ssl_cert) != OK) { + tls = Ref<StreamPeerTLS>(StreamPeerTLS::create()); + ERR_FAIL_COND_MSG(tls.is_null(), "SSL is not available in this build."); + tls->set_blocking_handshake_enabled(false); + if (tls->connect_to_stream(_tcp, verify_tls, _host, tls_cert) != OK) { disconnect_from_host(); _on_error(); return; } - _connection = ssl; + _connection = tls; } else { - ssl = static_cast<Ref<StreamPeerTLS>>(_connection); - ERR_FAIL_COND(ssl.is_null()); // Bug? - ssl->poll(); + tls = static_cast<Ref<StreamPeerTLS>>(_connection); + ERR_FAIL_COND(tls.is_null()); // Bug? + tls->poll(); } - if (ssl->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { + if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { return; // Need more polling. - } else if (ssl->get_status() != StreamPeerTLS::STATUS_CONNECTED) { + } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { disconnect_from_host(); _on_error(); return; // Error. @@ -356,7 +356,7 @@ void WSLClient::disconnect_from_host(int p_code, String p_reason) { _key = ""; _host = ""; _protocols.clear(); - _use_ssl = false; + _use_tls = false; _request = ""; _requested = 0; diff --git a/modules/websocket/wsl_client.h b/modules/websocket/wsl_client.h index dc4397f04a..dfb989fdd3 100644 --- a/modules/websocket/wsl_client.h +++ b/modules/websocket/wsl_client.h @@ -65,7 +65,7 @@ private: uint16_t _port = 0; Array _ip_candidates; Vector<String> _protocols; - bool _use_ssl = false; + bool _use_tls = false; IP::ResolverID _resolver_id = IP::RESOLVER_INVALID_ID; void _do_handshake(); @@ -73,7 +73,7 @@ private: public: Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override; - Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override; + Error connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_tls, const Vector<String> p_protocol = Vector<String>(), const Vector<String> p_custom_headers = Vector<String>()) override; int get_max_packet_size() const override; Ref<WebSocketPeer> get_peer(int p_peer_id) const override; void disconnect_from_host(int p_code = 1000, String p_reason = "") override; diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp index ddef360cf5..01dcd53839 100644 --- a/modules/websocket/wsl_server.cpp +++ b/modules/websocket/wsl_server.cpp @@ -102,16 +102,16 @@ Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uin return ERR_TIMEOUT; } - if (use_ssl) { - Ref<StreamPeerTLS> ssl = static_cast<Ref<StreamPeerTLS>>(connection); - if (ssl.is_null()) { + if (use_tls) { + Ref<StreamPeerTLS> tls = static_cast<Ref<StreamPeerTLS>>(connection); + if (tls.is_null()) { ERR_FAIL_V_MSG(ERR_BUG, "Couldn't get StreamPeerTLS for WebSocket handshake."); } - ssl->poll(); - if (ssl->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { + tls->poll(); + if (tls->get_status() == StreamPeerTLS::STATUS_HANDSHAKING) { return ERR_BUSY; - } else if (ssl->get_status() != StreamPeerTLS::STATUS_CONNECTED) { - print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", ssl->get_status())); + } else if (tls->get_status() != StreamPeerTLS::STATUS_CONNECTED) { + print_verbose(vformat("WebSocket SSL connection error during handshake (StreamPeerTLS status code %d).", tls->get_status())); return FAILED; } } @@ -247,12 +247,12 @@ void WSLServer::poll() { } Ref<PendingPeer> peer = memnew(PendingPeer); - if (private_key.is_valid() && ssl_cert.is_valid()) { - Ref<StreamPeerTLS> ssl = Ref<StreamPeerTLS>(StreamPeerTLS::create()); - ssl->set_blocking_handshake_enabled(false); - ssl->accept_stream(conn, private_key, ssl_cert, ca_chain); - peer->connection = ssl; - peer->use_ssl = true; + if (private_key.is_valid() && tls_cert.is_valid()) { + Ref<StreamPeerTLS> tls = Ref<StreamPeerTLS>(StreamPeerTLS::create()); + tls->set_blocking_handshake_enabled(false); + tls->accept_stream(conn, private_key, tls_cert, ca_chain); + peer->connection = tls; + peer->use_tls = true; } else { peer->connection = conn; } diff --git a/modules/websocket/wsl_server.h b/modules/websocket/wsl_server.h index ce91cfe888..df0c1dc68a 100644 --- a/modules/websocket/wsl_server.h +++ b/modules/websocket/wsl_server.h @@ -51,7 +51,7 @@ private: public: Ref<StreamPeerTCP> tcp; Ref<StreamPeer> connection; - bool use_ssl = false; + bool use_tls = false; uint64_t time = 0; uint8_t req_buf[WSL_MAX_HEADER_SIZE] = {}; diff --git a/modules/webxr/config.py b/modules/webxr/config.py index f676ef3483..8d75e7f531 100644 --- a/modules/webxr/config.py +++ b/modules/webxr/config.py @@ -1,5 +1,5 @@ def can_build(env, platform): - return not env["disable_3d"] + return env["opengl3"] and not env["disable_3d"] def configure(env): diff --git a/modules/webxr/godot_webxr.h b/modules/webxr/godot_webxr.h index 52104895d4..34d068be3e 100644 --- a/modules/webxr/godot_webxr.h +++ b/modules/webxr/godot_webxr.h @@ -65,8 +65,7 @@ extern int godot_webxr_get_view_count(); extern int *godot_webxr_get_render_target_size(); extern float *godot_webxr_get_transform_for_eye(int p_eye); extern float *godot_webxr_get_projection_for_eye(int p_eye); -extern int godot_webxr_get_external_texture_for_eye(int p_eye); -extern void godot_webxr_commit_for_eye(int p_eye); +extern void godot_webxr_commit_for_eye(int p_eye, unsigned int p_destination_fbo); extern void godot_webxr_sample_controller_data(); extern int godot_webxr_get_controller_count(); diff --git a/modules/webxr/native/library_godot_webxr.js b/modules/webxr/native/library_godot_webxr.js index c4b21defce..9b75796ee5 100644 --- a/modules/webxr/native/library_godot_webxr.js +++ b/modules/webxr/native/library_godot_webxr.js @@ -32,9 +32,6 @@ const GodotWebXR = { $GodotWebXR: { gl: null, - texture_ids: [null, null], - textures: [null, null], - session: null, space: null, frame: null, @@ -77,110 +74,6 @@ const GodotWebXR = { }, 0); }, - // Some custom WebGL code for blitting our eye textures to the - // framebuffer we get from WebXR. - shaderProgram: null, - programInfo: null, - buffer: null, - // Vertex shader source. - vsSource: ` - const vec2 scale = vec2(0.5, 0.5); - attribute vec4 aVertexPosition; - - varying highp vec2 vTextureCoord; - - void main () { - gl_Position = aVertexPosition; - vTextureCoord = aVertexPosition.xy * scale + scale; - } - `, - // Fragment shader source. - fsSource: ` - varying highp vec2 vTextureCoord; - - uniform sampler2D uSampler; - - void main() { - gl_FragColor = texture2D(uSampler, vTextureCoord); - } - `, - - initShaderProgram: (gl, vsSource, fsSource) => { - const vertexShader = GodotWebXR.loadShader(gl, gl.VERTEX_SHADER, vsSource); - const fragmentShader = GodotWebXR.loadShader(gl, gl.FRAGMENT_SHADER, fsSource); - - const shaderProgram = gl.createProgram(); - gl.attachShader(shaderProgram, vertexShader); - gl.attachShader(shaderProgram, fragmentShader); - gl.linkProgram(shaderProgram); - - if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { - GodotRuntime.error(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`); - return null; - } - - return shaderProgram; - }, - loadShader: (gl, type, source) => { - const shader = gl.createShader(type); - gl.shaderSource(shader, source); - gl.compileShader(shader); - - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - GodotRuntime.error(`An error occurred compiling the shader: ${gl.getShaderInfoLog(shader)}`); - gl.deleteShader(shader); - return null; - } - - return shader; - }, - initBuffer: (gl) => { - const positionBuffer = gl.createBuffer(); - gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); - const positions = [ - -1.0, -1.0, - 1.0, -1.0, - -1.0, 1.0, - 1.0, 1.0, - ]; - gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); - return positionBuffer; - }, - blitTexture: (gl, texture) => { - if (GodotWebXR.shaderProgram === null) { - GodotWebXR.shaderProgram = GodotWebXR.initShaderProgram(gl, GodotWebXR.vsSource, GodotWebXR.fsSource); - GodotWebXR.programInfo = { - program: GodotWebXR.shaderProgram, - attribLocations: { - vertexPosition: gl.getAttribLocation(GodotWebXR.shaderProgram, 'aVertexPosition'), - }, - uniformLocations: { - uSampler: gl.getUniformLocation(GodotWebXR.shaderProgram, 'uSampler'), - }, - }; - GodotWebXR.buffer = GodotWebXR.initBuffer(gl); - } - - const orig_program = gl.getParameter(gl.CURRENT_PROGRAM); - gl.useProgram(GodotWebXR.shaderProgram); - - gl.bindBuffer(gl.ARRAY_BUFFER, GodotWebXR.buffer); - gl.vertexAttribPointer(GodotWebXR.programInfo.attribLocations.vertexPosition, 2, gl.FLOAT, false, 0, 0); - gl.enableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.uniform1i(GodotWebXR.programInfo.uniformLocations.uSampler, 0); - - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); - - // Restore state. - gl.bindTexture(gl.TEXTURE_2D, null); - gl.disableVertexAttribArray(GodotWebXR.programInfo.attribLocations.vertexPosition); - gl.bindBuffer(gl.ARRAY_BUFFER, null); - gl.useProgram(orig_program); - }, - // Holds the controllers list between function calls. controllers: [], @@ -370,22 +263,6 @@ const GodotWebXR = { .catch((e) => { }); } - // Clean-up the textures we allocated for each view. - const gl = GodotWebXR.gl; - for (let i = 0; i < GodotWebXR.textures.length; i++) { - const texture = GodotWebXR.textures[i]; - if (texture !== null) { - gl.deleteTexture(texture); - } - GodotWebXR.textures[i] = null; - - const texture_id = GodotWebXR.texture_ids[i]; - if (texture_id !== null) { - GL.textures[texture_id] = null; - } - GodotWebXR.texture_ids[i] = null; - } - GodotWebXR.session = null; GodotWebXR.space = null; GodotWebXR.frame = null; @@ -460,50 +337,9 @@ const GodotWebXR = { return buf; }, - godot_webxr_get_external_texture_for_eye__proxy: 'sync', - godot_webxr_get_external_texture_for_eye__sig: 'ii', - godot_webxr_get_external_texture_for_eye: function (p_eye) { - if (!GodotWebXR.session) { - return 0; - } - - const view_index = (p_eye === 2 /* ARVRInterface::EYE_RIGHT */) ? 1 : 0; - if (GodotWebXR.texture_ids[view_index]) { - return GodotWebXR.texture_ids[view_index]; - } - - // Check pose separately and after returning the cached texture id, - // because we won't get a pose in some cases if we lose tracking, and - // we don't want to return 0 just because tracking was lost. - if (!GodotWebXR.pose) { - return 0; - } - - const glLayer = GodotWebXR.session.renderState.baseLayer; - const view = GodotWebXR.pose.views[view_index]; - const viewport = glLayer.getViewport(view); - const gl = GodotWebXR.gl; - - const texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, viewport.width, viewport.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.bindTexture(gl.TEXTURE_2D, null); - - const texture_id = GL.getNewId(GL.textures); - GL.textures[texture_id] = texture; - GodotWebXR.textures[view_index] = texture; - GodotWebXR.texture_ids[view_index] = texture_id; - return texture_id; - }, - godot_webxr_commit_for_eye__proxy: 'sync', - godot_webxr_commit_for_eye__sig: 'vi', - godot_webxr_commit_for_eye: function (p_eye) { + godot_webxr_commit_for_eye__sig: 'vii', + godot_webxr_commit_for_eye: function (p_eye, p_destination_fbo) { if (!GodotWebXR.session || !GodotWebXR.pose) { return; } @@ -514,18 +350,29 @@ const GodotWebXR = { const viewport = glLayer.getViewport(view); const gl = GodotWebXR.gl; + const framebuffer = GL.framebuffers[p_destination_fbo]; + const orig_framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); - const orig_viewport = gl.getParameter(gl.VIEWPORT); + const orig_read_framebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING); + const orig_read_buffer = gl.getParameter(gl.READ_BUFFER); + const orig_draw_framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING); - // Bind to WebXR's framebuffer. - gl.bindFramebuffer(gl.FRAMEBUFFER, glLayer.framebuffer); - gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); + // Copy from Godot render target into framebuffer from WebXR. + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer); + gl.readBuffer(gl.COLOR_ATTACHMENT0); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glLayer.framebuffer); - GodotWebXR.blitTexture(gl, GodotWebXR.textures[view_index]); + // Flip Y upside down on destination. + gl.blitFramebuffer(0, 0, viewport.width, viewport.height, + viewport.x, viewport.height, viewport.width, viewport.y, + gl.COLOR_BUFFER_BIT, gl.NEAREST); // Restore state. gl.bindFramebuffer(gl.FRAMEBUFFER, orig_framebuffer); - gl.viewport(orig_viewport[0], orig_viewport[1], orig_viewport[2], orig_viewport[3]); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, orig_read_framebuffer); + gl.readBuffer(orig_read_buffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, orig_draw_framebuffer); }, godot_webxr_sample_controller_data__proxy: 'sync', diff --git a/modules/webxr/webxr_interface_js.cpp b/modules/webxr/webxr_interface_js.cpp index 7d97dbfa0b..d0c7484aa1 100644 --- a/modules/webxr/webxr_interface_js.cpp +++ b/modules/webxr/webxr_interface_js.cpp @@ -34,9 +34,11 @@ #include "core/input/input.h" #include "core/os/os.h" +#include "drivers/gles3/storage/texture_storage.h" #include "emscripten.h" #include "godot_webxr.h" #include "servers/rendering/renderer_compositor.h" +#include "servers/rendering/rendering_server_globals.h" #include <stdlib.h> @@ -232,6 +234,8 @@ bool WebXRInterfaceJS::initialize() { } // we must create a tracker for our head + head_transform.basis = Basis(); + head_transform.origin = Vector3(); head_tracker.instantiate(); head_tracker->set_tracker_type(XRServer::TRACKER_HEAD); head_tracker->set_tracker_name("head"); @@ -334,15 +338,17 @@ Transform3D WebXRInterfaceJS::get_camera_transform() { XRServer *xr_server = XRServer::get_singleton(); ERR_FAIL_NULL_V(xr_server, transform_for_eye); - float *js_matrix = godot_webxr_get_transform_for_eye(0); - if (!initialized || js_matrix == nullptr) { - return transform_for_eye; - } + if (initialized) { + float world_scale = xr_server->get_world_scale(); - transform_for_eye = _js_matrix_to_transform(js_matrix); - free(js_matrix); + // just scale our origin point of our transform + Transform3D _head_transform = head_transform; + _head_transform.origin *= world_scale; + + transform_for_eye = (xr_server->get_reference_frame()) * _head_transform; + } - return xr_server->get_reference_frame() * transform_for_eye; + return transform_for_eye; }; Transform3D WebXRInterfaceJS::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) { @@ -360,6 +366,14 @@ Transform3D WebXRInterfaceJS::get_transform_for_view(uint32_t p_view, const Tran transform_for_eye = _js_matrix_to_transform(js_matrix); free(js_matrix); + float world_scale = xr_server->get_world_scale(); + // Scale only the center point of our eye transform, so we don't scale the + // distance between the eyes. + Transform3D _head_transform = head_transform; + transform_for_eye.origin -= _head_transform.origin; + _head_transform.origin *= world_scale; + transform_for_eye.origin += _head_transform.origin; + return p_cam_transform * xr_server->get_reference_frame() * transform_for_eye; }; @@ -394,29 +408,33 @@ Vector<BlitToScreen> WebXRInterfaceJS::post_draw_viewport(RID p_render_target, c return blit_to_screen; } - // @todo Refactor this to be based on "views" rather than "eyes". - godot_webxr_commit_for_eye(1); - if (godot_webxr_get_view_count() > 1) { - godot_webxr_commit_for_eye(2); + GLES3::TextureStorage *texture_storage = dynamic_cast<GLES3::TextureStorage *>(RSG::texture_storage); + if (!texture_storage) { + return blit_to_screen; } + GLES3::RenderTarget *rt = texture_storage->get_render_target(p_render_target); + + // @todo Support multiple eyes! + godot_webxr_commit_for_eye(1, rt->fbo); + return blit_to_screen; }; void WebXRInterfaceJS::process() { if (initialized) { - godot_webxr_sample_controller_data(); - + // Get the "head" position. + float *js_matrix = godot_webxr_get_transform_for_eye(0); + if (js_matrix != nullptr) { + head_transform = _js_matrix_to_transform(js_matrix); + free(js_matrix); + } if (head_tracker.is_valid()) { - // TODO set default pose to our head location (i.e. get_camera_transform without world scale and reference frame applied) - // head_tracker->set_pose("default", head_transform, Vector3(), Vector3()); + head_tracker->set_pose("default", head_transform, Vector3(), Vector3()); } + godot_webxr_sample_controller_data(); int controller_count = godot_webxr_get_controller_count(); - if (controller_count == 0) { - return; - } - for (int i = 0; i < controller_count; i++) { _update_tracker(i); } diff --git a/modules/webxr/webxr_interface_js.h b/modules/webxr/webxr_interface_js.h index dbe89dad83..319adc2ac9 100644 --- a/modules/webxr/webxr_interface_js.h +++ b/modules/webxr/webxr_interface_js.h @@ -45,6 +45,7 @@ class WebXRInterfaceJS : public WebXRInterface { private: bool initialized; Ref<XRPositionalTracker> head_tracker; + Transform3D head_transform; String session_mode; String required_features; |