diff options
762 files changed, 13247 insertions, 13069 deletions
diff --git a/.clang-format b/.clang-format index e011f060b7..f7527b8927 100644 --- a/.clang-format +++ b/.clang-format @@ -1,6 +1,6 @@ # Commented out parameters are those with the same value as base LLVM style. # We can uncomment them if we want to change their value, or enforce the -# chosen value in case the base style changes (last sync: Clang 13.0). +# chosen value in case the base style changes (last sync: Clang 14.0). --- ### General config, applies to all languages ### BasedOnStyle: LLVM @@ -15,7 +15,6 @@ AlignAfterOpenBracket: DontAlign AlignOperands: DontAlign AlignTrailingComments: false # AllowAllArgumentsOnNextLine: true -# AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false # AllowShortEnumsOnASingleLine: true # AllowShortBlocksOnASingleLine: Never @@ -62,8 +61,8 @@ BreakConstructorInitializers: AfterColon # BreakStringLiterals: true ColumnLimit: 0 # CommentPragmas: '^ IWYU pragma:' +# QualifierAlignment: Leave # CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 8 ContinuationIndentWidth: 8 Cpp11BracedListStyle: false @@ -73,6 +72,9 @@ Cpp11BracedListStyle: false # EmptyLineAfterAccessModifier: Never # EmptyLineBeforeAccessModifier: LogicalBlock # ExperimentalAutoDetectBinPacking: false +# PackConstructorInitializers: BinPack +ConstructorInitializerAllOnOneLineOrOnePerLine: true +# AllowAllConstructorInitializersOnNextLine: true # FixNamespaceComments: true # ForEachMacros: # - foreach @@ -112,6 +114,7 @@ KeepEmptyLinesAtTheStartOfBlocks: false # PenaltyBreakBeforeFirstCallParameter: 19 # PenaltyBreakComment: 300 # PenaltyBreakFirstLessLess: 120 +# PenaltyBreakOpenParenthesis: 0 # PenaltyBreakString: 1000 # PenaltyBreakTemplateDeclaration: 10 # PenaltyExcessCharacter: 1000000 @@ -121,6 +124,8 @@ KeepEmptyLinesAtTheStartOfBlocks: false # PPIndentWidth: -1 # ReferenceAlignment: Pointer # ReflowComments: true +# RemoveBracesLLVM: false +# SeparateDefinitionBlocks: Leave # ShortNamespaceLines: 1 # SortIncludes: CaseSensitive # SortJavaStaticImport: Before @@ -134,15 +139,20 @@ KeepEmptyLinesAtTheStartOfBlocks: false # SpaceBeforeCtorInitializerColon: true # SpaceBeforeInheritanceColon: true # SpaceBeforeParens: ControlStatements +# SpaceBeforeParensOptions: +# AfterControlStatements: true +# AfterForeachMacros: true +# AfterFunctionDefinitionName: false +# AfterFunctionDeclarationName: false +# AfterIfMacros: true +# AfterOverloadedOperator: false +# BeforeNonEmptyParentheses: false # SpaceAroundPointerQualifiers: Default # SpaceBeforeRangeBasedForLoopColon: true -# SpaceInEmptyParentheses: false -# SpacesBeforeTrailingComments: 1 # SpaceInEmptyBlock: false # SpaceInEmptyParentheses: false # SpacesBeforeTrailingComments: 1 # SpacesInAngles: Never -# SpacesInContainerLiterals: true # SpacesInConditionalStatement: false # SpacesInContainerLiterals: true # SpacesInCStyleCastParentheses: false diff --git a/.clang-tidy b/.clang-tidy index b623aef133..fa57c94a21 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,5 @@ --- -Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,modernize-redundant-void-arg,modernize-use-bool-literals,modernize-use-default-member-init,modernize-use-nullptr,readability-braces-around-statements' +Checks: 'clang-diagnostic-*,clang-analyzer-*,-*,modernize-redundant-void-arg,modernize-use-bool-literals,modernize-use-default-member-init,modernize-use-nullptr,readability-braces-around-statements,readability-redundant-member-init' WarningsAsErrors: '' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false diff --git a/.github/workflows/linux_builds.yml b/.github/workflows/linux_builds.yml index 1594f5b2d9..7ac364c45f 100644 --- a/.github/workflows/linux_builds.yml +++ b/.github/workflows/linux_builds.yml @@ -193,14 +193,6 @@ jobs: cp -f extension_api.json godot-cpp/godot-headers/ cp -f core/extension/gdnative_interface.h godot-cpp/godot-headers/godot/ - # Build godot-cpp library - - name: Build godot-cpp library - if: ${{ matrix.godot-cpp-test }} - run: | - cd godot-cpp - scons target=${{ matrix.target }} generate_bindings=yes -j2 - cd .. - # Build godot-cpp test extension - name: Build godot-cpp test extension if: ${{ matrix.godot-cpp-test }} diff --git a/.github/workflows/static_checks.yml b/.github/workflows/static_checks.yml index 724bebbd13..5531509007 100644 --- a/.github/workflows/static_checks.yml +++ b/.github/workflows/static_checks.yml @@ -27,7 +27,7 @@ jobs: sudo apt-get install -qq dos2unix recode clang-format-13 libxml2-utils sudo update-alternatives --remove-all clang-format sudo update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-13 100 - sudo pip3 install black==21.10b0 pygments + sudo pip3 install black==22.3.0 pygments - name: File formatting checks (file_format.sh) run: | diff --git a/core/config/engine.h b/core/config/engine.h index 1adab9b96f..eac96852b3 100644 --- a/core/config/engine.h +++ b/core/config/engine.h @@ -40,7 +40,7 @@ class Engine { public: struct Singleton { StringName name; - Object *ptr; + Object *ptr = nullptr; StringName class_name; //used for binding generation hinting bool user_created = false; Singleton(const StringName &p_name = StringName(), Object *p_ptr = nullptr, const StringName &p_class_name = StringName()); diff --git a/core/config/project_settings.cpp b/core/config/project_settings.cpp index 93c1abe7b5..06bfc0c562 100644 --- a/core/config/project_settings.cpp +++ b/core/config/project_settings.cpp @@ -145,7 +145,7 @@ String ProjectSettings::localize_path(const String &p_path) const { return p_path.simplify_path(); } - DirAccessRef dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String path = p_path.replace("\\", "/").simplify_path(); @@ -537,8 +537,8 @@ Error ProjectSettings::_setup(const String &p_path, const String &p_main_pack, b // Nothing was found, try to find a project file in provided path (`p_path`) // or, if requested (`p_upwards`) in parent directories. - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V_MSG(!d, ERR_CANT_CREATE, "Cannot create DirAccess for path '" + p_path + "'."); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V_MSG(d.is_null(), ERR_CANT_CREATE, "Cannot create DirAccess for path '" + p_path + "'."); d->change_dir(p_path); String current_dir = d->get_current_dir(); @@ -613,17 +613,14 @@ bool ProjectSettings::has_setting(String p_var) const { Error ProjectSettings::_load_settings_binary(const String &p_path) { Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); if (err != OK) { return err; } uint8_t hdr[4]; f->get_buffer(hdr, 4); - if (hdr[0] != 'E' || hdr[1] != 'C' || hdr[2] != 'F' || hdr[3] != 'G') { - memdelete(f); - ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Corrupted header in binary project.binary (not ECFG)."); - } + ERR_FAIL_COND_V_MSG((hdr[0] != 'E' || hdr[1] != 'C' || hdr[2] != 'F' || hdr[3] != 'G'), ERR_FILE_CORRUPT, "Corrupted header in binary project.binary (not ECFG)."); uint32_t count = f->get_32(); @@ -646,16 +643,14 @@ Error ProjectSettings::_load_settings_binary(const String &p_path) { set(key, value); } - f->close(); - memdelete(f); return OK; } Error ProjectSettings::_load_settings_text(const String &p_path) { Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); - if (!f) { + if (f.is_null()) { // FIXME: Above 'err' error code is ERR_FILE_CANT_OPEN if the file is missing // This needs to be streamlined if we want decent error reporting return ERR_FILE_NOT_FOUND; @@ -680,25 +675,18 @@ Error ProjectSettings::_load_settings_text(const String &p_path) { err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true); if (err == ERR_FILE_EOF) { - memdelete(f); // If we're loading a project.godot from source code, we can operate some // ProjectSettings conversions if need be. _convert_to_last_version(config_version); last_save_time = FileAccess::get_modified_time(get_resource_path().plus_file("project.godot")); return OK; - } else if (err != OK) { - ERR_PRINT("Error parsing " + p_path + " at line " + itos(lines) + ": " + error_text + " File might be corrupted."); - memdelete(f); - return err; } + ERR_FAIL_COND_V_MSG(err != OK, err, "Error parsing " + p_path + " at line " + itos(lines) + ": " + error_text + " File might be corrupted."); if (!assign.is_empty()) { if (section.is_empty() && assign == "config_version") { config_version = value; - if (config_version > CONFIG_VERSION) { - memdelete(f); - ERR_FAIL_V_MSG(ERR_FILE_CANT_OPEN, vformat("Can't open project at '%s', its `config_version` (%d) is from a more recent and incompatible version of the engine. Expected config version: %d.", p_path, config_version, CONFIG_VERSION)); - } + ERR_FAIL_COND_V_MSG(config_version > CONFIG_VERSION, ERR_FILE_CANT_OPEN, vformat("Can't open project at '%s', its `config_version` (%d) is from a more recent and incompatible version of the engine. Expected config version: %d.", p_path, config_version, CONFIG_VERSION)); } else { if (section.is_empty()) { set(assign, value); @@ -778,7 +766,7 @@ Error ProjectSettings::save() { Error ProjectSettings::_save_settings_binary(const String &p_file, const Map<String, List<String>> &props, const CustomMap &p_custom, const String &p_custom_features) { Error err; - FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_file, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err != OK, err, "Couldn't save project.binary at " + p_file + "."); uint8_t hdr[4] = { 'E', 'C', 'F', 'G' }; @@ -798,19 +786,13 @@ Error ProjectSettings::_save_settings_binary(const String &p_file, const Map<Str int len; err = encode_variant(p_custom_features, nullptr, len, false); - if (err != OK) { - memdelete(file); - ERR_FAIL_V(err); - } + ERR_FAIL_COND_V(err != OK, err); Vector<uint8_t> buff; buff.resize(len); err = encode_variant(p_custom_features, buff.ptrw(), len, false); - if (err != OK) { - memdelete(file); - ERR_FAIL_V(err); - } + ERR_FAIL_COND_V(err != OK, err); file->store_32(len); file->store_buffer(buff.ptr(), buff.size()); @@ -834,33 +816,24 @@ Error ProjectSettings::_save_settings_binary(const String &p_file, const Map<Str int len; err = encode_variant(value, nullptr, len, true); - if (err != OK) { - memdelete(file); - } ERR_FAIL_COND_V_MSG(err != OK, ERR_INVALID_DATA, "Error when trying to encode Variant."); Vector<uint8_t> buff; buff.resize(len); err = encode_variant(value, buff.ptrw(), len, true); - if (err != OK) { - memdelete(file); - } ERR_FAIL_COND_V_MSG(err != OK, ERR_INVALID_DATA, "Error when trying to encode Variant."); file->store_32(len); file->store_buffer(buff.ptr(), buff.size()); } } - file->close(); - memdelete(file); - return OK; } Error ProjectSettings::_save_settings_text(const String &p_file, const Map<String, List<String>> &props, const CustomMap &p_custom, const String &p_custom_features) { Error err; - FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_file, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err != OK, err, "Couldn't save project.godot - " + p_file + "."); @@ -905,9 +878,6 @@ Error ProjectSettings::_save_settings_text(const String &p_file, const Map<Strin } } - file->close(); - memdelete(file); - return OK; } diff --git a/core/core_bind.cpp b/core/core_bind.cpp index 706395afa9..892b74c26a 100644 --- a/core/core_bind.cpp +++ b/core/core_bind.cpp @@ -1027,10 +1027,10 @@ Error File::open_encrypted(const String &p_path, ModeFlags p_mode_flags, const V return err; } - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + Ref<FileAccessEncrypted> fae; + fae.instantiate(); err = fae->open_and_parse(f, p_key, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ); if (err) { - memdelete(fae); close(); return err; } @@ -1044,10 +1044,10 @@ Error File::open_encrypted_pass(const String &p_path, ModeFlags p_mode_flags, co return err; } - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + Ref<FileAccessEncrypted> fae; + fae.instantiate(); err = fae->open_and_parse_password(f, p_pass, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ); if (err) { - memdelete(fae); close(); return err; } @@ -1057,14 +1057,13 @@ Error File::open_encrypted_pass(const String &p_path, ModeFlags p_mode_flags, co } Error File::open_compressed(const String &p_path, ModeFlags p_mode_flags, CompressionMode p_compress_mode) { - FileAccessCompressed *fac = memnew(FileAccessCompressed); - + Ref<FileAccessCompressed> fac; + fac.instantiate(); fac->configure("GCPF", (Compression::Mode)p_compress_mode); Error err = fac->_open(p_path, p_mode_flags); if (err) { - memdelete(fac); return err; } @@ -1073,25 +1072,22 @@ Error File::open_compressed(const String &p_path, ModeFlags p_mode_flags, Compre } Error File::open(const String &p_path, ModeFlags p_mode_flags) { - close(); Error err; f = FileAccess::open(p_path, p_mode_flags, &err); - if (f) { + if (f.is_valid()) { f->set_big_endian(big_endian); } return err; } void File::flush() { - ERR_FAIL_COND_MSG(!f, "File must be opened before flushing."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before flushing."); f->flush(); } void File::close() { - if (f) { - memdelete(f); - } - f = nullptr; + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened."); + f.unref(); } bool File::is_open() const { @@ -1099,79 +1095,79 @@ bool File::is_open() const { } String File::get_path() const { - ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), "", "File must be opened before use, or is lacking read-write permission."); return f->get_path(); } String File::get_path_absolute() const { - ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), "", "File must be opened before use, or is lacking read-write permission."); return f->get_path_absolute(); } void File::seek(int64_t p_position) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); ERR_FAIL_COND_MSG(p_position < 0, "Seek position must be a positive integer."); f->seek(p_position); } void File::seek_end(int64_t p_position) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->seek_end(p_position); } uint64_t File::get_position() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_position(); } uint64_t File::get_length() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_length(); } bool File::eof_reached() const { - ERR_FAIL_COND_V_MSG(!f, false, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), false, "File must be opened before use, or is lacking read-write permission."); return f->eof_reached(); } uint8_t File::get_8() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_8(); } uint16_t File::get_16() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_16(); } uint32_t File::get_32() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_32(); } uint64_t File::get_64() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_64(); } float File::get_float() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_float(); } double File::get_double() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_double(); } real_t File::get_real() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use, or is lacking read-write permission."); return f->get_real(); } Vector<uint8_t> File::get_buffer(int64_t p_length) const { Vector<uint8_t> data; - ERR_FAIL_COND_V_MSG(!f, data, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), data, "File must be opened before use, or is lacking read-write permission."); ERR_FAIL_COND_V_MSG(p_length < 0, data, "Length of buffer cannot be smaller than 0."); if (p_length == 0) { @@ -1192,11 +1188,11 @@ Vector<uint8_t> File::get_buffer(int64_t p_length) const { } String File::get_as_text() const { - ERR_FAIL_COND_V_MSG(!f, String(), "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), String(), "File must be opened before use, or is lacking read-write permission."); String text; uint64_t original_pos = f->get_position(); - f->seek(0); + const_cast<FileAccess *>(*f)->seek(0); String l = get_line(); while (!eof_reached()) { @@ -1205,7 +1201,7 @@ String File::get_as_text() const { } text += l; - f->seek(original_pos); + const_cast<FileAccess *>(*f)->seek(original_pos); return text; } @@ -1219,12 +1215,12 @@ String File::get_sha256(const String &p_path) const { } String File::get_line() const { - ERR_FAIL_COND_V_MSG(!f, String(), "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), String(), "File must be opened before use, or is lacking read-write permission."); return f->get_line(); } Vector<String> File::get_csv_line(const String &p_delim) const { - ERR_FAIL_COND_V_MSG(!f, Vector<String>(), "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), Vector<String>(), "File must be opened before use, or is lacking read-write permission."); return f->get_csv_line(p_delim); } @@ -1235,7 +1231,7 @@ Vector<String> File::get_csv_line(const String &p_delim) const { void File::set_big_endian(bool p_big_endian) { big_endian = p_big_endian; - if (f) { + if (f.is_valid()) { f->set_big_endian(p_big_endian); } } @@ -1245,84 +1241,84 @@ bool File::is_big_endian() { } Error File::get_error() const { - if (!f) { + if (f.is_null()) { return ERR_UNCONFIGURED; } return f->get_error(); } void File::store_8(uint8_t p_dest) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_8(p_dest); } void File::store_16(uint16_t p_dest) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_16(p_dest); } void File::store_32(uint32_t p_dest) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_32(p_dest); } void File::store_64(uint64_t p_dest) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_64(p_dest); } void File::store_float(float p_dest) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_float(p_dest); } void File::store_double(double p_dest) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_double(p_dest); } void File::store_real(real_t p_real) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_real(p_real); } void File::store_string(const String &p_string) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_string(p_string); } void File::store_pascal_string(const String &p_string) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_pascal_string(p_string); } String File::get_pascal_string() { - ERR_FAIL_COND_V_MSG(!f, "", "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), "", "File must be opened before use, or is lacking read-write permission."); return f->get_pascal_string(); } void File::store_line(const String &p_string) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_line(p_string); } void File::store_csv_line(const Vector<String> &p_values, const String &p_delim) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); f->store_csv_line(p_values, p_delim); } void File::store_buffer(const Vector<uint8_t> &p_buffer) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); uint64_t len = p_buffer.size(); if (len == 0) { @@ -1339,7 +1335,7 @@ bool File::file_exists(const String &p_name) { } void File::store_var(const Variant &p_var, bool p_full_objects) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use, or is lacking read-write permission."); int len; Error err = encode_variant(p_var, nullptr, len, p_full_objects); ERR_FAIL_COND_MSG(err != OK, "Error when trying to encode Variant."); @@ -1356,7 +1352,7 @@ void File::store_var(const Variant &p_var, bool p_full_objects) { } Variant File::get_var(bool p_allow_objects) const { - ERR_FAIL_COND_V_MSG(!f, Variant(), "File must be opened before use, or is lacking read-write permission."); + ERR_FAIL_COND_V_MSG(f.is_null(), Variant(), "File must be opened before use, or is lacking read-write permission."); uint32_t len = get_32(); Vector<uint8_t> buff = get_buffer(len); ERR_FAIL_COND_V((uint32_t)buff.size() != len, Variant()); @@ -1440,24 +1436,14 @@ void File::_bind_methods() { BIND_ENUM_CONSTANT(COMPRESSION_GZIP); } -File::~File() { - if (f) { - memdelete(f); - } -} - ////// Directory ////// Error Directory::open(const String &p_path) { Error err; - DirAccess *alt = DirAccess::open(p_path, &err); - - if (!alt) { + Ref<DirAccess> alt = DirAccess::open(p_path, &err); + if (alt.is_null()) { return err; } - if (d) { - memdelete(d); - } d = alt; dir_open = true; @@ -1465,7 +1451,7 @@ Error Directory::open(const String &p_path) { } bool Directory::is_open() const { - return d && dir_open; + return d.is_valid() && dir_open; } Error Directory::list_dir_begin() { @@ -1550,7 +1536,7 @@ int Directory::get_current_drive() { } Error Directory::change_dir(String p_dir) { - ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory is not configured properly."); + ERR_FAIL_COND_V_MSG(d.is_null(), ERR_UNCONFIGURED, "Directory is not configured properly."); Error err = d->change_dir(p_dir); if (err != OK) { @@ -1567,25 +1553,25 @@ String Directory::get_current_dir() { } Error Directory::make_dir(String p_dir) { - ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory is not configured properly."); + ERR_FAIL_COND_V_MSG(d.is_null(), ERR_UNCONFIGURED, "Directory is not configured properly."); if (!p_dir.is_relative_path()) { - DirAccessRef da = DirAccess::create_for_path(p_dir); + Ref<DirAccess> da = DirAccess::create_for_path(p_dir); return da->make_dir(p_dir); } return d->make_dir(p_dir); } Error Directory::make_dir_recursive(String p_dir) { - ERR_FAIL_COND_V_MSG(!d, ERR_UNCONFIGURED, "Directory is not configured properly."); + ERR_FAIL_COND_V_MSG(d.is_null(), ERR_UNCONFIGURED, "Directory is not configured properly."); if (!p_dir.is_relative_path()) { - DirAccessRef da = DirAccess::create_for_path(p_dir); + Ref<DirAccess> da = DirAccess::create_for_path(p_dir); return da->make_dir_recursive(p_dir); } return d->make_dir_recursive(p_dir); } bool Directory::file_exists(String p_file) { - ERR_FAIL_COND_V_MSG(!d, false, "Directory is not configured properly."); + ERR_FAIL_COND_V_MSG(d.is_null(), false, "Directory is not configured properly."); if (!p_file.is_relative_path()) { return FileAccess::exists(p_file); } @@ -1593,7 +1579,7 @@ bool Directory::file_exists(String p_file) { } bool Directory::dir_exists(String p_dir) { - ERR_FAIL_COND_V_MSG(!d, false, "Directory is not configured properly."); + ERR_FAIL_COND_V_MSG(d.is_null(), false, "Directory is not configured properly."); if (!p_dir.is_relative_path()) { return DirAccess::exists(p_dir); } @@ -1601,7 +1587,7 @@ bool Directory::dir_exists(String p_dir) { } uint64_t Directory::get_space_left() { - ERR_FAIL_COND_V_MSG(!d, 0, "Directory must be opened before use."); + ERR_FAIL_COND_V_MSG(d.is_null(), 0, "Directory must be opened before use."); return d->get_space_left() / 1024 * 1024; // Truncate to closest MiB. } @@ -1615,7 +1601,7 @@ Error Directory::rename(String p_from, String p_to) { ERR_FAIL_COND_V_MSG(p_from.is_empty() || p_from == "." || p_from == "..", ERR_INVALID_PARAMETER, "Invalid path to rename."); if (!p_from.is_relative_path()) { - DirAccessRef da = DirAccess::create_for_path(p_from); + Ref<DirAccess> da = DirAccess::create_for_path(p_from); ERR_FAIL_COND_V_MSG(!da->file_exists(p_from) && !da->dir_exists(p_from), ERR_DOES_NOT_EXIST, "File or directory does not exist."); return da->rename(p_from, p_to); } @@ -1627,7 +1613,7 @@ Error Directory::rename(String p_from, String p_to) { Error Directory::remove(String p_name) { ERR_FAIL_COND_V_MSG(!is_open(), ERR_UNCONFIGURED, "Directory must be opened before use."); if (!p_name.is_relative_path()) { - DirAccessRef da = DirAccess::create_for_path(p_name); + Ref<DirAccess> da = DirAccess::create_for_path(p_name); return da->remove(p_name); } @@ -1669,12 +1655,6 @@ Directory::Directory() { d = DirAccess::create(DirAccess::ACCESS_RESOURCES); } -Directory::~Directory() { - if (d) { - memdelete(d); - } -} - ////// Marshalls ////// Marshalls *Marshalls::singleton = nullptr; diff --git a/core/core_bind.h b/core/core_bind.h index 907f37c5fa..591cacdabb 100644 --- a/core/core_bind.h +++ b/core/core_bind.h @@ -349,7 +349,7 @@ public: class File : public RefCounted { GDCLASS(File, RefCounted); - FileAccess *f = nullptr; + Ref<FileAccess> f; bool big_endian = false; protected: @@ -442,12 +442,11 @@ public: uint64_t get_modified_time(const String &p_file) const; File() {} - virtual ~File(); }; class Directory : public RefCounted { GDCLASS(Directory, RefCounted); - DirAccess *d; + Ref<DirAccess> d; bool dir_open = false; bool include_navigational = false; @@ -495,7 +494,6 @@ public: Error remove(String p_name); Directory(); - virtual ~Directory(); }; class Marshalls : public Object { diff --git a/core/debugger/engine_profiler.cpp b/core/debugger/engine_profiler.cpp index c858b1febd..6235d19405 100644 --- a/core/debugger/engine_profiler.cpp +++ b/core/debugger/engine_profiler.cpp @@ -55,13 +55,13 @@ Error EngineProfiler::bind(const String &p_name) { EngineDebugger::Profiler prof( this, [](void *p_user, bool p_enable, const Array &p_opts) { - ((EngineProfiler *)p_user)->toggle(p_enable, p_opts); + static_cast<EngineProfiler *>(p_user)->toggle(p_enable, p_opts); }, [](void *p_user, const Array &p_data) { - ((EngineProfiler *)p_user)->add(p_data); + static_cast<EngineProfiler *>(p_user)->add(p_data); }, [](void *p_user, double p_frame_time, double p_idle_time, double p_physics_time, double p_physics_frame_time) { - ((EngineProfiler *)p_user)->tick(p_frame_time, p_idle_time, p_physics_time, p_physics_frame_time); + static_cast<EngineProfiler *>(p_user)->tick(p_frame_time, p_idle_time, p_physics_time, p_physics_frame_time); }); registration = p_name; EngineDebugger::register_profiler(p_name, prof); diff --git a/core/debugger/local_debugger.cpp b/core/debugger/local_debugger.cpp index c9f7d81a90..131cbaed6c 100644 --- a/core/debugger/local_debugger.cpp +++ b/core/debugger/local_debugger.cpp @@ -369,11 +369,11 @@ LocalDebugger::LocalDebugger() { Profiler scr_prof( scripts_profiler, [](void *p_user, bool p_enable, const Array &p_opts) { - ((ScriptsProfiler *)p_user)->toggle(p_enable, p_opts); + static_cast<ScriptsProfiler *>(p_user)->toggle(p_enable, p_opts); }, nullptr, [](void *p_user, double p_frame_time, double p_idle_time, double p_physics_time, double p_physics_frame_time) { - ((ScriptsProfiler *)p_user)->tick(p_frame_time, p_idle_time, p_physics_time, p_physics_frame_time); + static_cast<ScriptsProfiler *>(p_user)->tick(p_frame_time, p_idle_time, p_physics_time, p_physics_frame_time); }); register_profiler("scripts", scr_prof); } diff --git a/core/debugger/remote_debugger.cpp b/core/debugger/remote_debugger.cpp index 2fce23d003..425261aa6c 100644 --- a/core/debugger/remote_debugger.cpp +++ b/core/debugger/remote_debugger.cpp @@ -161,8 +161,9 @@ public: if (!monitor_value.is_num()) { ERR_PRINT("Value of custom monitor '" + String(custom_monitor_names[i]) + "' is not a number"); arr[i + max] = Variant(); + } else { + arr[i + max] = monitor_value; } - arr[i + max] = monitor_value; } EngineDebugger::get_singleton()->send_message("performance:profile_frame", arr); @@ -189,7 +190,7 @@ void RemoteDebugger::_err_handler(void *p_this, const char *p_func, const char * return; //ignore script errors, those go through debugger } - RemoteDebugger *rd = (RemoteDebugger *)p_this; + RemoteDebugger *rd = static_cast<RemoteDebugger *>(p_this); if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive errors during flush. return; } @@ -208,7 +209,7 @@ void RemoteDebugger::_err_handler(void *p_this, const char *p_func, const char * } void RemoteDebugger::_print_handler(void *p_this, const String &p_string, bool p_error) { - RemoteDebugger *rd = (RemoteDebugger *)p_this; + RemoteDebugger *rd = static_cast<RemoteDebugger *>(p_this); if (rd->flushing && Thread::get_caller_id() == rd->flush_thread) { // Can't handle recursive prints during flush. return; @@ -656,12 +657,12 @@ RemoteDebugger::RemoteDebugger(Ref<RemoteDebuggerPeer> p_peer) { // Core and profiler captures. Capture core_cap(this, [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) { - return ((RemoteDebugger *)p_user)->_core_capture(p_cmd, p_data, r_captured); + return static_cast<RemoteDebugger *>(p_user)->_core_capture(p_cmd, p_data, r_captured); }); register_message_capture("core", core_cap); Capture profiler_cap(this, [](void *p_user, const String &p_cmd, const Array &p_data, bool &r_captured) { - return ((RemoteDebugger *)p_user)->_profiler_capture(p_cmd, p_data, r_captured); + return static_cast<RemoteDebugger *>(p_user)->_profiler_capture(p_cmd, p_data, r_captured); }); register_message_capture("profiler", profiler_cap); diff --git a/core/debugger/remote_debugger_peer.cpp b/core/debugger/remote_debugger_peer.cpp index 7c7d38ab0a..950500884e 100644 --- a/core/debugger/remote_debugger_peer.cpp +++ b/core/debugger/remote_debugger_peer.cpp @@ -162,7 +162,7 @@ Error RemoteDebuggerPeerTCP::connect_to_host(const String &p_host, uint16_t p_po int port = p_port; const int tries = 6; - int waits[tries] = { 1, 10, 100, 1000, 1000, 1000 }; + const int waits[tries] = { 1, 10, 100, 1000, 1000, 1000 }; tcp_client->connect_to_host(ip, port); @@ -192,7 +192,7 @@ Error RemoteDebuggerPeerTCP::connect_to_host(const String &p_host, uint16_t p_po void RemoteDebuggerPeerTCP::_thread_func(void *p_ud) { // Update in time for 144hz monitors const uint64_t min_tick = 6900; - RemoteDebuggerPeerTCP *peer = (RemoteDebuggerPeerTCP *)p_ud; + RemoteDebuggerPeerTCP *peer = static_cast<RemoteDebuggerPeerTCP *>(p_ud); while (peer->running && peer->is_peer_connected()) { uint64_t ticks_usec = OS::get_singleton()->get_ticks_usec(); peer->_poll(); diff --git a/core/debugger/remote_debugger_peer.h b/core/debugger/remote_debugger_peer.h index 010336ffd3..473fd8d712 100644 --- a/core/debugger/remote_debugger_peer.h +++ b/core/debugger/remote_debugger_peer.h @@ -81,13 +81,13 @@ public: Error connect_to_host(const String &p_host, uint16_t p_port); - void poll(); - bool is_peer_connected(); - bool has_message(); - Array get_message(); - Error put_message(const Array &p_arr); - int get_max_message_size() const; - void close(); + void poll() override; + bool is_peer_connected() override; + bool has_message() override; + Array get_message() override; + Error put_message(const Array &p_arr) override; + int get_max_message_size() const override; + void close() override; RemoteDebuggerPeerTCP(Ref<StreamPeerTCP> p_stream = Ref<StreamPeerTCP>()); ~RemoteDebuggerPeerTCP(); diff --git a/core/error/error_macros.cpp b/core/error/error_macros.cpp index ceccd43259..8add4b9a3a 100644 --- a/core/error/error_macros.cpp +++ b/core/error/error_macros.cpp @@ -50,7 +50,7 @@ void add_error_handler(ErrorHandlerList *p_handler) { _global_unlock(); } -void remove_error_handler(ErrorHandlerList *p_handler) { +void remove_error_handler(const ErrorHandlerList *p_handler) { _global_lock(); ErrorHandlerList *prev = nullptr; diff --git a/core/error/error_macros.h b/core/error/error_macros.h index 01e22e84b7..2cfb5421c6 100644 --- a/core/error/error_macros.h +++ b/core/error/error_macros.h @@ -58,7 +58,7 @@ struct ErrorHandlerList { }; void add_error_handler(ErrorHandlerList *p_handler); -void remove_error_handler(ErrorHandlerList *p_handler); +void remove_error_handler(const ErrorHandlerList *p_handler); // Functions used by the error macros. void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, bool p_editor_notify = false, ErrorHandlerType p_type = ERR_HANDLER_ERROR); diff --git a/core/extension/extension_api_dump.cpp b/core/extension/extension_api_dump.cpp index 9acc28f51e..f64c30dca5 100644 --- a/core/extension/extension_api_dump.cpp +++ b/core/extension/extension_api_dump.cpp @@ -869,9 +869,8 @@ void NativeExtensionAPIDump::generate_extension_json_file(const String &p_path) json.instantiate(); String text = json->stringify(api, "\t", false); - FileAccessRef fa = FileAccess::open(p_path, FileAccess::WRITE); + Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE); CharString cs = text.ascii(); fa->store_buffer((const uint8_t *)cs.ptr(), cs.length()); - fa->close(); } #endif diff --git a/core/extension/gdnative_interface.cpp b/core/extension/gdnative_interface.cpp index b5b340731d..a312ce4ebd 100644 --- a/core/extension/gdnative_interface.cpp +++ b/core/extension/gdnative_interface.cpp @@ -241,6 +241,13 @@ static GDNativeBool gdnative_variant_booleanize(const GDNativeVariantPtr p_self) return self->booleanize(); } +static void gdnative_variant_sub(const GDNativeVariantPtr p_a, const GDNativeVariantPtr p_b, GDNativeVariantPtr r_dst) { + const Variant *a = (const Variant *)p_a; + const Variant *b = (const Variant *)p_b; + memnew_placement(r_dst, Variant); + Variant::sub(*a, *b, *(Variant *)r_dst); +} + static void gdnative_variant_blend(const GDNativeVariantPtr p_a, const GDNativeVariantPtr p_b, float p_c, GDNativeVariantPtr r_dst) { const Variant *a = (const Variant *)p_a; const Variant *b = (const Variant *)p_b; @@ -939,6 +946,7 @@ void gdnative_setup_interface(GDNativeInterface *p_interface) { gdni.variant_iter_get = gdnative_variant_iter_get; gdni.variant_hash_compare = gdnative_variant_hash_compare; gdni.variant_booleanize = gdnative_variant_booleanize; + gdni.variant_sub = gdnative_variant_sub; gdni.variant_blend = gdnative_variant_blend; gdni.variant_interpolate = gdnative_variant_interpolate; gdni.variant_duplicate = gdnative_variant_duplicate; diff --git a/core/extension/gdnative_interface.h b/core/extension/gdnative_interface.h index 732a1b5af0..2bac52dc4a 100644 --- a/core/extension/gdnative_interface.h +++ b/core/extension/gdnative_interface.h @@ -416,6 +416,7 @@ typedef struct { void (*variant_iter_get)(const GDNativeVariantPtr p_self, GDNativeVariantPtr r_iter, GDNativeVariantPtr r_ret, GDNativeBool *r_valid); GDNativeBool (*variant_hash_compare)(const GDNativeVariantPtr p_self, const GDNativeVariantPtr p_other); GDNativeBool (*variant_booleanize)(const GDNativeVariantPtr p_self); + void (*variant_sub)(const GDNativeVariantPtr p_a, const GDNativeVariantPtr p_b, GDNativeVariantPtr r_dst); void (*variant_blend)(const GDNativeVariantPtr p_a, const GDNativeVariantPtr p_b, float p_c, GDNativeVariantPtr r_dst); void (*variant_interpolate)(const GDNativeVariantPtr p_a, const GDNativeVariantPtr p_b, float p_c, GDNativeVariantPtr r_dst); void (*variant_duplicate)(const GDNativeVariantPtr p_self, GDNativeVariantPtr r_ret, GDNativeBool p_deep); diff --git a/core/extension/native_extension.cpp b/core/extension/native_extension.cpp index 1a39c937e8..34a11758f8 100644 --- a/core/extension/native_extension.cpp +++ b/core/extension/native_extension.cpp @@ -112,7 +112,7 @@ public: static GDNativeInterface gdnative_interface; void NativeExtension::_register_extension_class(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name, const char *p_parent_class_name, const GDNativeExtensionClassCreationInfo *p_extension_funcs) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; ERR_FAIL_COND_MSG(!String(class_name).is_valid_identifier(), "Attempt to register extension class '" + class_name + "', which is not a valid class identifier."); @@ -163,7 +163,7 @@ void NativeExtension::_register_extension_class(const GDNativeExtensionClassLibr ClassDB::register_extension_class(&extension->native_extension); } void NativeExtension::_register_extension_class_method(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name, const GDNativeExtensionClassMethodInfo *p_method_info) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; StringName method_name = p_method_info->name; @@ -177,7 +177,7 @@ void NativeExtension::_register_extension_class_method(const GDNativeExtensionCl ClassDB::bind_method_custom(class_name, method); } void NativeExtension::_register_extension_class_integer_constant(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name, const char *p_enum_name, const char *p_constant_name, GDNativeInt p_constant_value) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension constant '" + String(p_constant_name) + "' for unexisting class '" + class_name + "'."); @@ -188,7 +188,7 @@ void NativeExtension::_register_extension_class_integer_constant(const GDNativeE } void NativeExtension::_register_extension_class_property(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name, const GDNativePropertyInfo *p_info, const char *p_setter, const char *p_getter) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class property '" + String(p_info->name) + "' for unexisting class '" + class_name + "'."); @@ -206,7 +206,7 @@ void NativeExtension::_register_extension_class_property(const GDNativeExtension } void NativeExtension::_register_extension_class_property_group(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name, const char *p_group_name, const char *p_prefix) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class property group '" + String(p_group_name) + "' for unexisting class '" + class_name + "'."); @@ -215,7 +215,7 @@ void NativeExtension::_register_extension_class_property_group(const GDNativeExt } void NativeExtension::_register_extension_class_property_subgroup(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name, const char *p_subgroup_name, const char *p_prefix) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class property subgroup '" + String(p_subgroup_name) + "' for unexisting class '" + class_name + "'."); @@ -224,7 +224,7 @@ void NativeExtension::_register_extension_class_property_subgroup(const GDNative } void NativeExtension::_register_extension_class_signal(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name, const char *p_signal_name, const GDNativePropertyInfo *p_argument_info, GDNativeInt p_argument_count) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class signal '" + String(p_signal_name) + "' for unexisting class '" + class_name + "'."); @@ -245,7 +245,7 @@ void NativeExtension::_register_extension_class_signal(const GDNativeExtensionCl } void NativeExtension::_unregister_extension_class(const GDNativeExtensionClassLibraryPtr p_library, const char *p_class_name) { - NativeExtension *self = (NativeExtension *)p_library; + NativeExtension *self = static_cast<NativeExtension *>(p_library); StringName class_name = p_class_name; ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to unregister unexisting extension class '" + class_name + "'."); diff --git a/core/extension/native_extension_manager.cpp b/core/extension/native_extension_manager.cpp index 509405494b..5436f7d51e 100644 --- a/core/extension/native_extension_manager.cpp +++ b/core/extension/native_extension_manager.cpp @@ -112,8 +112,8 @@ void NativeExtensionManager::deinitialize_extensions(NativeExtension::Initializa } void NativeExtensionManager::load_extensions() { - FileAccessRef f = FileAccess::open(NativeExtension::get_extension_list_config_file(), FileAccess::READ); - while (f && !f->eof_reached()) { + Ref<FileAccess> f = FileAccess::open(NativeExtension::get_extension_list_config_file(), FileAccess::READ); + while (f.is_valid() && !f->eof_reached()) { String s = f->get_line().strip_edges(); if (!s.is_empty()) { LoadStatus err = load_extension(s); diff --git a/core/input/input.cpp b/core/input/input.cpp index 12c715a64c..0db20a7c82 100644 --- a/core/input/input.cpp +++ b/core/input/input.cpp @@ -772,6 +772,8 @@ void Input::action_press(const StringName &p_action, float p_strength) { action.process_frame = Engine::get_singleton()->get_process_frames(); action.pressed = true; action.strength = p_strength; + action.raw_strength = p_strength; + action.exact = true; action_state[p_action] = action; } @@ -783,6 +785,8 @@ void Input::action_release(const StringName &p_action) { action.process_frame = Engine::get_singleton()->get_process_frames(); action.pressed = false; action.strength = 0.f; + action.raw_strength = 0.f; + action.exact = true; action_state[p_action] = action; } @@ -1072,7 +1076,6 @@ void Input::_axis_event(int p_device, JoyAxis p_axis, float p_value) { Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, JoyButton p_button) { JoyEvent event; - event.type = TYPE_MAX; for (int i = 0; i < mapping.bindings.size(); i++) { const JoyBinding binding = mapping.bindings[i]; @@ -1108,7 +1111,6 @@ Input::JoyEvent Input::_get_mapped_button_event(const JoyDeviceMapping &mapping, Input::JoyEvent Input::_get_mapped_axis_event(const JoyDeviceMapping &mapping, JoyAxis p_axis, float p_value) { JoyEvent event; - event.type = TYPE_MAX; for (int i = 0; i < mapping.bindings.size(); i++) { const JoyBinding binding = mapping.bindings[i]; diff --git a/core/input/input.h b/core/input/input.h index ac688b53b8..bbdac46805 100644 --- a/core/input/input.h +++ b/core/input/input.h @@ -157,9 +157,9 @@ private: }; struct JoyEvent { - int type; - int index; // Can be either JoyAxis or JoyButton. - float value; + int type = TYPE_MAX; + int index = -1; // Can be either JoyAxis or JoyButton. + float value = 0.f; }; struct JoyBinding { diff --git a/core/input/input_event.cpp b/core/input/input_event.cpp index b8ab722b12..2d4c203748 100644 --- a/core/input/input_event.cpp +++ b/core/input/input_event.cpp @@ -47,30 +47,30 @@ int InputEvent::get_device() const { } bool InputEvent::is_action(const StringName &p_action, bool p_exact_match) const { - return InputMap::get_singleton()->event_is_action(Ref<InputEvent>((InputEvent *)this), p_action, p_exact_match); + return InputMap::get_singleton()->event_is_action(Ref<InputEvent>(const_cast<InputEvent *>(this)), p_action, p_exact_match); } bool InputEvent::is_action_pressed(const StringName &p_action, bool p_allow_echo, bool p_exact_match) const { bool pressed; - bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>((InputEvent *)this), p_action, p_exact_match, &pressed, nullptr, nullptr); + bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>(const_cast<InputEvent *>(this)), p_action, p_exact_match, &pressed, nullptr, nullptr); return valid && pressed && (p_allow_echo || !is_echo()); } bool InputEvent::is_action_released(const StringName &p_action, bool p_exact_match) const { bool pressed; - bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>((InputEvent *)this), p_action, p_exact_match, &pressed, nullptr, nullptr); + bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>(const_cast<InputEvent *>(this)), p_action, p_exact_match, &pressed, nullptr, nullptr); return valid && !pressed; } float InputEvent::get_action_strength(const StringName &p_action, bool p_exact_match) const { float strength; - bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>((InputEvent *)this), p_action, p_exact_match, nullptr, &strength, nullptr); + bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>(const_cast<InputEvent *>(this)), p_action, p_exact_match, nullptr, &strength, nullptr); return valid ? strength : 0.0f; } float InputEvent::get_action_raw_strength(const StringName &p_action, bool p_exact_match) const { float raw_strength; - bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>((InputEvent *)this), p_action, p_exact_match, nullptr, nullptr, &raw_strength); + bool valid = InputMap::get_singleton()->event_get_action_status(Ref<InputEvent>(const_cast<InputEvent *>(this)), p_action, p_exact_match, nullptr, nullptr, &raw_strength); return valid ? raw_strength : 0.0f; } @@ -83,7 +83,7 @@ bool InputEvent::is_echo() const { } Ref<InputEvent> InputEvent::xformed_by(const Transform2D &p_xform, const Vector2 &p_local_ofs) const { - return Ref<InputEvent>((InputEvent *)this); + return Ref<InputEvent>(const_cast<InputEvent *>(this)); } bool InputEvent::action_match(const Ref<InputEvent> &p_event, bool p_exact_match, float p_deadzone, bool *r_pressed, float *r_strength, float *r_raw_strength) const { diff --git a/core/io/config_file.cpp b/core/io/config_file.cpp index c942b417e4..bc24cac955 100644 --- a/core/io/config_file.cpp +++ b/core/io/config_file.cpp @@ -129,12 +129,9 @@ void ConfigFile::erase_section_key(const String &p_section, const String &p_key) Error ConfigFile::save(const String &p_path) { Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { - if (file) { - memdelete(file); - } return err; } @@ -143,17 +140,16 @@ Error ConfigFile::save(const String &p_path) { Error ConfigFile::save_encrypted(const String &p_path, const Vector<uint8_t> &p_key) { Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { return err; } - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + Ref<FileAccessEncrypted> fae; + fae.instantiate(); err = fae->open_and_parse(f, p_key, FileAccessEncrypted::MODE_WRITE_AES256); if (err) { - memdelete(fae); - memdelete(f); return err; } return _internal_save(fae); @@ -161,24 +157,23 @@ Error ConfigFile::save_encrypted(const String &p_path, const Vector<uint8_t> &p_ Error ConfigFile::save_encrypted_pass(const String &p_path, const String &p_pass) { Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err); if (err) { return err; } - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + Ref<FileAccessEncrypted> fae; + fae.instantiate(); err = fae->open_and_parse_password(f, p_pass, FileAccessEncrypted::MODE_WRITE_AES256); if (err) { - memdelete(fae); - memdelete(f); return err; } return _internal_save(fae); } -Error ConfigFile::_internal_save(FileAccess *file) { +Error ConfigFile::_internal_save(Ref<FileAccess> file) { for (OrderedHashMap<String, OrderedHashMap<String, Variant>>::Element E = values.front(); E; E = E.next()) { if (E != values.front()) { file->store_string("\n"); @@ -194,16 +189,14 @@ Error ConfigFile::_internal_save(FileAccess *file) { } } - memdelete(file); - return OK; } Error ConfigFile::load(const String &p_path) { Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); - if (!f) { + if (f.is_null()) { return err; } @@ -212,17 +205,16 @@ Error ConfigFile::load(const String &p_path) { Error ConfigFile::load_encrypted(const String &p_path, const Vector<uint8_t> &p_key) { Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { return err; } - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + Ref<FileAccessEncrypted> fae; + fae.instantiate(); err = fae->open_and_parse(f, p_key, FileAccessEncrypted::MODE_READ); if (err) { - memdelete(fae); - memdelete(f); return err; } return _internal_load(p_path, fae); @@ -230,31 +222,28 @@ Error ConfigFile::load_encrypted(const String &p_path, const Vector<uint8_t> &p_ Error ConfigFile::load_encrypted_pass(const String &p_path, const String &p_pass) { Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { return err; } - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); + Ref<FileAccessEncrypted> fae; + fae.instantiate(); err = fae->open_and_parse_password(f, p_pass, FileAccessEncrypted::MODE_READ); if (err) { - memdelete(fae); - memdelete(f); return err; } return _internal_load(p_path, fae); } -Error ConfigFile::_internal_load(const String &p_path, FileAccess *f) { +Error ConfigFile::_internal_load(const String &p_path, Ref<FileAccess> f) { VariantParser::StreamFile stream; stream.f = f; Error err = _parse(p_path, &stream); - memdelete(f); - return err; } diff --git a/core/io/config_file.h b/core/io/config_file.h index 71e9080fb7..7a52b0e16a 100644 --- a/core/io/config_file.h +++ b/core/io/config_file.h @@ -43,8 +43,8 @@ class ConfigFile : public RefCounted { PackedStringArray _get_sections() const; PackedStringArray _get_section_keys(const String &p_section) const; - Error _internal_load(const String &p_path, FileAccess *f); - Error _internal_save(FileAccess *file); + Error _internal_load(const String &p_path, Ref<FileAccess> f); + Error _internal_save(Ref<FileAccess> file); Error _parse(const String &p_path, VariantParser::Stream *p_stream); diff --git a/core/io/dir_access.cpp b/core/io/dir_access.cpp index 73efdeb38e..433a7efb21 100644 --- a/core/io/dir_access.cpp +++ b/core/io/dir_access.cpp @@ -217,8 +217,8 @@ String DirAccess::fix_path(String p_path) const { DirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX] = { nullptr, nullptr, nullptr }; -DirAccess *DirAccess::create_for_path(const String &p_path) { - DirAccess *da = nullptr; +Ref<DirAccess> DirAccess::create_for_path(const String &p_path) { + Ref<DirAccess> da; if (p_path.begins_with("res://")) { da = create(ACCESS_RESOURCES); } else if (p_path.begins_with("user://")) { @@ -230,25 +230,23 @@ DirAccess *DirAccess::create_for_path(const String &p_path) { return da; } -DirAccess *DirAccess::open(const String &p_path, Error *r_error) { - DirAccess *da = create_for_path(p_path); - - ERR_FAIL_COND_V_MSG(!da, nullptr, "Cannot create DirAccess for path '" + p_path + "'."); +Ref<DirAccess> DirAccess::open(const String &p_path, Error *r_error) { + Ref<DirAccess> da = create_for_path(p_path); + ERR_FAIL_COND_V_MSG(da.is_null(), nullptr, "Cannot create DirAccess for path '" + p_path + "'."); Error err = da->change_dir(p_path); if (r_error) { *r_error = err; } if (err != OK) { - memdelete(da); return nullptr; } return da; } -DirAccess *DirAccess::create(AccessType p_access) { - DirAccess *da = create_func[p_access] ? create_func[p_access]() : nullptr; - if (da) { +Ref<DirAccess> DirAccess::create(AccessType p_access) { + Ref<DirAccess> da = create_func[p_access] ? create_func[p_access]() : nullptr; + if (da.is_valid()) { da->_access_type = p_access; // for ACCESS_RESOURCES and ACCESS_FILESYSTEM, current_dir already defaults to where game was started @@ -264,54 +262,45 @@ DirAccess *DirAccess::create(AccessType p_access) { } String DirAccess::get_full_path(const String &p_path, AccessType p_access) { - DirAccess *d = DirAccess::create(p_access); - if (!d) { + Ref<DirAccess> d = DirAccess::create(p_access); + if (d.is_null()) { return p_path; } d->change_dir(p_path); String full = d->get_current_dir(); - memdelete(d); return full; } Error DirAccess::copy(String p_from, String p_to, int p_chmod_flags) { //printf("copy %s -> %s\n",p_from.ascii().get_data(),p_to.ascii().get_data()); Error err; - FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ, &err); - - if (err) { - ERR_PRINT("Failed to open " + p_from); - return err; - } - - FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE, &err); - if (err) { - fsrc->close(); - memdelete(fsrc); - ERR_PRINT("Failed to open " + p_to); - return err; - } + { + Ref<FileAccess> fsrc = FileAccess::open(p_from, FileAccess::READ, &err); + ERR_FAIL_COND_V_MSG(err != OK, err, "Failed to open " + p_from); + + Ref<FileAccess> fdst = FileAccess::open(p_to, FileAccess::WRITE, &err); + ERR_FAIL_COND_V_MSG(err != OK, err, "Failed to open " + p_to); + + fsrc->seek_end(0); + int size = fsrc->get_position(); + fsrc->seek(0); + err = OK; + while (size--) { + if (fsrc->get_error() != OK) { + err = fsrc->get_error(); + break; + } + if (fdst->get_error() != OK) { + err = fdst->get_error(); + break; + } - fsrc->seek_end(0); - int size = fsrc->get_position(); - fsrc->seek(0); - err = OK; - while (size--) { - if (fsrc->get_error() != OK) { - err = fsrc->get_error(); - break; - } - if (fdst->get_error() != OK) { - err = fdst->get_error(); - break; + fdst->store_8(fsrc->get_8()); } - - fdst->store_8(fsrc->get_8()); } if (err == OK && p_chmod_flags != -1) { - fdst->close(); err = FileAccess::set_unix_permissions(p_to, p_chmod_flags); // If running on a platform with no chmod support (i.e., Windows), don't fail if (err == ERR_UNAVAILABLE) { @@ -319,9 +308,6 @@ Error DirAccess::copy(String p_from, String p_to, int p_chmod_flags) { } } - memdelete(fsrc); - memdelete(fdst); - return err; } @@ -343,7 +329,7 @@ public: } }; -Error DirAccess::_copy_dir(DirAccess *p_target_da, String p_to, int p_chmod_flags, bool p_copy_links) { +Error DirAccess::_copy_dir(Ref<DirAccess> &p_target_da, String p_to, int p_chmod_flags, bool p_copy_links) { List<String> dirs; String curdir = get_current_dir(); @@ -399,14 +385,11 @@ Error DirAccess::_copy_dir(DirAccess *p_target_da, String p_to, int p_chmod_flag Error DirAccess::copy_dir(String p_from, String p_to, int p_chmod_flags, bool p_copy_links) { ERR_FAIL_COND_V_MSG(!dir_exists(p_from), ERR_FILE_NOT_FOUND, "Source directory doesn't exist."); - DirAccess *target_da = DirAccess::create_for_path(p_to); - ERR_FAIL_COND_V_MSG(!target_da, ERR_CANT_CREATE, "Cannot create DirAccess for path '" + p_to + "'."); + Ref<DirAccess> target_da = DirAccess::create_for_path(p_to); + ERR_FAIL_COND_V_MSG(target_da.is_null(), ERR_CANT_CREATE, "Cannot create DirAccess for path '" + p_to + "'."); if (!target_da->dir_exists(p_to)) { Error err = target_da->make_dir_recursive(p_to); - if (err) { - memdelete(target_da); - } ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot create directory '" + p_to + "'."); } @@ -416,12 +399,11 @@ Error DirAccess::copy_dir(String p_from, String p_to, int p_chmod_flags, bool p_ DirChanger dir_changer(this, p_from); Error err = _copy_dir(target_da, p_to, p_chmod_flags, p_copy_links); - memdelete(target_da); return err; } bool DirAccess::exists(String p_dir) { - DirAccessRef da = DirAccess::create_for_path(p_dir); + Ref<DirAccess> da = DirAccess::create_for_path(p_dir); return da->change_dir(p_dir) == OK; } diff --git a/core/io/dir_access.h b/core/io/dir_access.h index b97d097842..0125f011b5 100644 --- a/core/io/dir_access.h +++ b/core/io/dir_access.h @@ -31,11 +31,12 @@ #ifndef DIR_ACCESS_H #define DIR_ACCESS_H +#include "core/object/ref_counted.h" #include "core/string/ustring.h" #include "core/typedefs.h" //@ TODO, excellent candidate for THREAD_SAFE MACRO, should go through all these and add THREAD_SAFE where it applies -class DirAccess { +class DirAccess : public RefCounted { public: enum AccessType { ACCESS_RESOURCES, @@ -44,13 +45,13 @@ public: ACCESS_MAX }; - typedef DirAccess *(*CreateFunc)(); + typedef Ref<DirAccess> (*CreateFunc)(); private: AccessType _access_type = ACCESS_FILESYSTEM; static CreateFunc create_func[ACCESS_MAX]; ///< set this to instance a filesystem object - Error _copy_dir(DirAccess *p_target_da, String p_to, int p_chmod_flags, bool p_copy_links); + Error _copy_dir(Ref<DirAccess> &p_target_da, String p_to, int p_chmod_flags, bool p_copy_links); protected: String _get_root_path() const; @@ -59,7 +60,7 @@ protected: String fix_path(String p_path) const; template <class T> - static DirAccess *_create_builtin() { + static Ref<DirAccess> _create_builtin() { return memnew(T); } @@ -77,7 +78,7 @@ public: virtual bool drives_are_shortcuts(); virtual Error change_dir(String p_dir) = 0; ///< can be relative or absolute, return false on success - virtual String get_current_dir(bool p_include_drive = true) = 0; ///< return current dir location + virtual String get_current_dir(bool p_include_drive = true) const = 0; ///< return current dir location virtual Error make_dir(String p_dir) = 0; virtual Error make_dir_recursive(String p_dir); virtual Error erase_contents_recursive(); //super dangerous, use with care! @@ -101,51 +102,29 @@ public: // Meant for editor code when we want to quickly remove a file without custom // handling (e.g. removing a cache file). static void remove_file_or_error(String p_path) { - DirAccess *da = create(ACCESS_FILESYSTEM); + Ref<DirAccess> da = create(ACCESS_FILESYSTEM); if (da->file_exists(p_path)) { if (da->remove(p_path) != OK) { ERR_FAIL_MSG("Cannot remove file or directory: " + p_path); } } - memdelete(da); } virtual String get_filesystem_type() const = 0; static String get_full_path(const String &p_path, AccessType p_access); - static DirAccess *create_for_path(const String &p_path); + static Ref<DirAccess> create_for_path(const String &p_path); - static DirAccess *create(AccessType p_access); + static Ref<DirAccess> create(AccessType p_access); template <class T> static void make_default(AccessType p_access) { create_func[p_access] = _create_builtin<T>; } - static DirAccess *open(const String &p_path, Error *r_error = nullptr); + static Ref<DirAccess> open(const String &p_path, Error *r_error = nullptr); DirAccess() {} virtual ~DirAccess() {} }; -struct DirAccessRef { - _FORCE_INLINE_ DirAccess *operator->() { - return f; - } - - operator bool() const { return f != nullptr; } - - DirAccess *f = nullptr; - - DirAccessRef(DirAccess *fa) { f = fa; } - DirAccessRef(DirAccessRef &&other) { - f = other.f; - other.f = nullptr; - } - ~DirAccessRef() { - if (f) { - memdelete(f); - } - } -}; - #endif // DIR_ACCESS_H diff --git a/core/io/file_access.cpp b/core/io/file_access.cpp index 86836454c5..7d8da1b11c 100644 --- a/core/io/file_access.cpp +++ b/core/io/file_access.cpp @@ -42,10 +42,10 @@ FileAccess::FileCloseFailNotify FileAccess::close_fail_notify = nullptr; bool FileAccess::backup_save = false; -FileAccess *FileAccess::create(AccessType p_access) { +Ref<FileAccess> FileAccess::create(AccessType p_access) { ERR_FAIL_INDEX_V(p_access, ACCESS_MAX, nullptr); - FileAccess *ret = create_func[p_access](); + Ref<FileAccess> ret = create_func[p_access](); ret->_set_access_type(p_access); return ret; } @@ -55,11 +55,10 @@ bool FileAccess::exists(const String &p_name) { return true; } - FileAccess *f = open(p_name, READ); - if (!f) { + Ref<FileAccess> f = open(p_name, READ); + if (f.is_null()) { return false; } - memdelete(f); return true; } @@ -67,8 +66,8 @@ void FileAccess::_set_access_type(AccessType p_access) { _access_type = p_access; } -FileAccess *FileAccess::create_for_path(const String &p_path) { - FileAccess *ret = nullptr; +Ref<FileAccess> FileAccess::create_for_path(const String &p_path) { + Ref<FileAccess> ret; if (p_path.begins_with("res://")) { ret = create(ACCESS_RESOURCES); } else if (p_path.begins_with("user://")) { @@ -85,13 +84,13 @@ Error FileAccess::reopen(const String &p_path, int p_mode_flags) { return _open(p_path, p_mode_flags); } -FileAccess *FileAccess::open(const String &p_path, int p_mode_flags, Error *r_error) { +Ref<FileAccess> FileAccess::open(const String &p_path, int p_mode_flags, Error *r_error) { //try packed data first - FileAccess *ret = nullptr; + Ref<FileAccess> ret; if (!(p_mode_flags & WRITE) && PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled()) { ret = PackedData::get_singleton()->try_open_path(p_path); - if (ret) { + if (ret.is_valid()) { if (r_error) { *r_error = OK; } @@ -106,8 +105,7 @@ FileAccess *FileAccess::open(const String &p_path, int p_mode_flags, Error *r_er *r_error = err; } if (err != OK) { - memdelete(ret); - ret = nullptr; + ret.unref(); } return ret; @@ -463,11 +461,10 @@ uint64_t FileAccess::get_modified_time(const String &p_file) { return 0; } - FileAccess *fa = create_for_path(p_file); - ERR_FAIL_COND_V_MSG(!fa, 0, "Cannot create FileAccess for path '" + p_file + "'."); + Ref<FileAccess> fa = create_for_path(p_file); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "Cannot create FileAccess for path '" + p_file + "'."); uint64_t mt = fa->_get_modified_time(p_file); - memdelete(fa); return mt; } @@ -476,11 +473,10 @@ uint32_t FileAccess::get_unix_permissions(const String &p_file) { return 0; } - FileAccess *fa = create_for_path(p_file); - ERR_FAIL_COND_V_MSG(!fa, 0, "Cannot create FileAccess for path '" + p_file + "'."); + Ref<FileAccess> fa = create_for_path(p_file); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "Cannot create FileAccess for path '" + p_file + "'."); uint32_t mt = fa->_get_unix_permissions(p_file); - memdelete(fa); return mt; } @@ -489,11 +485,10 @@ Error FileAccess::set_unix_permissions(const String &p_file, uint32_t p_permissi return ERR_UNAVAILABLE; } - FileAccess *fa = create_for_path(p_file); - ERR_FAIL_COND_V_MSG(!fa, ERR_CANT_CREATE, "Cannot create FileAccess for path '" + p_file + "'."); + Ref<FileAccess> fa = create_for_path(p_file); + ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create FileAccess for path '" + p_file + "'."); Error err = fa->_set_unix_permissions(p_file, p_permissions); - memdelete(fa); return err; } @@ -559,8 +554,8 @@ void FileAccess::store_buffer(const uint8_t *p_src, uint64_t p_length) { } Vector<uint8_t> FileAccess::get_file_as_array(const String &p_path, Error *r_error) { - FileAccess *f = FileAccess::open(p_path, READ, r_error); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, READ, r_error); + if (f.is_null()) { if (r_error) { // if error requested, do not throw error return Vector<uint8_t>(); } @@ -569,7 +564,6 @@ Vector<uint8_t> FileAccess::get_file_as_array(const String &p_path, Error *r_err Vector<uint8_t> data; data.resize(f->get_length()); f->get_buffer(data.ptrw(), data.size()); - memdelete(f); return data; } @@ -592,8 +586,8 @@ String FileAccess::get_file_as_string(const String &p_path, Error *r_error) { } String FileAccess::get_md5(const String &p_file) { - FileAccess *f = FileAccess::open(p_file, READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_file, READ); + if (f.is_null()) { return String(); } @@ -615,8 +609,6 @@ String FileAccess::get_md5(const String &p_file) { unsigned char hash[16]; ctx.finish(hash); - memdelete(f); - return String::md5(hash); } @@ -625,8 +617,8 @@ String FileAccess::get_multiple_md5(const Vector<String> &p_file) { ctx.start(); for (int i = 0; i < p_file.size(); i++) { - FileAccess *f = FileAccess::open(p_file[i], READ); - ERR_CONTINUE(!f); + Ref<FileAccess> f = FileAccess::open(p_file[i], READ); + ERR_CONTINUE(f.is_null()); unsigned char step[32768]; @@ -639,7 +631,6 @@ String FileAccess::get_multiple_md5(const Vector<String> &p_file) { break; } } - memdelete(f); } unsigned char hash[16]; @@ -649,8 +640,8 @@ String FileAccess::get_multiple_md5(const Vector<String> &p_file) { } String FileAccess::get_sha256(const String &p_file) { - FileAccess *f = FileAccess::open(p_file, READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_file, READ); + if (f.is_null()) { return String(); } @@ -672,6 +663,5 @@ String FileAccess::get_sha256(const String &p_file) { unsigned char hash[32]; ctx.finish(hash); - memdelete(f); return String::hex_encode_buffer(hash, 32); } diff --git a/core/io/file_access.h b/core/io/file_access.h index a6cb5d9fc6..e2c11142d7 100644 --- a/core/io/file_access.h +++ b/core/io/file_access.h @@ -32,6 +32,7 @@ #define FILE_ACCESS_H #include "core/math/math_defs.h" +#include "core/object/ref_counted.h" #include "core/os/memory.h" #include "core/string/ustring.h" #include "core/typedefs.h" @@ -40,7 +41,7 @@ * Multi-Platform abstraction for accessing to files. */ -class FileAccess { +class FileAccess : public RefCounted { public: enum AccessType { ACCESS_RESOURCES, @@ -51,7 +52,7 @@ public: typedef void (*FileCloseFailNotify)(const String &); - typedef FileAccess *(*CreateFunc)(); + typedef Ref<FileAccess> (*CreateFunc)(); bool big_endian = false; bool real_is_double = false; @@ -71,7 +72,7 @@ private: AccessType _access_type = ACCESS_FILESYSTEM; static CreateFunc create_func[ACCESS_MAX]; /** default file access creation function for a platform */ template <class T> - static FileAccess *_create_builtin() { + static Ref<FileAccess> _create_builtin() { return memnew(T); } @@ -87,7 +88,6 @@ public: WRITE_READ = 7, }; - virtual void close() = 0; ///< close a file virtual bool is_open() const = 0; ///< true when file is open virtual String get_path() const { return ""; } /// returns the path for the current open file @@ -148,9 +148,9 @@ public: virtual Error reopen(const String &p_path, int p_mode_flags); ///< does not change the AccessType - static FileAccess *create(AccessType p_access); /// Create a file access (for the current platform) this is the only portable way of accessing files. - static FileAccess *create_for_path(const String &p_path); - static FileAccess *open(const String &p_path, int p_mode_flags, Error *r_error = nullptr); /// Create a file access (for the current platform) this is the only portable way of accessing files. + static Ref<FileAccess> create(AccessType p_access); /// Create a file access (for the current platform) this is the only portable way of accessing files. + static Ref<FileAccess> create_for_path(const String &p_path); + static Ref<FileAccess> open(const String &p_path, int p_mode_flags, Error *r_error = nullptr); /// Create a file access (for the current platform) this is the only portable way of accessing files. static CreateFunc get_create_func(AccessType p_access); static bool exists(const String &p_name); ///< return true if a file exists static uint64_t get_modified_time(const String &p_file); @@ -176,27 +176,4 @@ public: virtual ~FileAccess() {} }; -struct FileAccessRef { - _FORCE_INLINE_ FileAccess *operator->() { - return f; - } - - operator bool() const { return f != nullptr; } - - FileAccess *f; - - operator FileAccess *() { return f; } - - FileAccessRef(FileAccess *fa) { f = fa; } - FileAccessRef(FileAccessRef &&other) { - f = other.f; - other.f = nullptr; - } - ~FileAccessRef() { - if (f) { - memdelete(f); - } - } -}; - #endif // FILE_ACCESS_H diff --git a/core/io/file_access_compressed.cpp b/core/io/file_access_compressed.cpp index 85faf04315..1d0a718166 100644 --- a/core/io/file_access_compressed.cpp +++ b/core/io/file_access_compressed.cpp @@ -58,12 +58,12 @@ void FileAccessCompressed::configure(const String &p_magic, Compression::Mode p_ } \ } -Error FileAccessCompressed::open_after_magic(FileAccess *p_base) { +Error FileAccessCompressed::open_after_magic(Ref<FileAccess> p_base) { f = p_base; cmode = (Compression::Mode)f->get_32(); block_size = f->get_32(); if (block_size == 0) { - f = nullptr; // Let the caller to handle the FileAccess object if failed to open as compressed file. + f.unref(); ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Can't open compressed file '" + p_base->get_path() + "' with block size 0, it is corrupted."); } read_total = f->get_32(); @@ -97,17 +97,13 @@ Error FileAccessCompressed::open_after_magic(FileAccess *p_base) { Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_COND_V(p_mode_flags == READ_WRITE, ERR_UNAVAILABLE); - - if (f) { - close(); - } + _close(); Error err; f = FileAccess::open(p_path, p_mode_flags, &err); if (err != OK) { //not openable - - f = nullptr; + f.unref(); return err; } @@ -127,8 +123,7 @@ Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) { rmagic[4] = 0; err = ERR_FILE_UNRECOGNIZED; if (magic != rmagic || (err = open_after_magic(f)) != OK) { - memdelete(f); - f = nullptr; + f.unref(); return err; } } @@ -136,8 +131,8 @@ Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) { return OK; } -void FileAccessCompressed::close() { - if (!f) { +void FileAccessCompressed::_close() { + if (f.is_null()) { return; } @@ -182,17 +177,15 @@ void FileAccessCompressed::close() { buffer.clear(); read_blocks.clear(); } - - memdelete(f); - f = nullptr; + f.unref(); } bool FileAccessCompressed::is_open() const { - return f != nullptr; + return f.is_valid(); } void FileAccessCompressed::seek(uint64_t p_position) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use."); if (writing) { ERR_FAIL_COND(p_position > write_max); @@ -222,7 +215,7 @@ void FileAccessCompressed::seek(uint64_t p_position) { } void FileAccessCompressed::seek_end(int64_t p_position) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use."); if (writing) { seek(write_max + p_position); } else { @@ -231,7 +224,7 @@ void FileAccessCompressed::seek_end(int64_t p_position) { } uint64_t FileAccessCompressed::get_position() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use."); if (writing) { return write_pos; } else { @@ -240,7 +233,7 @@ uint64_t FileAccessCompressed::get_position() const { } uint64_t FileAccessCompressed::get_length() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use."); if (writing) { return write_max; } else { @@ -249,7 +242,7 @@ uint64_t FileAccessCompressed::get_length() const { } bool FileAccessCompressed::eof_reached() const { - ERR_FAIL_COND_V_MSG(!f, false, "File must be opened before use."); + ERR_FAIL_COND_V_MSG(f.is_null(), false, "File must be opened before use."); if (writing) { return false; } else { @@ -258,7 +251,7 @@ bool FileAccessCompressed::eof_reached() const { } uint8_t FileAccessCompressed::get_8() const { - ERR_FAIL_COND_V_MSG(!f, 0, "File must be opened before use."); + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use."); ERR_FAIL_COND_V_MSG(writing, 0, "File has not been opened in read mode."); if (at_end) { @@ -291,7 +284,7 @@ uint8_t FileAccessCompressed::get_8() const { uint64_t FileAccessCompressed::get_buffer(uint8_t *p_dst, uint64_t p_length) const { ERR_FAIL_COND_V(!p_dst && p_length > 0, -1); - ERR_FAIL_COND_V_MSG(!f, -1, "File must be opened before use."); + ERR_FAIL_COND_V_MSG(f.is_null(), -1, "File must be opened before use."); ERR_FAIL_COND_V_MSG(writing, -1, "File has not been opened in read mode."); if (at_end) { @@ -332,14 +325,14 @@ Error FileAccessCompressed::get_error() const { } void FileAccessCompressed::flush() { - ERR_FAIL_COND_MSG(!f, "File must be opened before use."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use."); ERR_FAIL_COND_MSG(!writing, "File has not been opened in write mode."); // compressed files keep data in memory till close() } void FileAccessCompressed::store_8(uint8_t p_dest) { - ERR_FAIL_COND_MSG(!f, "File must be opened before use."); + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use."); ERR_FAIL_COND_MSG(!writing, "File has not been opened in write mode."); WRITE_FIT(1); @@ -347,16 +340,15 @@ void FileAccessCompressed::store_8(uint8_t p_dest) { } bool FileAccessCompressed::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); - if (!fa) { + Ref<FileAccess> fa = FileAccess::open(p_name, FileAccess::READ); + if (fa.is_null()) { return false; } - memdelete(fa); return true; } uint64_t FileAccessCompressed::_get_modified_time(const String &p_file) { - if (f) { + if (f.is_valid()) { return f->get_modified_time(p_file); } else { return 0; @@ -364,21 +356,19 @@ uint64_t FileAccessCompressed::_get_modified_time(const String &p_file) { } uint32_t FileAccessCompressed::_get_unix_permissions(const String &p_file) { - if (f) { + if (f.is_valid()) { return f->_get_unix_permissions(p_file); } return 0; } Error FileAccessCompressed::_set_unix_permissions(const String &p_file, uint32_t p_permissions) { - if (f) { + if (f.is_valid()) { return f->_set_unix_permissions(p_file, p_permissions); } return FAILED; } FileAccessCompressed::~FileAccessCompressed() { - if (f) { - close(); - } + _close(); } diff --git a/core/io/file_access_compressed.h b/core/io/file_access_compressed.h index 97ef3fbdeb..b8382e61d9 100644 --- a/core/io/file_access_compressed.h +++ b/core/io/file_access_compressed.h @@ -61,15 +61,16 @@ class FileAccessCompressed : public FileAccess { String magic = "GCMP"; mutable Vector<uint8_t> buffer; - FileAccess *f = nullptr; + Ref<FileAccess> f; + + void _close(); public: void configure(const String &p_magic, Compression::Mode p_mode = Compression::MODE_ZSTD, uint32_t p_block_size = 4096); - Error open_after_magic(FileAccess *p_base); + Error open_after_magic(Ref<FileAccess> p_base); virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(uint64_t p_position); ///< seek to a given position diff --git a/core/io/file_access_encrypted.cpp b/core/io/file_access_encrypted.cpp index 8ee19d3d06..d1b014a0be 100644 --- a/core/io/file_access_encrypted.cpp +++ b/core/io/file_access_encrypted.cpp @@ -36,7 +36,7 @@ #include <stdio.h> -Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode, bool p_with_magic) { +Error FileAccessEncrypted::open_and_parse(Ref<FileAccess> p_base, const Vector<uint8_t> &p_key, Mode p_mode, bool p_with_magic) { ERR_FAIL_COND_V_MSG(file != nullptr, ERR_ALREADY_IN_USE, "Can't open file while another file from path '" + file->get_path_absolute() + "' is open."); ERR_FAIL_COND_V(p_key.size() != 32, ERR_INVALID_PARAMETER); @@ -99,7 +99,7 @@ Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector<uint8 return OK; } -Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode) { +Error FileAccessEncrypted::open_and_parse_password(Ref<FileAccess> p_base, const String &p_key, Mode p_mode) { String cs = p_key.md5_text(); ERR_FAIL_COND_V(cs.length() != 32, ERR_INVALID_PARAMETER); Vector<uint8_t> key; @@ -115,30 +115,11 @@ Error FileAccessEncrypted::_open(const String &p_path, int p_mode_flags) { return OK; } -void FileAccessEncrypted::close() { - if (!file) { +void FileAccessEncrypted::_close() { + if (file.is_null()) { return; } - _release(); - - file->close(); - memdelete(file); - - file = nullptr; -} - -void FileAccessEncrypted::release() { - if (!file) { - return; - } - - _release(); - - file = nullptr; -} - -void FileAccessEncrypted::_release() { if (writing) { Vector<uint8_t> compressed; uint64_t len = data.size(); @@ -176,6 +157,8 @@ void FileAccessEncrypted::_release() { file->store_buffer(compressed.ptr(), compressed.size()); data.clear(); } + + file.unref(); } bool FileAccessEncrypted::is_open() const { @@ -183,7 +166,7 @@ bool FileAccessEncrypted::is_open() const { } String FileAccessEncrypted::get_path() const { - if (file) { + if (file.is_valid()) { return file->get_path(); } else { return ""; @@ -191,7 +174,7 @@ String FileAccessEncrypted::get_path() const { } String FileAccessEncrypted::get_path_absolute() const { - if (file) { + if (file.is_valid()) { return file->get_path_absolute(); } else { return ""; @@ -291,11 +274,10 @@ void FileAccessEncrypted::store_8(uint8_t p_dest) { } bool FileAccessEncrypted::file_exists(const String &p_name) { - FileAccess *fa = FileAccess::open(p_name, FileAccess::READ); - if (!fa) { + Ref<FileAccess> fa = FileAccess::open(p_name, FileAccess::READ); + if (fa.is_null()) { return false; } - memdelete(fa); return true; } @@ -313,7 +295,5 @@ Error FileAccessEncrypted::_set_unix_permissions(const String &p_file, uint32_t } FileAccessEncrypted::~FileAccessEncrypted() { - if (file) { - close(); - } + _close(); } diff --git a/core/io/file_access_encrypted.h b/core/io/file_access_encrypted.h index be5904c894..0d1ee6a4d8 100644 --- a/core/io/file_access_encrypted.h +++ b/core/io/file_access_encrypted.h @@ -46,7 +46,7 @@ public: private: Vector<uint8_t> key; bool writing = false; - FileAccess *file = nullptr; + Ref<FileAccess> file; uint64_t base = 0; uint64_t length = 0; Vector<uint8_t> data; @@ -54,15 +54,13 @@ private: mutable bool eofed = false; bool use_magic = true; - void _release(); + void _close(); public: - Error open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode, bool p_with_magic = true); - Error open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode); + Error open_and_parse(Ref<FileAccess> p_base, const Vector<uint8_t> &p_key, Mode p_mode, bool p_with_magic = true); + Error open_and_parse_password(Ref<FileAccess> p_base, const String &p_key, Mode p_mode); virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file - virtual void release(); ///< finish and keep base file open virtual bool is_open() const; ///< true when file is open virtual String get_path() const; /// returns the path for the current open file diff --git a/core/io/file_access_memory.cpp b/core/io/file_access_memory.cpp index 4aca26b007..943dc72307 100644 --- a/core/io/file_access_memory.cpp +++ b/core/io/file_access_memory.cpp @@ -60,7 +60,7 @@ void FileAccessMemory::cleanup() { memdelete(files); } -FileAccess *FileAccessMemory::create() { +Ref<FileAccess> FileAccessMemory::create() { return memnew(FileAccessMemory); } @@ -94,10 +94,6 @@ Error FileAccessMemory::_open(const String &p_path, int p_mode_flags) { return OK; } -void FileAccessMemory::close() { - data = nullptr; -} - bool FileAccessMemory::is_open() const { return data != nullptr; } diff --git a/core/io/file_access_memory.h b/core/io/file_access_memory.h index 50b23e1f32..868b8ed481 100644 --- a/core/io/file_access_memory.h +++ b/core/io/file_access_memory.h @@ -38,7 +38,7 @@ class FileAccessMemory : public FileAccess { uint64_t length = 0; mutable uint64_t pos = 0; - static FileAccess *create(); + static Ref<FileAccess> create(); public: static void register_file(String p_name, Vector<uint8_t> p_data); @@ -46,7 +46,6 @@ public: virtual Error open_custom(const uint8_t *p_data, uint64_t p_len); ///< open a file virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(uint64_t p_position); ///< seek to a given position diff --git a/core/io/file_access_network.cpp b/core/io/file_access_network.cpp index cb38ac0928..1365b4b593 100644 --- a/core/io/file_access_network.cpp +++ b/core/io/file_access_network.cpp @@ -165,7 +165,7 @@ void FileAccessNetworkClient::_thread_func() { } void FileAccessNetworkClient::_thread_func(void *s) { - FileAccessNetworkClient *self = (FileAccessNetworkClient *)s; + FileAccessNetworkClient *self = static_cast<FileAccessNetworkClient *>(s); self->_thread_func(); } @@ -254,9 +254,8 @@ void FileAccessNetwork::_respond(uint64_t p_len, Error p_status) { Error FileAccessNetwork::_open(const String &p_path, int p_mode_flags) { ERR_FAIL_COND_V(p_mode_flags != READ, ERR_UNAVAILABLE); - if (opened) { - close(); - } + _close(); + FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; DEBUG_PRINT("open: " + p_path); @@ -287,7 +286,7 @@ Error FileAccessNetwork::_open(const String &p_path, int p_mode_flags) { return response; } -void FileAccessNetwork::close() { +void FileAccessNetwork::_close() { if (!opened) { return; } @@ -483,7 +482,7 @@ FileAccessNetwork::FileAccessNetwork() { } FileAccessNetwork::~FileAccessNetwork() { - close(); + _close(); FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton; nc->lock_mutex(); diff --git a/core/io/file_access_network.h b/core/io/file_access_network.h index 6cae49b540..6afbf6adf5 100644 --- a/core/io/file_access_network.h +++ b/core/io/file_access_network.h @@ -113,6 +113,7 @@ class FileAccessNetwork : public FileAccess { void _queue_page(int32_t p_page) const; void _respond(uint64_t p_len, Error p_status); void _set_block(uint64_t p_offset, const Vector<uint8_t> &p_block); + void _close(); public: enum Command { @@ -131,7 +132,6 @@ public: }; virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(uint64_t p_position); ///< seek to a given position diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp index 7dbea96c3d..c6e14ffee7 100644 --- a/core/io/file_access_pack.cpp +++ b/core/io/file_access_pack.cpp @@ -126,8 +126,8 @@ PackedData::~PackedData() { ////////////////////////////////////////////////////////////////// bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { return false; } @@ -137,19 +137,13 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, if (magic != PACK_HEADER_MAGIC) { // loading with offset feature not supported for self contained exe files - if (p_offset != 0) { - f->close(); - memdelete(f); - ERR_FAIL_V_MSG(false, "Loading self-contained executable with offset not supported."); - } + ERR_FAIL_COND_V_MSG(p_offset != 0, false, "Loading self-contained executable with offset not supported."); //maybe at the end.... self contained exe f->seek_end(); f->seek(f->get_position() - 4); magic = f->get_32(); if (magic != PACK_HEADER_MAGIC) { - f->close(); - memdelete(f); return false; } f->seek(f->get_position() - 12); @@ -159,8 +153,6 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, magic = f->get_32(); if (magic != PACK_HEADER_MAGIC) { - f->close(); - memdelete(f); return false; } } @@ -170,16 +162,8 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, uint32_t ver_minor = f->get_32(); f->get_32(); // patch number, not used for validation. - if (version != PACK_FORMAT_VERSION) { - f->close(); - memdelete(f); - ERR_FAIL_V_MSG(false, "Pack version unsupported: " + itos(version) + "."); - } - if (ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR)) { - f->close(); - memdelete(f); - ERR_FAIL_V_MSG(false, "Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "."); - } + ERR_FAIL_COND_V_MSG(version != PACK_FORMAT_VERSION, false, "Pack version unsupported: " + itos(version) + "."); + ERR_FAIL_COND_V_MSG(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), false, "Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "."); uint32_t pack_flags = f->get_32(); uint64_t file_base = f->get_64(); @@ -194,12 +178,9 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, int file_count = f->get_32(); if (enc_directory) { - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); - if (!fae) { - f->close(); - memdelete(f); - ERR_FAIL_V_MSG(false, "Can't open encrypted pack directory."); - } + Ref<FileAccessEncrypted> fae; + fae.instantiate(); + ERR_FAIL_COND_V_MSG(fae.is_null(), false, "Can't open encrypted pack directory."); Vector<uint8_t> key; key.resize(32); @@ -208,12 +189,7 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, } Error err = fae->open_and_parse(f, key, FileAccessEncrypted::MODE_READ, false); - if (err) { - f->close(); - memdelete(f); - memdelete(fae); - ERR_FAIL_V_MSG(false, "Can't open encrypted pack directory."); - } + ERR_FAIL_COND_V_MSG(err, false, "Can't open encrypted pack directory."); f = fae; } @@ -236,12 +212,10 @@ bool PackedSourcePCK::try_open_pack(const String &p_path, bool p_replace_files, PackedData::get_singleton()->add_path(p_path, path, ofs + p_offset, size, md5, this, p_replace_files, (flags & PACK_FILE_ENCRYPTED)); } - f->close(); - memdelete(f); return true; } -FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) { +Ref<FileAccess> PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) { return memnew(FileAccessPack(p_path, *p_file)); } @@ -252,15 +226,17 @@ Error FileAccessPack::_open(const String &p_path, int p_mode_flags) { return ERR_UNAVAILABLE; } -void FileAccessPack::close() { - f->close(); -} - bool FileAccessPack::is_open() const { - return f->is_open(); + if (f.is_valid()) { + return f->is_open(); + } else { + return false; + } } void FileAccessPack::seek(uint64_t p_position) { + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use."); + if (p_position > pf.size) { eof = true; } else { @@ -288,6 +264,7 @@ bool FileAccessPack::eof_reached() const { } uint8_t FileAccessPack::get_8() const { + ERR_FAIL_COND_V_MSG(f.is_null(), 0, "File must be opened before use."); if (pos >= pf.size) { eof = true; return 0; @@ -298,6 +275,7 @@ uint8_t FileAccessPack::get_8() const { } uint64_t FileAccessPack::get_buffer(uint8_t *p_dst, uint64_t p_length) const { + ERR_FAIL_COND_V_MSG(f.is_null(), -1, "File must be opened before use."); ERR_FAIL_COND_V(!p_dst && p_length > 0, -1); if (eof) { @@ -321,6 +299,8 @@ uint64_t FileAccessPack::get_buffer(uint8_t *p_dst, uint64_t p_length) const { } void FileAccessPack::set_big_endian(bool p_big_endian) { + ERR_FAIL_COND_MSG(f.is_null(), "File must be opened before use."); + FileAccess::set_big_endian(p_big_endian); f->set_big_endian(p_big_endian); } @@ -351,16 +331,15 @@ bool FileAccessPack::file_exists(const String &p_name) { FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) : pf(p_file), f(FileAccess::open(pf.pack, FileAccess::READ)) { - ERR_FAIL_COND_MSG(!f, "Can't open pack-referenced file '" + String(pf.pack) + "'."); + ERR_FAIL_COND_MSG(f.is_null(), "Can't open pack-referenced file '" + String(pf.pack) + "'."); f->seek(pf.offset); off = pf.offset; if (pf.encrypted) { - FileAccessEncrypted *fae = memnew(FileAccessEncrypted); - if (!fae) { - ERR_FAIL_MSG("Can't open encrypted pack-referenced file '" + String(pf.pack) + "'."); - } + Ref<FileAccessEncrypted> fae; + fae.instantiate(); + ERR_FAIL_COND_MSG(fae.is_null(), "Can't open encrypted pack-referenced file '" + String(pf.pack) + "'."); Vector<uint8_t> key; key.resize(32); @@ -369,10 +348,7 @@ FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFil } Error err = fae->open_and_parse(f, key, FileAccessEncrypted::MODE_READ, false); - if (err) { - memdelete(fae); - ERR_FAIL_MSG("Can't open encrypted pack-referenced file '" + String(pf.pack) + "'."); - } + ERR_FAIL_COND_MSG(err, "Can't open encrypted pack-referenced file '" + String(pf.pack) + "'."); f = fae; off = 0; } @@ -380,13 +356,6 @@ FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFil eof = false; } -FileAccessPack::~FileAccessPack() { - if (f) { - f->close(); - memdelete(f); - } -} - ////////////////////////////////////////////////////////////////////////////////// // DIR ACCESS ////////////////////////////////////////////////////////////////////////////////// @@ -507,7 +476,7 @@ Error DirAccessPack::change_dir(String p_dir) { } } -String DirAccessPack::get_current_dir(bool p_include_drive) { +String DirAccessPack::get_current_dir(bool p_include_drive) const { PackedData::PackedDir *pd = current; String p = current->name; diff --git a/core/io/file_access_pack.h b/core/io/file_access_pack.h index 6eee2f593d..44df2029bd 100644 --- a/core/io/file_access_pack.h +++ b/core/io/file_access_pack.h @@ -64,7 +64,7 @@ public: uint64_t offset; //if offset is ZERO, the file was ERASED uint64_t size; uint8_t md5[16]; - PackSource *src; + PackSource *src = nullptr; bool encrypted; }; @@ -103,7 +103,7 @@ private: Vector<PackSource *> sources; - PackedDir *root; + PackedDir *root = nullptr; static PackedData *singleton; bool disabled = false; @@ -120,10 +120,10 @@ public: static PackedData *get_singleton() { return singleton; } Error add_pack(const String &p_path, bool p_replace_files, uint64_t p_offset); - _FORCE_INLINE_ FileAccess *try_open_path(const String &p_path); + _FORCE_INLINE_ Ref<FileAccess> try_open_path(const String &p_path); _FORCE_INLINE_ bool has_path(const String &p_path); - _FORCE_INLINE_ DirAccess *try_open_directory(const String &p_path); + _FORCE_INLINE_ Ref<DirAccess> try_open_directory(const String &p_path); _FORCE_INLINE_ bool has_directory(const String &p_path); PackedData(); @@ -133,14 +133,14 @@ public: class PackSource { public: virtual bool try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset) = 0; - virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file) = 0; + virtual Ref<FileAccess> get_file(const String &p_path, PackedData::PackedFile *p_file) = 0; virtual ~PackSource() {} }; class PackedSourcePCK : public PackSource { public: - virtual bool try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset); - virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); + virtual bool try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset) override; + virtual Ref<FileAccess> get_file(const String &p_path, PackedData::PackedFile *p_file) override; }; class FileAccessPack : public FileAccess { @@ -150,14 +150,13 @@ class FileAccessPack : public FileAccess { mutable bool eof; uint64_t off; - FileAccess *f; + Ref<FileAccess> f; virtual Error _open(const String &p_path, int p_mode_flags); virtual uint64_t _get_modified_time(const String &p_file) { return 0; } virtual uint32_t _get_unix_permissions(const String &p_file) { return 0; } virtual Error _set_unix_permissions(const String &p_file, uint32_t p_permissions) { return FAILED; } public: - virtual void close(); virtual bool is_open() const; virtual void seek(uint64_t p_position); @@ -183,10 +182,9 @@ public: virtual bool file_exists(const String &p_name); FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file); - ~FileAccessPack(); }; -FileAccess *PackedData::try_open_path(const String &p_path) { +Ref<FileAccess> PackedData::try_open_path(const String &p_path) { PathMD5 pmd5(p_path.md5_buffer()); Map<PathMD5, PackedFile>::Element *E = files.find(pmd5); if (!E) { @@ -204,9 +202,8 @@ bool PackedData::has_path(const String &p_path) { } bool PackedData::has_directory(const String &p_path) { - DirAccess *da = try_open_directory(p_path); - if (da) { - memdelete(da); + Ref<DirAccess> da = try_open_directory(p_path); + if (da.is_valid()) { return true; } else { return false; @@ -233,7 +230,7 @@ public: virtual String get_drive(int p_drive); virtual Error change_dir(String p_dir); - virtual String get_current_dir(bool p_include_drive = true); + virtual String get_current_dir(bool p_include_drive = true) const; virtual bool file_exists(String p_file); virtual bool dir_exists(String p_dir); @@ -252,14 +249,12 @@ public: virtual String get_filesystem_type() const; DirAccessPack(); - ~DirAccessPack() {} }; -DirAccess *PackedData::try_open_directory(const String &p_path) { - DirAccess *da = memnew(DirAccessPack()); +Ref<DirAccess> PackedData::try_open_directory(const String &p_path) { + Ref<DirAccess> da = memnew(DirAccessPack()); if (da->change_dir(p_path) != OK) { - memdelete(da); - da = nullptr; + da = Ref<DirAccess>(); } return da; } diff --git a/core/io/file_access_zip.cpp b/core/io/file_access_zip.cpp index 6347862775..17f2335a8e 100644 --- a/core/io/file_access_zip.cpp +++ b/core/io/file_access_zip.cpp @@ -38,20 +38,26 @@ ZipArchive *ZipArchive::instance = nullptr; extern "C" { -static void *godot_open(void *data, const char *p_fname, int mode) { +struct ZipData { + Ref<FileAccess> f; +}; + +static void *godot_open(voidpf opaque, const char *p_fname, int mode) { if (mode & ZLIB_FILEFUNC_MODE_WRITE) { return nullptr; } - FileAccess *f = FileAccess::open(p_fname, FileAccess::READ); - ERR_FAIL_COND_V(!f, nullptr); + Ref<FileAccess> f = FileAccess::open(p_fname, FileAccess::READ); + ERR_FAIL_COND_V(f.is_null(), nullptr); - return f; + ZipData *zd = memnew(ZipData); + zd->f = f; + return zd; } -static uLong godot_read(void *data, void *fdata, void *buf, uLong size) { - FileAccess *f = (FileAccess *)fdata; - f->get_buffer((uint8_t *)buf, size); +static uLong godot_read(voidpf opaque, voidpf stream, void *buf, uLong size) { + ZipData *zd = (ZipData *)stream; + zd->f->get_buffer((uint8_t *)buf, size); return size; } @@ -60,42 +66,38 @@ static uLong godot_write(voidpf opaque, voidpf stream, const void *buf, uLong si } static long godot_tell(voidpf opaque, voidpf stream) { - FileAccess *f = (FileAccess *)stream; - return f->get_position(); + ZipData *zd = (ZipData *)stream; + return zd->f->get_position(); } static long godot_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess *f = (FileAccess *)stream; + ZipData *zd = (ZipData *)stream; uint64_t pos = offset; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_position() + offset; + pos = zd->f->get_position() + offset; break; case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_length() + offset; + pos = zd->f->get_length() + offset; break; default: break; } - f->seek(pos); + zd->f->seek(pos); return 0; } static int godot_close(voidpf opaque, voidpf stream) { - FileAccess *f = (FileAccess *)stream; - if (f) { - f->close(); - memdelete(f); - f = nullptr; - } + ZipData *zd = (ZipData *)stream; + memdelete(zd); return 0; } static int godot_testerror(voidpf opaque, voidpf stream) { - FileAccess *f = (FileAccess *)stream; - return f->get_error() != OK ? 1 : 0; + ZipData *zd = (ZipData *)stream; + return zd->f->get_error() != OK ? 1 : 0; } static voidpf godot_alloc(voidpf opaque, uInt items, uInt size) { @@ -208,7 +210,7 @@ bool ZipArchive::file_exists(String p_name) const { return files.has(p_name); } -FileAccess *ZipArchive::get_file(const String &p_path, PackedData::PackedFile *p_file) { +Ref<FileAccess> ZipArchive::get_file(const String &p_path, PackedData::PackedFile *p_file) { return memnew(FileAccessZip(p_path, *p_file)); } @@ -233,7 +235,7 @@ ZipArchive::~ZipArchive() { } Error FileAccessZip::_open(const String &p_path, int p_mode_flags) { - close(); + _close(); ERR_FAIL_COND_V(p_mode_flags & FileAccess::WRITE, FAILED); ZipArchive *arch = ZipArchive::get_singleton(); @@ -247,7 +249,7 @@ Error FileAccessZip::_open(const String &p_path, int p_mode_flags) { return OK; } -void FileAccessZip::close() { +void FileAccessZip::_close() { if (!zfile) { return; } @@ -339,7 +341,7 @@ FileAccessZip::FileAccessZip(const String &p_path, const PackedData::PackedFile } FileAccessZip::~FileAccessZip() { - close(); + _close(); } #endif // MINIZIP_ENABLED diff --git a/core/io/file_access_zip.h b/core/io/file_access_zip.h index 7cd5893101..2504aeedc4 100644 --- a/core/io/file_access_zip.h +++ b/core/io/file_access_zip.h @@ -67,8 +67,8 @@ public: bool file_exists(String p_name) const; - virtual bool try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset); - FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file); + virtual bool try_open_pack(const String &p_path, bool p_replace_files, uint64_t p_offset) override; + Ref<FileAccess> get_file(const String &p_path, PackedData::PackedFile *p_file) override; static ZipArchive *get_singleton(); @@ -82,9 +82,10 @@ class FileAccessZip : public FileAccess { mutable bool at_eof; + void _close(); + public: virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(uint64_t p_position); ///< seek to a given position diff --git a/core/io/image.cpp b/core/io/image.cpp index fad9942017..4aed5a913a 100644 --- a/core/io/image.cpp +++ b/core/io/image.cpp @@ -3276,7 +3276,7 @@ Ref<Image> Image::rgbe_to_srgb() { for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { - new_image->set_pixel(col, row, get_pixel(col, row).to_srgb()); + new_image->set_pixel(col, row, get_pixel(col, row).linear_to_srgb()); } } diff --git a/core/io/image_loader.cpp b/core/io/image_loader.cpp index 5518ec8ceb..2ccc95f0de 100644 --- a/core/io/image_loader.cpp +++ b/core/io/image_loader.cpp @@ -44,17 +44,14 @@ bool ImageFormatLoader::recognize(const String &p_extension) const { return false; } -Error ImageLoader::load_image(String p_file, Ref<Image> p_image, FileAccess *p_custom, bool p_force_linear, float p_scale) { +Error ImageLoader::load_image(String p_file, Ref<Image> p_image, Ref<FileAccess> p_custom, bool p_force_linear, float p_scale) { ERR_FAIL_COND_V_MSG(p_image.is_null(), ERR_INVALID_PARAMETER, "It's not a reference to a valid Image object."); - FileAccess *f = p_custom; - if (!f) { + Ref<FileAccess> f = p_custom; + if (f.is_null()) { Error err; f = FileAccess::open(p_file, FileAccess::READ, &err); - if (!f) { - ERR_PRINT("Error opening file '" + p_file + "'."); - return err; - } + ERR_FAIL_COND_V_MSG(f.is_null(), err, "Error opening file '" + p_file + "'."); } String extension = p_file.get_extension(); @@ -69,18 +66,10 @@ Error ImageLoader::load_image(String p_file, Ref<Image> p_image, FileAccess *p_c } if (err != ERR_FILE_UNRECOGNIZED) { - if (!p_custom) { - memdelete(f); - } - return err; } } - if (!p_custom) { - memdelete(f); - } - return ERR_FILE_UNRECOGNIZED; } @@ -123,8 +112,8 @@ void ImageLoader::cleanup() { ///////////////// RES ResourceFormatLoaderImage::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { if (r_error) { *r_error = ERR_CANT_OPEN; } @@ -136,7 +125,6 @@ RES ResourceFormatLoaderImage::load(const String &p_path, const String &p_origin bool unrecognized = header[0] != 'G' || header[1] != 'D' || header[2] != 'I' || header[3] != 'M'; if (unrecognized) { - memdelete(f); if (r_error) { *r_error = ERR_FILE_UNRECOGNIZED; } @@ -155,7 +143,6 @@ RES ResourceFormatLoaderImage::load(const String &p_path, const String &p_origin } if (idx == -1) { - memdelete(f); if (r_error) { *r_error = ERR_FILE_UNRECOGNIZED; } @@ -167,8 +154,6 @@ RES ResourceFormatLoaderImage::load(const String &p_path, const String &p_origin Error err = ImageLoader::loader[idx]->load_image(image, f, false, 1.0); - memdelete(f); - if (err != OK) { if (r_error) { *r_error = err; diff --git a/core/io/image_loader.h b/core/io/image_loader.h index 37d7620f96..9409617268 100644 --- a/core/io/image_loader.h +++ b/core/io/image_loader.h @@ -44,7 +44,7 @@ class ImageFormatLoader { friend class ResourceFormatLoaderImage; protected: - virtual Error load_image(Ref<Image> p_image, FileAccess *p_fileaccess, bool p_force_linear, float p_scale) = 0; + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) = 0; virtual void get_recognized_extensions(List<String> *p_extensions) const = 0; bool recognize(const String &p_extension) const; @@ -58,7 +58,7 @@ class ImageLoader { protected: public: - static Error load_image(String p_file, Ref<Image> p_image, FileAccess *p_custom = nullptr, bool p_force_linear = false, float p_scale = 1.0); + static Error load_image(String p_file, Ref<Image> p_image, Ref<FileAccess> p_custom = Ref<FileAccess>(), bool p_force_linear = false, float p_scale = 1.0); static void get_recognized_extensions(List<String> *p_extensions); static ImageFormatLoader *recognize(const String &p_extension); diff --git a/core/io/ip.cpp b/core/io/ip.cpp index 2f88307d94..52674150bb 100644 --- a/core/io/ip.cpp +++ b/core/io/ip.cpp @@ -109,7 +109,7 @@ struct _IP_ResolverPrivate { } static void _thread_function(void *self) { - _IP_ResolverPrivate *ipr = (_IP_ResolverPrivate *)self; + _IP_ResolverPrivate *ipr = static_cast<_IP_ResolverPrivate *>(self); while (!ipr->thread_abort) { ipr->sem.wait(); diff --git a/core/io/ip.h b/core/io/ip.h index ebd944a949..06ff8a4d70 100644 --- a/core/io/ip.h +++ b/core/io/ip.h @@ -62,7 +62,7 @@ public: typedef int ResolverID; private: - _IP_ResolverPrivate *resolver; + _IP_ResolverPrivate *resolver = nullptr; protected: static IP *singleton; diff --git a/core/io/logger.cpp b/core/io/logger.cpp index 2b6f230434..c19fc2820b 100644 --- a/core/io/logger.cpp +++ b/core/io/logger.cpp @@ -115,21 +115,14 @@ void Logger::logf_error(const char *p_format, ...) { va_end(argp); } -void RotatedFileLogger::close_file() { - if (file) { - memdelete(file); - file = nullptr; - } -} - void RotatedFileLogger::clear_old_backups() { int max_backups = max_files - 1; // -1 for the current file String basename = base_path.get_file().get_basename(); String extension = base_path.get_extension(); - DirAccessRef da = DirAccess::open(base_path.get_base_dir()); - if (!da) { + Ref<DirAccess> da = DirAccess::open(base_path.get_base_dir()); + if (da.is_null()) { return; } @@ -155,7 +148,7 @@ void RotatedFileLogger::clear_old_backups() { } void RotatedFileLogger::rotate_file() { - close_file(); + file.unref(); if (FileAccess::exists(base_path)) { if (max_files > 1) { @@ -165,20 +158,21 @@ void RotatedFileLogger::rotate_file() { backup_name += "." + base_path.get_extension(); } - DirAccessRef da = DirAccess::open(base_path.get_base_dir()); - if (da) { + Ref<DirAccess> da = DirAccess::open(base_path.get_base_dir()); + if (da.is_valid()) { da->copy(base_path, backup_name); } clear_old_backups(); } } else { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_USERDATA); - if (da) { + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_USERDATA); + if (da.is_valid()) { da->make_dir_recursive(base_path.get_base_dir()); } } file = FileAccess::open(base_path, FileAccess::WRITE); + file->detach_from_objectdb(); // Note: This FileAccess instance will exist longer than ObjectDB, therefor can't be registered in ObjectDB. } RotatedFileLogger::RotatedFileLogger(const String &p_base_path, int p_max_files) : @@ -192,7 +186,7 @@ void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) { return; } - if (file) { + if (file.is_valid()) { const int static_buf_size = 512; char static_buf[static_buf_size]; char *buf = static_buf; @@ -218,10 +212,6 @@ void RotatedFileLogger::logv(const char *p_format, va_list p_list, bool p_err) { } } -RotatedFileLogger::~RotatedFileLogger() { - close_file(); -} - void StdLogger::logv(const char *p_format, va_list p_list, bool p_err) { if (!should_log(p_err)) { return; diff --git a/core/io/logger.h b/core/io/logger.h index 047ee3d0f1..e3ac00f11c 100644 --- a/core/io/logger.h +++ b/core/io/logger.h @@ -81,9 +81,8 @@ class RotatedFileLogger : public Logger { String base_path; int max_files; - FileAccess *file = nullptr; + Ref<FileAccess> file; - void close_file(); void clear_old_backups(); void rotate_file(); @@ -91,8 +90,6 @@ public: RotatedFileLogger(const String &p_base_path, int p_max_files = 10); virtual void logv(const char *p_format, va_list p_list, bool p_err) _PRINTF_FORMAT_ATTRIBUTE_2_0; - - virtual ~RotatedFileLogger(); }; class CompositeLogger : public Logger { diff --git a/core/io/packed_data_container.cpp b/core/io/packed_data_container.cpp index 14183b472b..027fdd51aa 100644 --- a/core/io/packed_data_container.cpp +++ b/core/io/packed_data_container.cpp @@ -105,7 +105,7 @@ Variant PackedDataContainer::_get_at_ofs(uint32_t p_ofs, const uint8_t *p_buf, b if (type == TYPE_ARRAY || type == TYPE_DICT) { Ref<PackedDataContainerRef> pdcr = memnew(PackedDataContainerRef); - Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>((PackedDataContainer *)this); + Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>(const_cast<PackedDataContainer *>(this)); pdcr->from = pdc; pdcr->offset = p_ofs; diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp index b3bf0cff2d..aa1b323db2 100644 --- a/core/io/pck_packer.cpp +++ b/core/io/pck_packer.cpp @@ -83,13 +83,8 @@ Error PCKPacker::pck_start(const String &p_file, int p_alignment, const String & } enc_dir = p_encrypt_directory; - if (file != nullptr) { - memdelete(file); - } - file = FileAccess::open(p_file, FileAccess::WRITE); - - ERR_FAIL_COND_V_MSG(!file, ERR_CANT_CREATE, "Can't open file to write: " + String(p_file) + "."); + ERR_FAIL_COND_V_MSG(file.is_null(), ERR_CANT_CREATE, "Can't open file to write: " + String(p_file) + "."); alignment = p_alignment; @@ -112,8 +107,8 @@ Error PCKPacker::pck_start(const String &p_file, int p_alignment, const String & } Error PCKPacker::add_file(const String &p_file, const String &p_src, bool p_encrypt) { - FileAccess *f = FileAccess::open(p_src, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_src, FileAccess::READ); + if (f.is_null()) { return ERR_FILE_CANT_OPEN; } @@ -149,14 +144,11 @@ Error PCKPacker::add_file(const String &p_file, const String &p_src, bool p_encr files.push_back(pf); - f->close(); - memdelete(f); - return OK; } Error PCKPacker::flush(bool p_verbose) { - ERR_FAIL_COND_V_MSG(!file, ERR_INVALID_PARAMETER, "File must be opened before use."); + ERR_FAIL_COND_V_MSG(file.is_null(), ERR_INVALID_PARAMETER, "File must be opened before use."); int64_t file_base_ofs = file->get_position(); file->store_64(0); // files base @@ -168,12 +160,12 @@ Error PCKPacker::flush(bool p_verbose) { // write the index file->store_32(files.size()); - FileAccessEncrypted *fae = nullptr; - FileAccess *fhead = file; + Ref<FileAccessEncrypted> fae; + Ref<FileAccess> fhead = file; if (enc_dir) { - fae = memnew(FileAccessEncrypted); - ERR_FAIL_COND_V(!fae, ERR_CANT_CREATE); + fae.instantiate(); + ERR_FAIL_COND_V(fae.is_null(), ERR_CANT_CREATE); Error err = fae->open_and_parse(file, key, FileAccessEncrypted::MODE_WRITE_AES256, false); ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); @@ -202,9 +194,9 @@ Error PCKPacker::flush(bool p_verbose) { fhead->store_32(flags); } - if (fae) { - fae->release(); - memdelete(fae); + if (fae.is_valid()) { + fhead.unref(); + fae.unref(); } int header_padding = _get_pad(alignment, file->get_position()); @@ -222,14 +214,13 @@ Error PCKPacker::flush(bool p_verbose) { int count = 0; for (int i = 0; i < files.size(); i++) { - FileAccess *src = FileAccess::open(files[i].src_path, FileAccess::READ); + Ref<FileAccess> src = FileAccess::open(files[i].src_path, FileAccess::READ); uint64_t to_write = files[i].size; - fae = nullptr; - FileAccess *ftmp = file; + Ref<FileAccess> ftmp = file; if (files[i].encrypted) { - fae = memnew(FileAccessEncrypted); - ERR_FAIL_COND_V(!fae, ERR_CANT_CREATE); + fae.instantiate(); + ERR_FAIL_COND_V(fae.is_null(), ERR_CANT_CREATE); Error err = fae->open_and_parse(file, key, FileAccessEncrypted::MODE_WRITE_AES256, false); ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE); @@ -242,9 +233,9 @@ Error PCKPacker::flush(bool p_verbose) { to_write -= read; } - if (fae) { - fae->release(); - memdelete(fae); + if (fae.is_valid()) { + ftmp.unref(); + fae.unref(); } int pad = _get_pad(alignment, file->get_position()); @@ -252,8 +243,6 @@ Error PCKPacker::flush(bool p_verbose) { file->store_8(Math::rand() % 256); } - src->close(); - memdelete(src); count += 1; const int file_num = files.size(); if (p_verbose && (file_num > 0)) { @@ -265,15 +254,8 @@ Error PCKPacker::flush(bool p_verbose) { printf("\n"); } - file->close(); + file.unref(); memdelete_arr(buf); return OK; } - -PCKPacker::~PCKPacker() { - if (file != nullptr) { - memdelete(file); - } - file = nullptr; -} diff --git a/core/io/pck_packer.h b/core/io/pck_packer.h index 583171a70b..77ec293fb2 100644 --- a/core/io/pck_packer.h +++ b/core/io/pck_packer.h @@ -38,7 +38,7 @@ class FileAccess; class PCKPacker : public RefCounted { GDCLASS(PCKPacker, RefCounted); - FileAccess *file = nullptr; + Ref<FileAccess> file; int alignment = 0; uint64_t ofs = 0; @@ -63,7 +63,6 @@ public: Error flush(bool p_verbose = false); PCKPacker() {} - ~PCKPacker(); }; #endif // PCK_PACKER_H diff --git a/core/io/resource.cpp b/core/io/resource.cpp index f90a6e9304..bf91438810 100644 --- a/core/io/resource.cpp +++ b/core/io/resource.cpp @@ -538,10 +538,10 @@ void ResourceCache::dump(const char *p_file, bool p_short) { Map<String, int> type_count; - FileAccess *f = nullptr; + Ref<FileAccess> f; if (p_file) { f = FileAccess::open(String::utf8(p_file), FileAccess::WRITE); - ERR_FAIL_COND_MSG(!f, "Cannot create file at path '" + String::utf8(p_file) + "'."); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file at path '" + String::utf8(p_file) + "'."); } const String *K = nullptr; @@ -555,21 +555,17 @@ void ResourceCache::dump(const char *p_file, bool p_short) { type_count[r->get_class()]++; if (!p_short) { - if (f) { + if (f.is_valid()) { f->store_line(r->get_class() + ": " + r->get_path()); } } } for (const KeyValue<String, int> &E : type_count) { - if (f) { + if (f.is_valid()) { f->store_line(E.key + " count: " + itos(E.value)); } } - if (f) { - f->close(); - memdelete(f); - } lock.read_unlock(); #else diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp index b65993e3dd..8d4dbc3f73 100644 --- a/core/io/resource_format_binary.cpp +++ b/core/io/resource_format_binary.cpp @@ -101,6 +101,50 @@ void ResourceLoaderBinary::_advance_padding(uint32_t p_len) { } } +static Error read_reals(real_t *dst, Ref<FileAccess> &f, size_t count) { + if (f->real_is_double) { + if (sizeof(real_t) == 8) { + // Ideal case with double-precision + f->get_buffer((uint8_t *)dst, count * sizeof(double)); +#ifdef BIG_ENDIAN_ENABLED + { + uint64_t *dst = (uint64_t *)dst; + for (size_t i = 0; i < count; i++) { + dst[i] = BSWAP64(dst[i]); + } + } +#endif + } else if (sizeof(real_t) == 4) { + // May be slower, but this is for compatibility. Eventually the data should be converted. + for (size_t i = 0; i < count; ++i) { + dst[i] = f->get_double(); + } + } else { + ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "real_t size is neither 4 nor 8!"); + } + } else { + if (sizeof(real_t) == 4) { + // Ideal case with float-precision + f->get_buffer((uint8_t *)dst, count * sizeof(float)); +#ifdef BIG_ENDIAN_ENABLED + { + uint32_t *dst = (uint32_t *)dst; + for (size_t i = 0; i < count; i++) { + dst[i] = BSWAP32(dst[i]); + } + } +#endif + } else if (sizeof(real_t) == 8) { + for (size_t i = 0; i < count; ++i) { + dst[i] = f->get_float(); + } + } else { + ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "real_t size is neither 4 nor 8!"); + } + } + return OK; +} + StringName ResourceLoaderBinary::_get_string() { uint32_t id = f->get_32(); if (id & 0x80000000) { @@ -528,21 +572,9 @@ Error ResourceLoaderBinary::parse_variant(Variant &r_v) { Vector<Vector2> array; array.resize(len); Vector2 *w = array.ptrw(); - if (sizeof(Vector2) == 8) { - f->get_buffer((uint8_t *)w, len * sizeof(real_t) * 2); -#ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr = (uint32_t *)w.ptr(); - for (int i = 0; i < len * 2; i++) { - ptr[i] = BSWAP32(ptr[i]); - } - } - -#endif - - } else { - ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Vector2 size is NOT 8!"); - } + static_assert(sizeof(Vector2) == 2 * sizeof(real_t)); + const Error err = read_reals(reinterpret_cast<real_t *>(w), f, len * 2); + ERR_FAIL_COND_V(err != OK, err); r_v = array; @@ -553,21 +585,9 @@ Error ResourceLoaderBinary::parse_variant(Variant &r_v) { Vector<Vector3> array; array.resize(len); Vector3 *w = array.ptrw(); - if (sizeof(Vector3) == 12) { - f->get_buffer((uint8_t *)w, len * sizeof(real_t) * 3); -#ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr = (uint32_t *)w.ptr(); - for (int i = 0; i < len * 3; i++) { - ptr[i] = BSWAP32(ptr[i]); - } - } - -#endif - - } else { - ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Vector3 size is NOT 12!"); - } + static_assert(sizeof(Vector3) == 3 * sizeof(real_t)); + const Error err = read_reals(reinterpret_cast<real_t *>(w), f, len * 3); + ERR_FAIL_COND_V(err != OK, err); r_v = array; @@ -578,22 +598,19 @@ Error ResourceLoaderBinary::parse_variant(Variant &r_v) { Vector<Color> array; array.resize(len); Color *w = array.ptrw(); - if (sizeof(Color) == 16) { - f->get_buffer((uint8_t *)w, len * sizeof(real_t) * 4); + // Colors always use `float` even with double-precision support enabled + static_assert(sizeof(Color) == 4 * sizeof(float)); + f->get_buffer((uint8_t *)w, len * sizeof(float) * 4); #ifdef BIG_ENDIAN_ENABLED - { - uint32_t *ptr = (uint32_t *)w.ptr(); - for (int i = 0; i < len * 4; i++) { - ptr[i] = BSWAP32(ptr[i]); - } + { + uint32_t *ptr = (uint32_t *)w.ptr(); + for (int i = 0; i < len * 4; i++) { + ptr[i] = BSWAP32(ptr[i]); } + } #endif - } else { - ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "Color size is NOT 16!"); - } - r_v = array; } break; default: { @@ -772,7 +789,7 @@ Error ResourceLoaderBinary::load() { resource_cache.push_back(res); if (main) { - f->close(); + f.unref(); resource = res; resource->set_as_translation_remapped(translation_remapped); error = OK; @@ -787,13 +804,13 @@ void ResourceLoaderBinary::set_translation_remapped(bool p_remapped) { translation_remapped = p_remapped; } -static void save_ustring(FileAccess *f, const String &p_string) { +static void save_ustring(Ref<FileAccess> f, const String &p_string) { CharString utf8 = p_string.utf8(); f->store_32(utf8.length() + 1); f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } -static String get_ustring(FileAccess *f) { +static String get_ustring(Ref<FileAccess> f) { int len = f->get_32(); Vector<char> str_buf; str_buf.resize(len); @@ -817,7 +834,7 @@ String ResourceLoaderBinary::get_unicode_string() { return s; } -void ResourceLoaderBinary::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) { +void ResourceLoaderBinary::get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types) { open(p_f, false, true); if (error) { return; @@ -839,7 +856,7 @@ void ResourceLoaderBinary::get_dependencies(FileAccess *p_f, List<String> *p_dep } } -void ResourceLoaderBinary::open(FileAccess *p_f, bool p_no_resources, bool p_keep_uuid_paths) { +void ResourceLoaderBinary::open(Ref<FileAccess> p_f, bool p_no_resources, bool p_keep_uuid_paths) { error = OK; f = p_f; @@ -847,11 +864,11 @@ void ResourceLoaderBinary::open(FileAccess *p_f, bool p_no_resources, bool p_kee f->get_buffer(header, 4); if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { // Compressed. - FileAccessCompressed *fac = memnew(FileAccessCompressed); + Ref<FileAccessCompressed> fac; + fac.instantiate(); error = fac->open_after_magic(f); if (error != OK) { - memdelete(fac); - f->close(); + f.unref(); ERR_FAIL_MSG("Failed to open binary resource file: " + local_path + "."); } f = fac; @@ -859,7 +876,7 @@ void ResourceLoaderBinary::open(FileAccess *p_f, bool p_no_resources, bool p_kee } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { // Not normal. error = ERR_FILE_UNRECOGNIZED; - f->close(); + f.unref(); ERR_FAIL_MSG("Unrecognized binary resource file: " + local_path + "."); } @@ -884,7 +901,7 @@ void ResourceLoaderBinary::open(FileAccess *p_f, bool p_no_resources, bool p_kee print_bl("format: " + itos(ver_format)); if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { - f->close(); + f.unref(); ERR_FAIL_MSG(vformat("File '%s' can't be loaded, as it uses a format version (%d) or engine version (%d.%d) which are not supported by your engine version (%s).", local_path, ver_format, ver_major, ver_minor, VERSION_BRANCH)); } @@ -961,12 +978,12 @@ void ResourceLoaderBinary::open(FileAccess *p_f, bool p_no_resources, bool p_kee if (f->eof_reached()) { error = ERR_FILE_CORRUPT; - f->close(); + f.unref(); ERR_FAIL_MSG("Premature end of file (EOF): " + local_path + "."); } } -String ResourceLoaderBinary::recognize(FileAccess *p_f) { +String ResourceLoaderBinary::recognize(Ref<FileAccess> p_f) { error = OK; f = p_f; @@ -974,11 +991,11 @@ String ResourceLoaderBinary::recognize(FileAccess *p_f) { f->get_buffer(header, 4); if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { // Compressed. - FileAccessCompressed *fac = memnew(FileAccessCompressed); + Ref<FileAccessCompressed> fac; + fac.instantiate(); error = fac->open_after_magic(f); if (error != OK) { - memdelete(fac); - f->close(); + f.unref(); return ""; } f = fac; @@ -986,7 +1003,7 @@ String ResourceLoaderBinary::recognize(FileAccess *p_f) { } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { // Not normal. error = ERR_FILE_UNRECOGNIZED; - f->close(); + f.unref(); return ""; } @@ -1000,7 +1017,7 @@ String ResourceLoaderBinary::recognize(FileAccess *p_f) { uint32_t ver_format = f->get_32(); if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { - f->close(); + f.unref(); return ""; } @@ -1009,19 +1026,13 @@ String ResourceLoaderBinary::recognize(FileAccess *p_f) { return type; } -ResourceLoaderBinary::~ResourceLoaderBinary() { - if (f) { - memdelete(f); - } -} - RES ResourceFormatLoaderBinary::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) { if (r_error) { *r_error = ERR_FILE_CANT_OPEN; } Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot open file '" + p_path + "'."); @@ -1079,8 +1090,8 @@ bool ResourceFormatLoaderBinary::handles_type(const String &p_type) const { } void ResourceFormatLoaderBinary::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_MSG(!f, "Cannot open file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file '" + p_path + "'."); ResourceLoaderBinary loader; loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path); @@ -1089,10 +1100,10 @@ void ResourceFormatLoaderBinary::get_dependencies(const String &p_path, List<Str } Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot open file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, "Cannot open file '" + p_path + "'."); - FileAccess *fw = nullptr; + Ref<FileAccess> fw; String local_path = p_path.get_base_dir(); @@ -1100,36 +1111,26 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, cons f->get_buffer(header, 4); if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') { // Compressed. - FileAccessCompressed *fac = memnew(FileAccessCompressed); + Ref<FileAccessCompressed> fac; + fac.instantiate(); Error err = fac->open_after_magic(f); - if (err != OK) { - memdelete(fac); - memdelete(f); - ERR_FAIL_V_MSG(err, "Cannot open file '" + p_path + "'."); - } + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'."); f = fac; - FileAccessCompressed *facw = memnew(FileAccessCompressed); + Ref<FileAccessCompressed> facw; + facw.instantiate(); facw->configure("RSCC"); err = facw->_open(p_path + ".depren", FileAccess::WRITE); - if (err) { - memdelete(fac); - memdelete(facw); - ERR_FAIL_COND_V_MSG(err, ERR_FILE_CORRUPT, "Cannot create file '" + p_path + ".depren'."); - } + ERR_FAIL_COND_V_MSG(err, ERR_FILE_CORRUPT, "Cannot create file '" + p_path + ".depren'."); fw = facw; } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') { // Not normal. - memdelete(f); ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, "Unrecognized binary resource file '" + local_path + "'."); } else { fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); - if (!fw) { - memdelete(f); - } - ERR_FAIL_COND_V_MSG(!fw, ERR_CANT_CREATE, "Cannot create file '" + p_path + ".depren'."); + ERR_FAIL_COND_V_MSG(fw.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + ".depren'."); uint8_t magic[4] = { 'R', 'S', 'R', 'C' }; fw->store_buffer(magic, 4); @@ -1152,10 +1153,8 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, cons uint32_t ver_format = f->get_32(); if (ver_format < FORMAT_VERSION_CAN_RENAME_DEPS) { - memdelete(f); - memdelete(fw); { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->remove(p_path + ".depren"); } @@ -1184,8 +1183,6 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, cons } if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) { - memdelete(f); - memdelete(fw); ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, vformat("File '%s' can't be loaded, as it uses a format version (%d) or engine version (%d.%d) which are not supported by your engine version (%s).", local_path, ver_format, ver_major, ver_minor, VERSION_BRANCH)); @@ -1294,22 +1291,19 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, cons fw->seek(md_ofs); fw->store_64(importmd_ofs + size_diff); - memdelete(f); - memdelete(fw); - if (!all_ok) { return ERR_CANT_CREATE; } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(p_path); da->rename(p_path + ".depren", p_path); return OK; } String ResourceFormatLoaderBinary::get_resource_type(const String &p_path) const { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { return ""; //could not read } @@ -1326,8 +1320,8 @@ ResourceUID::ID ResourceFormatLoaderBinary::get_resource_uid(const String &p_pat return ResourceUID::INVALID_ID; } - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { return ResourceUID::INVALID_ID; //could not read } @@ -1345,7 +1339,7 @@ ResourceUID::ID ResourceFormatLoaderBinary::get_resource_uid(const String &p_pat /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// -void ResourceFormatSaverBinaryInstance::_pad_buffer(FileAccess *f, int p_bytes) { +void ResourceFormatSaverBinaryInstance::_pad_buffer(Ref<FileAccess> f, int p_bytes) { int extra = 4 - (p_bytes % 4); if (extra < 4) { for (int i = 0; i < extra; i++) { @@ -1354,7 +1348,7 @@ void ResourceFormatSaverBinaryInstance::_pad_buffer(FileAccess *f, int p_bytes) } } -void ResourceFormatSaverBinaryInstance::write_variant(FileAccess *f, const Variant &p_property, Map<RES, int> &resource_map, Map<RES, int> &external_resources, Map<StringName, int> &string_map, const PropertyInfo &p_hint) { +void ResourceFormatSaverBinaryInstance::write_variant(Ref<FileAccess> f, const Variant &p_property, Map<RES, int> &resource_map, Map<RES, int> &external_resources, Map<StringName, int> &string_map, const PropertyInfo &p_hint) { switch (p_property.get_type()) { case Variant::NIL: { f->store_32(VARIANT_NIL); @@ -1813,14 +1807,14 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant &p_variant } } -void ResourceFormatSaverBinaryInstance::save_unicode_string(FileAccess *f, const String &p_string, bool p_bit_on_len) { +void ResourceFormatSaverBinaryInstance::save_unicode_string(Ref<FileAccess> p_f, const String &p_string, bool p_bit_on_len) { CharString utf8 = p_string.utf8(); if (p_bit_on_len) { - f->store_32((utf8.length() + 1) | 0x80000000); + p_f->store_32((utf8.length() + 1) | 0x80000000); } else { - f->store_32(utf8.length() + 1); + p_f->store_32(utf8.length() + 1); } - f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); + p_f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } int ResourceFormatSaverBinaryInstance::get_string_index(const String &p_string) { @@ -1836,15 +1830,13 @@ int ResourceFormatSaverBinaryInstance::get_string_index(const String &p_string) Error ResourceFormatSaverBinaryInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { Error err; + Ref<FileAccess> f; if (p_flags & ResourceSaver::FLAG_COMPRESS) { - FileAccessCompressed *fac = memnew(FileAccessCompressed); + Ref<FileAccessCompressed> fac; + fac.instantiate(); fac->configure("RSCC"); f = fac; err = fac->_open(p_path, FileAccess::WRITE); - if (err) { - memdelete(f); - } - } else { f = FileAccess::open(p_path, FileAccess::WRITE, &err); } @@ -1885,8 +1877,6 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path, const RES &p f->store_32(FORMAT_VERSION); if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { - f->close(); - memdelete(f); return ERR_CANT_CREATE; } @@ -2044,14 +2034,9 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path, const RES &p f->store_buffer((const uint8_t *)"RSRC", 4); //magic at end if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { - f->close(); - memdelete(f); return ERR_CANT_CREATE; } - f->close(); - memdelete(f); - return OK; } diff --git a/core/io/resource_format_binary.h b/core/io/resource_format_binary.h index c80c9b0ac9..72a3c6751d 100644 --- a/core/io/resource_format_binary.h +++ b/core/io/resource_format_binary.h @@ -43,7 +43,7 @@ class ResourceLoaderBinary { Ref<Resource> resource; uint32_t ver_format = 0; - FileAccess *f = nullptr; + Ref<FileAccess> f; uint64_t importmd_ofs = 0; @@ -98,12 +98,11 @@ public: void set_translation_remapped(bool p_remapped); void set_remaps(const Map<String, String> &p_remaps) { remaps = p_remaps; } - void open(FileAccess *p_f, bool p_no_resources = false, bool p_keep_uuid_paths = false); - String recognize(FileAccess *p_f); - void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types); + void open(Ref<FileAccess> p_f, bool p_no_resources = false, bool p_keep_uuid_paths = false); + String recognize(Ref<FileAccess> p_f); + void get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types); ResourceLoaderBinary() {} - ~ResourceLoaderBinary(); }; class ResourceFormatLoaderBinary : public ResourceFormatLoader { @@ -127,7 +126,6 @@ class ResourceFormatSaverBinaryInstance { bool skip_editor; bool big_endian; bool takeover_paths; - FileAccess *f; String magic; Set<RES> resource_set; @@ -155,9 +153,9 @@ class ResourceFormatSaverBinaryInstance { List<Property> properties; }; - static void _pad_buffer(FileAccess *f, int p_bytes); + static void _pad_buffer(Ref<FileAccess> f, int p_bytes); void _find_resources(const Variant &p_variant, bool p_main = false); - static void save_unicode_string(FileAccess *f, const String &p_string, bool p_bit_on_len = false); + static void save_unicode_string(Ref<FileAccess> f, const String &p_string, bool p_bit_on_len = false); int get_string_index(const String &p_string); public: @@ -170,7 +168,7 @@ public: RESERVED_FIELDS = 11 }; Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); - static void write_variant(FileAccess *f, const Variant &p_property, Map<RES, int> &resource_map, Map<RES, int> &external_resources, Map<StringName, int> &string_map, const PropertyInfo &p_hint = PropertyInfo()); + static void write_variant(Ref<FileAccess> f, const Variant &p_property, Map<RES, int> &resource_map, Map<RES, int> &external_resources, Map<StringName, int> &string_map, const PropertyInfo &p_hint = PropertyInfo()); }; class ResourceFormatSaverBinary : public ResourceFormatSaver { diff --git a/core/io/resource_importer.cpp b/core/io/resource_importer.cpp index 9b6440e2a2..b4f73b3b25 100644 --- a/core/io/resource_importer.cpp +++ b/core/io/resource_importer.cpp @@ -40,9 +40,9 @@ bool ResourceFormatImporter::SortImporterByName::operator()(const Ref<ResourceIm Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndType &r_path_and_type, bool *r_valid) const { Error err; - FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); - if (!f) { + if (f.is_null()) { if (r_valid) { *r_valid = false; } @@ -70,11 +70,9 @@ Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndTy err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true); if (err == ERR_FILE_EOF) { - memdelete(f); return OK; } else if (err != OK) { ERR_PRINT("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text); - memdelete(f); return err; } @@ -110,8 +108,6 @@ Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndTy } } - memdelete(f); - if (r_path_and_type.path.is_empty() || r_path_and_type.type.is_empty()) { return ERR_FILE_CORRUPT; } @@ -270,9 +266,9 @@ String ResourceFormatImporter::get_internal_resource_path(const String &p_path) void ResourceFormatImporter::get_internal_resource_path_list(const String &p_path, List<String> *r_paths) { Error err; - FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); - if (!f) { + if (f.is_null()) { return; } @@ -292,11 +288,9 @@ void ResourceFormatImporter::get_internal_resource_path_list(const String &p_pat err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, nullptr, true); if (err == ERR_FILE_EOF) { - memdelete(f); return; } else if (err != OK) { ERR_PRINT("ResourceFormatImporter::get_internal_resource_path_list - " + p_path + ".import:" + itos(lines) + " error: " + error_text); - memdelete(f); return; } @@ -310,7 +304,6 @@ void ResourceFormatImporter::get_internal_resource_path_list(const String &p_pat break; } } - memdelete(f); } String ResourceFormatImporter::get_import_group_file(const String &p_path) const { diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp index 2419c76dd3..fe9693aa20 100644 --- a/core/io/resource_loader.cpp +++ b/core/io/resource_loader.cpp @@ -206,7 +206,7 @@ RES ResourceLoader::_load(const String &p_path, const String &p_original_path, c vformat("Failed loading resource: %s. Make sure resources have been imported by opening the project in the editor at least once.", p_path)); #ifdef TOOLS_ENABLED - FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES); + Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES); ERR_FAIL_COND_V_MSG(!file_check->file_exists(p_path), RES(), "Resource file not found: " + p_path + "."); #endif @@ -817,9 +817,8 @@ String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_rem if (new_path == p_path) { // Did not remap. // Try file remap. Error err; - FileAccess *f = FileAccess::open(p_path + ".remap", FileAccess::READ, &err); - - if (f) { + Ref<FileAccess> f = FileAccess::open(p_path + ".remap", FileAccess::READ, &err); + if (f.is_valid()) { VariantParser::StreamFile stream; stream.f = f; @@ -849,8 +848,6 @@ String ResourceLoader::_path_remap(const String &p_path, bool *r_translation_rem break; } } - - memdelete(f); } } diff --git a/core/io/resource_uid.cpp b/core/io/resource_uid.cpp index d0335bed3a..515b7c710e 100644 --- a/core/io/resource_uid.cpp +++ b/core/io/resource_uid.cpp @@ -135,12 +135,12 @@ void ResourceUID::remove_id(ID p_id) { Error ResourceUID::save_to_cache() { String cache_file = get_cache_file(); if (!FileAccess::exists(cache_file)) { - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES); d->make_dir_recursive(String(cache_file).get_base_dir()); //ensure base dir exists } - FileAccessRef f = FileAccess::open(cache_file, FileAccess::WRITE); - if (!f) { + Ref<FileAccess> f = FileAccess::open(cache_file, FileAccess::WRITE); + if (f.is_null()) { return ERR_CANT_OPEN; } @@ -163,8 +163,8 @@ Error ResourceUID::save_to_cache() { } Error ResourceUID::load_from_cache() { - FileAccessRef f = FileAccess::open(get_cache_file(), FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(get_cache_file(), FileAccess::READ); + if (f.is_null()) { return ERR_CANT_OPEN; } @@ -201,12 +201,12 @@ Error ResourceUID::update_cache() { } MutexLock l(mutex); - FileAccess *f = nullptr; + Ref<FileAccess> f; for (OrderedHashMap<ID, Cache>::Element E = unique_ids.front(); E; E = E.next()) { if (!E.get().saved_to_cache) { - if (f == nullptr) { + if (f.is_null()) { f = FileAccess::open(get_cache_file(), FileAccess::READ_WRITE); //append - if (!f) { + if (f.is_null()) { return ERR_CANT_OPEN; } f->seek_end(); @@ -220,11 +220,9 @@ Error ResourceUID::update_cache() { } } - if (f != nullptr) { + if (f.is_valid()) { f->seek(0); f->store_32(cache_entries); //update amount of entries - f->close(); - memdelete(f); } changed = false; diff --git a/core/io/resource_uid.h b/core/io/resource_uid.h index 1ea44b9d06..0b7ffdf6d0 100644 --- a/core/io/resource_uid.h +++ b/core/io/resource_uid.h @@ -46,7 +46,7 @@ public: static String get_cache_file(); private: - void *crypto; // CryptoCore::RandomGenerator (avoid including crypto_core.h) + void *crypto = nullptr; // CryptoCore::RandomGenerator (avoid including crypto_core.h) Mutex mutex; struct Cache { CharString cs; diff --git a/core/io/translation_loader_po.cpp b/core/io/translation_loader_po.cpp index 801bd8b0bf..ae1ad304d7 100644 --- a/core/io/translation_loader_po.cpp +++ b/core/io/translation_loader_po.cpp @@ -34,7 +34,7 @@ #include "core/string/translation.h" #include "core/string/translation_po.h" -RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { +RES TranslationLoaderPO::load_translation(Ref<FileAccess> f, Error *r_error) { if (r_error) { *r_error = ERR_FILE_CORRUPT; } @@ -49,9 +49,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { uint16_t version_maj = f->get_16(); uint16_t version_min = f->get_16(); - if (version_maj > 1) { - ERR_FAIL_V_MSG(RES(), vformat("Unsupported MO file %s, version %d.%d.", path, version_maj, version_min)); - } + ERR_FAIL_COND_V_MSG(version_maj > 1, RES(), vformat("Unsupported MO file %s, version %d.%d.", path, version_maj, version_min)); uint32_t num_strings = f->get_32(); uint32_t id_table_offset = f->get_32(); @@ -98,7 +96,6 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { { Vector<uint8_t> data; f->seek(trans_table_offset + i * 8); - uint32_t str_start = 0; uint32_t str_len = f->get_32(); uint32_t str_offset = f->get_32(); @@ -116,6 +113,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { translation->set_plural_rule(config.substr(p_start, p_end - p_start)); } } else { + uint32_t str_start = 0; Vector<String> plural_msg; for (uint32_t j = 0; j < str_len + 1; j++) { if (data[j] == 0x00) { @@ -134,7 +132,6 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { } } - memdelete(f); } else { // Try to load as text PO file. f->seek(0); @@ -173,7 +170,6 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { // If we reached last line and it's not a content line, break, otherwise let processing that last loop if (is_eof && l.is_empty()) { if (status == STATUS_READING_ID || status == STATUS_READING_CONTEXT || (status == STATUS_READING_PLURAL && plural_index != plural_forms - 1)) { - memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected EOF while reading PO file at: " + path + ":" + itos(line)); } else { break; @@ -181,10 +177,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { } if (l.begins_with("msgctxt")) { - if (status != STATUS_READING_STRING && status != STATUS_READING_PLURAL) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Unexpected 'msgctxt', was expecting 'msgid_plural' or 'msgstr' before 'msgctxt' while parsing: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(status != STATUS_READING_STRING && status != STATUS_READING_PLURAL, RES(), "Unexpected 'msgctxt', was expecting 'msgid_plural' or 'msgstr' before 'msgctxt' while parsing: " + path + ":" + itos(line)); // In PO file, "msgctxt" appears before "msgid". If we encounter a "msgctxt", we add what we have read // and set "entered_context" to true to prevent adding twice. @@ -192,10 +185,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { if (status == STATUS_READING_STRING) { translation->add_message(msg_id, msg_str, msg_context); } else if (status == STATUS_READING_PLURAL) { - if (plural_index != plural_forms - 1) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Number of 'msgstr[]' doesn't match with number of plural forms: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, RES(), "Number of 'msgstr[]' doesn't match with number of plural forms: " + path + ":" + itos(line)); translation->add_plural_message(msg_id, msgs_plural, msg_context); } } @@ -207,10 +197,8 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { if (l.begins_with("msgid_plural")) { if (plural_forms == 0) { - memdelete(f); ERR_FAIL_V_MSG(RES(), "PO file uses 'msgid_plural' but 'Plural-Forms' is invalid or missing in header: " + path + ":" + itos(line)); } else if (status != STATUS_READING_ID) { - memdelete(f); ERR_FAIL_V_MSG(RES(), "Unexpected 'msgid_plural', was expecting 'msgid' before 'msgid_plural' while parsing: " + path + ":" + itos(line)); } // We don't record the message in "msgid_plural" itself as tr_n(), TTRN(), RTRN() interfaces provide the plural string already. @@ -221,20 +209,14 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { msgs_plural.resize(plural_forms); status = STATUS_READING_PLURAL; } else if (l.begins_with("msgid")) { - if (status == STATUS_READING_ID) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Unexpected 'msgid', was expecting 'msgstr' while parsing: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(status == STATUS_READING_ID, RES(), "Unexpected 'msgid', was expecting 'msgstr' while parsing: " + path + ":" + itos(line)); if (!msg_id.is_empty()) { if (!skip_this && !entered_context) { if (status == STATUS_READING_STRING) { translation->add_message(msg_id, msg_str, msg_context); } else if (status == STATUS_READING_PLURAL) { - if (plural_index != plural_forms - 1) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Number of 'msgstr[]' doesn't match with number of plural forms: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, RES(), "Number of 'msgstr[]' doesn't match with number of plural forms: " + path + ":" + itos(line)); translation->add_plural_message(msg_id, msgs_plural, msg_context); } } @@ -263,18 +245,11 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { } if (l.begins_with("msgstr[")) { - if (status != STATUS_READING_PLURAL) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Unexpected 'msgstr[]', was expecting 'msgid_plural' before 'msgstr[]' while parsing: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(status != STATUS_READING_PLURAL, RES(), "Unexpected 'msgstr[]', was expecting 'msgid_plural' before 'msgstr[]' while parsing: " + path + ":" + itos(line)); plural_index++; // Increment to add to the next slot in vector msgs_plural. l = l.substr(9, l.length()).strip_edges(); } else if (l.begins_with("msgstr")) { - if (status != STATUS_READING_ID) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Unexpected 'msgstr', was expecting 'msgid' before 'msgstr' while parsing: " + path + ":" + itos(line)); - } - + ERR_FAIL_COND_V_MSG(status != STATUS_READING_ID, RES(), "Unexpected 'msgstr', was expecting 'msgid' before 'msgstr' while parsing: " + path + ":" + itos(line)); l = l.substr(6, l.length()).strip_edges(); status = STATUS_READING_STRING; } @@ -287,10 +262,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { continue; // Nothing to read or comment. } - if (!l.begins_with("\"") || status == STATUS_NONE) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Invalid line '" + l + "' while parsing: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(!l.begins_with("\"") || status == STATUS_NONE, RES(), "Invalid line '" + l + "' while parsing: " + path + ":" + itos(line)); l = l.substr(1, l.length()); // Find final quote, ignoring escaped ones (\"). @@ -312,10 +284,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { escape_next = false; } - if (end_pos == -1) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Expected '\"' at end of message while parsing: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(end_pos == -1, RES(), "Expected '\"' at end of message while parsing: " + path + ":" + itos(line)); l = l.substr(0, end_pos); l = l.c_unescape(); @@ -327,18 +296,13 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { } else if (status == STATUS_READING_CONTEXT) { msg_context += l; } else if (status == STATUS_READING_PLURAL && plural_index >= 0) { - if (plural_index >= plural_forms) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Unexpected plural form while parsing: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(plural_index >= plural_forms, RES(), "Unexpected plural form while parsing: " + path + ":" + itos(line)); msgs_plural.write[plural_index] = msgs_plural[plural_index] + l; } line++; } - memdelete(f); - // Add the last set of data from last iteration. if (status == STATUS_READING_STRING) { if (!msg_id.is_empty()) { @@ -350,10 +314,7 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error) { } } else if (status == STATUS_READING_PLURAL) { if (!skip_this && !msg_id.is_empty()) { - if (plural_index != plural_forms - 1) { - memdelete(f); - ERR_FAIL_V_MSG(RES(), "Number of 'msgstr[]' doesn't match with number of plural forms: " + path + ":" + itos(line)); - } + ERR_FAIL_COND_V_MSG(plural_index != plural_forms - 1, RES(), "Number of 'msgstr[]' doesn't match with number of plural forms: " + path + ":" + itos(line)); translation->add_plural_message(msg_id, msgs_plural, msg_context); } } @@ -388,8 +349,8 @@ RES TranslationLoaderPO::load(const String &p_path, const String &p_original_pat *r_error = ERR_CANT_OPEN; } - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, RES(), "Cannot open file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), RES(), "Cannot open file '" + p_path + "'."); return load_translation(f, r_error); } diff --git a/core/io/translation_loader_po.h b/core/io/translation_loader_po.h index 1c58896a00..7da361cf24 100644 --- a/core/io/translation_loader_po.h +++ b/core/io/translation_loader_po.h @@ -37,7 +37,7 @@ class TranslationLoaderPO : public ResourceFormatLoader { public: - static RES load_translation(FileAccess *f, Error *r_error = nullptr); + static RES load_translation(Ref<FileAccess> f, Error *r_error = nullptr); virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = nullptr, bool p_use_sub_threads = false, float *r_progress = nullptr, CacheMode p_cache_mode = CACHE_MODE_REUSE); virtual void get_recognized_extensions(List<String> *p_extensions) const; virtual bool handles_type(const String &p_type) const; diff --git a/core/io/udp_server.h b/core/io/udp_server.h index 4a7546fddf..47f06b2490 100644 --- a/core/io/udp_server.h +++ b/core/io/udp_server.h @@ -43,7 +43,7 @@ protected: }; struct Peer { - PacketPeerUDP *peer; + PacketPeerUDP *peer = nullptr; IPAddress ip; uint16_t port = 0; diff --git a/core/io/xml_parser.cpp b/core/io/xml_parser.cpp index 360da46f96..7b43193f47 100644 --- a/core/io/xml_parser.cpp +++ b/core/io/xml_parser.cpp @@ -472,7 +472,7 @@ Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) { Error XMLParser::open(const String &p_path) { Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'."); @@ -488,8 +488,6 @@ Error XMLParser::open(const String &p_path) { data[length] = 0; P = data; - memdelete(file); - return OK; } diff --git a/core/io/zip_io.cpp b/core/io/zip_io.cpp index 2c4f8346ab..2cc844b628 100644 --- a/core/io/zip_io.cpp +++ b/core/io/zip_io.cpp @@ -30,73 +30,69 @@ #include "zip_io.h" -void *zipio_open(void *data, const char *p_fname, int mode) { - FileAccess *&f = *(FileAccess **)data; +void *zipio_open(voidpf opaque, const char *p_fname, int mode) { + ZipIOData *zd = (ZipIOData *)opaque; String fname; fname.parse_utf8(p_fname); if (mode & ZLIB_FILEFUNC_MODE_WRITE) { - f = FileAccess::open(fname, FileAccess::WRITE); + zd->f = FileAccess::open(fname, FileAccess::WRITE); } else { - f = FileAccess::open(fname, FileAccess::READ); + zd->f = FileAccess::open(fname, FileAccess::READ); } - if (!f) { + if (zd->f.is_null()) { return nullptr; } - return data; + return opaque; } -uLong zipio_read(void *data, void *fdata, void *buf, uLong size) { - FileAccess *f = *(FileAccess **)data; - return f->get_buffer((uint8_t *)buf, size); +uLong zipio_read(voidpf opaque, voidpf stream, void *buf, uLong size) { + ZipIOData *zd = (ZipIOData *)opaque; + return zd->f->get_buffer((uint8_t *)buf, size); } uLong zipio_write(voidpf opaque, voidpf stream, const void *buf, uLong size) { - FileAccess *f = *(FileAccess **)opaque; - f->store_buffer((uint8_t *)buf, size); + ZipIOData *zd = (ZipIOData *)opaque; + zd->f->store_buffer((uint8_t *)buf, size); return size; } long zipio_tell(voidpf opaque, voidpf stream) { - FileAccess *f = *(FileAccess **)opaque; - return f->get_position(); + ZipIOData *zd = (ZipIOData *)opaque; + return zd->f->get_position(); } long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) { - FileAccess *f = *(FileAccess **)opaque; + ZipIOData *zd = (ZipIOData *)opaque; uint64_t pos = offset; switch (origin) { case ZLIB_FILEFUNC_SEEK_CUR: - pos = f->get_position() + offset; + pos = zd->f->get_position() + offset; break; case ZLIB_FILEFUNC_SEEK_END: - pos = f->get_length() + offset; + pos = zd->f->get_length() + offset; break; default: break; } - f->seek(pos); + zd->f->seek(pos); return 0; } int zipio_close(voidpf opaque, voidpf stream) { - FileAccess *&f = *(FileAccess **)opaque; - if (f) { - f->close(); - memdelete(f); - f = nullptr; - } + ZipIOData *zd = (ZipIOData *)opaque; + memdelete(zd); return 0; } int zipio_testerror(voidpf opaque, voidpf stream) { - FileAccess *f = *(FileAccess **)opaque; - return (f && f->get_error() != OK) ? 1 : 0; + ZipIOData *zd = (ZipIOData *)opaque; + return (zd->f.is_valid() && zd->f->get_error() != OK) ? 1 : 0; } voidpf zipio_alloc(voidpf opaque, uInt items, uInt size) { @@ -109,9 +105,9 @@ void zipio_free(voidpf opaque, voidpf address) { memfree(address); } -zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) { +zlib_filefunc_def zipio_create_io() { zlib_filefunc_def io; - io.opaque = p_file; + io.opaque = (void *)memnew(ZipIOData); io.zopen_file = zipio_open; io.zread_file = zipio_read; io.zwrite_file = zipio_write; diff --git a/core/io/zip_io.h b/core/io/zip_io.h index 6a29703449..3bcd1f830d 100644 --- a/core/io/zip_io.h +++ b/core/io/zip_io.h @@ -39,8 +39,12 @@ #include "thirdparty/minizip/unzip.h" #include "thirdparty/minizip/zip.h" -void *zipio_open(void *data, const char *p_fname, int mode); -uLong zipio_read(void *data, void *fdata, void *buf, uLong size); +struct ZipIOData { + Ref<FileAccess> f; +}; + +void *zipio_open(voidpf opaque, const char *p_fname, int mode); +uLong zipio_read(voidpf opaque, voidpf stream, void *buf, uLong size); uLong zipio_write(voidpf opaque, voidpf stream, const void *buf, uLong size); long zipio_tell(voidpf opaque, voidpf stream); @@ -53,6 +57,6 @@ int zipio_testerror(voidpf opaque, voidpf stream); voidpf zipio_alloc(voidpf opaque, uInt items, uInt size); void zipio_free(voidpf opaque, voidpf address); -zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file); +zlib_filefunc_def zipio_create_io(); #endif // ZIP_IO_H diff --git a/core/math/basis.cpp b/core/math/basis.cpp index 84f9d12bb1..eb6703aff2 100644 --- a/core/math/basis.cpp +++ b/core/math/basis.cpp @@ -1002,7 +1002,7 @@ void Basis::rotate_sh(real_t *p_values) { const static real_t s_scale_dst2 = s_c3 * s_c_scale_inv; const static real_t s_scale_dst4 = s_c5 * s_c_scale_inv; - real_t src[9] = { p_values[0], p_values[1], p_values[2], p_values[3], p_values[4], p_values[5], p_values[6], p_values[7], p_values[8] }; + const real_t src[9] = { p_values[0], p_values[1], p_values[2], p_values[3], p_values[4], p_values[5], p_values[6], p_values[7], p_values[8] }; real_t m00 = elements[0][0]; real_t m01 = elements[0][1]; diff --git a/core/math/bvh.h b/core/math/bvh.h index f429ce189b..9f6ab9f736 100644 --- a/core/math/bvh.h +++ b/core/math/bvh.h @@ -763,19 +763,19 @@ private: tree._extra[p_handle.id()].last_updated_tick = 0; } - PairCallback pair_callback; - UnpairCallback unpair_callback; - CheckPairCallback check_pair_callback; - void *pair_callback_userdata; - void *unpair_callback_userdata; - void *check_pair_callback_userdata; + PairCallback pair_callback = nullptr; + UnpairCallback unpair_callback = nullptr; + CheckPairCallback check_pair_callback = nullptr; + void *pair_callback_userdata = nullptr; + void *unpair_callback_userdata = nullptr; + void *check_pair_callback_userdata = nullptr; BVHTREE_CLASS tree; // for collision pairing, // maintain a list of all items moved etc on each frame / tick LocalVector<BVHHandle, uint32_t, true> changed_items; - uint32_t _tick; + uint32_t _tick = 1; // Start from 1 so items with 0 indicate never updated. class BVHLockedFunction { public: @@ -801,23 +801,16 @@ private: } private: - Mutex *_mutex; + Mutex *_mutex = nullptr; }; Mutex _mutex; // local toggle for turning on and off thread safety in project settings - bool _thread_safe; + bool _thread_safe = BVH_THREAD_SAFE; public: - BVH_Manager() { - _tick = 1; // start from 1 so items with 0 indicate never updated - pair_callback = nullptr; - unpair_callback = nullptr; - pair_callback_userdata = nullptr; - unpair_callback_userdata = nullptr; - _thread_safe = BVH_THREAD_SAFE; - } + BVH_Manager() {} }; #undef BVHTREE_CLASS diff --git a/core/math/color.h b/core/math/color.h index b90a0f33a2..91e0bf5532 100644 --- a/core/math/color.h +++ b/core/math/color.h @@ -169,14 +169,14 @@ struct _NO_DISCARD_ Color { return res; } - _FORCE_INLINE_ Color to_linear() const { + _FORCE_INLINE_ Color srgb_to_linear() const { return Color( r < 0.04045f ? r * (1.0 / 12.92) : Math::pow((r + 0.055f) * (float)(1.0 / (1 + 0.055)), 2.4f), g < 0.04045f ? g * (1.0 / 12.92) : Math::pow((g + 0.055f) * (float)(1.0 / (1 + 0.055)), 2.4f), b < 0.04045f ? b * (1.0 / 12.92) : Math::pow((b + 0.055f) * (float)(1.0 / (1 + 0.055)), 2.4f), a); } - _FORCE_INLINE_ Color to_srgb() const { + _FORCE_INLINE_ Color linear_to_srgb() const { return Color( r < 0.0031308f ? 12.92f * r : (1.0f + 0.055f) * Math::pow(r, 1.0f / 2.4f) - 0.055f, g < 0.0031308f ? 12.92f * g : (1.0f + 0.055f) * Math::pow(g, 1.0f / 2.4f) - 0.055f, diff --git a/core/math/expression.h b/core/math/expression.h index 9b87bdd6ec..d43cc4091a 100644 --- a/core/math/expression.h +++ b/core/math/expression.h @@ -147,7 +147,7 @@ private: bool is_op = false; union { Variant::Operator op; - ENode *node; + ENode *node = nullptr; }; }; diff --git a/core/math/face3.cpp b/core/math/face3.cpp index 5bc1bc25e6..fb92f6b0df 100644 --- a/core/math/face3.cpp +++ b/core/math/face3.cpp @@ -208,7 +208,7 @@ bool Face3::intersects_aabb(const AABB &p_aabb) const { /** TEST ALL EDGES **/ - Vector3 edge_norms[3] = { + const Vector3 edge_norms[3] = { vertex[0] - vertex[1], vertex[1] - vertex[2], vertex[2] - vertex[0], diff --git a/core/math/face3.h b/core/math/face3.h index c61d6ad66e..23260336fa 100644 --- a/core/math/face3.h +++ b/core/math/face3.h @@ -133,7 +133,7 @@ bool Face3::intersects_aabb2(const AABB &p_aabb) const { #undef TEST_AXIS - Vector3 edge_norms[3] = { + const Vector3 edge_norms[3] = { vertex[0] - vertex[1], vertex[1] - vertex[2], vertex[2] - vertex[0], diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h index 44340b97ae..b741277872 100644 --- a/core/math/math_funcs.h +++ b/core/math/math_funcs.h @@ -473,16 +473,16 @@ public: uint32_t x = ci.ui; uint32_t sign = (unsigned short)(x >> 31); uint32_t mantissa; - uint32_t exp; + uint32_t exponent; uint16_t hf; // get mantissa mantissa = x & ((1 << 23) - 1); // get exponent bits - exp = x & (0xFF << 23); - if (exp >= 0x47800000) { + exponent = x & (0xFF << 23); + if (exponent >= 0x47800000) { // check if the original single precision float number is a NaN - if (mantissa && (exp == (0xFF << 23))) { + if (mantissa && (exponent == (0xFF << 23))) { // we have a single precision NaN mantissa = (1 << 23) - 1; } else { @@ -493,17 +493,18 @@ public: (uint16_t)(mantissa >> 13); } // check if exponent is <= -15 - else if (exp <= 0x38000000) { - /*// store a denorm half-float value or zero - exp = (0x38000000 - exp) >> 23; - mantissa >>= (14 + exp); - - hf = (((uint16_t)sign) << 15) | (uint16_t)(mantissa); - */ + else if (exponent <= 0x38000000) { + /* + // store a denorm half-float value or zero + exponent = (0x38000000 - exponent) >> 23; + mantissa >>= (14 + exponent); + + hf = (((uint16_t)sign) << 15) | (uint16_t)(mantissa); + */ hf = 0; //denormals do not work for 3D, convert to zero } else { hf = (((uint16_t)sign) << 15) | - (uint16_t)((exp - 0x38000000) >> 13) | + (uint16_t)((exponent - 0x38000000) >> 13) | (uint16_t)(mantissa >> 13); } diff --git a/core/math/octree.h b/core/math/octree.h index e73f8213b3..65ab9e2292 100644 --- a/core/math/octree.h +++ b/core/math/octree.h @@ -134,7 +134,7 @@ private: List<PairData *, AL> pair_list; struct OctantOwner { - Octant *octant; + Octant *octant = nullptr; typename List<Element *, AL>::Element *E; }; // an element can be in max 8 octants @@ -147,7 +147,7 @@ private: int refcount; bool intersect; Element *A, *B; - void *ud; + void *ud = nullptr; typename List<PairData *, AL>::Element *eA, *eB; }; @@ -156,18 +156,18 @@ private: ElementMap element_map; PairMap pair_map; - PairCallback pair_callback; - UnpairCallback unpair_callback; - void *pair_callback_userdata; - void *unpair_callback_userdata; + PairCallback pair_callback = nullptr; + UnpairCallback unpair_callback = nullptr; + void *pair_callback_userdata = nullptr; + void *unpair_callback_userdata = nullptr; - OctreeElementID last_element_id; - uint64_t pass; + OctreeElementID last_element_id = 1; + uint64_t pass = 1; - real_t unit_size; - Octant *root; - int octant_count; - int pair_count; + real_t unit_size = 1.0; + Octant *root = nullptr; + int octant_count = 0; + int pair_count = 0; _FORCE_INLINE_ void _pair_check(PairData *p_pair) { bool intersect = p_pair->A->aabb.intersects_inclusive(p_pair->B->aabb); @@ -294,7 +294,7 @@ private: const Vector3 *points; int point_count; T **result_array; - int *result_idx; + int *result_idx = nullptr; int result_max; uint32_t mask; }; @@ -1265,18 +1265,7 @@ void Octree<T, use_pairs, AL>::set_unpair_callback(UnpairCallback p_callback, vo template <class T, bool use_pairs, class AL> Octree<T, use_pairs, AL>::Octree(real_t p_unit_size) { - last_element_id = 1; - pass = 1; unit_size = p_unit_size; - root = nullptr; - - octant_count = 0; - pair_count = 0; - - pair_callback = nullptr; - unpair_callback = nullptr; - pair_callback_userdata = nullptr; - unpair_callback_userdata = nullptr; } #endif // OCTREE_H diff --git a/core/math/triangle_mesh.cpp b/core/math/triangle_mesh.cpp index debc5cd00d..e146c4a4e3 100644 --- a/core/math/triangle_mesh.cpp +++ b/core/math/triangle_mesh.cpp @@ -231,14 +231,14 @@ Vector3 TriangleMesh::get_area_normal(const AABB &p_aabb) const { } case VISIT_LEFT_BIT: { stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.left | TEST_AABB_BIT; level++; + stack[level] = b.left | TEST_AABB_BIT; continue; } case VISIT_RIGHT_BIT: { stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.right | TEST_AABB_BIT; level++; + stack[level] = b.right | TEST_AABB_BIT; continue; } case VISIT_DONE_BIT: { @@ -331,14 +331,14 @@ bool TriangleMesh::intersect_segment(const Vector3 &p_begin, const Vector3 &p_en } case VISIT_LEFT_BIT: { stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.left | TEST_AABB_BIT; level++; + stack[level] = b.left | TEST_AABB_BIT; continue; } case VISIT_RIGHT_BIT: { stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.right | TEST_AABB_BIT; level++; + stack[level] = b.right | TEST_AABB_BIT; continue; } case VISIT_DONE_BIT: { @@ -431,14 +431,14 @@ bool TriangleMesh::intersect_ray(const Vector3 &p_begin, const Vector3 &p_dir, V } case VISIT_LEFT_BIT: { stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.left | TEST_AABB_BIT; level++; + stack[level] = b.left | TEST_AABB_BIT; continue; } case VISIT_RIGHT_BIT: { stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.right | TEST_AABB_BIT; level++; + stack[level] = b.right | TEST_AABB_BIT; continue; } case VISIT_DONE_BIT: { @@ -551,14 +551,14 @@ bool TriangleMesh::intersect_convex_shape(const Plane *p_planes, int p_plane_cou } case VISIT_LEFT_BIT: { stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.left | TEST_AABB_BIT; level++; + stack[level] = b.left | TEST_AABB_BIT; continue; } case VISIT_RIGHT_BIT: { stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.right | TEST_AABB_BIT; level++; + stack[level] = b.right | TEST_AABB_BIT; continue; } case VISIT_DONE_BIT: { @@ -644,14 +644,14 @@ bool TriangleMesh::inside_convex_shape(const Plane *p_planes, int p_plane_count, } case VISIT_LEFT_BIT: { stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.left | TEST_AABB_BIT; level++; + stack[level] = b.left | TEST_AABB_BIT; continue; } case VISIT_RIGHT_BIT: { stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node; - stack[level + 1] = b.right | TEST_AABB_BIT; level++; + stack[level] = b.right | TEST_AABB_BIT; continue; } case VISIT_DONE_BIT: { diff --git a/core/object/callable_method_pointer.h b/core/object/callable_method_pointer.h index 3cd9ad3819..577d4b9fbd 100644 --- a/core/object/callable_method_pointer.h +++ b/core/object/callable_method_pointer.h @@ -38,7 +38,7 @@ #include "core/variant/callable.h" class CallableCustomMethodPointerBase : public CallableCustom { - uint32_t *comp_ptr; + uint32_t *comp_ptr = nullptr; uint32_t comp_size; uint32_t h; #ifdef DEBUG_METHODS_ENABLED diff --git a/core/object/class_db.h b/core/object/class_db.h index b8a4b3ea2b..5da8523743 100644 --- a/core/object/class_db.h +++ b/core/object/class_db.h @@ -85,8 +85,8 @@ public: int index; StringName setter; StringName getter; - MethodBind *_setptr; - MethodBind *_getptr; + MethodBind *_setptr = nullptr; + MethodBind *_getptr = nullptr; Variant::Type type; }; diff --git a/core/object/message_queue.h b/core/object/message_queue.h index eaab01d0aa..2219cdb8f6 100644 --- a/core/object/message_queue.h +++ b/core/object/message_queue.h @@ -62,10 +62,10 @@ class MessageQueue { }; }; - uint8_t *buffer; + uint8_t *buffer = nullptr; uint32_t buffer_end = 0; uint32_t buffer_max_used = 0; - uint32_t buffer_size; + uint32_t buffer_size = 0; void _call_function(const Callable &p_callable, const Variant *p_args, int p_argcount, bool p_show_error); diff --git a/core/object/object.cpp b/core/object/object.cpp index c2cd42ff91..897b5d18de 100644 --- a/core/object/object.cpp +++ b/core/object/object.cpp @@ -1848,6 +1848,13 @@ Object::Object() { _construct_object(false); } +void Object::detach_from_objectdb() { + if (_instance_id != ObjectID()) { + ObjectDB::remove_instance(this); + _instance_id = ObjectID(); + } +} + Object::~Object() { if (script_instance) { memdelete(script_instance); @@ -1887,8 +1894,10 @@ Object::~Object() { c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true); } - ObjectDB::remove_instance(this); - _instance_id = ObjectID(); + if (_instance_id != ObjectID()) { + ObjectDB::remove_instance(this); + _instance_id = ObjectID(); + } _predelete_ok = 2; if (_instance_bindings != nullptr) { diff --git a/core/object/object.h b/core/object/object.h index b640c4e78a..c3e3c68b59 100644 --- a/core/object/object.h +++ b/core/object/object.h @@ -538,8 +538,8 @@ private: std::mutex _instance_binding_mutex; struct InstanceBinding { - void *binding; - void *token; + void *binding = nullptr; + void *token = nullptr; GDNativeInstanceBindingFreeCallback free_callback = nullptr; GDNativeInstanceBindingReferenceCallback reference_callback = nullptr; }; @@ -633,6 +633,7 @@ public: bool _is_gpl_reversed() const { return false; } + void detach_from_objectdb(); _FORCE_INLINE_ ObjectID get_instance_id() const { return _instance_id; } template <class T> @@ -849,7 +850,7 @@ class ObjectDB { uint64_t validator : OBJECTDB_VALIDATOR_BITS; uint64_t next_free : OBJECTDB_SLOT_MAX_COUNT_BITS; uint64_t is_ref_counted : 1; - Object *object; + Object *object = nullptr; }; static SpinLock spin_lock; diff --git a/core/object/ref_counted.h b/core/object/ref_counted.h index 8eb1c97cce..dcacf19890 100644 --- a/core/object/ref_counted.h +++ b/core/object/ref_counted.h @@ -261,7 +261,7 @@ struct PtrToArg<Ref<T>> { typedef Ref<T> EncodeT; _FORCE_INLINE_ static void encode(Ref<T> p_val, const void *p_ptr) { - *(Ref<RefCounted> *)p_ptr = p_val; + *(const_cast<Ref<RefCounted> *>(reinterpret_cast<const Ref<RefCounted> *>(p_ptr))) = p_val; } }; diff --git a/core/object/script_language.cpp b/core/object/script_language.cpp index 11440c37fe..a5d25bf533 100644 --- a/core/object/script_language.cpp +++ b/core/object/script_language.cpp @@ -144,7 +144,7 @@ void ScriptServer::register_language(ScriptLanguage *p_language) { _languages[_language_count++] = p_language; } -void ScriptServer::unregister_language(ScriptLanguage *p_language) { +void ScriptServer::unregister_language(const ScriptLanguage *p_language) { for (int i = 0; i < _language_count; i++) { if (_languages[i] == p_language) { _language_count--; diff --git a/core/object/script_language.h b/core/object/script_language.h index af4f276825..69002c81f4 100644 --- a/core/object/script_language.h +++ b/core/object/script_language.h @@ -68,7 +68,7 @@ public: _FORCE_INLINE_ static int get_language_count() { return _language_count; } static ScriptLanguage *get_language(int p_idx); static void register_language(ScriptLanguage *p_language); - static void unregister_language(ScriptLanguage *p_language); + static void unregister_language(const ScriptLanguage *p_language); static void set_reload_scripts_on_save(bool p_enable); static bool is_reload_scripts_on_save_enabled(); @@ -430,42 +430,42 @@ public: extern uint8_t script_encryption_key[32]; class PlaceHolderScriptInstance : public ScriptInstance { - Object *owner; + Object *owner = nullptr; List<PropertyInfo> properties; Map<StringName, Variant> values; Map<StringName, Variant> constants; - ScriptLanguage *language; + ScriptLanguage *language = nullptr; Ref<Script> script; public: - virtual bool set(const StringName &p_name, const Variant &p_value); - virtual bool get(const StringName &p_name, Variant &r_ret) const; - virtual void get_property_list(List<PropertyInfo> *p_properties) const; - virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = nullptr) const; + virtual bool set(const StringName &p_name, const Variant &p_value) override; + virtual bool get(const StringName &p_name, Variant &r_ret) const override; + virtual void get_property_list(List<PropertyInfo> *p_properties) const override; + virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = nullptr) const override; - virtual void get_method_list(List<MethodInfo> *p_list) const; - virtual bool has_method(const StringName &p_method) const; + virtual void get_method_list(List<MethodInfo> *p_list) const override; + virtual bool has_method(const StringName &p_method) const override; - virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { + virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); } - virtual void notification(int p_notification) {} + virtual void notification(int p_notification) override {} - virtual Ref<Script> get_script() const { return script; } + virtual Ref<Script> get_script() const override { return script; } - virtual ScriptLanguage *get_language() { return language; } + virtual ScriptLanguage *get_language() override { return language; } - Object *get_owner() { return owner; } + Object *get_owner() override { return owner; } void update(const List<PropertyInfo> &p_properties, const Map<StringName, Variant> &p_values); //likely changed in editor - virtual bool is_placeholder() const { return true; } + virtual bool is_placeholder() const override { return true; } - virtual void property_set_fallback(const StringName &p_name, const Variant &p_value, bool *r_valid = nullptr); - virtual Variant property_get_fallback(const StringName &p_name, bool *r_valid = nullptr); + virtual void property_set_fallback(const StringName &p_name, const Variant &p_value, bool *r_valid = nullptr) override; + virtual Variant property_get_fallback(const StringName &p_name, bool *r_valid = nullptr) override; - virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const { return Vector<Multiplayer::RPCConfig>(); } + virtual const Vector<Multiplayer::RPCConfig> get_rpc_methods() const override { return Vector<Multiplayer::RPCConfig>(); } PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script, Object *p_owner); ~PlaceHolderScriptInstance(); diff --git a/core/os/memory.h b/core/os/memory.h index 27eaad5010..baa96ef3e9 100644 --- a/core/os/memory.h +++ b/core/os/memory.h @@ -186,9 +186,9 @@ void memdelete_arr(T *p_class) { struct _GlobalNil { int color = 1; - _GlobalNil *right; - _GlobalNil *left; - _GlobalNil *parent; + _GlobalNil *right = nullptr; + _GlobalNil *left = nullptr; + _GlobalNil *parent = nullptr; _GlobalNil(); }; diff --git a/core/os/os.cpp b/core/os/os.cpp index 2e5db145a4..846aeb16c5 100644 --- a/core/os/os.cpp +++ b/core/os/os.cpp @@ -80,7 +80,9 @@ void OS::print_error(const char *p_function, const char *p_file, int p_line, con return; } - _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type); + if (_logger) { + _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type); + } } void OS::print(const char *p_format, ...) { @@ -91,7 +93,9 @@ void OS::print(const char *p_format, ...) { va_list argp; va_start(argp, p_format); - _logger->logv(p_format, argp, false); + if (_logger) { + _logger->logv(p_format, argp, false); + } va_end(argp); } @@ -104,7 +108,9 @@ void OS::printerr(const char *p_format, ...) { va_list argp; va_start(argp, p_format); - _logger->logv(p_format, argp, true); + if (_logger) { + _logger->logv(p_format, argp, true); + } va_end(argp); } @@ -173,7 +179,7 @@ void OS::dump_memory_to_file(const char *p_file) { //Memory::dump_static_mem_to_file(p_file); } -static FileAccess *_OSPRF = nullptr; +static Ref<FileAccess> _OSPRF; static void _OS_printres(Object *p_obj) { Resource *res = Object::cast_to<Resource>(p_obj); @@ -182,7 +188,7 @@ static void _OS_printres(Object *p_obj) { } String str = vformat("%s - %s - %s", res->to_string(), res->get_name(), res->get_path()); - if (_OSPRF) { + if (_OSPRF.is_valid()) { _OSPRF->store_line(str); } else { print_line(str); @@ -190,24 +196,19 @@ static void _OS_printres(Object *p_obj) { } void OS::print_all_resources(String p_to_file) { - ERR_FAIL_COND(!p_to_file.is_empty() && _OSPRF); + ERR_FAIL_COND(!p_to_file.is_empty() && _OSPRF.is_valid()); if (!p_to_file.is_empty()) { Error err; _OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err); if (err != OK) { - _OSPRF = nullptr; + _OSPRF.unref(); ERR_FAIL_MSG("Can't print all resources to file: " + String(p_to_file) + "."); } } ObjectDB::debug_objects(_OS_printres); - if (!p_to_file.is_empty()) { - if (_OSPRF) { - memdelete(_OSPRF); - } - _OSPRF = nullptr; - } + _OSPRF.unref(); } void OS::print_resources_in_use(bool p_short) { @@ -332,7 +333,7 @@ void OS::ensure_user_data_dir() { return; } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = da->make_dir_recursive(dd); ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + "."); } @@ -550,6 +551,8 @@ OS::OS() { } OS::~OS() { - memdelete(_logger); + if (_logger) { + memdelete(_logger); + } singleton = nullptr; } diff --git a/core/os/os.h b/core/os/os.h index 808d704b3d..b3c66ff18c 100644 --- a/core/os/os.h +++ b/core/os/os.h @@ -60,8 +60,6 @@ class OS { bool _stdout_enabled = true; bool _stderr_enabled = true; - char *last_error; - CompositeLogger *_logger = nullptr; bool restart_on_exit = false; diff --git a/core/os/pool_allocator.cpp b/core/os/pool_allocator.cpp index 190617f967..f622e2c7c5 100644 --- a/core/os/pool_allocator.cpp +++ b/core/os/pool_allocator.cpp @@ -149,7 +149,7 @@ void PoolAllocator::compact_up(int p_from) { } } -bool PoolAllocator::find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry) { +bool PoolAllocator::find_entry_index(EntryIndicesPos *p_map_pos, const Entry *p_entry) { EntryArrayPos entry_pos = entry_max; for (int i = 0; i < entry_count; i++) { @@ -424,7 +424,7 @@ bool PoolAllocator::is_locked(ID p_mem) const { } mt_lock(); - const Entry *e = ((PoolAllocator *)(this))->get_entry(p_mem); + const Entry *e = const_cast<PoolAllocator *>(this)->get_entry(p_mem); if (!e) { mt_unlock(); ERR_PRINT("!e"); diff --git a/core/os/pool_allocator.h b/core/os/pool_allocator.h index 11a252bc54..27a936ed78 100644 --- a/core/os/pool_allocator.h +++ b/core/os/pool_allocator.h @@ -75,13 +75,13 @@ private: typedef int EntryArrayPos; typedef int EntryIndicesPos; - Entry *entry_array; - int *entry_indices; + Entry *entry_array = nullptr; + int *entry_indices = nullptr; int entry_max; int entry_count; - uint8_t *pool; - void *mem_ptr; + uint8_t *pool = nullptr; + void *mem_ptr = nullptr; int pool_size; int free_mem; @@ -108,7 +108,7 @@ private: void compact_up(int p_from = 0); bool get_free_entry(EntryArrayPos *p_pos); bool find_hole(EntryArrayPos *p_pos, int p_for_size); - bool find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry); + bool find_entry_index(EntryIndicesPos *p_map_pos, const Entry *p_entry); Entry *get_entry(ID p_mem); const Entry *get_entry(ID p_mem) const; diff --git a/core/string/print_string.cpp b/core/string/print_string.cpp index 97e119bcf6..919c9e08e3 100644 --- a/core/string/print_string.cpp +++ b/core/string/print_string.cpp @@ -45,7 +45,7 @@ void add_print_handler(PrintHandlerList *p_handler) { _global_unlock(); } -void remove_print_handler(PrintHandlerList *p_handler) { +void remove_print_handler(const PrintHandlerList *p_handler) { _global_lock(); PrintHandlerList *prev = nullptr; diff --git a/core/string/print_string.h b/core/string/print_string.h index 669d2ea316..f7d0f25030 100644 --- a/core/string/print_string.h +++ b/core/string/print_string.h @@ -54,13 +54,21 @@ String stringify_variants(Variant p_var, Args... p_args) { } void add_print_handler(PrintHandlerList *p_handler); -void remove_print_handler(PrintHandlerList *p_handler); +void remove_print_handler(const PrintHandlerList *p_handler); extern bool _print_line_enabled; extern bool _print_error_enabled; extern void __print_line(String p_string); extern void print_error(String p_string); extern void print_verbose(String p_string); -#define print_line(...) __print_line(stringify_variants(__VA_ARGS__)) + +inline void print_line(Variant v) { + __print_line(stringify_variants(v)); +} + +template <typename... Args> +void print_line(Variant p_var, Args... p_args) { + __print_line(stringify_variants(p_var, p_args...)); +} #endif // PRINT_STRING_H diff --git a/core/string/string_name.h b/core/string/string_name.h index 6f08d32981..f4233854ac 100644 --- a/core/string/string_name.h +++ b/core/string/string_name.h @@ -70,7 +70,7 @@ class StringName { _Data *_data = nullptr; union _HashUnion { - _Data *ptr; + _Data *ptr = nullptr; uint32_t hash; }; diff --git a/core/string/translation.cpp b/core/string/translation.cpp index c41828de05..d6d361b5f1 100644 --- a/core/string/translation.cpp +++ b/core/string/translation.cpp @@ -891,7 +891,7 @@ String TranslationServer::wrap_with_fakebidi_characters(String &p_message) const return res; } -String TranslationServer::add_padding(String &p_message, int p_length) const { +String TranslationServer::add_padding(const String &p_message, int p_length) const { String res; String prefix = pseudolocalization_prefix; String suffix; @@ -921,7 +921,7 @@ const char32_t *TranslationServer::get_accented_version(char32_t p_character) co } bool TranslationServer::is_placeholder(String &p_message, int p_index) const { - return p_message[p_index] == '%' && p_index < p_message.size() - 1 && + return p_index < p_message.size() - 1 && p_message[p_index] == '%' && (p_message[p_index + 1] == 's' || p_message[p_index + 1] == 'c' || p_message[p_index + 1] == 'd' || p_message[p_index + 1] == 'o' || p_message[p_index + 1] == 'x' || p_message[p_index + 1] == 'X' || p_message[p_index + 1] == 'f'); } diff --git a/core/string/translation.h b/core/string/translation.h index 947ca4c6d8..ded6ed5925 100644 --- a/core/string/translation.h +++ b/core/string/translation.h @@ -96,7 +96,7 @@ class TranslationServer : public Object { String double_vowels(String &p_message) const; String replace_with_accented_string(String &p_message) const; String wrap_with_fakebidi_characters(String &p_message) const; - String add_padding(String &p_message, int p_length) const; + String add_padding(const String &p_message, int p_length) const; const char32_t *get_accented_version(char32_t p_character) const; bool is_placeholder(String &p_message, int p_index) const; diff --git a/core/string/translation_po.cpp b/core/string/translation_po.cpp index 1c991ee12d..3f94e064ec 100644 --- a/core/string/translation_po.cpp +++ b/core/string/translation_po.cpp @@ -35,7 +35,7 @@ #ifdef DEBUG_TRANSLATION_PO void TranslationPO::print_translation_map() { Error err; - FileAccess *file = FileAccess::open("translation_map_print_test.txt", FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open("translation_map_print_test.txt", FileAccess::WRITE, &err); if (err != OK) { ERR_PRINT("Failed to open translation_map_print_test.txt"); return; @@ -62,7 +62,6 @@ void TranslationPO::print_translation_map() { file->store_line(""); } } - file->close(); } #endif diff --git a/core/templates/command_queue_mt.h b/core/templates/command_queue_mt.h index 1ecb81c2a2..7d3e31b5bc 100644 --- a/core/templates/command_queue_mt.h +++ b/core/templates/command_queue_mt.h @@ -215,7 +215,7 @@ T *instance; \ M method; \ SEMIC_SEP_LIST(PARAM_DECL, N); \ - virtual void call() { \ + virtual void call() override { \ (instance->*method)(COMMA_SEP_LIST(ARG, N)); \ } \ }; @@ -227,7 +227,7 @@ T *instance; \ M method; \ SEMIC_SEP_LIST(PARAM_DECL, N); \ - virtual void call() { \ + virtual void call() override { \ *ret = (instance->*method)(COMMA_SEP_LIST(ARG, N)); \ } \ }; @@ -238,7 +238,7 @@ T *instance; \ M method; \ SEMIC_SEP_LIST(PARAM_DECL, N); \ - virtual void call() { \ + virtual void call() override { \ (instance->*method)(COMMA_SEP_LIST(ARG, N)); \ } \ }; @@ -311,9 +311,9 @@ class CommandQueueMT { }; struct SyncCommand : public CommandBase { - SyncSemaphore *sync_sem; + SyncSemaphore *sync_sem = nullptr; - virtual void post() { + virtual void post() override { sync_sem->sem.post(); } }; diff --git a/core/templates/cowdata.h b/core/templates/cowdata.h index 326616b607..f1ac32928f 100644 --- a/core/templates/cowdata.h +++ b/core/templates/cowdata.h @@ -86,13 +86,6 @@ private: return reinterpret_cast<uint32_t *>(_ptr) - 1; } - _FORCE_INLINE_ T *_get_data() const { - if (!_ptr) { - return nullptr; - } - return reinterpret_cast<T *>(_ptr); - } - _FORCE_INLINE_ size_t _get_alloc_size(size_t p_elements) const { return next_power_of_2(p_elements * sizeof(T)); } @@ -128,11 +121,11 @@ public: _FORCE_INLINE_ T *ptrw() { _copy_on_write(); - return (T *)_get_data(); + return _ptr; } _FORCE_INLINE_ const T *ptr() const { - return _get_data(); + return _ptr; } _FORCE_INLINE_ int size() const { @@ -150,19 +143,19 @@ public: _FORCE_INLINE_ void set(int p_index, const T &p_elem) { ERR_FAIL_INDEX(p_index, size()); _copy_on_write(); - _get_data()[p_index] = p_elem; + _ptr[p_index] = p_elem; } _FORCE_INLINE_ T &get_m(int p_index) { CRASH_BAD_INDEX(p_index, size()); _copy_on_write(); - return _get_data()[p_index]; + return _ptr[p_index]; } _FORCE_INLINE_ const T &get(int p_index) const { CRASH_BAD_INDEX(p_index, size()); - return _get_data()[p_index]; + return _ptr[p_index]; } Error resize(int p_size); @@ -249,7 +242,7 @@ uint32_t CowData<T>::_copy_on_write() { } else { for (uint32_t i = 0; i < current_size; i++) { - memnew_placement(&_data[i], T(_get_data()[i])); + memnew_placement(&_data[i], T(_ptr[i])); } } @@ -308,10 +301,8 @@ Error CowData<T>::resize(int p_size) { // construct the newly created elements if (!__has_trivial_constructor(T)) { - T *elems = _get_data(); - for (int i = *_get_size(); i < p_size; i++) { - memnew_placement(&elems[i], T); + memnew_placement(&_ptr[i], T); } } @@ -321,7 +312,7 @@ Error CowData<T>::resize(int p_size) { if (!__has_trivial_destructor(T)) { // deinitialize no longer needed elements for (uint32_t i = p_size; i < *_get_size(); i++) { - T *t = &_get_data()[i]; + T *t = &_ptr[i]; t->~T(); } } diff --git a/core/templates/map.h b/core/templates/map.h index f228640a1e..c54da1dc03 100644 --- a/core/templates/map.h +++ b/core/templates/map.h @@ -178,7 +178,7 @@ public: private: struct _Data { Element *_root = nullptr; - Element *_nil; + Element *_nil = nullptr; int size_cache = 0; _FORCE_INLINE_ _Data() { @@ -344,7 +344,7 @@ private: void _insert_rb_fix(Element *p_new_node) { Element *node = p_new_node; Element *nparent = node->parent; - Element *ngrand_parent; + Element *ngrand_parent = nullptr; while (nparent->color == RED) { ngrand_parent = nparent->parent; @@ -500,7 +500,7 @@ private: Element *rp = ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : p_node->_next; Element *node = (rp->left == _data._nil) ? rp->right : rp->left; - Element *sibling; + Element *sibling = nullptr; if (rp == rp->parent->left) { rp->parent->left = node; sibling = rp->parent->right; diff --git a/core/templates/oa_hash_map.h b/core/templates/oa_hash_map.h index 4e712fccf2..e4d9323c45 100644 --- a/core/templates/oa_hash_map.h +++ b/core/templates/oa_hash_map.h @@ -306,7 +306,7 @@ public: bool valid; const TKey *key; - TValue *value; + TValue *value = nullptr; private: uint32_t pos; diff --git a/core/templates/safe_list.h b/core/templates/safe_list.h index 53fc3fe5f9..e850f3bd5e 100644 --- a/core/templates/safe_list.h +++ b/core/templates/safe_list.h @@ -75,8 +75,8 @@ public: class Iterator { friend class SafeList; - SafeListNode *cursor; - SafeList *list; + SafeListNode *cursor = nullptr; + SafeList *list = nullptr; Iterator(SafeListNode *p_cursor, SafeList *p_list) : cursor(p_cursor), list(p_list) { @@ -203,7 +203,7 @@ public: } // Calling this will cause zero to many deallocations. - void maybe_cleanup() { + bool maybe_cleanup() { SafeListNode *cursor = nullptr; SafeListNode *new_graveyard_head = nullptr; do { @@ -212,7 +212,7 @@ public: if (active_iterator_count.load() != 0) { // It's not safe to clean up with an active iterator, because that iterator // could be pointing to an element that we want to delete. - return; + return false; } // Any iterator created after this point will never point to a deleted node. // Swap it out with the current graveyard head. @@ -225,6 +225,17 @@ public: tmp->deletion_fn(tmp->val); memdelete_allocator<SafeListNode, A>(tmp); } + return true; + } + + ~SafeList() { +#ifdef DEBUG_ENABLED + if (!maybe_cleanup()) { + ERR_PRINT("There are still iterators around when destructing a SafeList. Memory will be leaked. This is a bug."); + } +#else + maybe_cleanup(); +#endif } }; @@ -253,8 +264,8 @@ public: class Iterator { friend class SafeList; - SafeListNode *cursor; - SafeList *list; + SafeListNode *cursor = nullptr; + SafeList *list = nullptr; public: Iterator(SafeListNode *p_cursor, SafeList *p_list) : @@ -353,11 +364,11 @@ public: } // Calling this will cause zero to many deallocations. - void maybe_cleanup() { + bool maybe_cleanup() { SafeListNode *cursor = graveyard_head; if (active_iterator_count != 0) { // It's not safe to clean up with an active iterator, because that iterator could be pointing to an element that we want to delete. - return; + return false; } graveyard_head = nullptr; // Our graveyard list is now unreachable by any active iterators, detached from the main graveyard head and ready for deletion. @@ -367,6 +378,17 @@ public: tmp->deletion_fn(tmp->val); memdelete_allocator<SafeListNode, A>(tmp); } + return true; + } + + ~SafeList() { +#ifdef DEBUG_ENABLED + if (!maybe_cleanup()) { + ERR_PRINT("There are still iterators around when destructing a SafeList. Memory will be leaked. This is a bug."); + } +#else + maybe_cleanup(); +#endif } }; diff --git a/core/templates/self_list.h b/core/templates/self_list.h index 7f2236fa3a..719b5f2e63 100644 --- a/core/templates/self_list.h +++ b/core/templates/self_list.h @@ -108,7 +108,7 @@ public: private: List *_root = nullptr; - T *_self; + T *_self = nullptr; SelfList<T> *_next = nullptr; SelfList<T> *_prev = nullptr; diff --git a/core/templates/set.h b/core/templates/set.h index cdc6e8447d..a8a0a77712 100644 --- a/core/templates/set.h +++ b/core/templates/set.h @@ -328,7 +328,7 @@ private: void _insert_rb_fix(Element *p_new_node) { Element *node = p_new_node; Element *nparent = node->parent; - Element *ngrand_parent; + Element *ngrand_parent = nullptr; while (nparent->color == RED) { ngrand_parent = nparent->parent; @@ -482,7 +482,7 @@ private: Element *rp = ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : p_node->_next; Element *node = (rp->left == _data._nil) ? rp->right : rp->left; - Element *sibling; + Element *sibling = nullptr; if (rp == rp->parent->left) { rp->parent->left = node; sibling = rp->parent->right; diff --git a/core/templates/thread_work_pool.h b/core/templates/thread_work_pool.h index 957af44f48..b0cebf04f1 100644 --- a/core/templates/thread_work_pool.h +++ b/core/templates/thread_work_pool.h @@ -52,7 +52,7 @@ class ThreadWorkPool { C *instance; M method; U userdata; - virtual void work() { + virtual void work() override { while (true) { uint32_t work_index = index->fetch_add(1, std::memory_order_relaxed); if (work_index >= max_elements) { @@ -68,7 +68,7 @@ class ThreadWorkPool { Semaphore start; Semaphore completed; std::atomic<bool> exit; - BaseWork *work; + BaseWork *work = nullptr; }; ThreadData *threads = nullptr; diff --git a/core/variant/callable_bind.cpp b/core/variant/callable_bind.cpp index 797e8afede..1a400b4360 100644 --- a/core/variant/callable_bind.cpp +++ b/core/variant/callable_bind.cpp @@ -40,8 +40,8 @@ String CallableCustomBind::get_as_text() const { } bool CallableCustomBind::_equal_func(const CallableCustom *p_a, const CallableCustom *p_b) { - const CallableCustomBind *a = (const CallableCustomBind *)p_a; - const CallableCustomBind *b = (const CallableCustomBind *)p_b; + const CallableCustomBind *a = static_cast<const CallableCustomBind *>(p_a); + const CallableCustomBind *b = static_cast<const CallableCustomBind *>(p_b); if (!(a->callable != b->callable)) { return false; @@ -55,8 +55,8 @@ bool CallableCustomBind::_equal_func(const CallableCustom *p_a, const CallableCu } bool CallableCustomBind::_less_func(const CallableCustom *p_a, const CallableCustom *p_b) { - const CallableCustomBind *a = (const CallableCustomBind *)p_a; - const CallableCustomBind *b = (const CallableCustomBind *)p_b; + const CallableCustomBind *a = static_cast<const CallableCustomBind *>(p_a); + const CallableCustomBind *b = static_cast<const CallableCustomBind *>(p_b); if (a->callable < b->callable) { return true; @@ -117,8 +117,8 @@ String CallableCustomUnbind::get_as_text() const { } bool CallableCustomUnbind::_equal_func(const CallableCustom *p_a, const CallableCustom *p_b) { - const CallableCustomUnbind *a = (const CallableCustomUnbind *)p_a; - const CallableCustomUnbind *b = (const CallableCustomUnbind *)p_b; + const CallableCustomUnbind *a = static_cast<const CallableCustomUnbind *>(p_a); + const CallableCustomUnbind *b = static_cast<const CallableCustomUnbind *>(p_b); if (!(a->callable != b->callable)) { return false; @@ -132,8 +132,8 @@ bool CallableCustomUnbind::_equal_func(const CallableCustom *p_a, const Callable } bool CallableCustomUnbind::_less_func(const CallableCustom *p_a, const CallableCustom *p_b) { - const CallableCustomUnbind *a = (const CallableCustomUnbind *)p_a; - const CallableCustomUnbind *b = (const CallableCustomUnbind *)p_b; + const CallableCustomUnbind *a = static_cast<const CallableCustomUnbind *>(p_a); + const CallableCustomUnbind *b = static_cast<const CallableCustomUnbind *>(p_b); if (a->callable < b->callable) { return true; diff --git a/core/variant/callable_bind.h b/core/variant/callable_bind.h index 4f79a29629..a5c830e109 100644 --- a/core/variant/callable_bind.h +++ b/core/variant/callable_bind.h @@ -43,14 +43,14 @@ class CallableCustomBind : public CallableCustom { public: //for every type that inherits, these must always be the same for this type - virtual uint32_t hash() const; - virtual String get_as_text() const; - virtual CompareEqualFunc get_compare_equal_func() const; - virtual CompareLessFunc get_compare_less_func() const; - virtual StringName get_method() const; - virtual ObjectID get_object() const; //must always be able to provide an object - virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const; - virtual const Callable *get_base_comparator() const; + virtual uint32_t hash() const override; + virtual String get_as_text() const override; + virtual CompareEqualFunc get_compare_equal_func() const override; + virtual CompareLessFunc get_compare_less_func() const override; + virtual StringName get_method() const override; + virtual ObjectID get_object() const override; //must always be able to provide an object + virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override; + virtual const Callable *get_base_comparator() const override; Callable get_callable() { return callable; } Vector<Variant> get_binds() { return binds; } @@ -68,14 +68,14 @@ class CallableCustomUnbind : public CallableCustom { public: //for every type that inherits, these must always be the same for this type - virtual uint32_t hash() const; - virtual String get_as_text() const; - virtual CompareEqualFunc get_compare_equal_func() const; - virtual CompareLessFunc get_compare_less_func() const; - virtual StringName get_method() const; - virtual ObjectID get_object() const; //must always be able to provide an object - virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const; - virtual const Callable *get_base_comparator() const; + virtual uint32_t hash() const override; + virtual String get_as_text() const override; + virtual CompareEqualFunc get_compare_equal_func() const override; + virtual CompareLessFunc get_compare_less_func() const override; + virtual StringName get_method() const override; + virtual ObjectID get_object() const override; //must always be able to provide an object + virtual void call(const Variant **p_arguments, int p_argcount, Variant &r_return_value, Callable::CallError &r_call_error) const override; + virtual const Callable *get_base_comparator() const override; Callable get_callable() { return callable; } int get_unbinds() { return argcount; } diff --git a/core/variant/variant.h b/core/variant/variant.h index ca18249f36..475bf7158d 100644 --- a/core/variant/variant.h +++ b/core/variant/variant.h @@ -511,6 +511,7 @@ public: Variant recursive_duplicate(bool p_deep, int recursion_count) const; static void blend(const Variant &a, const Variant &b, float c, Variant &r_dst); static void interpolate(const Variant &a, const Variant &b, float c, Variant &r_dst); + static void sub(const Variant &a, const Variant &b, Variant &r_dst); /* Built-In Methods */ diff --git a/core/variant/variant_call.cpp b/core/variant/variant_call.cpp index c11925fa8c..f1daf1de13 100644 --- a/core/variant/variant_call.cpp +++ b/core/variant/variant_call.cpp @@ -1656,8 +1656,8 @@ static void _register_variant_builtin_methods() { bind_method(Color, darkened, sarray("amount"), varray()); bind_method(Color, blend, sarray("over"), varray()); bind_method(Color, get_luminance, sarray(), varray()); - bind_method(Color, to_linear, sarray(), varray()); - bind_method(Color, to_srgb, sarray(), varray()); + bind_method(Color, srgb_to_linear, sarray(), varray()); + bind_method(Color, linear_to_srgb, sarray(), varray()); bind_method(Color, is_equal_approx, sarray("to"), varray()); diff --git a/core/variant/variant_parser.h b/core/variant/variant_parser.h index e5585076c2..07d89d30cb 100644 --- a/core/variant/variant_parser.h +++ b/core/variant/variant_parser.h @@ -49,11 +49,11 @@ public: }; struct StreamFile : public Stream { - FileAccess *f = nullptr; + Ref<FileAccess> f; - virtual char32_t get_char(); - virtual bool is_utf8() const; - virtual bool is_eof() const; + virtual char32_t get_char() override; + virtual bool is_utf8() const override; + virtual bool is_eof() const override; StreamFile() {} }; @@ -62,9 +62,9 @@ public: String s; int pos = 0; - virtual char32_t get_char(); - virtual bool is_utf8() const; - virtual bool is_eof() const; + virtual char32_t get_char() override; + virtual bool is_utf8() const override; + virtual bool is_eof() const override; StreamString() {} }; diff --git a/core/variant/variant_setget.cpp b/core/variant/variant_setget.cpp index e604ff9567..705aa27be6 100644 --- a/core/variant/variant_setget.cpp +++ b/core/variant/variant_setget.cpp @@ -1868,6 +1868,110 @@ Variant Variant::recursive_duplicate(bool p_deep, int recursion_count) const { } } +void Variant::sub(const Variant &a, const Variant &b, Variant &r_dst) { + if (a.type != b.type) { + return; + } + + switch (a.type) { + case NIL: { + r_dst = Variant(); + } + return; + case INT: { + int64_t va = a._data._int; + int64_t vb = b._data._int; + r_dst = int(va - vb); + } + return; + case FLOAT: { + double ra = a._data._float; + double rb = b._data._float; + r_dst = ra - rb; + } + return; + case VECTOR2: { + r_dst = *reinterpret_cast<const Vector2 *>(a._data._mem) - *reinterpret_cast<const Vector2 *>(b._data._mem); + } + return; + case VECTOR2I: { + int32_t vax = reinterpret_cast<const Vector2i *>(a._data._mem)->x; + int32_t vbx = reinterpret_cast<const Vector2i *>(b._data._mem)->x; + int32_t vay = reinterpret_cast<const Vector2i *>(a._data._mem)->y; + int32_t vby = reinterpret_cast<const Vector2i *>(b._data._mem)->y; + r_dst = Vector2i(int32_t(vax - vbx), int32_t(vay - vby)); + } + return; + case RECT2: { + const Rect2 *ra = reinterpret_cast<const Rect2 *>(a._data._mem); + const Rect2 *rb = reinterpret_cast<const Rect2 *>(b._data._mem); + r_dst = Rect2(ra->position - rb->position, ra->size - rb->size); + } + return; + case RECT2I: { + const Rect2i *ra = reinterpret_cast<const Rect2i *>(a._data._mem); + const Rect2i *rb = reinterpret_cast<const Rect2i *>(b._data._mem); + + int32_t vax = ra->position.x; + int32_t vay = ra->position.y; + int32_t vbx = ra->size.x; + int32_t vby = ra->size.y; + int32_t vcx = rb->position.x; + int32_t vcy = rb->position.y; + int32_t vdx = rb->size.x; + int32_t vdy = rb->size.y; + + r_dst = Rect2i(int32_t(vax - vbx), int32_t(vay - vby), int32_t(vcx - vdx), int32_t(vcy - vdy)); + } + return; + case VECTOR3: { + r_dst = *reinterpret_cast<const Vector3 *>(a._data._mem) - *reinterpret_cast<const Vector3 *>(b._data._mem); + } + return; + case VECTOR3I: { + int32_t vax = reinterpret_cast<const Vector3i *>(a._data._mem)->x; + int32_t vbx = reinterpret_cast<const Vector3i *>(b._data._mem)->x; + int32_t vay = reinterpret_cast<const Vector3i *>(a._data._mem)->y; + int32_t vby = reinterpret_cast<const Vector3i *>(b._data._mem)->y; + int32_t vaz = reinterpret_cast<const Vector3i *>(a._data._mem)->z; + int32_t vbz = reinterpret_cast<const Vector3i *>(b._data._mem)->z; + r_dst = Vector3i(int32_t(vax - vbx), int32_t(vay - vby), int32_t(vaz - vbz)); + } + return; + case AABB: { + const ::AABB *ra = reinterpret_cast<const ::AABB *>(a._data._mem); + const ::AABB *rb = reinterpret_cast<const ::AABB *>(b._data._mem); + r_dst = ::AABB(ra->position - rb->position, ra->size - rb->size); + } + return; + case QUATERNION: { + Quaternion empty_rot; + const Quaternion *qa = reinterpret_cast<const Quaternion *>(a._data._mem); + const Quaternion *qb = reinterpret_cast<const Quaternion *>(b._data._mem); + r_dst = (*qb).inverse() * *qa; + } + return; + case COLOR: { + const Color *ca = reinterpret_cast<const Color *>(a._data._mem); + const Color *cb = reinterpret_cast<const Color *>(b._data._mem); + float new_r = ca->r - cb->r; + float new_g = ca->g - cb->g; + float new_b = ca->b - cb->b; + float new_a = ca->a - cb->a; + new_r = new_r > 1.0 ? 1.0 : new_r; + new_g = new_g > 1.0 ? 1.0 : new_g; + new_b = new_b > 1.0 ? 1.0 : new_b; + new_a = new_a > 1.0 ? 1.0 : new_a; + r_dst = Color(new_r, new_g, new_b, new_a); + } + return; + default: { + r_dst = a; + } + return; + } +} + void Variant::blend(const Variant &a, const Variant &b, float c, Variant &r_dst) { if (a.type != b.type) { if (a.is_num() && b.is_num()) { diff --git a/core/variant/variant_utility.cpp b/core/variant/variant_utility.cpp index 05fb577e2c..6ed85815be 100644 --- a/core/variant/variant_utility.cpp +++ b/core/variant/variant_utility.cpp @@ -470,20 +470,20 @@ struct VariantUtilityFunctions { r_error.argument = 1; return String(); } - String str; + String s; for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); if (i == 0) { - str = os; + s = os; } else { - str += os; + s += os; } } r_error.error = Callable::CallError::CALL_OK; - return str; + return s; } static inline String error_string(Error error) { @@ -495,98 +495,98 @@ struct VariantUtilityFunctions { } static inline void print(const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { - String str; + String s; for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); if (i == 0) { - str = os; + s = os; } else { - str += os; + s += os; } } - print_line(str); + print_line(s); r_error.error = Callable::CallError::CALL_OK; } static inline void print_verbose(const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { if (OS::get_singleton()->is_stdout_verbose()) { - String str; + String s; for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); if (i == 0) { - str = os; + s = os; } else { - str += os; + s += os; } } // No need to use `print_verbose()` as this call already only happens // when verbose mode is enabled. This avoids performing string argument concatenation // when not needed. - print_line(str); + print_line(s); } r_error.error = Callable::CallError::CALL_OK; } static inline void printerr(const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { - String str; + String s; for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); if (i == 0) { - str = os; + s = os; } else { - str += os; + s += os; } } - print_error(str); + print_error(s); r_error.error = Callable::CallError::CALL_OK; } static inline void printt(const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { - String str; + String s; for (int i = 0; i < p_arg_count; i++) { if (i) { - str += "\t"; + s += "\t"; } - str += p_args[i]->operator String(); + s += p_args[i]->operator String(); } - print_line(str); + print_line(s); r_error.error = Callable::CallError::CALL_OK; } static inline void prints(const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { - String str; + String s; for (int i = 0; i < p_arg_count; i++) { if (i) { - str += " "; + s += " "; } - str += p_args[i]->operator String(); + s += p_args[i]->operator String(); } - print_line(str); + print_line(s); r_error.error = Callable::CallError::CALL_OK; } static inline void printraw(const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { - String str; + String s; for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); if (i == 0) { - str = os; + s = os; } else { - str += os; + s += os; } } - OS::get_singleton()->print("%s", str.utf8().get_data()); + OS::get_singleton()->print("%s", s.utf8().get_data()); r_error.error = Callable::CallError::CALL_OK; } @@ -595,18 +595,18 @@ struct VariantUtilityFunctions { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.argument = 1; } - String str; + String s; for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); if (i == 0) { - str = os; + s = os; } else { - str += os; + s += os; } } - ERR_PRINT(str); + ERR_PRINT(s); r_error.error = Callable::CallError::CALL_OK; } @@ -615,18 +615,18 @@ struct VariantUtilityFunctions { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.argument = 1; } - String str; + String s; for (int i = 0; i < p_arg_count; i++) { String os = p_args[i]->operator String(); if (i == 0) { - str = os; + s = os; } else { - str += os; + s += os; } } - WARN_PRINT(str); + WARN_PRINT(s); r_error.error = Callable::CallError::CALL_OK; } diff --git a/doc/classes/@GlobalScope.xml b/doc/classes/@GlobalScope.xml index a2b310ca82..da6513a08b 100644 --- a/doc/classes/@GlobalScope.xml +++ b/doc/classes/@GlobalScope.xml @@ -2546,13 +2546,13 @@ The property is a translatable string. </constant> <constant name="PROPERTY_USAGE_GROUP" value="128" enum="PropertyUsageFlags"> - Used to group properties together in the editor. + Used to group properties together in the editor. See [EditorInspector]. </constant> <constant name="PROPERTY_USAGE_CATEGORY" value="256" enum="PropertyUsageFlags"> Used to categorize properties together in the editor. </constant> <constant name="PROPERTY_USAGE_SUBGROUP" value="512" enum="PropertyUsageFlags"> - Used to group properties together in the editor in a subgroup (under a group). + Used to group properties together in the editor in a subgroup (under a group). See [EditorInspector]. </constant> <constant name="PROPERTY_USAGE_NO_INSTANCE_STATE" value="2048" enum="PropertyUsageFlags"> The property does not save its state in [PackedScene]. diff --git a/doc/classes/AnimationLibrary.xml b/doc/classes/AnimationLibrary.xml new file mode 100644 index 0000000000..0a731edadd --- /dev/null +++ b/doc/classes/AnimationLibrary.xml @@ -0,0 +1,70 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="AnimationLibrary" inherits="Resource" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <methods> + <method name="add_animation"> + <return type="int" enum="Error" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="animation" type="Animation" /> + <description> + </description> + </method> + <method name="get_animation" qualifiers="const"> + <return type="Animation" /> + <argument index="0" name="name" type="StringName" /> + <description> + </description> + </method> + <method name="get_animation_list" qualifiers="const"> + <return type="StringName[]" /> + <description> + </description> + </method> + <method name="has_animation" qualifiers="const"> + <return type="bool" /> + <argument index="0" name="name" type="StringName" /> + <description> + </description> + </method> + <method name="remove_animation"> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <description> + </description> + </method> + <method name="rename_animation"> + <return type="void" /> + <argument index="0" name="name" type="StringName" /> + <argument index="1" name="newname" type="StringName" /> + <description> + </description> + </method> + </methods> + <members> + <member name="_data" type="Dictionary" setter="_set_data" getter="_get_data" default="{}"> + </member> + </members> + <signals> + <signal name="animation_added"> + <argument index="0" name="name" type="Animation" /> + <description> + </description> + </signal> + <signal name="animation_removed"> + <argument index="0" name="name" type="Animation" /> + <description> + </description> + </signal> + <signal name="animation_renamed"> + <argument index="0" name="name" type="Animation" /> + <argument index="1" name="to_name" type="Animation" /> + <description> + </description> + </signal> + </signals> +</class> diff --git a/doc/classes/AnimationPlayer.xml b/doc/classes/AnimationPlayer.xml index b1d04ce1f2..625cf3c47c 100644 --- a/doc/classes/AnimationPlayer.xml +++ b/doc/classes/AnimationPlayer.xml @@ -14,12 +14,11 @@ <link title="Third Person Shooter Demo">https://godotengine.org/asset-library/asset/678</link> </tutorials> <methods> - <method name="add_animation"> + <method name="add_animation_library"> <return type="int" enum="Error" /> <argument index="0" name="name" type="StringName" /> - <argument index="1" name="animation" type="Animation" /> + <argument index="1" name="library" type="AnimationLibrary" /> <description> - Adds [code]animation[/code] to the player accessible with the key [code]name[/code]. </description> </method> <method name="advance"> @@ -63,6 +62,12 @@ Returns the name of [code]animation[/code] or an empty string if not found. </description> </method> + <method name="find_animation_library" qualifiers="const"> + <return type="StringName" /> + <argument index="0" name="animation" type="Animation" /> + <description> + </description> + </method> <method name="get_animation" qualifiers="const"> <return type="Animation" /> <argument index="0" name="name" type="StringName" /> @@ -70,6 +75,17 @@ Returns the [Animation] with key [code]name[/code] or [code]null[/code] if not found. </description> </method> + <method name="get_animation_library" qualifiers="const"> + <return type="AnimationLibrary" /> + <argument index="0" name="name" type="StringName" /> + <description> + </description> + </method> + <method name="get_animation_library_list" qualifiers="const"> + <return type="StringName[]" /> + <description> + </description> + </method> <method name="get_animation_list" qualifiers="const"> <return type="PackedStringArray" /> <description> @@ -103,6 +119,12 @@ Returns [code]true[/code] if the [AnimationPlayer] stores an [Animation] with key [code]name[/code]. </description> </method> + <method name="has_animation_library" qualifiers="const"> + <return type="bool" /> + <argument index="0" name="name" type="StringName" /> + <description> + </description> + </method> <method name="is_playing" qualifiers="const"> <return type="bool" /> <description> @@ -138,19 +160,17 @@ [b]Note:[/b] If a looped animation is currently playing, the queued animation will never play unless the looped animation is stopped somehow. </description> </method> - <method name="remove_animation"> + <method name="remove_animation_library"> <return type="void" /> <argument index="0" name="name" type="StringName" /> <description> - Removes the animation with key [code]name[/code]. </description> </method> - <method name="rename_animation"> + <method name="rename_animation_library"> <return type="void" /> <argument index="0" name="name" type="StringName" /> <argument index="1" name="newname" type="StringName" /> <description> - Renames an existing animation with key [code]name[/code] to [code]newname[/code]. </description> </method> <method name="seek"> diff --git a/doc/classes/Array.xml b/doc/classes/Array.xml index 27331d3f96..ef4f86f1a9 100644 --- a/doc/classes/Array.xml +++ b/doc/classes/Array.xml @@ -194,7 +194,7 @@ <return type="void" /> <argument index="0" name="value" type="Variant" /> <description> - Removes the first occurrence of a value from the array. To remove an element by index, use [method remove_at] instead. + Removes the first occurrence of a value from the array. If the value does not exist in the array, nothing happens. To remove an element by index, use [method remove_at] instead. [b]Note:[/b] This method acts in-place and doesn't return a value. [b]Note:[/b] On large arrays, this method will be slower if the removed element is close to the beginning of the array (index 0). This is because all elements placed after the removed element have to be reindexed. </description> diff --git a/doc/classes/Camera3D.xml b/doc/classes/Camera3D.xml index f7a0d41626..5008cd826e 100644 --- a/doc/classes/Camera3D.xml +++ b/doc/classes/Camera3D.xml @@ -192,7 +192,7 @@ The camera's projection mode. In [constant PROJECTION_PERSPECTIVE] mode, objects' Z distance from the camera's local space scales their perceived size. </member> <member name="size" type="float" setter="set_size" getter="get_size" default="1.0"> - The camera's size measured as 1/2 the width or height. Only applicable in orthogonal mode. Since [member keep_aspect] locks on axis, [code]size[/code] sets the other axis' size length. + The camera's size measured as 1/2 the width or height. Only applicable in orthogonal and frustum modes. Since [member keep_aspect] locks on axis, [code]size[/code] sets the other axis' size length. </member> <member name="v_offset" type="float" setter="set_v_offset" getter="get_v_offset" default="0.0"> The vertical (Y) offset of the camera viewport. diff --git a/doc/classes/CanvasItem.xml b/doc/classes/CanvasItem.xml index 5205a1db3b..6cd2da520f 100644 --- a/doc/classes/CanvasItem.xml +++ b/doc/classes/CanvasItem.xml @@ -103,8 +103,9 @@ <argument index="1" name="to" type="Vector2" /> <argument index="2" name="color" type="Color" /> <argument index="3" name="width" type="float" default="1.0" /> + <argument index="4" name="antialiased" type="bool" default="false" /> <description> - Draws a line from a 2D point to another, with a given color and width. See also [method draw_multiline] and [method draw_polyline]. + Draws a line from a 2D point to another, with a given color and width. It can be optionally antialiased. See also [method draw_multiline] and [method draw_polyline]. </description> </method> <method name="draw_mesh"> @@ -191,7 +192,7 @@ <argument index="2" name="width" type="float" default="1.0" /> <argument index="3" name="antialiased" type="bool" default="false" /> <description> - Draws interconnected line segments with a uniform [code]color[/code] and [code]width[/code]. When drawing large amounts of lines, this is faster than using individual [method draw_line] calls. To draw disconnected lines, use [method draw_multiline] instead. See also [method draw_polygon]. + Draws interconnected line segments with a uniform [code]color[/code] and [code]width[/code] and optional antialiasing. When drawing large amounts of lines, this is faster than using individual [method draw_line] calls. To draw disconnected lines, use [method draw_multiline] instead. See also [method draw_polygon]. </description> </method> <method name="draw_polyline_colors"> @@ -201,7 +202,7 @@ <argument index="2" name="width" type="float" default="1.0" /> <argument index="3" name="antialiased" type="bool" default="false" /> <description> - Draws interconnected line segments with a uniform [code]width[/code] and segment-by-segment coloring. Colors assigned to line segments match by index between [code]points[/code] and [code]colors[/code]. When drawing large amounts of lines, this is faster than using individual [method draw_line] calls. To draw disconnected lines, use [method draw_multiline_colors] instead. See also [method draw_polygon]. + Draws interconnected line segments with a uniform [code]width[/code] and segment-by-segment coloring, and optional antialiasing. Colors assigned to line segments match by index between [code]points[/code] and [code]colors[/code]. When drawing large amounts of lines, this is faster than using individual [method draw_line] calls. To draw disconnected lines, use [method draw_multiline_colors] instead. See also [method draw_polygon]. </description> </method> <method name="draw_primitive"> @@ -480,9 +481,6 @@ <member name="show_behind_parent" type="bool" setter="set_draw_behind_parent" getter="is_draw_behind_parent_enabled" default="false"> If [code]true[/code], the object draws behind its parent. </member> - <member name="show_on_top" type="bool" setter="_set_on_top" getter="_is_on_top"> - If [code]true[/code], the object draws on top of its parent. - </member> <member name="texture_filter" type="int" setter="set_texture_filter" getter="get_texture_filter" enum="CanvasItem.TextureFilter" default="0"> The texture filtering mode to use on this [CanvasItem]. </member> diff --git a/doc/classes/CharacterBody2D.xml b/doc/classes/CharacterBody2D.xml index 28060f6579..63d493248f 100644 --- a/doc/classes/CharacterBody2D.xml +++ b/doc/classes/CharacterBody2D.xml @@ -183,7 +183,7 @@ If [code]true[/code], during a jump against the ceiling, the body will slide, if [code]false[/code] it will be stopped and will fall vertically. </member> <member name="up_direction" type="Vector2" setter="set_up_direction" getter="get_up_direction" default="Vector2(0, -1)"> - Direction vector used to determine what is a wall and what is a floor (or a ceiling), rather than a wall, when calling [method move_and_slide]. Defaults to [code]Vector2.UP[/code]. If set to [code]Vector2(0, 0)[/code], everything is considered a wall. This is useful for topdown games. + Vector pointing upwards, used to determine what is a wall and what is a floor (or a ceiling) when calling [method move_and_slide]. Defaults to [code]Vector2.UP[/code]. As the vector will be normalized it can't be equal to [constant Vector2.ZERO], if you want all collisions to be reported as walls, consider using [constant MOTION_MODE_FLOATING] as [member motion_mode]. </member> <member name="velocity" type="Vector2" setter="set_velocity" getter="get_velocity" default="Vector2(0, 0)"> Current velocity vector in pixels per second, used and modified during calls to [method move_and_slide]. diff --git a/doc/classes/CharacterBody3D.xml b/doc/classes/CharacterBody3D.xml index 4895e2cff7..6c5cd62fe1 100644 --- a/doc/classes/CharacterBody3D.xml +++ b/doc/classes/CharacterBody3D.xml @@ -168,7 +168,7 @@ If [code]true[/code], during a jump against the ceiling, the body will slide, if [code]false[/code] it will be stopped and will fall vertically. </member> <member name="up_direction" type="Vector3" setter="set_up_direction" getter="get_up_direction" default="Vector3(0, 1, 0)"> - Direction vector used to determine what is a wall and what is a floor (or a ceiling), rather than a wall, when calling [method move_and_slide]. Defaults to [code]Vector3.UP[/code]. If set to [code]Vector3(0, 0, 0)[/code], everything is considered a wall. This is useful for topdown games. + Vector pointing upwards, used to determine what is a wall and what is a floor (or a ceiling) when calling [method move_and_slide]. Defaults to [code]Vector3.UP[/code]. As the vector will be normalized it can't be equal to [constant Vector3.ZERO], if you want all collisions to be reported as walls, consider using [constant MOTION_MODE_FLOATING] as [member motion_mode]. </member> <member name="velocity" type="Vector3" setter="set_velocity" getter="get_velocity" default="Vector3(0, 0, 0)"> Current velocity vector (typically meters per second), used and modified during calls to [method move_and_slide]. diff --git a/doc/classes/CheckBox.xml b/doc/classes/CheckBox.xml index 606f5ca51f..462ab81587 100644 --- a/doc/classes/CheckBox.xml +++ b/doc/classes/CheckBox.xml @@ -54,23 +54,25 @@ The check icon to display when the [CheckBox] is checked. </theme_item> <theme_item name="checked_disabled" data_type="icon" type="Texture2D"> - The check icon to display when the [CheckBox] is checked and disabled. + The check icon to display when the [CheckBox] is checked and is disabled. </theme_item> <theme_item name="radio_checked" data_type="icon" type="Texture2D"> - If the [CheckBox] is configured as a radio button, the icon to display when the [CheckBox] is checked. + The check icon to display when the [CheckBox] is configured as a radio button and is checked. </theme_item> <theme_item name="radio_checked_disabled" data_type="icon" type="Texture2D"> + The check icon to display when the [CheckBox] is configured as a radio button, is disabled, and is unchecked. </theme_item> <theme_item name="radio_unchecked" data_type="icon" type="Texture2D"> - If the [CheckBox] is configured as a radio button, the icon to display when the [CheckBox] is unchecked. + The check icon to display when the [CheckBox] is configured as a radio button and is unchecked. </theme_item> <theme_item name="radio_unchecked_disabled" data_type="icon" type="Texture2D"> + The check icon to display when the [CheckBox] is configured as a radio button, is disabled, and is unchecked. </theme_item> <theme_item name="unchecked" data_type="icon" type="Texture2D"> The check icon to display when the [CheckBox] is unchecked. </theme_item> <theme_item name="unchecked_disabled" data_type="icon" type="Texture2D"> - The check icon to display when the [CheckBox] is unchecked and disabled. + The check icon to display when the [CheckBox] is unchecked and is disabled. </theme_item> <theme_item name="disabled" data_type="style" type="StyleBox"> The [StyleBox] to display as a background when the [CheckBox] is disabled. diff --git a/doc/classes/CollisionObject2D.xml b/doc/classes/CollisionObject2D.xml index 99bf9f7853..5d025985cc 100644 --- a/doc/classes/CollisionObject2D.xml +++ b/doc/classes/CollisionObject2D.xml @@ -5,6 +5,7 @@ </brief_description> <description> CollisionObject2D is the base class for 2D physics objects. It can hold any number of 2D collision [Shape2D]s. Each shape must be assigned to a [i]shape owner[/i]. The CollisionObject2D can have any number of shape owners. Shape owners are not nodes and do not appear in the editor, but are accessible through code using the [code]shape_owner_*[/code] methods. + [b]Note:[/b] Only collisions between objects within the same canvas ([Viewport] canvas or [CanvasLayer]) are supported. The behavior of collisions between objects in different canvases is undefined. </description> <tutorials> </tutorials> diff --git a/doc/classes/Color.xml b/doc/classes/Color.xml index 5b48804d9d..7b8a57ed22 100644 --- a/doc/classes/Color.xml +++ b/doc/classes/Color.xml @@ -183,7 +183,7 @@ <description> Returns the luminance of the color in the [code][0.0, 1.0][/code] range. This is useful when determining light or dark color. Colors with a luminance smaller than 0.5 can be generally considered dark. - [b]Note:[/b] [method get_luminance] relies on the colour being in the linear color space to return an accurate relative luminance value. If the color is in the sRGB color space, use [method to_linear] to convert it to the linear color space first. + [b]Note:[/b] [method get_luminance] relies on the colour being in the linear color space to return an accurate relative luminance value. If the color is in the sRGB color space, use [method srgb_to_linear] to convert it to the linear color space first. </description> </method> <method name="get_named_color" qualifiers="static"> @@ -321,6 +321,18 @@ [/codeblocks] </description> </method> + <method name="linear_to_srgb" qualifiers="const"> + <return type="Color" /> + <description> + Returns the color converted to the [url=https://en.wikipedia.org/wiki/SRGB]sRGB[/url] color space. This assumes the original color is in the linear color space. See also [method srgb_to_linear] which performs the opposite operation. + </description> + </method> + <method name="srgb_to_linear" qualifiers="const"> + <return type="Color" /> + <description> + Returns the color converted to the linear color space. This assumes the original color is in the sRGB color space. See also [method linear_to_srgb] which performs the opposite operation. + </description> + </method> <method name="to_abgr32" qualifiers="const"> <return type="int" /> <description> @@ -405,12 +417,6 @@ [/codeblocks] </description> </method> - <method name="to_linear" qualifiers="const"> - <return type="Color" /> - <description> - Returns the color converted to the linear color space. This assumes the original color is in the sRGB color space. See also [method to_srgb] which performs the opposite operation. - </description> - </method> <method name="to_rgba32" qualifiers="const"> <return type="int" /> <description> @@ -443,12 +449,6 @@ [/codeblocks] </description> </method> - <method name="to_srgb" qualifiers="const"> - <return type="Color" /> - <description> - Returns the color converted to the [url=https://en.wikipedia.org/wiki/SRGB]sRGB[/url] color space. This assumes the original color is in the linear color space. See also [method to_linear] which performs the opposite operation. - </description> - </method> </methods> <members> <member name="a" type="float" setter="" getter="" default="1.0"> diff --git a/doc/classes/EditorInspector.xml b/doc/classes/EditorInspector.xml index cd249ed319..365e1f13a9 100644 --- a/doc/classes/EditorInspector.xml +++ b/doc/classes/EditorInspector.xml @@ -1,11 +1,15 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="EditorInspector" inherits="ScrollContainer" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd"> <brief_description> - A tab used to edit properties of the selected node. + A control used to edit properties of an object. </brief_description> <description> - The editor inspector is by default located on the right-hand side of the editor. It's used to edit the properties of the selected node. For example, you can select a node such as the Sprite2D then edit its transform through the inspector tool. The editor inspector is an essential tool in the game development workflow. - [b]Note:[/b] This class shouldn't be instantiated directly. Instead, access the singleton using [method EditorInterface.get_inspector]. + This is the control that implements property editing in the editor's Settings dialogs, the Inspector dock, etc. To get the [EditorInspector] used in the editor's Inspector dock, use [method EditorInterface.get_inspector]. + [EditorInspector] will show properties in the same order as the array returned by [method Object.get_property_list]. + If a property's name is path-like (i.e. if it contains forward slashes), [EditorInspector] will create nested sections for "directories" along the path. For example, if a property is named [code]highlighting/gdscript/node_path_color[/code], it will be shown as "Node Path Color" inside the "GDScript" section nested inside the "Highlighting" section. + If a property has [constant @GlobalScope.PROPERTY_USAGE_GROUP] usage, it will group subsequent properties whose name starts with the property's hint string. The group ends when a property does not start with that hint string or when a new group starts. An empty group name effectively ends the current group. [EditorInspector] will create a top-level section for each group. For example, if a property with group usage is named [code]Collide With[/code] and its hint string is [code]collide_with_[/code], a subsequent [code]collide_with_area[/code] property will be shown as "Area" inside the "Collide With" section. + If a property has [constant @GlobalScope.PROPERTY_USAGE_SUBGROUP] usage, a subgroup will be created in the same way as a group, and a second-level section will be created for each subgroup. + [b]Note:[/b] Unlike sections created from path-like property names, [EditorInspector] won't capitalize the name for sections created from groups. So properties with group usage usually use capitalized names instead of snake_cased names. </description> <tutorials> </tutorials> diff --git a/doc/classes/EditorSceneFormatImporter.xml b/doc/classes/EditorSceneFormatImporter.xml index 63c1498f20..0290d7207d 100644 --- a/doc/classes/EditorSceneFormatImporter.xml +++ b/doc/classes/EditorSceneFormatImporter.xml @@ -29,16 +29,8 @@ <method name="_get_option_visibility" qualifiers="virtual const"> <return type="Variant" /> <argument index="0" name="path" type="String" /> - <argument index="1" name="option" type="String" /> - <description> - </description> - </method> - <method name="_import_animation" qualifiers="virtual"> - <return type="Animation" /> - <argument index="0" name="path" type="String" /> - <argument index="1" name="flags" type="int" /> - <argument index="2" name="options" type="Dictionary" /> - <argument index="3" name="bake_fps" type="int" /> + <argument index="1" name="for_animation" type="bool" /> + <argument index="2" name="option" type="String" /> <description> </description> </method> @@ -63,5 +55,7 @@ </constant> <constant name="IMPORT_USE_NAMED_SKIN_BINDS" value="16"> </constant> + <constant name="IMPORT_DISCARD_MESHES_AND_MATERIALS" value="32"> + </constant> </constants> </class> diff --git a/doc/classes/EditorScenePostImportPlugin.xml b/doc/classes/EditorScenePostImportPlugin.xml index de9d5e067a..0fdbd5db1e 100644 --- a/doc/classes/EditorScenePostImportPlugin.xml +++ b/doc/classes/EditorScenePostImportPlugin.xml @@ -34,7 +34,8 @@ <method name="_get_internal_option_visibility" qualifiers="virtual const"> <return type="Variant" /> <argument index="0" name="category" type="int" /> - <argument index="1" name="option" type="String" /> + <argument index="1" name="for_animation" type="bool" /> + <argument index="2" name="option" type="String" /> <description> Return true or false whether a given option should be visible. Return null to ignore. </description> @@ -42,7 +43,8 @@ <method name="_get_option_visibility" qualifiers="virtual const"> <return type="Variant" /> <argument index="0" name="path" type="String" /> - <argument index="1" name="option" type="String" /> + <argument index="1" name="for_animation" type="bool" /> + <argument index="2" name="option" type="String" /> <description> Return true or false whether a given option should be visible. Return null to ignore. </description> diff --git a/doc/classes/NavigationServer2D.xml b/doc/classes/NavigationServer2D.xml index a59666356c..e007dfd9b5 100644 --- a/doc/classes/NavigationServer2D.xml +++ b/doc/classes/NavigationServer2D.xml @@ -110,11 +110,11 @@ Sets the current velocity of the agent. </description> </method> - <method name="free" qualifiers="const"> + <method name="free_rid" qualifiers="const"> <return type="void" /> - <argument index="0" name="object" type="RID" /> + <argument index="0" name="rid" type="RID" /> <description> - Destroy the RID + Destroys the given RID. </description> </method> <method name="map_create" qualifiers="const"> diff --git a/doc/classes/NavigationServer3D.xml b/doc/classes/NavigationServer3D.xml index 7d11a30647..c987bc9042 100644 --- a/doc/classes/NavigationServer3D.xml +++ b/doc/classes/NavigationServer3D.xml @@ -110,11 +110,11 @@ Sets the current velocity of the agent. </description> </method> - <method name="free" qualifiers="const"> + <method name="free_rid" qualifiers="const"> <return type="void" /> - <argument index="0" name="object" type="RID" /> + <argument index="0" name="rid" type="RID" /> <description> - Destroy the RID + Destroys the given RID. </description> </method> <method name="map_create" qualifiers="const"> diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml index b1a6ed7740..7079036879 100644 --- a/doc/classes/Node.xml +++ b/doc/classes/Node.xml @@ -84,6 +84,17 @@ [b]Note:[/b] [method _ready] may be called only once for each node. After removing a node from the scene tree and adding it again, [code]_ready[/code] will not be called a second time. This can be bypassed by requesting another call with [method request_ready], which may be called anywhere before adding the node again. </description> </method> + <method name="_shortcut_input" qualifiers="virtual"> + <return type="void" /> + <argument index="0" name="event" type="InputEvent" /> + <description> + Called when an [InputEventKey] or [InputEventShortcut] hasn't been consumed by [method _input] or any GUI [Control] item. The input event propagates up through the node tree until a node consumes it. + It is only called if shortcut processing is enabled, which is done automatically if this method is overridden, and can be toggled with [method set_process_shortcut_input]. + To consume the input event and stop it propagating further to other nodes, [method Viewport.set_input_as_handled] can be called. + This method can be used to handle shortcuts. + [b]Note:[/b] This method is only called if the node is present in the scene tree (i.e. if it's not orphan). + </description> + </method> <method name="_unhandled_input" qualifiers="virtual"> <return type="void" /> <argument index="0" name="event" type="InputEvent" /> @@ -102,6 +113,7 @@ Called when an [InputEventKey] or [InputEventShortcut] hasn't been consumed by [method _input] or any GUI [Control] item. The input event propagates up through the node tree until a node consumes it. It is only called if unhandled key input processing is enabled, which is done automatically if this method is overridden, and can be toggled with [method set_process_unhandled_key_input]. To consume the input event and stop it propagating further to other nodes, [method Viewport.set_input_as_handled] can be called. + This method can be used to handle Unicode character input with [kbd]Alt[/kbd], [kbd]Alt + Ctrl[/kbd], and [kbd]Alt + Shift[/kbd] modifiers, after shortcuts were handled. For gameplay input, this and [method _unhandled_input] are usually a better fit than [method _input] as they allow the GUI to intercept the events first. [b]Note:[/b] This method is only called if the node is present in the scene tree (i.e. if it's not an orphan). </description> @@ -462,6 +474,12 @@ Returns [code]true[/code] if internal processing is enabled (see [method set_process_internal]). </description> </method> + <method name="is_processing_shortcut_input" qualifiers="const"> + <return type="bool" /> + <description> + Returns [code]true[/code] if the node is processing shortcuts (see [method set_process_shortcut_input]). + </description> + </method> <method name="is_processing_unhandled_input" qualifiers="const"> <return type="bool" /> <description> @@ -673,6 +691,13 @@ [b]Warning:[/b] Built-in Nodes rely on the internal processing for their own logic, so changing this value from your code may lead to unexpected behavior. Script access to this internal logic is provided for specific advanced uses, but is unsafe and not supported. </description> </method> + <method name="set_process_shortcut_input"> + <return type="void" /> + <argument index="0" name="enable" type="bool" /> + <description> + Enables shortcut processing. Enabled automatically if [method _shortcut_input] is overridden. Any calls to this before [method _ready] will be ignored. + </description> + </method> <method name="set_process_unhandled_input"> <return type="void" /> <argument index="0" name="enable" type="bool" /> @@ -707,7 +732,7 @@ The override to the default [MultiplayerAPI]. Set to [code]null[/code] to use the default [SceneTree] one. </member> <member name="editor_description" type="String" setter="set_editor_description" getter="get_editor_description" default=""""> - Add a custom description to a node. + Add a custom description to a node. It will be displayed in a tooltip when hovered in editor's scene tree. </member> <member name="multiplayer" type="MultiplayerAPI" setter="" getter="get_multiplayer"> The [MultiplayerAPI] instance associated with this node. Either the [member custom_multiplayer], or the default SceneTree one (if inside tree). diff --git a/doc/classes/OptionButton.xml b/doc/classes/OptionButton.xml index 25e41116a2..b7145ab923 100644 --- a/doc/classes/OptionButton.xml +++ b/doc/classes/OptionButton.xml @@ -30,8 +30,9 @@ </method> <method name="add_separator"> <return type="void" /> + <argument index="0" name="text" type="String" default="""" /> <description> - Adds a separator to the list of items. Separators help to group items. Separator also takes up an index and is appended at the end. + Adds a separator to the list of items. Separators help to group items, and can optionally be given a [code]text[/code] header. A separator also gets an index assigned, and is appended at the end of the item list. </description> </method> <method name="clear"> @@ -89,6 +90,12 @@ [b]Warning:[/b] This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their [member Window.visible] property. </description> </method> + <method name="get_selectable_item" qualifiers="const"> + <return type="int" /> + <argument index="0" name="from_last" type="bool" default="false" /> + <description> + </description> + </method> <method name="get_selected_id" qualifiers="const"> <return type="int" /> <description> @@ -101,6 +108,11 @@ Gets the metadata of the selected item. Metadata for items can be set using [method set_item_metadata]. </description> </method> + <method name="has_selectable_items" qualifiers="const"> + <return type="bool" /> + <description> + </description> + </method> <method name="is_item_disabled" qualifiers="const"> <return type="bool" /> <argument index="0" name="idx" type="int" /> @@ -108,6 +120,12 @@ Returns [code]true[/code] if the item at index [code]idx[/code] is disabled. </description> </method> + <method name="is_item_separator" qualifiers="const"> + <return type="bool" /> + <argument index="0" name="idx" type="int" /> + <description> + </description> + </method> <method name="remove_item"> <return type="void" /> <argument index="0" name="idx" type="int" /> diff --git a/doc/classes/Position2D.xml b/doc/classes/Position2D.xml index 881ec028de..754fd1fdf1 100644 --- a/doc/classes/Position2D.xml +++ b/doc/classes/Position2D.xml @@ -8,4 +8,9 @@ </description> <tutorials> </tutorials> + <members> + <member name="gizmo_extents" type="float" setter="set_gizmo_extents" getter="get_gizmo_extents" default="10.0"> + Size of the gizmo cross that appears in the editor. + </member> + </members> </class> diff --git a/doc/classes/ProjectSettings.xml b/doc/classes/ProjectSettings.xml index c21a44c89b..ee32677b3a 100644 --- a/doc/classes/ProjectSettings.xml +++ b/doc/classes/ProjectSettings.xml @@ -512,7 +512,7 @@ </member> <member name="display/window/size/resizable" type="bool" setter="" getter="" default="true"> Allows the window to be resizable by default. - [b]Note:[/b] This setting is ignored on iOS and Android. + [b]Note:[/b] This setting is ignored on iOS. </member> <member name="display/window/size/viewport_height" type="int" setter="" getter="" default="600"> Sets the game's main viewport height. On desktop platforms, this is also the initial window height. diff --git a/doc/classes/RenderingServer.xml b/doc/classes/RenderingServer.xml index f1a15a08dd..5bb83c8ffd 100644 --- a/doc/classes/RenderingServer.xml +++ b/doc/classes/RenderingServer.xml @@ -183,6 +183,7 @@ <argument index="2" name="to" type="Vector2" /> <argument index="3" name="color" type="Color" /> <argument index="4" name="width" type="float" default="1.0" /> + <argument index="5" name="antialiased" type="bool" default="false" /> <description> </description> </method> @@ -3932,10 +3933,10 @@ [FogVolume] will have no shape, will cover the whole world and will not be culled. </constant> <constant name="VIEWPORT_SCALING_3D_MODE_BILINEAR" value="0" enum="ViewportScaling3DMode"> - Enables bilinear scaling on 3D viewports. The amount of scaling can be set using [member Viewport.scaling_3d_scale]. Values less then [code]1.0[/code] will result in undersampling while values greater than [code]1.0[/code] will result in supersampling. A value of [code]1.0[/code] disables scaling. + Use bilinear scaling for the viewport's 3D buffer. The amount of scaling can be set using [member Viewport.scaling_3d_scale]. Values less then [code]1.0[/code] will result in undersampling while values greater than [code]1.0[/code] will result in supersampling. A value of [code]1.0[/code] disables scaling. </constant> <constant name="VIEWPORT_SCALING_3D_MODE_FSR" value="1" enum="ViewportScaling3DMode"> - Enables FSR upscaling on 3D viewports. The amount of scaling can be set using [member Viewport.scaling_3d_scale]. Values less then [code]1.0[/code] will be result in the viewport being upscaled using FSR. Values greater than [code]1.0[/code] are not supported and bilinear supersampling will be used instead. A value of [code]1.0[/code] disables scaling. + Use AMD FidelityFX Super Resolution 1.0 upscaling for the viewport's 3D buffer. The amount of scaling can be set using [member Viewport.scaling_3d_scale]. Values less then [code]1.0[/code] will be result in the viewport being upscaled using FSR. Values greater than [code]1.0[/code] are not supported and bilinear downsampling will be used instead. A value of [code]1.0[/code] disables scaling. </constant> <constant name="VIEWPORT_SCALING_3D_MODE_MAX" value="2" enum="ViewportScaling3DMode"> </constant> diff --git a/doc/classes/RichTextLabel.xml b/doc/classes/RichTextLabel.xml index e805d3469c..02b67a4a5b 100644 --- a/doc/classes/RichTextLabel.xml +++ b/doc/classes/RichTextLabel.xml @@ -49,6 +49,12 @@ Clears the tag stack and sets [member text] to an empty string. </description> </method> + <method name="deselect"> + <return type="void" /> + <description> + Clears the current selection. + </description> + </method> <method name="get_character_line"> <return type="int" /> <argument index="0" name="character" type="int" /> @@ -88,6 +94,13 @@ Returns the vertical offset of the line found at the provided index. </description> </method> + <method name="get_menu" qualifiers="const"> + <return type="PopupMenu" /> + <description> + Returns the [PopupMenu] of this [RichTextLabel]. By default, this menu is displayed when right-clicking on the [RichTextLabel]. + [b]Warning:[/b] This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their [member Window.visible] property. + </description> + </method> <method name="get_paragraph_count" qualifiers="const"> <return type="int" /> <description> @@ -157,6 +170,12 @@ Installs a custom effect. [code]effect[/code] should be a valid [RichTextEffect]. </description> </method> + <method name="is_menu_visible" qualifiers="const"> + <return type="bool" /> + <description> + Returns whether the menu is visible. Use this instead of [code]get_menu().visible[/code] to improve performance (so the creation of the menu is avoided). + </description> + </method> <method name="newline"> <return type="void" /> <description> @@ -370,6 +389,13 @@ Scrolls the window's top line to match first line of the [code]paragraph[/code]. </description> </method> + <method name="select_all"> + <return type="void" /> + <description> + Select all the text. + If [member selection_enabled] is [code]false[/code], no selection will occur. + </description> + </method> <method name="set_cell_border_color"> <return type="void" /> <argument index="0" name="color" type="Color" /> @@ -420,6 +446,9 @@ If [code]true[/code], the label uses BBCode formatting. </member> <member name="clip_contents" type="bool" setter="set_clip_contents" getter="is_clipping_contents" overrides="Control" default="true" /> + <member name="context_menu_enabled" type="bool" setter="set_context_menu_enabled" getter="is_context_menu_enabled" default="false"> + If [code]true[/code], a right-click displays the context menu. + </member> <member name="custom_effects" type="Array" setter="set_effects" getter="get_effects" default="[]"> The currently installed custom effects. This is an array of [RichTextEffect]s. To add a custom effect, it's more convenient to use [method install_effect]. @@ -456,6 +485,9 @@ <member name="selection_enabled" type="bool" setter="set_selection_enabled" getter="is_selection_enabled" default="false"> If [code]true[/code], the label allows text selection. </member> + <member name="shortcut_keys_enabled" type="bool" setter="set_shortcut_keys_enabled" getter="is_shortcut_keys_enabled" default="true"> + If [code]true[/code], shortcut keys for context menu items are enabled, even if the context menu is disabled. + </member> <member name="structured_text_bidi_override" type="int" setter="set_structured_text_bidi_override" getter="get_structured_text_bidi_override" enum="Control.StructuredTextParser" default="0"> Set BiDi algorithm override for the structured text. </member> diff --git a/doc/classes/Signal.xml b/doc/classes/Signal.xml index c5855e30a4..049e7f8777 100644 --- a/doc/classes/Signal.xml +++ b/doc/classes/Signal.xml @@ -6,6 +6,8 @@ <description> </description> <tutorials> + <link title="Using Signals">$DOCS_URL/getting_started/step_by_step/signals.html</link> + <link title="GDScript Basics">$DOCS_URL/tutorials/scripting/gdscript/gdscript_basics.html#signals</link> </tutorials> <constructors> <constructor name="Signal"> diff --git a/doc/classes/SpinBox.xml b/doc/classes/SpinBox.xml index 5e3eb0c9f8..e84f9c38ff 100644 --- a/doc/classes/SpinBox.xml +++ b/doc/classes/SpinBox.xml @@ -25,6 +25,7 @@ The above code will create a [SpinBox], disable context menu on it and set the text alignment to right. See [Range] class for more options over the [SpinBox]. [b]Note:[/b] [SpinBox] relies on an underlying [LineEdit] node. To theme a [SpinBox]'s background, add theme items for [LineEdit] and customize them. + [b]Note:[/b] If you want to implement drag and drop for the underlying [LineEdit], you can use [method Control.set_drag_forwarding] on the node returned by [method get_line_edit]. </description> <tutorials> </tutorials> diff --git a/doc/classes/TextServer.xml b/doc/classes/TextServer.xml index b4339bef11..9ef800d7e1 100644 --- a/doc/classes/TextServer.xml +++ b/doc/classes/TextServer.xml @@ -1249,9 +1249,9 @@ <method name="shaped_text_get_word_breaks" qualifiers="const"> <return type="PackedInt32Array" /> <argument index="0" name="shaped" type="RID" /> - <argument index="1" name="grapheme_flags" type="int" /> + <argument index="1" name="grapheme_flags" type="int" default="264" /> <description> - Breaks text into words and returns array of character ranges. + Breaks text into words and returns array of character ranges. Use [code]grapheme_flags[/code] to set what characters are used for breaking (see [enum GraphemeFlag]). </description> </method> <method name="shaped_text_hit_test_grapheme" qualifiers="const"> diff --git a/doc/classes/Tree.xml b/doc/classes/Tree.xml index b8c39bee49..5abec4b437 100644 --- a/doc/classes/Tree.xml +++ b/doc/classes/Tree.xml @@ -179,8 +179,9 @@ <return type="Rect2" /> <argument index="0" name="item" type="TreeItem" /> <argument index="1" name="column" type="int" default="-1" /> + <argument index="2" name="button_index" type="int" default="-1" /> <description> - Returns the rectangle area for the specified [TreeItem]. If [code]column[/code] is specified, only get the position and size of that column, otherwise get the rectangle containing all columns. + Returns the rectangle area for the specified [TreeItem]. If [code]column[/code] is specified, only get the position and size of that column, otherwise get the rectangle containing all columns. If a button index is specified, the rectangle of that button will be returned. </description> </method> <method name="get_item_at_position" qualifiers="const"> diff --git a/doc/classes/Viewport.xml b/doc/classes/Viewport.xml index b5916f8c17..6f4720491d 100644 --- a/doc/classes/Viewport.xml +++ b/doc/classes/Viewport.xml @@ -332,10 +332,10 @@ Represents the size of the [enum ShadowAtlasQuadrantSubdiv] enum. </constant> <constant name="SCALING_3D_MODE_BILINEAR" value="0" enum="Scaling3DMode"> - Enables bilinear scaling on 3D viewports. The amount of scaling can be set using [member scaling_3d_scale]. Values less then [code]1.0[/code] will result in undersampling while values greater than [code]1.0[/code] will result in supersampling. A value of [code]1.0[/code] disables scaling. + Use bilinear scaling for the viewport's 3D buffer. The amount of scaling can be set using [member scaling_3d_scale]. Values less then [code]1.0[/code] will result in undersampling while values greater than [code]1.0[/code] will result in supersampling. A value of [code]1.0[/code] disables scaling. </constant> <constant name="SCALING_3D_MODE_FSR" value="1" enum="Scaling3DMode"> - Enables FSR upscaling on 3D viewports. The amount of scaling can be set using [member scaling_3d_scale]. Values less then [code]1.0[/code] will be result in the viewport being upscaled using FSR. Values greater than [code]1.0[/code] are not supported and bilinear supersampling will be used instead. A value of [code]1.0[/code] disables scaling. + Use AMD FidelityFX Super Resolution 1.0 upscaling for the viewport's 3D buffer. The amount of scaling can be set using [member scaling_3d_scale]. Values less then [code]1.0[/code] will be result in the viewport being upscaled using FSR. Values greater than [code]1.0[/code] are not supported and bilinear downsampling will be used instead. A value of [code]1.0[/code] disables scaling. </constant> <constant name="SCALING_3D_MODE_MAX" value="2" enum="Scaling3DMode"> Represents the size of the [enum Scaling3DMode] enum. diff --git a/doc/classes/Window.xml b/doc/classes/Window.xml index 9853f906bc..87a65db192 100644 --- a/doc/classes/Window.xml +++ b/doc/classes/Window.xml @@ -349,6 +349,15 @@ <argument index="0" name="files" type="PackedStringArray" /> <description> Emitted when files are dragged from the OS file manager and dropped in the game window. The argument is a list of file paths. + Note that this method only works with non-embedded windows, i.e. the main window and [Window]-derived nodes when [member Viewport.gui_embed_subwindows] is disabled in the main viewport. + Example usage: + [codeblock] + func _ready(): + get_viewport().files_dropped.connect(on_files_dropped) + + func on_files_dropped(files): + print(files) + [/codeblock] </description> </signal> <signal name="focus_entered"> diff --git a/doc/tools/make_rst.py b/doc/tools/make_rst.py index 365beb434b..eba4cee33a 100755 --- a/doc/tools/make_rst.py +++ b/doc/tools/make_rst.py @@ -58,7 +58,7 @@ strings_l10n = {} def print_error(error, state): # type: (str, State) -> None print("ERROR: {}".format(error)) - state.errored = True + state.num_errors += 1 class TypeName: @@ -163,8 +163,7 @@ class ClassDef: class State: def __init__(self): # type: () -> None - # Has any error been reported? - self.errored = False + self.num_errors = 0 self.classes = OrderedDict() # type: OrderedDict[str, ClassDef] self.current_class = "" # type: str @@ -194,7 +193,7 @@ class State: property_name = property.attrib["name"] if property_name in class_def.properties: - print_error("Duplicate property '{}', file: {}".format(property_name, class_name), self) + print_error('{}.xml: Duplicate property "{}".'.format(class_name, property_name), self) continue type_name = TypeName.from_element(property) @@ -305,7 +304,7 @@ class State: constant_def = ConstantDef(constant_name, value, constant.text) if enum is None: if constant_name in class_def.constants: - print_error("Duplicate constant '{}', file: {}".format(constant_name, class_name), self) + print_error('{}.xml: Duplicate constant "{}".'.format(class_name, constant_name), self) continue class_def.constants[constant_name] = constant_def @@ -328,7 +327,7 @@ class State: signal_name = signal.attrib["name"] if signal_name in class_def.signals: - print_error("Duplicate signal '{}', file: {}".format(signal_name, class_name), self) + print_error('{}.xml: Duplicate signal "{}".'.format(class_name, signal_name), self) continue params = parse_arguments(signal) @@ -351,8 +350,8 @@ class State: theme_item_id = "{}_{}".format(theme_item_data_name, theme_item_name) if theme_item_id in class_def.theme_items: print_error( - "Duplicate theme property '{}' of type '{}', file: {}".format( - theme_item_name, theme_item_data_name, class_name + '{}.xml: Duplicate theme item "{}" of type "{}".'.format( + class_name, theme_item_name, theme_item_data_name ), self, ) @@ -430,7 +429,7 @@ def main(): # type: () -> None if entry.msgid in BASE_STRINGS: strings_l10n[entry.msgid] = entry.msgstr else: - print("No PO file at '{}' for language '{}'.".format(lang_file, args.lang)) + print('No PO file at "{}" for language "{}".'.format(lang_file, args.lang)) print("Checking for errors in the XML class reference...") @@ -453,7 +452,7 @@ def main(): # type: () -> None elif os.path.isfile(path): if not path.endswith(".xml"): - print("Got non-.xml file '{}' in input, skipping.".format(path)) + print('Got non-.xml file "{}" in input, skipping.'.format(path)) continue file_list.append(path) @@ -465,17 +464,17 @@ def main(): # type: () -> None try: tree = ET.parse(cur_file) except ET.ParseError as e: - print_error("Parse error reading file '{}': {}".format(cur_file, e), state) + print_error("{}.xml: Parse error while reading the file: {}".format(cur_file, e), state) continue doc = tree.getroot() if "version" not in doc.attrib: - print_error("Version missing from 'doc', file: {}".format(cur_file), state) + print_error('{}.xml: "version" attribute missing from "doc".'.format(cur_file), state) continue name = doc.attrib["name"] if name in classes: - print_error("Duplicate class '{}'".format(name), state) + print_error('{}.xml: Duplicate class "{}".'.format(cur_file, name), state) continue classes[name] = (doc, cur_file) @@ -484,7 +483,7 @@ def main(): # type: () -> None try: state.parse_class(data[0], data[1]) except Exception as e: - print_error("Exception while parsing class '{}': {}".format(name, e), state) + print_error("{}.xml: Exception while parsing class: {}".format(name, e), state) state.sort_classes() @@ -499,12 +498,17 @@ def main(): # type: () -> None state.current_class = class_name make_rst_class(class_def, state, args.dry_run, args.output) - if not state.errored: - print("No errors found.") + if state.num_errors == 0: + print("No errors found in the class reference XML.") if not args.dry_run: print("Wrote reStructuredText files for each class to: %s" % args.output) else: - print("Errors were found in the class reference XML. Please check the messages above.") + if state.num_errors >= 2: + print( + "%d errors were found in the class reference XML. Please check the messages above." % state.num_errors + ) + else: + print("1 error was found in the class reference XML. Please check the messages above.") exit(1) @@ -856,7 +860,7 @@ def escape_rst(text, until_pos=-1): # type: (str) -> str def format_codeblock(code_type, post_text, indent_level, state): # types: str, str, int, state end_pos = post_text.find("[/" + code_type + "]") if end_pos == -1: - print_error("[" + code_type + "] without a closing tag, file: {}".format(state.current_class), state) + print_error("{}.xml: [" + code_type + "] without a closing tag.".format(state.current_class), state) return None code_text = post_text[len("[" + code_type + "]") : end_pos] @@ -875,9 +879,9 @@ def format_codeblock(code_type, post_text, indent_level, state): # types: str, if to_skip > indent_level: print_error( - "Four spaces should be used for indentation within [" + "{}.xml: Four spaces should be used for indentation within [" + code_type - + "], file: {}".format(state.current_class), + + "].".format(state.current_class), state, ) @@ -987,7 +991,7 @@ def rstize_text(text, state): # type: (str, State) -> str if param.find(".") != -1: ss = param.split(".") if len(ss) > 2: - print_error("Bad reference: '{}', file: {}".format(param, state.current_class), state) + print_error('{}.xml: Bad reference: "{}".'.format(state.current_class, param), state) class_param, method_param = ss else: @@ -1000,33 +1004,31 @@ def rstize_text(text, state): # type: (str, State) -> str if cmd.startswith("constructor"): if method_param not in class_def.constructors: print_error( - "Unresolved constructor '{}', file: {}".format(param, state.current_class), state + '{}.xml: Unresolved constructor "{}".'.format(state.current_class, param), state ) ref_type = "_constructor" if cmd.startswith("method"): if method_param not in class_def.methods: - print_error("Unresolved method '{}', file: {}".format(param, state.current_class), state) + print_error('{}.xml: Unresolved method "{}".'.format(state.current_class, param), state) ref_type = "_method" if cmd.startswith("operator"): if method_param not in class_def.operators: - print_error("Unresolved operator '{}', file: {}".format(param, state.current_class), state) + print_error('{}.xml: Unresolved operator "{}".'.format(state.current_class, param), state) ref_type = "_operator" elif cmd.startswith("member"): if method_param not in class_def.properties: - print_error("Unresolved member '{}', file: {}".format(param, state.current_class), state) + print_error('{}.xml: Unresolved member "{}".'.format(state.current_class, param), state) ref_type = "_property" elif cmd.startswith("theme_item"): if method_param not in class_def.theme_items: - print_error( - "Unresolved theme item '{}', file: {}".format(param, state.current_class), state - ) + print_error('{}.xml: Unresolved theme item "{}".'.format(state.current_class, param), state) ref_type = "_theme_{}".format(class_def.theme_items[method_param].data_name) elif cmd.startswith("signal"): if method_param not in class_def.signals: - print_error("Unresolved signal '{}', file: {}".format(param, state.current_class), state) + print_error('{}.xml: Unresolved signal "{}".'.format(state.current_class, param), state) ref_type = "_signal" elif cmd.startswith("constant"): @@ -1052,13 +1054,13 @@ def rstize_text(text, state): # type: (str, State) -> str break if not found: - print_error("Unresolved constant '{}', file: {}".format(param, state.current_class), state) + print_error('{}.xml: Unresolved constant "{}".'.format(state.current_class, param), state) ref_type = "_constant" else: print_error( - "Unresolved type reference '{}' in method reference '{}', file: {}".format( - class_param, param, state.current_class + '{}.xml: Unresolved type reference "{}" in method reference "{}".'.format( + state.current_class, class_param, param ), state, ) @@ -1078,7 +1080,7 @@ def rstize_text(text, state): # type: (str, State) -> str endurl_pos = text.find("[/url]", endq_pos + 1) if endurl_pos == -1: print_error( - "Tag depth mismatch for [url]: no closing [/url], file: {}".format(state.current_class), state + "{}.xml: Tag depth mismatch for [url]: no closing [/url]".format(state.current_class), state ) break link_title = text[endq_pos + 1 : endurl_pos] @@ -1203,7 +1205,9 @@ def rstize_text(text, state): # type: (str, State) -> str previous_pos = pos if tag_depth > 0: - print_error("Tag depth mismatch: too many/little open/close tags, file: {}".format(state.current_class), state) + print_error( + "{}.xml: Tag depth mismatch: too many (or too little) open/close tags.".format(state.current_class), state + ) return text @@ -1247,7 +1251,7 @@ def make_type(klass, state): # type: (str, State) -> str link_type = link_type[:-2] if link_type in state.classes: return ":ref:`{}<class_{}>`".format(klass, link_type) - print_error("Unresolved type '{}', file: {}".format(klass, state.current_class), state) + print_error('{}.xml: Unresolved type "{}".'.format(state.current_class, klass), state) return klass @@ -1271,7 +1275,7 @@ def make_enum(t, state): # type: (str, State) -> str # Don't fail for `Vector3.Axis`, as this enum is a special case which is expected not to be resolved. if "{}.{}".format(c, e) != "Vector3.Axis": - print_error("Unresolved enum '{}', file: {}".format(t, state.current_class), state) + print_error('{}.xml: Unresolved enum "{}".'.format(state.current_class, t), state) return t @@ -1429,7 +1433,7 @@ def sanitize_operator_name(dirty_name, state): # type: (str, State) -> str else: clear_name = "xxx" - print_error("Unsupported operator type '{}', please add the missing rule.".format(dirty_name), state) + print_error('Unsupported operator type "{}", please add the missing rule.'.format(dirty_name), state) return clear_name diff --git a/drivers/alsa/audio_driver_alsa.cpp b/drivers/alsa/audio_driver_alsa.cpp index 7884269103..f86c4d82ef 100644 --- a/drivers/alsa/audio_driver_alsa.cpp +++ b/drivers/alsa/audio_driver_alsa.cpp @@ -181,7 +181,7 @@ Error AudioDriverALSA::init() { } void AudioDriverALSA::thread_func(void *p_udata) { - AudioDriverALSA *ad = (AudioDriverALSA *)p_udata; + AudioDriverALSA *ad = static_cast<AudioDriverALSA *>(p_udata); while (!ad->exit_thread) { ad->lock(); diff --git a/drivers/alsamidi/midi_driver_alsamidi.cpp b/drivers/alsamidi/midi_driver_alsamidi.cpp index 0674c90cd6..c334146dd2 100644 --- a/drivers/alsamidi/midi_driver_alsamidi.cpp +++ b/drivers/alsamidi/midi_driver_alsamidi.cpp @@ -73,7 +73,7 @@ static int get_message_size(uint8_t message) { } void MIDIDriverALSAMidi::thread_func(void *p_udata) { - MIDIDriverALSAMidi *md = (MIDIDriverALSAMidi *)p_udata; + MIDIDriverALSAMidi *md = static_cast<MIDIDriverALSAMidi *>(p_udata); uint64_t timestamp = 0; uint8_t buffer[256]; int expected_size = 255; diff --git a/drivers/coreaudio/audio_driver_coreaudio.cpp b/drivers/coreaudio/audio_driver_coreaudio.cpp index e2b195350f..276e69e470 100644 --- a/drivers/coreaudio/audio_driver_coreaudio.cpp +++ b/drivers/coreaudio/audio_driver_coreaudio.cpp @@ -42,7 +42,7 @@ OSStatus AudioDriverCoreAudio::input_device_address_cb(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inClientData) { - AudioDriverCoreAudio *driver = (AudioDriverCoreAudio *)inClientData; + AudioDriverCoreAudio *driver = static_cast<AudioDriverCoreAudio *>(inClientData); // If our selected device is the Default call set_device to update the // kAudioOutputUnitProperty_CurrentDevice property @@ -56,7 +56,7 @@ OSStatus AudioDriverCoreAudio::input_device_address_cb(AudioObjectID inObjectID, OSStatus AudioDriverCoreAudio::output_device_address_cb(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inClientData) { - AudioDriverCoreAudio *driver = (AudioDriverCoreAudio *)inClientData; + AudioDriverCoreAudio *driver = static_cast<AudioDriverCoreAudio *>(inClientData); // If our selected device is the Default call set_device to update the // kAudioOutputUnitProperty_CurrentDevice property @@ -168,7 +168,7 @@ OSStatus AudioDriverCoreAudio::output_callback(void *inRefCon, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { - AudioDriverCoreAudio *ad = (AudioDriverCoreAudio *)inRefCon; + AudioDriverCoreAudio *ad = static_cast<AudioDriverCoreAudio *>(inRefCon); if (!ad->active || !ad->try_lock()) { for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) { @@ -209,7 +209,7 @@ OSStatus AudioDriverCoreAudio::input_callback(void *inRefCon, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { - AudioDriverCoreAudio *ad = (AudioDriverCoreAudio *)inRefCon; + AudioDriverCoreAudio *ad = static_cast<AudioDriverCoreAudio *>(inRefCon); if (!ad->active) { return 0; } diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp index 2b8241cd40..1ddaf3d6a7 100644 --- a/drivers/gles3/rasterizer_canvas_gles3.cpp +++ b/drivers/gles3/rasterizer_canvas_gles3.cpp @@ -363,7 +363,6 @@ void RasterizerCanvasGLES3::_render_item(RID p_render_target, const Item *p_item state.instance_data_array[r_index].dst_rect[i] = 0.0; state.instance_data_array[r_index].lights[i] = uint32_t(0); } - state.instance_data_array[r_index].flags = base_flags; state.instance_data_array[r_index].color_texture_pixel_size[0] = 0.0; state.instance_data_array[r_index].color_texture_pixel_size[1] = 0.0; diff --git a/drivers/gles3/rasterizer_canvas_gles3.h b/drivers/gles3/rasterizer_canvas_gles3.h index 4e825ab8b2..70066c5e2a 100644 --- a/drivers/gles3/rasterizer_canvas_gles3.h +++ b/drivers/gles3/rasterizer_canvas_gles3.h @@ -169,7 +169,7 @@ public: LocalVector<GLsync> fences; uint32_t current_buffer = 0; - InstanceData *instance_data_array; + InstanceData *instance_data_array = nullptr; bool canvas_texscreen_used; CanvasShaderGLES3 canvas_shader; RID canvas_shader_current_version; @@ -198,7 +198,7 @@ public: bool end_batch = false; Transform3D vp; - Light *using_light; + Light *using_light = nullptr; bool using_shadow; bool using_transparent_rt; @@ -220,9 +220,9 @@ public: typedef void Texture; - RasterizerSceneGLES3 *scene_render; + RasterizerSceneGLES3 *scene_render = nullptr; - RasterizerStorageGLES3 *storage; + RasterizerStorageGLES3 *storage = nullptr; void _set_uniforms(); diff --git a/drivers/gles3/rasterizer_gles3.h b/drivers/gles3/rasterizer_gles3.h index 55ee54e992..2279a502a2 100644 --- a/drivers/gles3/rasterizer_gles3.h +++ b/drivers/gles3/rasterizer_gles3.h @@ -41,6 +41,7 @@ #include "storage/config.h" #include "storage/decal_atlas_storage.h" #include "storage/material_storage.h" +#include "storage/mesh_storage.h" #include "storage/render_target_storage.h" #include "storage/texture_storage.h" @@ -57,6 +58,7 @@ protected: GLES3::TextureStorage texture_storage; GLES3::DecalAtlasStorage decal_atlas_storage; GLES3::MaterialStorage material_storage; + GLES3::MeshStorage mesh_storage; RasterizerStorageGLES3 storage; RasterizerCanvasGLES3 canvas; RasterizerSceneGLES3 scene; @@ -66,6 +68,7 @@ protected: public: RendererCanvasTextureStorage *get_canvas_texture_storage() { return &canvas_texture_storage; } RendererMaterialStorage *get_material_storage() { return &material_storage; } + RendererMeshStorage *get_mesh_storage() { return &mesh_storage; } RendererTextureStorage *get_texture_storage() { return &texture_storage; } RendererDecalAtlasStorage *get_decal_atlas_storage() { return &decal_atlas_storage; } RendererStorage *get_storage() { return &storage; } diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp index c71423a45d..3517d985f0 100644 --- a/drivers/gles3/rasterizer_storage_gles3.cpp +++ b/drivers/gles3/rasterizer_storage_gles3.cpp @@ -58,202 +58,6 @@ RID RasterizerStorageGLES3::sky_create() { void RasterizerStorageGLES3::sky_set_texture(RID p_sky, RID p_panorama, int p_radiance_size) { } -/* MESH API */ - -RID RasterizerStorageGLES3::mesh_allocate() { - return RID(); -} - -void RasterizerStorageGLES3::mesh_initialize(RID p_rid) { -} - -void RasterizerStorageGLES3::mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) { -} - -bool RasterizerStorageGLES3::mesh_needs_instance(RID p_mesh, bool p_has_skeleton) { - return false; -} - -RID RasterizerStorageGLES3::mesh_instance_create(RID p_base) { - return RID(); -} - -void RasterizerStorageGLES3::mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) { -} - -void RasterizerStorageGLES3::mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) { -} - -void RasterizerStorageGLES3::mesh_instance_check_for_update(RID p_mesh_instance) { -} - -void RasterizerStorageGLES3::update_mesh_instances() { -} - -void RasterizerStorageGLES3::reflection_probe_set_mesh_lod_threshold(RID p_probe, float p_ratio) { -} - -float RasterizerStorageGLES3::reflection_probe_get_mesh_lod_threshold(RID p_probe) const { - return 0.0; -} - -void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) { -} - -int RasterizerStorageGLES3::mesh_get_blend_shape_count(RID p_mesh) const { - return 0; -} - -void RasterizerStorageGLES3::mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) { -} - -RS::BlendShapeMode RasterizerStorageGLES3::mesh_get_blend_shape_mode(RID p_mesh) const { - return RS::BLEND_SHAPE_MODE_NORMALIZED; -} - -void RasterizerStorageGLES3::mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { -} - -void RasterizerStorageGLES3::mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { -} - -void RasterizerStorageGLES3::mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { -} - -void RasterizerStorageGLES3::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) { -} - -RID RasterizerStorageGLES3::mesh_surface_get_material(RID p_mesh, int p_surface) const { - return RID(); -} - -RS::SurfaceData RasterizerStorageGLES3::mesh_get_surface(RID p_mesh, int p_surface) const { - return RS::SurfaceData(); -} - -int RasterizerStorageGLES3::mesh_get_surface_count(RID p_mesh) const { - return 1; -} - -void RasterizerStorageGLES3::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) { -} - -AABB RasterizerStorageGLES3::mesh_get_custom_aabb(RID p_mesh) const { - return AABB(); -} - -AABB RasterizerStorageGLES3::mesh_get_aabb(RID p_mesh, RID p_skeleton) { - return AABB(); -} - -void RasterizerStorageGLES3::mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) { -} - -void RasterizerStorageGLES3::mesh_clear(RID p_mesh) { -} - -/* MULTIMESH API */ - -RID RasterizerStorageGLES3::multimesh_allocate() { - return RID(); -} - -void RasterizerStorageGLES3::multimesh_initialize(RID p_rid) { -} - -void RasterizerStorageGLES3::multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors, bool p_use_custom_data) { -} - -int RasterizerStorageGLES3::multimesh_get_instance_count(RID p_multimesh) const { - return 0; -} - -void RasterizerStorageGLES3::multimesh_set_mesh(RID p_multimesh, RID p_mesh) { -} - -void RasterizerStorageGLES3::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) { -} - -void RasterizerStorageGLES3::multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) { -} - -void RasterizerStorageGLES3::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) { -} - -void RasterizerStorageGLES3::multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) { -} - -RID RasterizerStorageGLES3::multimesh_get_mesh(RID p_multimesh) const { - return RID(); -} - -AABB RasterizerStorageGLES3::multimesh_get_aabb(RID p_multimesh) const { - return AABB(); -} - -Transform3D RasterizerStorageGLES3::multimesh_instance_get_transform(RID p_multimesh, int p_index) const { - return Transform3D(); -} - -Transform2D RasterizerStorageGLES3::multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const { - return Transform2D(); -} - -Color RasterizerStorageGLES3::multimesh_instance_get_color(RID p_multimesh, int p_index) const { - return Color(); -} - -Color RasterizerStorageGLES3::multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const { - return Color(); -} - -void RasterizerStorageGLES3::multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) { -} - -Vector<float> RasterizerStorageGLES3::multimesh_get_buffer(RID p_multimesh) const { - return Vector<float>(); -} - -void RasterizerStorageGLES3::multimesh_set_visible_instances(RID p_multimesh, int p_visible) { -} - -int RasterizerStorageGLES3::multimesh_get_visible_instances(RID p_multimesh) const { - return 0; -} - -/* SKELETON API */ - -RID RasterizerStorageGLES3::skeleton_allocate() { - return RID(); -} - -void RasterizerStorageGLES3::skeleton_initialize(RID p_rid) { -} - -void RasterizerStorageGLES3::skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton) { -} - -void RasterizerStorageGLES3::skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) { -} - -int RasterizerStorageGLES3::skeleton_get_bone_count(RID p_skeleton) const { - return 0; -} - -void RasterizerStorageGLES3::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) { -} - -Transform3D RasterizerStorageGLES3::skeleton_bone_get_transform(RID p_skeleton, int p_bone) const { - return Transform3D(); -} - -void RasterizerStorageGLES3::skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) { -} - -Transform2D RasterizerStorageGLES3::skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const { - return Transform2D(); -} - /* Light API */ RID RasterizerStorageGLES3::directional_light_allocate() { @@ -450,7 +254,11 @@ bool RasterizerStorageGLES3::reflection_probe_renders_shadows(RID p_probe) const void RasterizerStorageGLES3::base_update_dependency(RID p_base, DependencyTracker *p_instance) { } -void RasterizerStorageGLES3::skeleton_update_dependency(RID p_base, DependencyTracker *p_instance) { +void RasterizerStorageGLES3::reflection_probe_set_mesh_lod_threshold(RID p_probe, float p_ratio) { +} + +float RasterizerStorageGLES3::reflection_probe_get_mesh_lod_threshold(RID p_probe) const { + return 0.0; } /* VOXEL GI API */ diff --git a/drivers/gles3/rasterizer_storage_gles3.h b/drivers/gles3/rasterizer_storage_gles3.h index b9022142dd..105529ee3d 100644 --- a/drivers/gles3/rasterizer_storage_gles3.h +++ b/drivers/gles3/rasterizer_storage_gles3.h @@ -132,143 +132,6 @@ public: RID sky_create(); void sky_set_texture(RID p_sky, RID p_panorama, int p_radiance_size); - /* MESH API */ - - RID mesh_allocate() override; - void mesh_initialize(RID p_rid) override; - void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) override; - bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) override; - RID mesh_instance_create(RID p_base) override; - void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) override; - void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) override; - void mesh_instance_check_for_update(RID p_mesh_instance) override; - void update_mesh_instances() override; - void reflection_probe_set_mesh_lod_threshold(RID p_probe, float p_ratio) override; - float reflection_probe_get_mesh_lod_threshold(RID p_probe) const override; - - void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) override; - - int mesh_get_blend_shape_count(RID p_mesh) const override; - - void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) override; - RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const override; - - void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; - void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; - void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; - - void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) override; - RID mesh_surface_get_material(RID p_mesh, int p_surface) const override; - - RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const override; - int mesh_get_surface_count(RID p_mesh) const override; - - void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) override; - AABB mesh_get_custom_aabb(RID p_mesh) const override; - - AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) override; - void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) override; - void mesh_clear(RID p_mesh) override; - - /* MULTIMESH API */ - - struct MultiMesh { - RID mesh; - int instances = 0; - RS::MultimeshTransformFormat xform_format = RS::MULTIMESH_TRANSFORM_3D; - bool uses_colors = false; - bool uses_custom_data = false; - int visible_instances = -1; - AABB aabb; - bool aabb_dirty = false; - bool buffer_set = false; - uint32_t stride_cache = 0; - uint32_t color_offset_cache = 0; - uint32_t custom_data_offset_cache = 0; - - Vector<float> data_cache; //used if individual setting is used - bool *data_cache_dirty_regions = nullptr; - uint32_t data_cache_used_dirty_regions = 0; - - RID buffer; //storage buffer - RID uniform_set_3d; - RID uniform_set_2d; - - bool dirty = false; - MultiMesh *dirty_list = nullptr; - - Dependency dependency; - }; - - mutable RID_Owner<MultiMesh, true> multimesh_owner; - - MultiMesh *multimesh_dirty_list = nullptr; - - _FORCE_INLINE_ void _multimesh_make_local(MultiMesh *multimesh) const; - _FORCE_INLINE_ void _multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb); - _FORCE_INLINE_ void _multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb); - _FORCE_INLINE_ void _multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances); - void _update_dirty_multimeshes(); - - RID multimesh_allocate() override; - void multimesh_initialize(RID p_rid) override; - void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) override; - int multimesh_get_instance_count(RID p_multimesh) const override; - - void multimesh_set_mesh(RID p_multimesh, RID p_mesh) override; - void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) override; - void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) override; - void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) override; - void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) override; - - RID multimesh_get_mesh(RID p_multimesh) const override; - AABB multimesh_get_aabb(RID p_multimesh) const override; - - Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const override; - Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const override; - Color multimesh_instance_get_color(RID p_multimesh, int p_index) const override; - Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const override; - void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) override; - Vector<float> multimesh_get_buffer(RID p_multimesh) const override; - - void multimesh_set_visible_instances(RID p_multimesh, int p_visible) override; - int multimesh_get_visible_instances(RID p_multimesh) const override; - - _FORCE_INLINE_ RS::MultimeshTransformFormat multimesh_get_transform_format(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - return multimesh->xform_format; - } - - _FORCE_INLINE_ bool multimesh_uses_colors(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - return multimesh->uses_colors; - } - - _FORCE_INLINE_ bool multimesh_uses_custom_data(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - return multimesh->uses_custom_data; - } - - _FORCE_INLINE_ uint32_t multimesh_get_instances_to_draw(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - if (multimesh->visible_instances >= 0) { - return multimesh->visible_instances; - } - return multimesh->instances; - } - - /* SKELETON API */ - - RID skeleton_allocate() override; - void skeleton_initialize(RID p_rid) override; - void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) override; - void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) override; - int skeleton_get_bone_count(RID p_skeleton) const override; - void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) override; - Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const override; - void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) override; - Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const override; - /* Light API */ RID directional_light_allocate() override; @@ -328,6 +191,8 @@ public: void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) override; void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) override; void reflection_probe_set_resolution(RID p_probe, int p_resolution) override; + void reflection_probe_set_mesh_lod_threshold(RID p_probe, float p_ratio) override; + float reflection_probe_get_mesh_lod_threshold(RID p_probe) const override; AABB reflection_probe_get_aabb(RID p_probe) const override; RS::ReflectionProbeUpdateMode reflection_probe_get_update_mode(RID p_probe) const override; @@ -338,7 +203,6 @@ public: bool reflection_probe_renders_shadows(RID p_probe) const override; void base_update_dependency(RID p_base, DependencyTracker *p_instance) override; - void skeleton_update_dependency(RID p_base, DependencyTracker *p_instance) override; /* VOXEL GI API */ diff --git a/drivers/gles3/shader_gles3.cpp b/drivers/gles3/shader_gles3.cpp index 9349722625..1c946895a5 100644 --- a/drivers/gles3/shader_gles3.cpp +++ b/drivers/gles3/shader_gles3.cpp @@ -464,8 +464,8 @@ bool ShaderGLES3::_load_from_cache(Version *p_version) { String sha1 = _version_get_sha1(p_version); String path = shader_cache_dir.plus_file(name).plus_file(base_sha256).plus_file(sha1) + ".cache"; - FileAccessRef f = FileAccess::open(path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(path, FileAccess::READ); + if (f.is_null()) { return false; } @@ -530,8 +530,8 @@ void ShaderGLES3::_save_to_cache(Version *p_version) { String sha1 = _version_get_sha1(p_version); String path = shader_cache_dir.plus_file(name).plus_file(base_sha256).plus_file(sha1) + ".cache"; - FileAccessRef f = FileAccess::open(path, FileAccess::WRITE); - ERR_FAIL_COND(!f); + Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE); + ERR_FAIL_COND(f.is_null()); f->store_buffer((const uint8_t *)shader_file_header, 4); f->store_32(cache_file_version); //file version uint32_t variant_count = variant_count; @@ -541,8 +541,6 @@ void ShaderGLES3::_save_to_cache(Version *p_version) { f->store_32(p_version->variant_data[i].size()); //stage count f->store_buffer(p_version->variant_data[i].ptr(), p_version->variant_data[i].size()); } - - f->close(); #endif } @@ -554,11 +552,9 @@ void ShaderGLES3::_clear_version(Version *p_version) { for (int i = 0; i < variant_count; i++) { for (OAHashMap<uint64_t, Version::Specialization>::Iterator it = p_version->variants[i].iter(); it.valid; it = p_version->variants[i].next_iter(it)) { - if (it.valid) { - glDeleteShader(it.value->vert_id); - glDeleteShader(it.value->frag_id); - glDeleteProgram(it.value->id); - } + glDeleteShader(it.value->vert_id); + glDeleteShader(it.value->frag_id); + glDeleteProgram(it.value->id); } } @@ -644,8 +640,8 @@ void ShaderGLES3::initialize(const String &p_general_defines, int p_base_texture base_sha256 = hash_build.as_string().sha256_text(); - DirAccessRef d = DirAccess::open(shader_cache_dir); - ERR_FAIL_COND(!d); + Ref<DirAccess> d = DirAccess::open(shader_cache_dir); + ERR_FAIL_COND(d.is_null()); if (d->change_dir(name) != OK) { Error err = d->make_dir(name); ERR_FAIL_COND(err != OK); diff --git a/drivers/gles3/storage/material_storage.cpp b/drivers/gles3/storage/material_storage.cpp index f773a6160a..e519c428d2 100644 --- a/drivers/gles3/storage/material_storage.cpp +++ b/drivers/gles3/storage/material_storage.cpp @@ -576,10 +576,10 @@ void MaterialStorage::_update_material(Material *p_material) { } { - bool can_cast_shadow = false; - bool is_animated = false; - if (p_material->shader && p_material->shader->mode == RS::SHADER_SPATIAL) { + bool can_cast_shadow = false; + bool is_animated = false; + if (p_material->shader->spatial.blend_mode == Shader::Spatial::BLEND_MODE_MIX && (!p_material->shader->spatial.uses_alpha || p_material->shader->spatial.depth_draw_mode == Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS)) { can_cast_shadow = true; diff --git a/drivers/gles3/storage/material_storage.h b/drivers/gles3/storage/material_storage.h index bf17e66c2f..450ee7191f 100644 --- a/drivers/gles3/storage/material_storage.h +++ b/drivers/gles3/storage/material_storage.h @@ -66,7 +66,7 @@ struct Shader { RID self; RS::ShaderMode mode; - ShaderGLES3 *shader; + ShaderGLES3 *shader = nullptr; String code; SelfList<Material>::List materials; @@ -185,7 +185,7 @@ struct Shader { struct Material { RID self; - Shader *shader; + Shader *shader = nullptr; Map<StringName, Variant> params; SelfList<Material> list; SelfList<Material> dirty_list; diff --git a/drivers/gles3/storage/mesh_storage.cpp b/drivers/gles3/storage/mesh_storage.cpp new file mode 100644 index 0000000000..c2a431aff1 --- /dev/null +++ b/drivers/gles3/storage/mesh_storage.cpp @@ -0,0 +1,257 @@ +/*************************************************************************/ +/* mesh_storage.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifdef GLES3_ENABLED + +#include "mesh_storage.h" + +using namespace GLES3; + +MeshStorage *MeshStorage::singleton = nullptr; + +MeshStorage *MeshStorage::get_singleton() { + return singleton; +} + +MeshStorage::MeshStorage() { + singleton = this; +} + +MeshStorage::~MeshStorage() { + singleton = nullptr; +} + +/* MESH API */ + +RID MeshStorage::mesh_allocate() { + return RID(); +} + +void MeshStorage::mesh_initialize(RID p_rid) { +} + +void MeshStorage::mesh_free(RID p_rid) { +} + +void MeshStorage::mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) { +} + +bool MeshStorage::mesh_needs_instance(RID p_mesh, bool p_has_skeleton) { + return false; +} + +void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) { +} + +int MeshStorage::mesh_get_blend_shape_count(RID p_mesh) const { + return 0; +} + +void MeshStorage::mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) { +} + +RS::BlendShapeMode MeshStorage::mesh_get_blend_shape_mode(RID p_mesh) const { + return RS::BLEND_SHAPE_MODE_NORMALIZED; +} + +void MeshStorage::mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { +} + +void MeshStorage::mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { +} + +void MeshStorage::mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { +} + +void MeshStorage::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) { +} + +RID MeshStorage::mesh_surface_get_material(RID p_mesh, int p_surface) const { + return RID(); +} + +RS::SurfaceData MeshStorage::mesh_get_surface(RID p_mesh, int p_surface) const { + return RS::SurfaceData(); +} + +int MeshStorage::mesh_get_surface_count(RID p_mesh) const { + return 1; +} + +void MeshStorage::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) { +} + +AABB MeshStorage::mesh_get_custom_aabb(RID p_mesh) const { + return AABB(); +} + +AABB MeshStorage::mesh_get_aabb(RID p_mesh, RID p_skeleton) { + return AABB(); +} + +void MeshStorage::mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) { +} + +void MeshStorage::mesh_clear(RID p_mesh) { +} + +/* MESH INSTANCE API */ + +RID MeshStorage::mesh_instance_create(RID p_base) { + return RID(); +} + +void MeshStorage::mesh_instance_free(RID p_rid) { +} + +void MeshStorage::mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) { +} + +void MeshStorage::mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) { +} + +void MeshStorage::mesh_instance_check_for_update(RID p_mesh_instance) { +} + +void MeshStorage::update_mesh_instances() { +} + +/* MULTIMESH API */ + +RID MeshStorage::multimesh_allocate() { + return RID(); +} + +void MeshStorage::multimesh_initialize(RID p_rid) { +} + +void MeshStorage::multimesh_free(RID p_rid) { +} + +void MeshStorage::multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors, bool p_use_custom_data) { +} + +int MeshStorage::multimesh_get_instance_count(RID p_multimesh) const { + return 0; +} + +void MeshStorage::multimesh_set_mesh(RID p_multimesh, RID p_mesh) { +} + +void MeshStorage::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) { +} + +void MeshStorage::multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) { +} + +void MeshStorage::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) { +} + +void MeshStorage::multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) { +} + +RID MeshStorage::multimesh_get_mesh(RID p_multimesh) const { + return RID(); +} + +AABB MeshStorage::multimesh_get_aabb(RID p_multimesh) const { + return AABB(); +} + +Transform3D MeshStorage::multimesh_instance_get_transform(RID p_multimesh, int p_index) const { + return Transform3D(); +} + +Transform2D MeshStorage::multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const { + return Transform2D(); +} + +Color MeshStorage::multimesh_instance_get_color(RID p_multimesh, int p_index) const { + return Color(); +} + +Color MeshStorage::multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const { + return Color(); +} + +void MeshStorage::multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) { +} + +Vector<float> MeshStorage::multimesh_get_buffer(RID p_multimesh) const { + return Vector<float>(); +} + +void MeshStorage::multimesh_set_visible_instances(RID p_multimesh, int p_visible) { +} + +int MeshStorage::multimesh_get_visible_instances(RID p_multimesh) const { + return 0; +} + +/* SKELETON API */ + +RID MeshStorage::skeleton_allocate() { + return RID(); +} + +void MeshStorage::skeleton_initialize(RID p_rid) { +} + +void MeshStorage::skeleton_free(RID p_rid) { +} + +void MeshStorage::skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton) { +} + +void MeshStorage::skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) { +} + +int MeshStorage::skeleton_get_bone_count(RID p_skeleton) const { + return 0; +} + +void MeshStorage::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) { +} + +Transform3D MeshStorage::skeleton_bone_get_transform(RID p_skeleton, int p_bone) const { + return Transform3D(); +} + +void MeshStorage::skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) { +} + +Transform2D MeshStorage::skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const { + return Transform2D(); +} + +void MeshStorage::skeleton_update_dependency(RID p_base, RendererStorage::DependencyTracker *p_instance) { +} + +#endif // GLES3_ENABLED diff --git a/drivers/gles3/storage/mesh_storage.h b/drivers/gles3/storage/mesh_storage.h new file mode 100644 index 0000000000..3f44908049 --- /dev/null +++ b/drivers/gles3/storage/mesh_storage.h @@ -0,0 +1,204 @@ +/*************************************************************************/ +/* mesh_storage.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef MESH_STORAGE_GLES3_H +#define MESH_STORAGE_GLES3_H + +#ifdef GLES3_ENABLED + +#include "core/templates/local_vector.h" +#include "core/templates/rid_owner.h" +#include "core/templates/self_list.h" +#include "servers/rendering/storage/mesh_storage.h" + +namespace GLES3 { + +class MeshStorage : public RendererMeshStorage { +private: + static MeshStorage *singleton; + +public: + static MeshStorage *get_singleton(); + + MeshStorage(); + virtual ~MeshStorage(); + + /* MESH API */ + + virtual RID mesh_allocate() override; + virtual void mesh_initialize(RID p_rid) override; + virtual void mesh_free(RID p_rid) override; + + virtual void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) override; + virtual bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) override; + + virtual void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) override; + + virtual int mesh_get_blend_shape_count(RID p_mesh) const override; + + virtual void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) override; + virtual RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const override; + + virtual void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; + virtual void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; + virtual void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; + + virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) override; + virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const override; + + virtual RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const override; + virtual int mesh_get_surface_count(RID p_mesh) const override; + + virtual void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) override; + virtual AABB mesh_get_custom_aabb(RID p_mesh) const override; + + virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) override; + virtual void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) override; + virtual void mesh_clear(RID p_mesh) override; + + /* MESH INSTANCE API */ + + virtual RID mesh_instance_create(RID p_base) override; + virtual void mesh_instance_free(RID p_rid) override; + virtual void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) override; + virtual void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) override; + virtual void mesh_instance_check_for_update(RID p_mesh_instance) override; + virtual void update_mesh_instances() override; + + /* MULTIMESH API */ + + struct MultiMesh { + RID mesh; + int instances = 0; + RS::MultimeshTransformFormat xform_format = RS::MULTIMESH_TRANSFORM_3D; + bool uses_colors = false; + bool uses_custom_data = false; + int visible_instances = -1; + AABB aabb; + bool aabb_dirty = false; + bool buffer_set = false; + uint32_t stride_cache = 0; + uint32_t color_offset_cache = 0; + uint32_t custom_data_offset_cache = 0; + + Vector<float> data_cache; //used if individual setting is used + bool *data_cache_dirty_regions = nullptr; + uint32_t data_cache_used_dirty_regions = 0; + + RID buffer; //storage buffer + RID uniform_set_3d; + RID uniform_set_2d; + + bool dirty = false; + MultiMesh *dirty_list = nullptr; + + RendererStorage::Dependency dependency; + }; + + mutable RID_Owner<MultiMesh, true> multimesh_owner; + + MultiMesh *multimesh_dirty_list = nullptr; + + _FORCE_INLINE_ void _multimesh_make_local(MultiMesh *multimesh) const; + _FORCE_INLINE_ void _multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb); + _FORCE_INLINE_ void _multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb); + _FORCE_INLINE_ void _multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances); + void _update_dirty_multimeshes(); + + virtual RID multimesh_allocate() override; + virtual void multimesh_initialize(RID p_rid) override; + virtual void multimesh_free(RID p_rid) override; + virtual void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) override; + virtual int multimesh_get_instance_count(RID p_multimesh) const override; + + virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) override; + virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) override; + virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) override; + virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) override; + virtual void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) override; + + virtual RID multimesh_get_mesh(RID p_multimesh) const override; + virtual AABB multimesh_get_aabb(RID p_multimesh) const override; + + virtual Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const override; + virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const override; + virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const override; + virtual Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const override; + virtual void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) override; + virtual Vector<float> multimesh_get_buffer(RID p_multimesh) const override; + + virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) override; + virtual int multimesh_get_visible_instances(RID p_multimesh) const override; + + _FORCE_INLINE_ RS::MultimeshTransformFormat multimesh_get_transform_format(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + return multimesh->xform_format; + } + + _FORCE_INLINE_ bool multimesh_uses_colors(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + return multimesh->uses_colors; + } + + _FORCE_INLINE_ bool multimesh_uses_custom_data(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + return multimesh->uses_custom_data; + } + + _FORCE_INLINE_ uint32_t multimesh_get_instances_to_draw(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + if (multimesh->visible_instances >= 0) { + return multimesh->visible_instances; + } + return multimesh->instances; + } + + /* SKELETON API */ + + virtual RID skeleton_allocate() override; + virtual void skeleton_initialize(RID p_rid) override; + virtual void skeleton_free(RID p_rid) override; + + virtual void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) override; + virtual void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) override; + virtual int skeleton_get_bone_count(RID p_skeleton) const override; + virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) override; + virtual Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const override; + virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) override; + virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const override; + + virtual void skeleton_update_dependency(RID p_base, RendererStorage::DependencyTracker *p_instance) override; +}; + +} // namespace GLES3 + +#endif // GLES3_ENABLED + +#endif // !MESH_STORAGE_GLES3_H diff --git a/drivers/gles3/storage/texture_storage.h b/drivers/gles3/storage/texture_storage.h index 8a921fbe10..7656cdf67e 100644 --- a/drivers/gles3/storage/texture_storage.h +++ b/drivers/gles3/storage/texture_storage.h @@ -93,7 +93,7 @@ enum OpenGLTextureFlags { struct Texture { RID self; - Texture *proxy; + Texture *proxy = nullptr; Set<Texture *> proxy_owners; String path; @@ -125,20 +125,20 @@ struct Texture { uint16_t stored_cube_sides; - RenderTarget *render_target; + RenderTarget *render_target = nullptr; Vector<Ref<Image>> images; bool redraw_if_visible; RS::TextureDetectCallback detect_3d; - void *detect_3d_ud; + void *detect_3d_ud = nullptr; RS::TextureDetectCallback detect_srgb; - void *detect_srgb_ud; + void *detect_srgb_ud = nullptr; RS::TextureDetectCallback detect_normal; - void *detect_normal_ud; + void *detect_normal_ud = nullptr; CanvasTexture *canvas_texture = nullptr; diff --git a/drivers/gles3/texture_loader_gles3.cpp b/drivers/gles3/texture_loader_gles3.cpp index f8d4cfdc61..8c8724686d 100644 --- a/drivers/gles3/texture_loader_gles3.cpp +++ b/drivers/gles3/texture_loader_gles3.cpp @@ -52,7 +52,7 @@ RES ResourceFormatGLES2Texture::load(const String &p_path, const String &p_origi uint8_t **row_p = memnew_arr(uint8_t *, height); for (unsigned int i = 0; i < height; i++) { - row_p[i] = 0; //No colors any more, I want them to turn black + row_p[i] = nullptr; // No colors any more, I want them to turn black. } memdelete_arr(row_p); diff --git a/drivers/png/image_loader_png.cpp b/drivers/png/image_loader_png.cpp index 46e271f9c9..917bfec574 100644 --- a/drivers/png/image_loader_png.cpp +++ b/drivers/png/image_loader_png.cpp @@ -36,18 +36,16 @@ #include <string.h> -Error ImageLoaderPNG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale) { +Error ImageLoaderPNG::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) { const uint64_t buffer_size = f->get_length(); Vector<uint8_t> file_buffer; Error err = file_buffer.resize(buffer_size); if (err) { - f->close(); return err; } { uint8_t *writer = file_buffer.ptrw(); f->get_buffer(writer, buffer_size); - f->close(); } const uint8_t *reader = file_buffer.ptr(); return PNGDriverCommon::png_to_image(reader, buffer_size, p_force_linear, p_image); diff --git a/drivers/png/image_loader_png.h b/drivers/png/image_loader_png.h index af3bcd5b66..522cc901d4 100644 --- a/drivers/png/image_loader_png.h +++ b/drivers/png/image_loader_png.h @@ -40,7 +40,7 @@ private: static Ref<Image> load_mem_png(const uint8_t *p_png, int p_size); public: - virtual Error load_image(Ref<Image> p_image, FileAccess *f, bool p_force_linear, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderPNG(); }; diff --git a/drivers/png/resource_saver_png.cpp b/drivers/png/resource_saver_png.cpp index ca84fb6be9..8633d2dc4e 100644 --- a/drivers/png/resource_saver_png.cpp +++ b/drivers/png/resource_saver_png.cpp @@ -52,20 +52,16 @@ Error ResourceSaverPNG::save_image(const String &p_path, const Ref<Image> &p_img Vector<uint8_t> buffer; Error err = PNGDriverCommon::image_to_png(p_img, buffer); ERR_FAIL_COND_V_MSG(err, err, "Can't convert image to PNG."); - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save PNG at path: '%s'.", p_path)); const uint8_t *reader = buffer.ptr(); file->store_buffer(reader, buffer.size()); if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { - memdelete(file); return ERR_CANT_CREATE; } - file->close(); - memdelete(file); - return OK; } diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.cpp b/drivers/pulseaudio/audio_driver_pulseaudio.cpp index ef9bbc3483..0c27b76ed8 100644 --- a/drivers/pulseaudio/audio_driver_pulseaudio.cpp +++ b/drivers/pulseaudio/audio_driver_pulseaudio.cpp @@ -41,7 +41,7 @@ #endif void AudioDriverPulseAudio::pa_state_cb(pa_context *c, void *userdata) { - AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata; + AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata); switch (pa_context_get_state(c)) { case PA_CONTEXT_TERMINATED: @@ -65,7 +65,7 @@ void AudioDriverPulseAudio::pa_state_cb(pa_context *c, void *userdata) { } void AudioDriverPulseAudio::pa_sink_info_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata) { - AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata; + AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata); // If eol is set to a positive number, you're at the end of the list if (eol > 0) { @@ -84,7 +84,7 @@ void AudioDriverPulseAudio::pa_sink_info_cb(pa_context *c, const pa_sink_info *l } void AudioDriverPulseAudio::pa_source_info_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata) { - AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata; + AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata); // If eol is set to a positive number, you're at the end of the list if (eol > 0) { @@ -104,7 +104,7 @@ void AudioDriverPulseAudio::pa_source_info_cb(pa_context *c, const pa_source_inf void AudioDriverPulseAudio::pa_server_info_cb(pa_context *c, const pa_server_info *i, void *userdata) { ERR_FAIL_COND_MSG(!i, "PulseAudio server info is null."); - AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata; + AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata); ad->capture_default_device = i->default_source_name; ad->default_device = i->default_sink_name; @@ -588,7 +588,7 @@ AudioDriver::SpeakerMode AudioDriverPulseAudio::get_speaker_mode() const { } void AudioDriverPulseAudio::pa_sinklist_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata) { - AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata; + AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata); // If eol is set to a positive number, you're at the end of the list if (eol > 0) { @@ -771,7 +771,7 @@ void AudioDriverPulseAudio::capture_set_device(const String &p_name) { } void AudioDriverPulseAudio::pa_sourcelist_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata) { - AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)userdata; + AudioDriverPulseAudio *ad = static_cast<AudioDriverPulseAudio *>(userdata); // If eol is set to a positive number, you're at the end of the list if (eol > 0) { diff --git a/drivers/unix/dir_access_unix.cpp b/drivers/unix/dir_access_unix.cpp index af47173b41..7e6105f033 100644 --- a/drivers/unix/dir_access_unix.cpp +++ b/drivers/unix/dir_access_unix.cpp @@ -49,7 +49,7 @@ #include <mntent.h> #endif -DirAccess *DirAccessUnix::create_fs() { +Ref<DirAccess> DirAccessUnix::create_fs() { return memnew(DirAccessUnix); } @@ -374,7 +374,7 @@ Error DirAccessUnix::change_dir(String p_dir) { return OK; } -String DirAccessUnix::get_current_dir(bool p_include_drive) { +String DirAccessUnix::get_current_dir(bool p_include_drive) const { String base = _get_root_path(); if (!base.is_empty()) { String bd = current_dir.replace_first(base, ""); diff --git a/drivers/unix/dir_access_unix.h b/drivers/unix/dir_access_unix.h index f90f55605c..4fea7cd154 100644 --- a/drivers/unix/dir_access_unix.h +++ b/drivers/unix/dir_access_unix.h @@ -41,9 +41,9 @@ #include <unistd.h> class DirAccessUnix : public DirAccess { - DIR *dir_stream; + DIR *dir_stream = nullptr; - static DirAccess *create_fs(); + static Ref<DirAccess> create_fs(); String current_dir; bool _cisdir; @@ -67,7 +67,7 @@ public: virtual bool drives_are_shortcuts(); virtual Error change_dir(String p_dir); ///< can be relative or absolute, return false on success - virtual String get_current_dir(bool p_include_drive = true); ///< return current dir location + virtual String get_current_dir(bool p_include_drive = true) const; ///< return current dir location virtual Error make_dir(String p_dir); virtual bool file_exists(String p_file); diff --git a/drivers/unix/file_access_unix.cpp b/drivers/unix/file_access_unix.cpp index ea442ad8bf..e0b2994b63 100644 --- a/drivers/unix/file_access_unix.cpp +++ b/drivers/unix/file_access_unix.cpp @@ -71,10 +71,7 @@ void FileAccessUnix::check_errors() const { } Error FileAccessUnix::_open(const String &p_path, int p_mode_flags) { - if (f) { - fclose(f); - } - f = nullptr; + _close(); path_src = p_path; path = fix_path(p_path); @@ -148,7 +145,7 @@ Error FileAccessUnix::_open(const String &p_path, int p_mode_flags) { return OK; } -void FileAccessUnix::close() { +void FileAccessUnix::_close() { if (!f) { return; } @@ -336,14 +333,14 @@ Error FileAccessUnix::_set_unix_permissions(const String &p_file, uint32_t p_per return FAILED; } -FileAccess *FileAccessUnix::create_libc() { +Ref<FileAccess> FileAccessUnix::create_libc() { return memnew(FileAccessUnix); } CloseNotificationFunc FileAccessUnix::close_notification_func = nullptr; FileAccessUnix::~FileAccessUnix() { - close(); + _close(); } #endif diff --git a/drivers/unix/file_access_unix.h b/drivers/unix/file_access_unix.h index 8ebdcd2a2d..4340bbbc82 100644 --- a/drivers/unix/file_access_unix.h +++ b/drivers/unix/file_access_unix.h @@ -49,13 +49,13 @@ class FileAccessUnix : public FileAccess { String path; String path_src; - static FileAccess *create_libc(); + static Ref<FileAccess> create_libc(); + void _close(); public: static CloseNotificationFunc close_notification_func; virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual String get_path() const; /// returns the path for the current open file diff --git a/drivers/vulkan/rendering_device_vulkan.cpp b/drivers/vulkan/rendering_device_vulkan.cpp index f7c2fcb88a..400802686e 100644 --- a/drivers/vulkan/rendering_device_vulkan.cpp +++ b/drivers/vulkan/rendering_device_vulkan.cpp @@ -1484,7 +1484,7 @@ Error RenderingDeviceVulkan::_staging_buffer_allocate(uint32_t p_amount, uint32_ //this is an old block, which was already processed, let's reuse staging_buffer_blocks.write[staging_buffer_current].frame_used = frames_drawn; staging_buffer_blocks.write[staging_buffer_current].fill_amount = 0; - } else if (staging_buffer_blocks[staging_buffer_current].frame_used > frames_drawn - frame_count) { + } else { //this block may still be in use, let's not touch it unless we have to, so.. can we create a new one? if ((uint64_t)staging_buffer_blocks.size() * staging_buffer_block_size < staging_buffer_max_size) { //we are still allowed to create a new block, so let's do that and insert it for current pos @@ -4875,9 +4875,8 @@ Vector<uint8_t> RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Ve "Reflection of SPIR-V shader stage '" + String(shader_stage_names[p_spirv[i].shader_stage]) + "' failed obtaining push constants."); #if 0 if (pconstants[0] == nullptr) { - FileAccess *f = FileAccess::open("res://popo.spv", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open("res://popo.spv", FileAccess::WRITE); f->store_buffer((const uint8_t *)&SpirV[0], SpirV.size() * sizeof(uint32_t)); - memdelete(f); } #endif @@ -4965,8 +4964,8 @@ Vector<uint8_t> RenderingDeviceVulkan::shader_compile_binary_from_spirv(const Ve Vector<uint8_t> ret; ret.resize(total_size); - uint32_t offset = 0; { + uint32_t offset = 0; uint8_t *binptr = ret.ptrw(); binptr[0] = 'G'; binptr[1] = 'V'; @@ -5039,7 +5038,7 @@ RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_ uint32_t bin_data_size = decode_uint32(binptr + 8); - const RenderingDeviceVulkanShaderBinaryData &binary_data = *(const RenderingDeviceVulkanShaderBinaryData *)(binptr + 12); + const RenderingDeviceVulkanShaderBinaryData &binary_data = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinaryData *>(binptr + 12)); Shader::PushConstant push_constant; push_constant.push_constant_size = binary_data.push_constant_size; @@ -5051,7 +5050,7 @@ RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_ bool is_compute = binary_data.is_compute; - uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] }; + const uint32_t compute_local_size[3] = { binary_data.compute_local_size[0], binary_data.compute_local_size[1], binary_data.compute_local_size[2] }; read_offset += sizeof(uint32_t) * 3 + bin_data_size; @@ -5075,7 +5074,7 @@ RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_ ERR_FAIL_COND_V(read_offset + sizeof(uint32_t) >= binsize, RID()); uint32_t set_count = decode_uint32(binptr + read_offset); read_offset += sizeof(uint32_t); - const RenderingDeviceVulkanShaderBinaryDataBinding *set_ptr = (const RenderingDeviceVulkanShaderBinaryDataBinding *)(binptr + read_offset); + const RenderingDeviceVulkanShaderBinaryDataBinding *set_ptr = reinterpret_cast<const RenderingDeviceVulkanShaderBinaryDataBinding *>(binptr + read_offset); uint32_t set_size = set_count * sizeof(RenderingDeviceVulkanShaderBinaryDataBinding); ERR_FAIL_COND_V(read_offset + set_size >= binsize, RID()); @@ -5147,7 +5146,7 @@ RID RenderingDeviceVulkan::shader_create_from_bytecode(const Vector<uint8_t> &p_ Vector<Shader::SpecializationConstant> specialization_constants; for (uint32_t i = 0; i < binary_data.specialization_constant_count; i++) { - const RenderingDeviceVulkanShaderBinarySpecializationConstant &src_sc = *(const RenderingDeviceVulkanShaderBinarySpecializationConstant *)(binptr + read_offset); + const RenderingDeviceVulkanShaderBinarySpecializationConstant &src_sc = *(reinterpret_cast<const RenderingDeviceVulkanShaderBinarySpecializationConstant *>(binptr + read_offset)); Shader::SpecializationConstant sc; sc.constant.int_value = src_sc.int_value; sc.constant.type = PipelineSpecializationConstantType(src_sc.type); @@ -6334,7 +6333,7 @@ RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferForma rasterization_state_create_info.depthClampEnable = p_rasterization_state.enable_depth_clamp; rasterization_state_create_info.rasterizerDiscardEnable = p_rasterization_state.discard_primitives; rasterization_state_create_info.polygonMode = (p_rasterization_state.wireframe ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL); - static VkCullModeFlags cull_mode[3] = { + static const VkCullModeFlags cull_mode[3] = { VK_CULL_MODE_NONE, VK_CULL_MODE_FRONT_BIT, VK_CULL_MODE_BACK_BIT @@ -6361,7 +6360,7 @@ RID RenderingDeviceVulkan::render_pipeline_create(RID p_shader, FramebufferForma Vector<VkSampleMask> sample_mask; if (p_multisample_state.sample_mask.size()) { //use sample mask - int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = { + const int rasterization_sample_mask_expected_size[TEXTURE_SAMPLES_MAX] = { 1, 2, 4, 8, 16, 32, 64 }; ERR_FAIL_COND_V(rasterization_sample_mask_expected_size[p_multisample_state.sample_count] != p_multisample_state.sample_mask.size(), RID()); diff --git a/drivers/wasapi/audio_driver_wasapi.cpp b/drivers/wasapi/audio_driver_wasapi.cpp index c9609b469a..3a62850339 100644 --- a/drivers/wasapi/audio_driver_wasapi.cpp +++ b/drivers/wasapi/audio_driver_wasapi.cpp @@ -680,7 +680,7 @@ void AudioDriverWASAPI::write_sample(WORD format_tag, int bits_per_sample, BYTE } void AudioDriverWASAPI::thread_func(void *p_udata) { - AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata; + AudioDriverWASAPI *ad = static_cast<AudioDriverWASAPI *>(p_udata); uint32_t avail_frames = 0; uint32_t write_ofs = 0; diff --git a/drivers/windows/dir_access_windows.cpp b/drivers/windows/dir_access_windows.cpp index 6f3bad12c1..881575d245 100644 --- a/drivers/windows/dir_access_windows.cpp +++ b/drivers/windows/dir_access_windows.cpp @@ -185,7 +185,7 @@ Error DirAccessWindows::make_dir(String p_dir) { return ERR_CANT_CREATE; } -String DirAccessWindows::get_current_dir(bool p_include_drive) { +String DirAccessWindows::get_current_dir(bool p_include_drive) const { String base = _get_root_path(); if (!base.is_empty()) { String bd = current_dir.replace("\\", "/").replace_first(base, ""); diff --git a/drivers/windows/dir_access_windows.h b/drivers/windows/dir_access_windows.h index 78d37074e5..fbb07ddef8 100644 --- a/drivers/windows/dir_access_windows.h +++ b/drivers/windows/dir_access_windows.h @@ -64,7 +64,7 @@ public: virtual String get_drive(int p_drive); virtual Error change_dir(String p_dir); ///< can be relative or absolute, return false on success - virtual String get_current_dir(bool p_include_drive = true); ///< return current dir location + virtual String get_current_dir(bool p_include_drive = true) const; ///< return current dir location virtual bool file_exists(String p_file); virtual bool dir_exists(String p_dir); diff --git a/drivers/windows/file_access_windows.cpp b/drivers/windows/file_access_windows.cpp index 59dc1d8e77..1a66d19373 100644 --- a/drivers/windows/file_access_windows.cpp +++ b/drivers/windows/file_access_windows.cpp @@ -59,11 +59,10 @@ void FileAccessWindows::check_errors() const { } Error FileAccessWindows::_open(const String &p_path, int p_mode_flags) { + _close(); + path_src = p_path; path = fix_path(p_path); - if (f) { - close(); - } const WCHAR *mode_string; @@ -134,7 +133,7 @@ Error FileAccessWindows::_open(const String &p_path, int p_mode_flags) { } } -void FileAccessWindows::close() { +void FileAccessWindows::_close() { if (!f) { return; } @@ -350,7 +349,7 @@ Error FileAccessWindows::_set_unix_permissions(const String &p_file, uint32_t p_ } FileAccessWindows::~FileAccessWindows() { - close(); + _close(); } #endif // WINDOWS_ENABLED diff --git a/drivers/windows/file_access_windows.h b/drivers/windows/file_access_windows.h index 93d37c3b5a..5d67b6ca4f 100644 --- a/drivers/windows/file_access_windows.h +++ b/drivers/windows/file_access_windows.h @@ -48,9 +48,10 @@ class FileAccessWindows : public FileAccess { String path_src; String save_path; + void _close(); + public: virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual String get_path() const; /// returns the path for the current open file diff --git a/drivers/xaudio2/audio_driver_xaudio2.cpp b/drivers/xaudio2/audio_driver_xaudio2.cpp index 03fdfda23d..c32c7cf1e5 100644 --- a/drivers/xaudio2/audio_driver_xaudio2.cpp +++ b/drivers/xaudio2/audio_driver_xaudio2.cpp @@ -84,7 +84,7 @@ Error AudioDriverXAudio2::init() { } void AudioDriverXAudio2::thread_func(void *p_udata) { - AudioDriverXAudio2 *ad = (AudioDriverXAudio2 *)p_udata; + AudioDriverXAudio2 *ad = static_cast<AudioDriverXAudio2 *>(p_udata); while (!ad->exit_thread) { if (!ad->active) { diff --git a/editor/action_map_editor.cpp b/editor/action_map_editor.cpp index 96931efd3b..49c79d709b 100644 --- a/editor/action_map_editor.cpp +++ b/editor/action_map_editor.cpp @@ -61,29 +61,37 @@ static const char *_joy_axis_descriptions[(size_t)JoyAxis::MAX * 2] = { TTRC("Joystick 4 Down"), }; -String InputEventConfigurationDialog::get_event_text(const Ref<InputEvent> &p_event) { +String InputEventConfigurationDialog::get_event_text(const Ref<InputEvent> &p_event, bool p_include_device) const { ERR_FAIL_COND_V_MSG(p_event.is_null(), String(), "Provided event is not a valid instance of InputEvent"); - // Joypad motion events will display slightly differently than what the event->as_text() provides. See #43660. - Ref<InputEventJoypadMotion> jpmotion = p_event; - if (jpmotion.is_valid()) { + String text = p_event->as_text(); + + Ref<InputEventMouse> mouse = p_event; + Ref<InputEventJoypadMotion> jp_motion = p_event; + Ref<InputEventJoypadButton> jp_button = p_event; + if (jp_motion.is_valid()) { + // Joypad motion events will display slightly differently than what the event->as_text() provides. See #43660. String desc = TTR("Unknown Joypad Axis"); - if (jpmotion->get_axis() < JoyAxis::MAX) { - desc = RTR(_joy_axis_descriptions[2 * (size_t)jpmotion->get_axis() + (jpmotion->get_axis_value() < 0 ? 0 : 1)]); + if (jp_motion->get_axis() < JoyAxis::MAX) { + desc = RTR(_joy_axis_descriptions[2 * (size_t)jp_motion->get_axis() + (jp_motion->get_axis_value() < 0 ? 0 : 1)]); } - return vformat("Joypad Axis %s %s (%s)", itos((int64_t)jpmotion->get_axis()), jpmotion->get_axis_value() < 0 ? "-" : "+", desc); - } else { - return p_event->as_text(); + text = vformat("Joypad Axis %s %s (%s)", itos((int64_t)jp_motion->get_axis()), jp_motion->get_axis_value() < 0 ? "-" : "+", desc); + } + if (p_include_device && (mouse.is_valid() || jp_button.is_valid() || jp_motion.is_valid())) { + String device_string = _get_device_string(p_event->get_device()); + text += vformat(" - %s", device_string); } + + return text; } -void InputEventConfigurationDialog::_set_event(const Ref<InputEvent> &p_event) { +void InputEventConfigurationDialog::_set_event(const Ref<InputEvent> &p_event, bool p_update_input_list_selection) { if (p_event.is_valid()) { event = p_event; // Update Label - event_as_text->set_text(get_event_text(event)); + event_as_text->set_text(get_event_text(event, true)); Ref<InputEventKey> k = p_event; Ref<InputEventMouseButton> mb = p_event; @@ -122,7 +130,7 @@ void InputEventConfigurationDialog::_set_event(const Ref<InputEvent> &p_event) { additional_options_container->show(); // Update selected item in input list. - if (k.is_valid() || joyb.is_valid() || joym.is_valid() || mb.is_valid()) { + if (p_update_input_list_selection && (k.is_valid() || joyb.is_valid() || joym.is_valid() || mb.is_valid())) { TreeItem *category = input_list_tree->get_root()->get_first_child(); while (category) { TreeItem *input_item = category->get_first_child(); @@ -234,10 +242,13 @@ void InputEventConfigurationDialog::_listen_window_input(const Ref<InputEvent> & } } + // Create an editable reference + Ref<InputEvent> received_event = p_event; + // Check what the type is and if it is allowed. - Ref<InputEventKey> k = p_event; - Ref<InputEventJoypadButton> joyb = p_event; - Ref<InputEventJoypadMotion> joym = p_event; + Ref<InputEventKey> k = received_event; + Ref<InputEventJoypadButton> joyb = received_event; + Ref<InputEventJoypadMotion> joym = received_event; int type = 0; if (k.is_valid()) { @@ -266,7 +277,7 @@ void InputEventConfigurationDialog::_listen_window_input(const Ref<InputEvent> & } if (k.is_valid()) { - k->set_pressed(false); // to avoid serialisation of 'pressed' property - doesn't matter for actions anyway. + k->set_pressed(false); // To avoid serialisation of 'pressed' property - doesn't matter for actions anyway. // Maintain physical keycode option state if (physical_key_checkbox->is_pressed()) { k->set_keycode(Key::NONE); @@ -275,15 +286,17 @@ void InputEventConfigurationDialog::_listen_window_input(const Ref<InputEvent> & } } - Ref<InputEventWithModifiers> mod = p_event; + Ref<InputEventWithModifiers> mod = received_event; if (mod.is_valid()) { // Maintain store command option state mod->set_store_command(store_command_checkbox->is_pressed()); - mod->set_window_id(0); } - _set_event(p_event); + // Maintain device selection. + received_event->set_device(_get_current_device()); + + _set_event(received_event); set_input_as_handled(); } @@ -331,7 +344,7 @@ void InputEventConfigurationDialog::_update_input_list() { Ref<InputEventMouseButton> mb; mb.instantiate(); mb->set_button_index(mouse_buttons[i]); - String desc = get_event_text(mb); + String desc = get_event_text(mb, false); if (!search_term.is_empty() && desc.findn(search_term) == -1) { continue; @@ -354,7 +367,7 @@ void InputEventConfigurationDialog::_update_input_list() { Ref<InputEventJoypadButton> joyb; joyb.instantiate(); joyb->set_button_index((JoyButton)i); - String desc = get_event_text(joyb); + String desc = get_event_text(joyb, false); if (!search_term.is_empty() && desc.findn(search_term) == -1) { continue; @@ -380,7 +393,7 @@ void InputEventConfigurationDialog::_update_input_list() { joym.instantiate(); joym->set_axis((JoyAxis)axis); joym->set_axis_value(direction); - String desc = get_event_text(joym); + String desc = get_event_text(joym, false); if (!search_term.is_empty() && desc.findn(search_term) == -1) { continue; @@ -495,7 +508,7 @@ void InputEventConfigurationDialog::_input_list_item_selected() { k->set_meta_pressed(mod_checkboxes[MOD_META]->is_pressed()); k->set_store_command(store_command_checkbox->is_pressed()); - _set_event(k); + _set_event(k, false); } break; case InputEventConfigurationDialog::INPUT_MOUSE_BUTTON: { MouseButton idx = (MouseButton)(int)selected->get_meta("__index"); @@ -510,12 +523,19 @@ void InputEventConfigurationDialog::_input_list_item_selected() { mb->set_meta_pressed(mod_checkboxes[MOD_META]->is_pressed()); mb->set_store_command(store_command_checkbox->is_pressed()); - _set_event(mb); + // Maintain selected device + mb->set_device(_get_current_device()); + + _set_event(mb, false); } break; case InputEventConfigurationDialog::INPUT_JOY_BUTTON: { JoyButton idx = (JoyButton)(int)selected->get_meta("__index"); Ref<InputEventJoypadButton> jb = InputEventJoypadButton::create_reference(idx); - _set_event(jb); + + // Maintain selected device + jb->set_device(_get_current_device()); + + _set_event(jb, false); } break; case InputEventConfigurationDialog::INPUT_JOY_MOTION: { JoyAxis axis = (JoyAxis)(int)selected->get_meta("__axis"); @@ -525,24 +545,35 @@ void InputEventConfigurationDialog::_input_list_item_selected() { jm.instantiate(); jm->set_axis(axis); jm->set_axis_value(value); - _set_event(jm); + + // Maintain selected device + jm->set_device(_get_current_device()); + + _set_event(jm, false); } break; } } -void InputEventConfigurationDialog::_set_current_device(int i_device) { - device_id_option->select(i_device + 1); +void InputEventConfigurationDialog::_device_selection_changed(int p_option_button_index) { + // Subtract 1 as option index 0 corresponds to "All Devices" (value of -1) + // and option index 1 corresponds to device 0, etc... + event->set_device(p_option_button_index - 1); + event_as_text->set_text(get_event_text(event, true)); +} + +void InputEventConfigurationDialog::_set_current_device(int p_device) { + device_id_option->select(p_device + 1); } int InputEventConfigurationDialog::_get_current_device() const { return device_id_option->get_selected() - 1; } -String InputEventConfigurationDialog::_get_device_string(int i_device) const { - if (i_device == InputMap::ALL_DEVICES) { +String InputEventConfigurationDialog::_get_device_string(int p_device) const { + if (p_device == InputMap::ALL_DEVICES) { return TTR("All Devices"); } - return TTR("Device") + " " + itos(i_device); + return TTR("Device") + " " + itos(p_device); } void InputEventConfigurationDialog::_notification(int p_what) { @@ -558,8 +589,6 @@ void InputEventConfigurationDialog::_notification(int p_what) { icon_cache.joypad_button = get_theme_icon(SNAME("JoyButton"), SNAME("EditorIcons")); icon_cache.joypad_axis = get_theme_icon(SNAME("JoyAxis"), SNAME("EditorIcons")); - mouse_detection_rect->set_color(get_theme_color(SNAME("dark_color_2"), SNAME("Editor"))); - _update_input_list(); } break; } @@ -588,9 +617,12 @@ void InputEventConfigurationDialog::popup_and_configure(const Ref<InputEvent> &p // Switch to "Listen" tab tab_container->set_current_tab(0); + + // Select "All Devices" by default. + device_id_option->select(0); } - popup_centered(); + popup_centered(Size2(0, 400) * EDSCALE); } Ref<InputEvent> InputEventConfigurationDialog::get_event() const { @@ -622,8 +654,8 @@ InputEventConfigurationDialog::InputEventConfigurationDialog() { event_as_text = memnew(Label); event_as_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER); vb->add_child(event_as_text); - // Mouse button detection rect (Mouse button event outside this ColorRect will be ignored) - mouse_detection_rect = memnew(ColorRect); + // Mouse button detection rect (Mouse button event outside this rect will be ignored) + mouse_detection_rect = memnew(Panel); mouse_detection_rect->set_v_size_flags(Control::SIZE_EXPAND_FILL); vb->add_child(mouse_detection_rect); tab_container->add_child(vb); @@ -673,12 +705,13 @@ InputEventConfigurationDialog::InputEventConfigurationDialog() { device_id_option = memnew(OptionButton); device_id_option->set_h_size_flags(Control::SIZE_EXPAND_FILL); - device_container->add_child(device_id_option); - for (int i = -1; i < 8; i++) { device_id_option->add_item(_get_device_string(i)); } - _set_current_device(0); + device_id_option->connect("item_selected", callable_mp(this, &InputEventConfigurationDialog::_device_selection_changed)); + _set_current_device(InputMap::ALL_DEVICES); + device_container->add_child(device_id_option); + device_container->hide(); additional_options_container->add_child(device_container); @@ -1096,7 +1129,7 @@ void ActionMapEditor::update_action_list(const Vector<ActionInfo> &p_action_info TreeItem *event_item = action_tree->create_item(action_item); // First Column - Text - event_item->set_text(0, event_config_dialog->get_event_text(event)); // Need to us the special description for JoypadMotion here, so don't use as_text() directly. + event_item->set_text(0, event_config_dialog->get_event_text(event, true)); event_item->set_meta("__event", event); event_item->set_meta("__index", evnt_idx); @@ -1136,7 +1169,7 @@ void ActionMapEditor::update_action_list(const Vector<ActionInfo> &p_action_info void ActionMapEditor::show_message(const String &p_message) { message->set_text(p_message); - message->popup_centered(Size2(300, 100) * EDSCALE); + message->popup_centered(); } void ActionMapEditor::use_external_search_box(LineEdit *p_searchbox) { diff --git a/editor/action_map_editor.h b/editor/action_map_editor.h index 34c70c942e..b676c55403 100644 --- a/editor/action_map_editor.h +++ b/editor/action_map_editor.h @@ -63,24 +63,24 @@ private: Ref<InputEvent> event = Ref<InputEvent>(); - TabContainer *tab_container; + TabContainer *tab_container = nullptr; // Listening for input - Label *event_as_text; - ColorRect *mouse_detection_rect; + Label *event_as_text = nullptr; + Panel *mouse_detection_rect = nullptr; // List of All Key/Mouse/Joypad input options. int allowed_input_types; - Tree *input_list_tree; - LineEdit *input_list_search; + Tree *input_list_tree = nullptr; + LineEdit *input_list_search = nullptr; // Additional Options, shown depending on event selected - VBoxContainer *additional_options_container; + VBoxContainer *additional_options_container = nullptr; - HBoxContainer *device_container; - OptionButton *device_id_option; + HBoxContainer *device_container = nullptr; + OptionButton *device_id_option = nullptr; - HBoxContainer *mod_container; // Contains the subcontainer and the store command checkbox. + HBoxContainer *mod_container = nullptr; // Contains the subcontainer and the store command checkbox. enum ModCheckbox { MOD_ALT, @@ -93,11 +93,11 @@ private: String mods[MOD_MAX] = { "Alt", "Shift", "Command", "Ctrl", "Metakey" }; CheckBox *mod_checkboxes[MOD_MAX]; - CheckBox *store_command_checkbox; + CheckBox *store_command_checkbox = nullptr; - CheckBox *physical_key_checkbox; + CheckBox *physical_key_checkbox = nullptr; - void _set_event(const Ref<InputEvent> &p_event); + void _set_event(const Ref<InputEvent> &p_event, bool p_update_input_list_selection = true); void _tab_selected(int p_tab); void _listen_window_input(const Ref<InputEvent> &p_event); @@ -110,9 +110,10 @@ private: void _store_command_toggled(bool p_checked); void _physical_keycode_toggled(bool p_checked); - void _set_current_device(int i_device); + void _device_selection_changed(int p_option_button_index); + void _set_current_device(int p_device); int _get_current_device() const; - String _get_device_string(int i_device) const; + String _get_device_string(int p_device) const; protected: void _notification(int p_what); @@ -121,7 +122,7 @@ public: // Pass an existing event to configure it. Alternatively, pass no event to start with a blank configuration. void popup_and_configure(const Ref<InputEvent> &p_event = Ref<InputEvent>()); Ref<InputEvent> get_event() const; - String get_event_text(const Ref<InputEvent> &p_event); + String get_event_text(const Ref<InputEvent> &p_event, bool p_include_device) const; void set_allowed_input_types(int p_type_masks); @@ -149,7 +150,7 @@ private: }; Vector<ActionInfo> actions_cache; - Tree *action_tree; + Tree *action_tree = nullptr; // Storing which action/event is currently being edited in the InputEventConfigurationDialog. @@ -159,17 +160,17 @@ private: // Popups - InputEventConfigurationDialog *event_config_dialog; - AcceptDialog *message; + InputEventConfigurationDialog *event_config_dialog = nullptr; + AcceptDialog *message = nullptr; // Filtering and Adding actions bool show_builtin_actions = false; - CheckButton *show_builtin_actions_checkbutton; - LineEdit *action_list_search; + CheckButton *show_builtin_actions_checkbutton = nullptr; + LineEdit *action_list_search = nullptr; - HBoxContainer *add_hbox; - LineEdit *add_edit; + HBoxContainer *add_hbox = nullptr; + LineEdit *add_edit = nullptr; void _event_config_confirmed(); diff --git a/editor/animation_bezier_editor.cpp b/editor/animation_bezier_editor.cpp index 0dbe230699..8239745a3e 100644 --- a/editor/animation_bezier_editor.cpp +++ b/editor/animation_bezier_editor.cpp @@ -146,11 +146,10 @@ void AnimationBezierTrackEdit::_draw_track(int p_track, const Color &p_color) { int iterations = 10; float low = 0; float high = 1; - float middle; //narrow high and low as much as possible for (int k = 0; k < iterations; k++) { - middle = (low + high) / 2; + float middle = (low + high) / 2; Vector2 interp = _bezier_interp(middle, start, out_handle, in_handle, end); diff --git a/editor/animation_bezier_editor.h b/editor/animation_bezier_editor.h index fa6fc405f2..dcb6502440 100644 --- a/editor/animation_bezier_editor.h +++ b/editor/animation_bezier_editor.h @@ -49,7 +49,7 @@ class AnimationBezierTrackEdit : public Control { AnimationTimelineEdit *timeline = nullptr; UndoRedo *undo_redo = nullptr; Node *root = nullptr; - Control *play_position; //separate control used to draw so updates for only position changed are much faster + Control *play_position = nullptr; //separate control used to draw so updates for only position changed are much faster float play_position_pos = 0; Ref<Animation> animation; @@ -130,7 +130,7 @@ class AnimationBezierTrackEdit : public Control { float transition = 0; }; - AnimationTrackEditor *editor; + AnimationTrackEditor *editor = nullptr; struct EditPoint { Rect2 point_rect; diff --git a/editor/animation_track_editor.cpp b/editor/animation_track_editor.cpp index dc69a8cb08..685dde4d98 100644 --- a/editor/animation_track_editor.cpp +++ b/editor/animation_track_editor.cpp @@ -1961,11 +1961,21 @@ void AnimationTrackEdit::_notification(int p_what) { int limit = timeline->get_name_limit(); + if (track % 2 == 1) { + // Draw a background over odd lines to make long lists of tracks easier to read. + draw_rect(Rect2(Point2(1 * EDSCALE, 0), get_size() - Size2(1 * EDSCALE, 0)), Color(0.5, 0.5, 0.5, 0.05)); + } + + if (hovered) { + // Draw hover feedback. + draw_rect(Rect2(Point2(1 * EDSCALE, 0), get_size() - Size2(1 * EDSCALE, 0)), Color(0.5, 0.5, 0.5, 0.1)); + } + if (has_focus()) { Color accent = get_theme_color(SNAME("accent_color"), SNAME("Editor")); accent.a *= 0.7; // Offside so the horizontal sides aren't cutoff. - draw_rect(Rect2(Point2(1 * EDSCALE, 0), get_size() - Size2(1 * EDSCALE, 0)), accent, false); + draw_style_box(get_theme_stylebox(SNAME("Focus"), SNAME("EditorStyles")), Rect2(Point2(1 * EDSCALE, 0), get_size() - Size2(1 * EDSCALE, 0))); } Ref<Font> font = get_theme_font(SNAME("font"), SNAME("Label")); @@ -2236,7 +2246,16 @@ void AnimationTrackEdit::_notification(int p_what) { } } break; + case NOTIFICATION_MOUSE_ENTER: + hovered = true; + update(); + break; case NOTIFICATION_MOUSE_EXIT: + hovered = false; + // When the mouse cursor exits the track, we're no longer hovering any keyframe. + hovering_key_idx = -1; + update(); + [[fallthrough]]; case NOTIFICATION_DRAG_END: { cancel_drop(); } break; @@ -2348,7 +2367,13 @@ void AnimationTrackEdit::draw_key(int p_index, float p_pixels_sec, int p_x, bool } } - draw_texture(icon_to_draw, ofs); + // Use a different color for the currently hovered key. + // The color multiplier is chosen to work with both dark and light editor themes, + // and on both unselected and selected key icons. + draw_texture( + icon_to_draw, + ofs, + p_index == hovering_key_idx ? get_theme_color(SNAME("folder_icon_modulate"), SNAME("FileDialog")) : Color(1, 1, 1)); } // Helper. @@ -2935,6 +2960,59 @@ void AnimationTrackEdit::gui_input(const Ref<InputEvent> &p_event) { } Ref<InputEventMouseMotion> mm = p_event; + if (mm.is_valid()) { + const int previous_hovering_key_idx = hovering_key_idx; + + // Hovering compressed keyframes for editing is not possible. + if (!animation->track_is_compressed(track)) { + const float scale = timeline->get_zoom_scale(); + const int limit = timeline->get_name_limit(); + const int limit_end = get_size().width - timeline->get_buttons_width(); + // Left Border including space occupied by keyframes on t=0. + const int limit_start_hitbox = limit - type_icon->get_width(); + const Point2 pos = mm->get_position(); + + if (pos.x >= limit_start_hitbox && pos.x <= limit_end) { + // Use the same logic as key selection to ensure that hovering accurately represents + // which key will be selected when clicking. + int key_idx = -1; + float key_distance = 1e20; + + hovering_key_idx = -1; + + // Hovering should happen in the opposite order of drawing for more accurate overlap hovering. + for (int i = animation->track_get_key_count(track) - 1; i >= 0; i--) { + Rect2 rect = get_key_rect(i, scale); + float offset = animation->track_get_key_time(track, i) - timeline->get_value(); + offset = offset * scale + limit; + rect.position.x += offset; + + if (rect.has_point(pos)) { + if (is_key_selectable_by_distance()) { + const float distance = ABS(offset - pos.x); + if (key_idx == -1 || distance < key_distance) { + key_idx = i; + key_distance = distance; + hovering_key_idx = i; + } + } else { + // First one does it. + hovering_key_idx = i; + break; + } + } + } + + print_line(hovering_key_idx); + + if (hovering_key_idx != previous_hovering_key_idx) { + // Required to draw keyframe hover feedback on the correct keyframe. + update(); + } + } + } + } + if (mm.is_valid() && (mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE && moving_selection_attempt) { if (!moving_selection) { moving_selection = true; diff --git a/editor/animation_track_editor.h b/editor/animation_track_editor.h index 1baebc469e..0f6d12b4d4 100644 --- a/editor/animation_track_editor.h +++ b/editor/animation_track_editor.h @@ -54,27 +54,27 @@ class AnimationTimelineEdit : public Range { GDCLASS(AnimationTimelineEdit, Range); Ref<Animation> animation; - AnimationTrackEdit *track_edit; + AnimationTrackEdit *track_edit = nullptr; int name_limit; - Range *zoom; - Range *h_scroll; + Range *zoom = nullptr; + Range *h_scroll = nullptr; float play_position_pos; - HBoxContainer *len_hb; - EditorSpinSlider *length; - Button *loop; - TextureRect *time_icon; + HBoxContainer *len_hb = nullptr; + EditorSpinSlider *length = nullptr; + Button *loop = nullptr; + TextureRect *time_icon = nullptr; - MenuButton *add_track; - Control *play_position; //separate control used to draw so updates for only position changed are much faster - HScrollBar *hscroll; + MenuButton *add_track = nullptr; + Control *play_position = nullptr; //separate control used to draw so updates for only position changed are much faster + HScrollBar *hscroll = nullptr; void _zoom_changed(double); void _anim_length_changed(double p_new_len); void _anim_loop_pressed(); void _play_position_draw(); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; Rect2 hsize_rect; bool editing = false; @@ -146,12 +146,12 @@ class AnimationTrackEdit : public Control { MENU_KEY_ADD_RESET, MENU_KEY_DELETE }; - AnimationTimelineEdit *timeline; - UndoRedo *undo_redo; - Popup *path_popup; - LineEdit *path; - Node *root; - Control *play_position; //separate control used to draw so updates for only position changed are much faster + AnimationTimelineEdit *timeline = nullptr; + UndoRedo *undo_redo = nullptr; + Popup *path_popup = nullptr; + LineEdit *path = nullptr; + Node *root = nullptr; + Control *play_position = nullptr; //separate control used to draw so updates for only position changed are much faster float play_position_pos; NodePath node_path; @@ -169,9 +169,11 @@ class AnimationTrackEdit : public Control { Ref<Texture2D> type_icon; Ref<Texture2D> selected_icon; - PopupMenu *menu; + PopupMenu *menu = nullptr; + bool hovered = false; bool clicking_on_name = false; + int hovering_key_idx = -1; void _zoom_changed(); @@ -194,7 +196,7 @@ class AnimationTrackEdit : public Control { float moving_selection_from_ofs; bool in_group = false; - AnimationTrackEditor *editor; + AnimationTrackEditor *editor = nullptr; protected: static void _bind_methods(); @@ -285,27 +287,27 @@ class AnimationTrackEditor : public VBoxContainer { GDCLASS(AnimationTrackEditor, VBoxContainer); Ref<Animation> animation; - Node *root; - - MenuButton *edit; + Node *root = nullptr; - PanelContainer *main_panel; - HScrollBar *hscroll; - ScrollContainer *scroll; - VBoxContainer *track_vbox; - AnimationBezierTrackEdit *bezier_edit; + MenuButton *edit = nullptr; - Label *info_message; + PanelContainer *main_panel = nullptr; + HScrollBar *hscroll = nullptr; + ScrollContainer *scroll = nullptr; + VBoxContainer *track_vbox = nullptr; + AnimationBezierTrackEdit *bezier_edit = nullptr; - AnimationTimelineEdit *timeline; - HSlider *zoom; - EditorSpinSlider *step; - TextureRect *zoom_icon; - Button *snap; - Button *bezier_edit_icon; - OptionButton *snap_mode; + Label *info_message = nullptr; - Button *imported_anim_warning; + AnimationTimelineEdit *timeline = nullptr; + HSlider *zoom = nullptr; + EditorSpinSlider *step = nullptr; + TextureRect *zoom_icon = nullptr; + Button *snap = nullptr; + Button *bezier_edit_icon = nullptr; + OptionButton *snap_mode = nullptr; + + Button *imported_anim_warning = nullptr; void _show_imported_anim_warning(); void _snap_mode_changed(int p_mode); @@ -323,7 +325,7 @@ class AnimationTrackEditor : public VBoxContainer { void _track_remove_request(int p_track); void _track_grab_focus(int p_track); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; void _update_scroll(double); void _update_step(double p_new_step); @@ -336,9 +338,9 @@ class AnimationTrackEditor : public VBoxContainer { void _update_step_spinbox(); - PropertySelector *prop_selector; - PropertySelector *method_selector; - SceneTreeDialog *pick_track; + PropertySelector *prop_selector = nullptr; + PropertySelector *method_selector = nullptr; + SceneTreeDialog *pick_track = nullptr; int adding_track_type; NodePath adding_track_path; @@ -353,10 +355,10 @@ class AnimationTrackEditor : public VBoxContainer { bool advance = false; }; /* insert_data;*/ - Label *insert_confirm_text; - CheckBox *insert_confirm_bezier; - CheckBox *insert_confirm_reset; - ConfirmationDialog *insert_confirm; + Label *insert_confirm_text = nullptr; + CheckBox *insert_confirm_bezier = nullptr; + CheckBox *insert_confirm_reset = nullptr; + ConfirmationDialog *insert_confirm = nullptr; bool insert_queue = false; List<InsertData> insert_data; @@ -419,13 +421,13 @@ class AnimationTrackEditor : public VBoxContainer { void _move_selection_commit(); void _move_selection_cancel(); - AnimationTrackKeyEdit *key_edit; - AnimationMultiTrackKeyEdit *multi_key_edit; + AnimationTrackKeyEdit *key_edit = nullptr; + AnimationMultiTrackKeyEdit *multi_key_edit = nullptr; void _update_key_edit(); void _clear_key_edit(); - Control *box_selection; + Control *box_selection = nullptr; void _box_selection_draw(); bool box_selecting = false; Vector2 box_selecting_from; @@ -440,18 +442,18 @@ class AnimationTrackEditor : public VBoxContainer { ////////////// edit menu stuff - ConfirmationDialog *optimize_dialog; - SpinBox *optimize_linear_error; - SpinBox *optimize_angular_error; - SpinBox *optimize_max_angle; + ConfirmationDialog *optimize_dialog = nullptr; + SpinBox *optimize_linear_error = nullptr; + SpinBox *optimize_angular_error = nullptr; + SpinBox *optimize_max_angle = nullptr; - ConfirmationDialog *cleanup_dialog; - CheckBox *cleanup_keys; - CheckBox *cleanup_tracks; - CheckBox *cleanup_all; + ConfirmationDialog *cleanup_dialog = nullptr; + CheckBox *cleanup_keys = nullptr; + CheckBox *cleanup_tracks = nullptr; + CheckBox *cleanup_all = nullptr; - ConfirmationDialog *scale_dialog; - SpinBox *scale; + ConfirmationDialog *scale_dialog = nullptr; + SpinBox *scale = nullptr; void _select_all_tracks_for_copy(); @@ -464,13 +466,13 @@ class AnimationTrackEditor : public VBoxContainer { void _anim_duplicate_keys(bool transpose); void _view_group_toggle(); - Button *view_group; - Button *selected_filter; + Button *view_group = nullptr; + Button *selected_filter = nullptr; void _selection_changed(); - ConfirmationDialog *track_copy_dialog; - Tree *track_copy_select; + ConfirmationDialog *track_copy_dialog = nullptr; + Tree *track_copy_select = nullptr; struct TrackClipboard { NodePath full_path; diff --git a/editor/code_editor.h b/editor/code_editor.h index bbc45d6ec0..d52f57860c 100644 --- a/editor/code_editor.h +++ b/editor/code_editor.h @@ -43,10 +43,10 @@ class GotoLineDialog : public ConfirmationDialog { GDCLASS(GotoLineDialog, ConfirmationDialog); - Label *line_label; - LineEdit *line; + Label *line_label = nullptr; + LineEdit *line = nullptr; - CodeEdit *text_editor; + CodeEdit *text_editor = nullptr; virtual void ok_pressed() override; @@ -62,25 +62,25 @@ class CodeTextEditor; class FindReplaceBar : public HBoxContainer { GDCLASS(FindReplaceBar, HBoxContainer); - LineEdit *search_text; - Label *matches_label; - Button *find_prev; - Button *find_next; - CheckBox *case_sensitive; - CheckBox *whole_words; - TextureButton *hide_button; + LineEdit *search_text = nullptr; + Label *matches_label = nullptr; + Button *find_prev = nullptr; + Button *find_next = nullptr; + CheckBox *case_sensitive = nullptr; + CheckBox *whole_words = nullptr; + TextureButton *hide_button = nullptr; - LineEdit *replace_text; - Button *replace; - Button *replace_all; - CheckBox *selection_only; + LineEdit *replace_text = nullptr; + Button *replace = nullptr; + Button *replace_all = nullptr; + CheckBox *selection_only = nullptr; - VBoxContainer *vbc_lineedit; - HBoxContainer *hbc_button_replace; - HBoxContainer *hbc_option_replace; + VBoxContainer *vbc_lineedit = nullptr; + HBoxContainer *hbc_button_replace = nullptr; + HBoxContainer *hbc_option_replace = nullptr; CodeTextEditor *base_text_editor = nullptr; - CodeEdit *text_editor; + CodeEdit *text_editor = nullptr; int result_line; int result_col; @@ -139,25 +139,25 @@ typedef void (*CodeTextEditorCodeCompleteFunc)(void *p_ud, const String &p_code, class CodeTextEditor : public VBoxContainer { GDCLASS(CodeTextEditor, VBoxContainer); - CodeEdit *text_editor; + CodeEdit *text_editor = nullptr; FindReplaceBar *find_replace_bar = nullptr; - HBoxContainer *status_bar; + HBoxContainer *status_bar = nullptr; - Button *toggle_scripts_button; - Button *error_button; - Button *warning_button; + Button *toggle_scripts_button = nullptr; + Button *error_button = nullptr; + Button *warning_button = nullptr; - Label *line_and_col_txt; + Label *line_and_col_txt = nullptr; - Label *info; - Timer *idle; - Timer *code_complete_timer; + Label *info = nullptr; + Timer *idle = nullptr; + Timer *code_complete_timer = nullptr; - Timer *font_resize_timer; + Timer *font_resize_timer = nullptr; int font_resize_val; real_t font_size; - Label *error; + Label *error = nullptr; int error_line; int error_column; @@ -181,7 +181,7 @@ class CodeTextEditor : public VBoxContainer { Color completion_string_color; Color completion_comment_color; CodeTextEditorCodeCompleteFunc code_complete_func; - void *code_complete_ud; + void *code_complete_ud = nullptr; void _error_button_pressed(); void _warning_button_pressed(); diff --git a/editor/connections_dialog.h b/editor/connections_dialog.h index 58c584b8b2..4b1b8363dd 100644 --- a/editor/connections_dialog.h +++ b/editor/connections_dialog.h @@ -105,27 +105,27 @@ public: }; private: - Label *connect_to_label; - LineEdit *from_signal; - Node *source; + Label *connect_to_label = nullptr; + LineEdit *from_signal = nullptr; + Node *source = nullptr; StringName signal; - LineEdit *dst_method; - ConnectDialogBinds *cdbinds; + LineEdit *dst_method = nullptr; + ConnectDialogBinds *cdbinds = nullptr; bool edit_mode; NodePath dst_path; - VBoxContainer *vbc_right; - - SceneTreeEditor *tree; - AcceptDialog *error; - SpinBox *unbind_count; - EditorInspector *bind_editor; - OptionButton *type_list; - CheckBox *deferred; - CheckBox *oneshot; - CheckButton *advanced; + VBoxContainer *vbc_right = nullptr; + + SceneTreeEditor *tree = nullptr; + AcceptDialog *error = nullptr; + SpinBox *unbind_count = nullptr; + EditorInspector *bind_editor = nullptr; + OptionButton *type_list = nullptr; + CheckBox *deferred = nullptr; + CheckBox *oneshot = nullptr; + CheckButton *advanced = nullptr; Vector<Control *> bind_controls; - Label *error_label; + Label *error_label = nullptr; void ok_pressed() override; void _cancel_pressed(); @@ -186,16 +186,16 @@ class ConnectionsDock : public VBoxContainer { DISCONNECT }; - Node *selected_node; - ConnectionsDockTree *tree; + Node *selected_node = nullptr; + ConnectionsDockTree *tree = nullptr; - ConfirmationDialog *disconnect_all_dialog; - ConnectDialog *connect_dialog; - Button *connect_button; - PopupMenu *signal_menu; - PopupMenu *slot_menu; - UndoRedo *undo_redo; - LineEdit *search_box; + ConfirmationDialog *disconnect_all_dialog = nullptr; + ConnectDialog *connect_dialog = nullptr; + Button *connect_button = nullptr; + PopupMenu *signal_menu = nullptr; + PopupMenu *slot_menu = nullptr; + UndoRedo *undo_redo = nullptr; + LineEdit *search_box = nullptr; Map<StringName, Map<StringName, String>> descr_cache; diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp index f9858aa514..fbb61a1614 100644 --- a/editor/create_dialog.cpp +++ b/editor/create_dialog.cpp @@ -377,17 +377,17 @@ void CreateDialog::_confirmed() { return; } - FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("create_recent." + base_type), FileAccess::WRITE); - if (f) { - f->store_line(selected_item); - - for (int i = 0; i < MIN(32, recent->get_item_count()); i++) { - if (recent->get_item_text(i) != selected_item) { - f->store_line(recent->get_item_text(i)); + { + Ref<FileAccess> f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("create_recent." + base_type), FileAccess::WRITE); + if (f.is_valid()) { + f->store_line(selected_item); + + for (int i = 0; i < MIN(32, recent->get_item_count()); i++) { + if (recent->get_item_text(i) != selected_item) { + f->store_line(recent->get_item_text(i)); + } } } - - memdelete(f); } // To prevent, emitting an error from the transient window (shader dialog for example) hide this dialog before emitting the "create" signal. @@ -647,25 +647,26 @@ void CreateDialog::_save_and_update_favorite_list() { favorites->clear(); TreeItem *root = favorites->create_item(); - FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("favorites." + base_type), FileAccess::WRITE); - if (f) { - for (int i = 0; i < favorite_list.size(); i++) { - String l = favorite_list[i]; - String name = l.get_slicec(' ', 0); - if (!(ClassDB::class_exists(name) || ScriptServer::is_global_class(name))) { - continue; - } - f->store_line(l); + { + Ref<FileAccess> f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("favorites." + base_type), FileAccess::WRITE); + if (f.is_valid()) { + for (int i = 0; i < favorite_list.size(); i++) { + String l = favorite_list[i]; + String name = l.get_slicec(' ', 0); + if (!(ClassDB::class_exists(name) || ScriptServer::is_global_class(name))) { + continue; + } + f->store_line(l); - if (_is_class_disabled_by_feature_profile(name)) { - continue; - } + if (_is_class_disabled_by_feature_profile(name)) { + continue; + } - TreeItem *ti = favorites->create_item(root); - ti->set_text(0, l); - ti->set_icon(0, EditorNode::get_singleton()->get_class_icon(name, icon_fallback)); + TreeItem *ti = favorites->create_item(root); + ti->set_text(0, l); + ti->set_icon(0, EditorNode::get_singleton()->get_class_icon(name, icon_fallback)); + } } - memdelete(f); } emit_signal(SNAME("favorites_updated")); @@ -673,8 +674,8 @@ void CreateDialog::_save_and_update_favorite_list() { void CreateDialog::_load_favorites_and_history() { String dir = EditorSettings::get_singleton()->get_project_settings_dir(); - FileAccess *f = FileAccess::open(dir.plus_file("create_recent." + base_type), FileAccess::READ); - if (f) { + Ref<FileAccess> f = FileAccess::open(dir.plus_file("create_recent." + base_type), FileAccess::READ); + if (f.is_valid()) { while (!f->eof_reached()) { String l = f->get_line().strip_edges(); String name = l.get_slicec(' ', 0); @@ -683,12 +684,10 @@ void CreateDialog::_load_favorites_and_history() { recent->add_item(l, EditorNode::get_singleton()->get_class_icon(name, icon_fallback)); } } - - memdelete(f); } f = FileAccess::open(dir.plus_file("favorites." + base_type), FileAccess::READ); - if (f) { + if (f.is_valid()) { while (!f->eof_reached()) { String l = f->get_line().strip_edges(); @@ -696,8 +695,6 @@ void CreateDialog::_load_favorites_and_history() { favorite_list.push_back(l); } } - - memdelete(f); } } diff --git a/editor/create_dialog.h b/editor/create_dialog.h index fe7c89c059..31761be6fe 100644 --- a/editor/create_dialog.h +++ b/editor/create_dialog.h @@ -47,18 +47,18 @@ class CreateDialog : public ConfirmationDialog { OTHER_TYPE }; - LineEdit *search_box; - Tree *search_options; + LineEdit *search_box = nullptr; + Tree *search_options = nullptr; String base_type; String icon_fallback; String preferred_search_result_type; - Button *favorite; + Button *favorite = nullptr; Vector<String> favorite_list; - Tree *favorites; - ItemList *recent; - EditorHelpBit *help_bit; + Tree *favorites = nullptr; + ItemList *recent = nullptr; + EditorHelpBit *help_bit = nullptr; HashMap<String, TreeItem *> search_options_types; HashMap<String, String> custom_type_parents; diff --git a/editor/debugger/debug_adapter/debug_adapter_protocol.h b/editor/debugger/debug_adapter/debug_adapter_protocol.h index b54a5f1f3f..e4760bea54 100644 --- a/editor/debugger/debug_adapter/debug_adapter_protocol.h +++ b/editor/debugger/debug_adapter/debug_adapter_protocol.h @@ -76,7 +76,7 @@ class DebugAdapterProtocol : public Object { private: static DebugAdapterProtocol *singleton; - DebugAdapterParser *parser; + DebugAdapterParser *parser = nullptr; List<Ref<DAPeer>> clients; Ref<TCPServer> server; diff --git a/editor/debugger/editor_debugger_inspector.h b/editor/debugger/editor_debugger_inspector.h index 5cdc4417d0..8f523bfbdc 100644 --- a/editor/debugger/editor_debugger_inspector.h +++ b/editor/debugger/editor_debugger_inspector.h @@ -70,7 +70,7 @@ private: ObjectID inspected_object_id; Map<ObjectID, EditorDebuggerRemoteObject *> remote_objects; Set<RES> remote_dependencies; - EditorDebuggerRemoteObject *variables; + EditorDebuggerRemoteObject *variables = nullptr; void _object_selected(ObjectID p_object); void _object_edited(ObjectID p_id, const String &p_prop, const Variant &p_value); diff --git a/editor/debugger/editor_network_profiler.h b/editor/debugger/editor_network_profiler.h index 3e95eb0de6..3a604f5564 100644 --- a/editor/debugger/editor_network_profiler.h +++ b/editor/debugger/editor_network_profiler.h @@ -42,13 +42,13 @@ class EditorNetworkProfiler : public VBoxContainer { GDCLASS(EditorNetworkProfiler, VBoxContainer) private: - Button *activate; - Button *clear_button; - Tree *counters_display; - LineEdit *incoming_bandwidth_text; - LineEdit *outgoing_bandwidth_text; + Button *activate = nullptr; + Button *clear_button = nullptr; + Tree *counters_display = nullptr; + LineEdit *incoming_bandwidth_text = nullptr; + LineEdit *outgoing_bandwidth_text = nullptr; - Timer *frame_delay; + Timer *frame_delay = nullptr; Map<ObjectID, SceneDebugger::RPCNodeInfo> nodes_data; diff --git a/editor/debugger/editor_performance_profiler.h b/editor/debugger/editor_performance_profiler.h index 998ecc5bb6..a917ddbe28 100644 --- a/editor/debugger/editor_performance_profiler.h +++ b/editor/debugger/editor_performance_profiler.h @@ -62,9 +62,9 @@ private: OrderedHashMap<StringName, Monitor> monitors; Map<StringName, TreeItem *> base_map; - Tree *monitor_tree; - Control *monitor_draw; - Label *info_message; + Tree *monitor_tree = nullptr; + Control *monitor_draw = nullptr; + Label *info_message = nullptr; StringName marker_key; int marker_frame; const int MARGIN = 4; diff --git a/editor/debugger/editor_profiler.h b/editor/debugger/editor_profiler.h index 45f7ac39c1..34f34be7c3 100644 --- a/editor/debugger/editor_profiler.h +++ b/editor/debugger/editor_profiler.h @@ -90,20 +90,20 @@ public: }; private: - Button *activate; - Button *clear_button; - TextureRect *graph; + Button *activate = nullptr; + Button *clear_button = nullptr; + TextureRect *graph = nullptr; Ref<ImageTexture> graph_texture; Vector<uint8_t> graph_image; - Tree *variables; - HSplitContainer *h_split; + Tree *variables = nullptr; + HSplitContainer *h_split = nullptr; Set<StringName> plot_sigs; - OptionButton *display_mode; - OptionButton *display_time; + OptionButton *display_mode = nullptr; + OptionButton *display_time = nullptr; - SpinBox *cursor_metric_edit; + SpinBox *cursor_metric_edit = nullptr; Vector<Metric> frame_metrics; int total_metrics; @@ -119,8 +119,8 @@ private: bool seeking; - Timer *frame_delay; - Timer *plot_delay; + Timer *frame_delay = nullptr; + Timer *plot_delay = nullptr; void _update_frame(); diff --git a/editor/debugger/editor_visual_profiler.h b/editor/debugger/editor_visual_profiler.h index 55ba725ae8..14eacca02d 100644 --- a/editor/debugger/editor_visual_profiler.h +++ b/editor/debugger/editor_visual_profiler.h @@ -67,20 +67,20 @@ public: }; private: - Button *activate; - Button *clear_button; + Button *activate = nullptr; + Button *clear_button = nullptr; - TextureRect *graph; + TextureRect *graph = nullptr; Ref<ImageTexture> graph_texture; Vector<uint8_t> graph_image; - Tree *variables; - HSplitContainer *h_split; - CheckBox *frame_relative; - CheckBox *linked; + Tree *variables = nullptr; + HSplitContainer *h_split = nullptr; + CheckBox *frame_relative = nullptr; + CheckBox *linked = nullptr; - OptionButton *display_mode; + OptionButton *display_mode = nullptr; - SpinBox *cursor_metric_edit; + SpinBox *cursor_metric_edit = nullptr; Vector<Metric> frame_metrics; int last_metric; @@ -99,8 +99,8 @@ private: bool seeking; - Timer *frame_delay; - Timer *plot_delay; + Timer *frame_delay = nullptr; + Timer *plot_delay = nullptr; void _update_frame(bool p_focus_selected = false); diff --git a/editor/debugger/script_editor_debugger.cpp b/editor/debugger/script_editor_debugger.cpp index 1e8753acc0..3a3b35f8a5 100644 --- a/editor/debugger/script_editor_debugger.cpp +++ b/editor/debugger/script_editor_debugger.cpp @@ -164,7 +164,7 @@ void ScriptEditorDebugger::_file_selected(const String &p_file) { switch (file_dialog_purpose) { case SAVE_MONITORS_CSV: { Error err; - FileAccessRef file = FileAccess::open(p_file, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_file, FileAccess::WRITE, &err); if (err != OK) { ERR_PRINT("Failed to open " + p_file); @@ -209,7 +209,7 @@ void ScriptEditorDebugger::_file_selected(const String &p_file) { } break; case SAVE_VRAM_CSV: { Error err; - FileAccessRef file = FileAccess::open(p_file, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_file, FileAccess::WRITE, &err); if (err != OK) { ERR_PRINT("Failed to open " + p_file); diff --git a/editor/debugger/script_editor_debugger.h b/editor/debugger/script_editor_debugger.h index 486ac26ef7..ad90e63c16 100644 --- a/editor/debugger/script_editor_debugger.h +++ b/editor/debugger/script_editor_debugger.h @@ -85,26 +85,26 @@ private: ACTION_DELETE_ALL_BREAKPOINTS, }; - AcceptDialog *msgdialog; - - LineEdit *clicked_ctrl; - LineEdit *clicked_ctrl_type; - LineEdit *live_edit_root; - Button *le_set; - Button *le_clear; - Button *export_csv; - - VBoxContainer *errors_tab; - Tree *error_tree; - Button *expand_all_button; - Button *collapse_all_button; - Button *clear_button; - PopupMenu *item_menu; - - Tree *breakpoints_tree; - PopupMenu *breakpoints_menu; - - EditorFileDialog *file_dialog; + AcceptDialog *msgdialog = nullptr; + + LineEdit *clicked_ctrl = nullptr; + LineEdit *clicked_ctrl_type = nullptr; + LineEdit *live_edit_root = nullptr; + Button *le_set = nullptr; + Button *le_clear = nullptr; + Button *export_csv = nullptr; + + VBoxContainer *errors_tab = nullptr; + Tree *error_tree = nullptr; + Button *expand_all_button = nullptr; + Button *collapse_all_button = nullptr; + Button *clear_button = nullptr; + PopupMenu *item_menu = nullptr; + + Tree *breakpoints_tree = nullptr; + PopupMenu *breakpoints_menu = nullptr; + + EditorFileDialog *file_dialog = nullptr; enum FileDialogPurpose { SAVE_MONITORS_CSV, SAVE_VRAM_CSV, @@ -117,31 +117,31 @@ private: bool skip_breakpoints_value = false; Ref<Script> stack_script; - TabContainer *tabs; + TabContainer *tabs = nullptr; - Label *reason; + Label *reason = nullptr; - Button *skip_breakpoints; - Button *copy; - Button *step; - Button *next; - Button *dobreak; - Button *docontinue; + Button *skip_breakpoints = nullptr; + Button *copy = nullptr; + Button *step = nullptr; + Button *next = nullptr; + Button *dobreak = nullptr; + Button *docontinue = nullptr; // Reference to "Remote" tab in scene tree. Needed by _live_edit_set and buttons state. // Each debugger should have it's tree in the future I guess. const Tree *editor_remote_tree = nullptr; Map<int, String> profiler_signature; - Tree *vmem_tree; - Button *vmem_refresh; - Button *vmem_export; - LineEdit *vmem_total; + Tree *vmem_tree = nullptr; + Button *vmem_refresh = nullptr; + Button *vmem_export = nullptr; + LineEdit *vmem_total = nullptr; - Tree *stack_dump; + Tree *stack_dump = nullptr; LineEdit *search = nullptr; - EditorDebuggerInspector *inspector; - SceneDebuggerTree *scene_tree; + EditorDebuggerInspector *inspector = nullptr; + SceneDebuggerTree *scene_tree = nullptr; Ref<RemoteDebuggerPeer> peer; @@ -149,10 +149,10 @@ private: int last_path_id; Map<String, int> res_path_cache; - EditorProfiler *profiler; - EditorVisualProfiler *visual_profiler; - EditorNetworkProfiler *network_profiler; - EditorPerformanceProfiler *performance_profiler; + EditorProfiler *profiler = nullptr; + EditorVisualProfiler *visual_profiler = nullptr; + EditorNetworkProfiler *network_profiler = nullptr; + EditorPerformanceProfiler *performance_profiler = nullptr; OS::ProcessID remote_pid = 0; bool breaked = false; diff --git a/editor/dependency_editor.cpp b/editor/dependency_editor.cpp index 95b3a02631..35f40a159a 100644 --- a/editor/dependency_editor.cpp +++ b/editor/dependency_editor.cpp @@ -749,7 +749,7 @@ void OrphanResourcesDialog::_find_to_delete(TreeItem *p_item, List<String> &path } void OrphanResourcesDialog::_delete_confirm() { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); for (const String &E : paths) { da->remove(E); EditorFileSystem::get_singleton()->update_file(E); diff --git a/editor/dependency_editor.h b/editor/dependency_editor.h index 84642edd79..d1dc470c79 100644 --- a/editor/dependency_editor.h +++ b/editor/dependency_editor.h @@ -42,10 +42,10 @@ class EditorFileSystemDirectory; class DependencyEditor : public AcceptDialog { GDCLASS(DependencyEditor, AcceptDialog); - Tree *tree; - Button *fixdeps; + Tree *tree = nullptr; + Button *fixdeps = nullptr; - EditorFileDialog *search; + EditorFileDialog *search = nullptr; String replacing; String editing; @@ -71,8 +71,8 @@ public: class DependencyEditorOwners : public AcceptDialog { GDCLASS(DependencyEditorOwners, AcceptDialog); - ItemList *owners; - PopupMenu *file_options; + ItemList *owners = nullptr; + PopupMenu *file_options = nullptr; String editing; void _fill_owners(EditorFileSystemDirectory *efsd); @@ -95,8 +95,8 @@ public: class DependencyRemoveDialog : public ConfirmationDialog { GDCLASS(DependencyRemoveDialog, ConfirmationDialog); - Label *text; - Tree *owners; + Label *text = nullptr; + Tree *owners = nullptr; Map<String, String> all_remove_files; Vector<String> dirs_to_delete; @@ -142,9 +142,9 @@ public: private: String for_file; Mode mode; - Button *fdep; - Label *text; - Tree *files; + Button *fdep = nullptr; + Label *text = nullptr; + Tree *files = nullptr; void ok_pressed() override; void custom_action(const String &) override; @@ -156,9 +156,9 @@ public: class OrphanResourcesDialog : public ConfirmationDialog { GDCLASS(OrphanResourcesDialog, ConfirmationDialog); - DependencyEditor *dep_edit; - Tree *files; - ConfirmationDialog *delete_confirm; + DependencyEditor *dep_edit = nullptr; + Tree *files = nullptr; + ConfirmationDialog *delete_confirm = nullptr; void ok_pressed() override; bool _fill_owners(EditorFileSystemDirectory *efsd, HashMap<String, int> &refs, TreeItem *p_parent); diff --git a/editor/doc_tools.cpp b/editor/doc_tools.cpp index adad8fdba8..16cbc0f34d 100644 --- a/editor/doc_tools.cpp +++ b/editor/doc_tools.cpp @@ -1035,8 +1035,8 @@ static Error _parse_methods(Ref<XMLParser> &parser, Vector<DocData::MethodDoc> & Error DocTools::load_classes(const String &p_dir) { Error err; - DirAccessRef da = DirAccess::open(p_dir, &err); - if (!da) { + Ref<DirAccess> da = DirAccess::open(p_dir, &err); + if (da.is_null()) { return err; } @@ -1063,8 +1063,8 @@ Error DocTools::load_classes(const String &p_dir) { Error DocTools::erase_classes(const String &p_dir) { Error err; - DirAccessRef da = DirAccess::open(p_dir, &err); - if (!da) { + Ref<DirAccess> da = DirAccess::open(p_dir, &err); + if (da.is_null()) { return err; } @@ -1273,7 +1273,7 @@ Error DocTools::_load(Ref<XMLParser> parser) { return OK; } -static void _write_string(FileAccess *f, int p_tablevel, const String &p_string) { +static void _write_string(Ref<FileAccess> f, int p_tablevel, const String &p_string) { if (p_string.is_empty()) { return; } @@ -1284,7 +1284,7 @@ static void _write_string(FileAccess *f, int p_tablevel, const String &p_string) f->store_string(tab + p_string + "\n"); } -static void _write_method_doc(FileAccess *f, const String &p_name, Vector<DocData::MethodDoc> &p_method_docs) { +static void _write_method_doc(Ref<FileAccess> f, const String &p_name, Vector<DocData::MethodDoc> &p_method_docs) { if (!p_method_docs.is_empty()) { p_method_docs.sort(); _write_string(f, 1, "<" + p_name + "s>"); @@ -1350,7 +1350,7 @@ Error DocTools::save_classes(const String &p_default_path, const Map<String, Str Error err; String save_file = save_path.plus_file(c.name + ".xml"); - FileAccessRef f = FileAccess::open(save_file, FileAccess::WRITE, &err); + Ref<FileAccess> f = FileAccess::open(save_file, FileAccess::WRITE, &err); ERR_CONTINUE_MSG(err != OK, "Can't write doc file: " + save_file + "."); diff --git a/editor/editor_about.h b/editor/editor_about.h index 5a3b1e1987..6f05700582 100644 --- a/editor/editor_about.h +++ b/editor/editor_about.h @@ -56,11 +56,11 @@ private: void _version_button_pressed(); ScrollContainer *_populate_list(const String &p_name, const List<String> &p_sections, const char *const *const p_src[], const int p_flag_single_column = 0); - LinkButton *version_btn; - Tree *_tpl_tree; - RichTextLabel *_license_text; - RichTextLabel *_tpl_text; - TextureRect *_logo; + LinkButton *version_btn = nullptr; + Tree *_tpl_tree = nullptr; + RichTextLabel *_license_text = nullptr; + RichTextLabel *_tpl_text = nullptr; + TextureRect *_logo = nullptr; void _theme_changed(); diff --git a/editor/editor_asset_installer.cpp b/editor/editor_asset_installer.cpp index f1674c47c5..7dcb9a4088 100644 --- a/editor/editor_asset_installer.cpp +++ b/editor/editor_asset_installer.cpp @@ -64,8 +64,7 @@ void EditorAssetInstaller::open(const String &p_path, int p_depth) { package_path = p_path; Set<String> files_sorted; - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); unzFile pkg = unzOpen2(p_path.utf8().get_data(), &io); if (!pkg) { @@ -238,8 +237,7 @@ void EditorAssetInstaller::open(const String &p_path, int p_depth) { } void EditorAssetInstaller::ok_pressed() { - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); unzFile pkg = unzOpen2(package_path.utf8().get_data(), &io); if (!pkg) { @@ -259,6 +257,9 @@ void EditorAssetInstaller::ok_pressed() { unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String name = String::utf8(fname); @@ -277,7 +278,7 @@ void EditorAssetInstaller::ok_pressed() { dirpath = dirpath.substr(0, dirpath.length() - 1); } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->make_dir(dirpath); } else { Vector<uint8_t> data; @@ -288,10 +289,9 @@ void EditorAssetInstaller::ok_pressed() { unzReadCurrentFile(pkg, data.ptrw(), data.size()); unzCloseCurrentFile(pkg); - FileAccess *f = FileAccess::open(path, FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE); + if (f.is_valid()) { f->store_buffer(data.ptr(), data.size()); - memdelete(f); } else { failed_files.push_back(path); } diff --git a/editor/editor_asset_installer.h b/editor/editor_asset_installer.h index 58c232f351..deb320e7fa 100644 --- a/editor/editor_asset_installer.h +++ b/editor/editor_asset_installer.h @@ -36,11 +36,11 @@ class EditorAssetInstaller : public ConfirmationDialog { GDCLASS(EditorAssetInstaller, ConfirmationDialog); - Tree *tree; - Label *asset_contents; + Tree *tree = nullptr; + Label *asset_contents = nullptr; String package_path; String asset_name; - AcceptDialog *error; + AcceptDialog *error = nullptr; Map<String, TreeItem *> status_map; bool updating = false; void _item_edited(); diff --git a/editor/editor_audio_buses.h b/editor/editor_audio_buses.h index 0020b61370..81a6e5b86d 100644 --- a/editor/editor_audio_buses.h +++ b/editor/editor_audio_buses.h @@ -52,9 +52,9 @@ class EditorAudioBus : public PanelContainer { GDCLASS(EditorAudioBus, PanelContainer); Ref<Texture2D> disabled_vu; - LineEdit *track_name; - MenuButton *bus_options; - VSlider *slider; + LineEdit *track_name = nullptr; + MenuButton *bus_options = nullptr; + VSlider *slider = nullptr; int cc; static const int CHANNELS_MAX = 4; @@ -69,21 +69,21 @@ class EditorAudioBus : public PanelContainer { TextureProgressBar *vu_r = nullptr; } channel[CHANNELS_MAX]; - OptionButton *send; + OptionButton *send = nullptr; - PopupMenu *effect_options; - PopupMenu *bus_popup; - PopupMenu *delete_effect_popup; + PopupMenu *effect_options = nullptr; + PopupMenu *bus_popup = nullptr; + PopupMenu *delete_effect_popup = nullptr; - Panel *audio_value_preview_box; - Label *audio_value_preview_label; - Timer *preview_timer; + Panel *audio_value_preview_box = nullptr; + Label *audio_value_preview_label = nullptr; + Timer *preview_timer = nullptr; - Button *solo; - Button *mute; - Button *bypass; + Button *solo = nullptr; + Button *mute = nullptr; + Button *bypass = nullptr; - Tree *effects; + Tree *effects = nullptr; bool updating_bus = false; bool is_master; @@ -121,7 +121,7 @@ class EditorAudioBus : public PanelContainer { friend class EditorAudioBuses; - EditorAudioBuses *buses; + EditorAudioBuses *buses = nullptr; protected: static void _bind_methods(); @@ -153,22 +153,22 @@ public: class EditorAudioBuses : public VBoxContainer { GDCLASS(EditorAudioBuses, VBoxContainer); - HBoxContainer *top_hb; + HBoxContainer *top_hb = nullptr; - ScrollContainer *bus_scroll; - HBoxContainer *bus_hb; + ScrollContainer *bus_scroll = nullptr; + HBoxContainer *bus_hb = nullptr; - EditorAudioBusDrop *drop_end; + EditorAudioBusDrop *drop_end = nullptr; - Label *file; + Label *file = nullptr; - Button *add; - Button *load; - Button *save_as; - Button *_default; - Button *_new; + Button *add = nullptr; + Button *load = nullptr; + Button *save_as = nullptr; + Button *_default = nullptr; + Button *_new = nullptr; - Timer *save_timer; + Timer *save_timer = nullptr; String edited_path; void _add_bus(); @@ -191,7 +191,7 @@ class EditorAudioBuses : public VBoxContainer { void _load_default_layout(); void _new_layout(); - EditorFileDialog *file_dialog; + EditorFileDialog *file_dialog = nullptr; bool new_layout; void _file_dialog_callback(const String &p_string); @@ -262,7 +262,7 @@ public: class AudioBusesEditorPlugin : public EditorPlugin { GDCLASS(AudioBusesEditorPlugin, EditorPlugin); - EditorAudioBuses *audio_bus_editor; + EditorAudioBuses *audio_bus_editor = nullptr; public: virtual String get_name() const override { return "SampleLibrary"; } diff --git a/editor/editor_autoload_settings.cpp b/editor/editor_autoload_settings.cpp index b37b06748d..49bf24f864 100644 --- a/editor/editor_autoload_settings.cpp +++ b/editor/editor_autoload_settings.cpp @@ -406,7 +406,7 @@ Node *EditorAutoloadSettings::_create_autoload(const String &p_path) { } else if (script.is_valid()) { StringName ibt = script->get_instance_base_type(); bool valid_type = ClassDB::is_parent_class(ibt, "Node"); - ERR_FAIL_COND_V_MSG(!valid_type, nullptr, "Script does not inherit a Node: " + p_path + "."); + ERR_FAIL_COND_V_MSG(!valid_type, nullptr, "Script does not inherit from Node: " + p_path + "."); Object *obj = ClassDB::instantiate(ibt); diff --git a/editor/editor_command_palette.h b/editor/editor_command_palette.h index 41141af0c3..124703cca4 100644 --- a/editor/editor_command_palette.h +++ b/editor/editor_command_palette.h @@ -40,8 +40,8 @@ class EditorCommandPalette : public ConfirmationDialog { GDCLASS(EditorCommandPalette, ConfirmationDialog); static EditorCommandPalette *singleton; - LineEdit *command_search_box; - Tree *search_options; + LineEdit *command_search_box = nullptr; + Tree *search_options = nullptr; struct Command { Callable callable; diff --git a/editor/editor_data.cpp b/editor/editor_data.cpp index a5e76ba0c0..a58a279faa 100644 --- a/editor/editor_data.cpp +++ b/editor/editor_data.cpp @@ -824,7 +824,7 @@ void EditorData::save_edited_scene_state(EditorSelection *p_selection, EditorSel Dictionary EditorData::restore_edited_scene_state(EditorSelection *p_selection, EditorSelectionHistory *p_history) { ERR_FAIL_INDEX_V(current_edited_scene, edited_scene.size(), Dictionary()); - EditedScene &es = edited_scene.write[current_edited_scene]; + const EditedScene &es = edited_scene.write[current_edited_scene]; p_history->current_elem_idx = es.history_current; p_history->history = es.history_stored; diff --git a/editor/editor_dir_dialog.cpp b/editor/editor_dir_dialog.cpp index 866f28c03b..8494991892 100644 --- a/editor/editor_dir_dialog.cpp +++ b/editor/editor_dir_dialog.cpp @@ -156,15 +156,18 @@ void EditorDirDialog::_make_dir_confirm() { String dir = ti->get_metadata(0); - if (EditorFileSystem::get_singleton()->get_filesystem_path(dir + makedirname->get_text())) { + Ref<DirAccess> d = DirAccess::open(dir); + ERR_FAIL_COND_MSG(d.is_null(), "Cannot open directory '" + dir + "'."); + + const String stripped_dirname = makedirname->get_text().strip_edges(); + + if (d->dir_exists(stripped_dirname)) { mkdirerr->set_text(TTR("Could not create folder. File with that name already exists.")); mkdirerr->popup_centered(); return; } - DirAccessRef d = DirAccess::open(dir); - ERR_FAIL_COND_MSG(!d, "Cannot open directory '" + dir + "'."); - Error err = d->make_dir(makedirname->get_text()); + Error err = d->make_dir(stripped_dirname); if (err != OK) { mkdirerr->popup_centered(Size2(250, 80) * EDSCALE); } else { diff --git a/editor/editor_dir_dialog.h b/editor/editor_dir_dialog.h index e97b5ce8af..9baa37793b 100644 --- a/editor/editor_dir_dialog.h +++ b/editor/editor_dir_dialog.h @@ -39,14 +39,14 @@ class EditorDirDialog : public ConfirmationDialog { GDCLASS(EditorDirDialog, ConfirmationDialog); - ConfirmationDialog *makedialog; - LineEdit *makedirname; - AcceptDialog *mkdirerr; + ConfirmationDialog *makedialog = nullptr; + LineEdit *makedirname = nullptr; + AcceptDialog *mkdirerr = nullptr; - Button *makedir; + Button *makedir = nullptr; Set<String> opened_paths; - Tree *tree; + Tree *tree = nullptr; bool updating = false; void _item_collapsed(Object *p_item); diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp index a1081fcbfb..58a9175df1 100644 --- a/editor/editor_export.cpp +++ b/editor/editor_export.cpp @@ -327,12 +327,12 @@ Error EditorExportPlatform::_save_pack_file(void *p_userdata, const String &p_pa } } - FileAccessEncrypted *fae = nullptr; - FileAccess *ftmp = pd->f; + Ref<FileAccessEncrypted> fae; + Ref<FileAccess> ftmp = pd->f; if (sd.encrypted) { - fae = memnew(FileAccessEncrypted); - ERR_FAIL_COND_V(!fae, ERR_SKIP); + fae.instantiate(); + ERR_FAIL_COND_V(fae.is_null(), ERR_SKIP); Error err = fae->open_and_parse(ftmp, p_key, FileAccessEncrypted::MODE_WRITE_AES256, false); ERR_FAIL_COND_V(err != OK, ERR_SKIP); @@ -342,9 +342,9 @@ Error EditorExportPlatform::_save_pack_file(void *p_userdata, const String &p_pa // Store file content. ftmp->store_buffer(p_data.ptr(), p_data.size()); - if (fae) { - fae->release(); - memdelete(fae); + if (fae.is_valid()) { + ftmp.unref(); + fae.unref(); } int pad = _get_pad(PCK_PADDING, pd->f->get_position()); @@ -480,7 +480,7 @@ void EditorExportPlatform::_export_find_dependencies(const String &p_path, Set<S } } -void EditorExportPlatform::_edit_files_with_filter(DirAccess *da, const Vector<String> &p_filters, Set<String> &r_list, bool exclude) { +void EditorExportPlatform::_edit_files_with_filter(Ref<DirAccess> &da, const Vector<String> &p_filters, Set<String> &r_list, bool exclude) { da->list_dir_begin(); String cur_dir = da->get_current_dir().replace("\\", "/"); if (!cur_dir.ends_with("/")) { @@ -542,10 +542,9 @@ void EditorExportPlatform::_edit_filter_list(Set<String> &r_list, const String & filters.push_back(f); } - DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - ERR_FAIL_NULL(da); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + ERR_FAIL_COND(da.is_null()); _edit_files_with_filter(da, filters, r_list, exclude); - memdelete(da); } void EditorExportPlugin::set_export_preset(const Ref<EditorExportPreset> &p_preset) { @@ -1130,12 +1129,12 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b EditorProgress ep("savepack", TTR("Packing"), 102, true); // Create the temporary export directory if it doesn't exist. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->make_dir_recursive(EditorPaths::get_singleton()->get_cache_dir()); String tmppath = EditorPaths::get_singleton()->get_cache_dir().plus_file("packtmp"); - FileAccess *ftmp = FileAccess::open(tmppath, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!ftmp, ERR_CANT_CREATE, "Cannot create file '" + tmppath + "'."); + Ref<FileAccess> ftmp = FileAccess::open(tmppath, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(ftmp.is_null(), ERR_CANT_CREATE, "Cannot create file '" + tmppath + "'."); PackData pd; pd.ep = &ep; @@ -1144,7 +1143,9 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b Error err = export_project_files(p_preset, p_debug, _save_pack_file, &pd, _add_shared_object); - memdelete(ftmp); //close tmp file + // Close temp file. + pd.f.unref(); + ftmp.unref(); if (err != OK) { DirAccess::remove_file_or_error(tmppath); @@ -1154,19 +1155,19 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b pd.file_ofs.sort(); //do sort, so we can do binary search later - FileAccess *f; + Ref<FileAccess> f; int64_t embed_pos = 0; if (!p_embed) { // Regular output to separate PCK file f = FileAccess::open(p_path, FileAccess::WRITE); - if (!f) { + if (f.is_null()) { DirAccess::remove_file_or_error(tmppath); ERR_FAIL_V(ERR_CANT_CREATE); } } else { // Append to executable f = FileAccess::open(p_path, FileAccess::READ_WRITE); - if (!f) { + if (f.is_null()) { DirAccess::remove_file_or_error(tmppath); ERR_FAIL_V(ERR_FILE_CANT_OPEN); } @@ -1211,8 +1212,8 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b f->store_32(pd.file_ofs.size()); //amount of files - FileAccessEncrypted *fae = nullptr; - FileAccess *fhead = f; + Ref<FileAccessEncrypted> fae; + Ref<FileAccess> fhead = f; if (enc_pck && enc_directory) { String script_key = p_preset->get_script_encryption_key().to_lower(); @@ -1243,8 +1244,8 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b key.write[i] = v; } } - fae = memnew(FileAccessEncrypted); - ERR_FAIL_COND_V(!fae, ERR_SKIP); + fae.instantiate(); + ERR_FAIL_COND_V(fae.is_null(), ERR_SKIP); err = fae->open_and_parse(f, key, FileAccessEncrypted::MODE_WRITE_AES256, false); ERR_FAIL_COND_V(err != OK, ERR_SKIP); @@ -1272,9 +1273,9 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b fhead->store_32(flags); } - if (fae) { - fae->release(); - memdelete(fae); + if (fae.is_valid()) { + fhead.unref(); + fae.unref(); } int header_padding = _get_pad(PCK_PADDING, f->get_position()); @@ -1290,8 +1291,7 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b // Save the rest of the data. ftmp = FileAccess::open(tmppath, FileAccess::READ); - if (!ftmp) { - memdelete(f); + if (ftmp.is_null()) { DirAccess::remove_file_or_error(tmppath); ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Can't open file to read from path '" + String(tmppath) + "'."); } @@ -1307,7 +1307,7 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b f->store_buffer(buf, got); } - memdelete(ftmp); + ftmp.unref(); // Close temp file. if (p_embed) { // Ensure embedded data ends at a 64-bit multiple @@ -1326,7 +1326,6 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b } } - memdelete(f); DirAccess::remove_file_or_error(tmppath); return OK; @@ -1335,8 +1334,7 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, b Error EditorExportPlatform::save_zip(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path) { EditorProgress ep("savezip", TTR("Packing"), 102, true); - FileAccess *src_f; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); zipFile zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io); ZipData zd; @@ -1839,7 +1837,7 @@ Error EditorExportPlatformPC::export_project(const Ref<EditorExportPreset> &p_pr return ERR_FILE_NOT_FOUND; } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->make_dir_recursive(p_path.get_base_dir()); Error err = da->copy(template_path, p_path, get_chmod_flags()); diff --git a/editor/editor_export.h b/editor/editor_export.h index 7c61e7cff6..236f4d129c 100644 --- a/editor/editor_export.h +++ b/editor/editor_export.h @@ -184,7 +184,7 @@ private: }; struct PackData { - FileAccess *f = nullptr; + Ref<FileAccess> f; Vector<SavedData> file_ofs; EditorProgress *ep = nullptr; Vector<SharedObject> *so_files = nullptr; @@ -207,7 +207,7 @@ private: static Error _save_pack_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key); static Error _save_zip_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key); - void _edit_files_with_filter(DirAccess *da, const Vector<String> &p_filters, Set<String> &r_list, bool exclude); + void _edit_files_with_filter(Ref<DirAccess> &da, const Vector<String> &p_filters, Set<String> &r_list, bool exclude); void _edit_filter_list(Set<String> &r_list, const String &p_filter, bool exclude); static Error _add_shared_object(void *p_userdata, const SharedObject &p_so); @@ -380,7 +380,7 @@ class EditorExport : public Node { StringName _export_presets_updated; - Timer *save_timer; + Timer *save_timer = nullptr; bool block_save = false; static EditorExport *singleton; diff --git a/editor/editor_feature_profile.cpp b/editor/editor_feature_profile.cpp index cf45848ed3..a20f112b2a 100644 --- a/editor/editor_feature_profile.cpp +++ b/editor/editor_feature_profile.cpp @@ -198,13 +198,12 @@ Error EditorFeatureProfile::save_to_file(const String &p_path) { data["disabled_features"] = dis_features; - FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_CREATE, "Cannot create file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'."); JSON json; String text = json.stringify(data, "\t"); f->store_string(text); - f->close(); return OK; } @@ -350,8 +349,8 @@ void EditorFeatureProfileManager::_update_profile_list(const String &p_select_pr } Vector<String> profiles; - DirAccessRef d = DirAccess::open(EditorSettings::get_singleton()->get_feature_profiles_dir()); - ERR_FAIL_COND_MSG(!d, "Cannot open directory '" + EditorSettings::get_singleton()->get_feature_profiles_dir() + "'."); + Ref<DirAccess> d = DirAccess::open(EditorSettings::get_singleton()->get_feature_profiles_dir()); + ERR_FAIL_COND_MSG(d.is_null(), "Cannot open directory '" + EditorSettings::get_singleton()->get_feature_profiles_dir() + "'."); d->list_dir_begin(); while (true) { @@ -453,8 +452,8 @@ void EditorFeatureProfileManager::_profile_action(int p_action) { void EditorFeatureProfileManager::_erase_selected_profile() { String selected = _get_selected_profile(); ERR_FAIL_COND(selected.is_empty()); - DirAccessRef da = DirAccess::open(EditorSettings::get_singleton()->get_feature_profiles_dir()); - ERR_FAIL_COND_MSG(!da, "Cannot open directory '" + EditorSettings::get_singleton()->get_feature_profiles_dir() + "'."); + Ref<DirAccess> da = DirAccess::open(EditorSettings::get_singleton()->get_feature_profiles_dir()); + ERR_FAIL_COND_MSG(da.is_null(), "Cannot open directory '" + EditorSettings::get_singleton()->get_feature_profiles_dir() + "'."); da->remove(selected + ".profile"); if (selected == current_profile) { diff --git a/editor/editor_feature_profile.h b/editor/editor_feature_profile.h index 881f14638f..19df8a9686 100644 --- a/editor/editor_feature_profile.h +++ b/editor/editor_feature_profile.h @@ -117,25 +117,25 @@ class EditorFeatureProfileManager : public AcceptDialog { CLASS_OPTION_DISABLE_EDITOR }; - ConfirmationDialog *erase_profile_dialog; - ConfirmationDialog *new_profile_dialog; - LineEdit *new_profile_name; + ConfirmationDialog *erase_profile_dialog = nullptr; + ConfirmationDialog *new_profile_dialog = nullptr; + LineEdit *new_profile_name = nullptr; - LineEdit *current_profile_name; - OptionButton *profile_list; + LineEdit *current_profile_name = nullptr; + OptionButton *profile_list = nullptr; Button *profile_actions[PROFILE_MAX]; - HSplitContainer *h_split; + HSplitContainer *h_split = nullptr; - VBoxContainer *class_list_vbc; - Tree *class_list; - VBoxContainer *property_list_vbc; - Tree *property_list; - EditorHelpBit *description_bit; - Label *no_profile_selected_help; + VBoxContainer *class_list_vbc = nullptr; + Tree *class_list = nullptr; + VBoxContainer *property_list_vbc = nullptr; + Tree *property_list = nullptr; + EditorHelpBit *description_bit = nullptr; + Label *no_profile_selected_help = nullptr; - EditorFileDialog *import_profiles; - EditorFileDialog *export_profile; + EditorFileDialog *import_profiles = nullptr; + EditorFileDialog *export_profile = nullptr; void _profile_action(int p_action); void _profile_selected(int p_what); @@ -163,7 +163,7 @@ class EditorFeatureProfileManager : public AcceptDialog { void _property_item_edited(); void _save_and_update(); - Timer *update_timer; + Timer *update_timer = nullptr; void _emit_current_profile_changed(); static EditorFeatureProfileManager *singleton; diff --git a/editor/editor_file_dialog.cpp b/editor/editor_file_dialog.cpp index ab403c4212..dca69ffd5f 100644 --- a/editor/editor_file_dialog.cpp +++ b/editor/editor_file_dialog.cpp @@ -106,7 +106,7 @@ void EditorFileDialog::_notification(int p_what) { case NOTIFICATION_VISIBILITY_CHANGED: { if (!is_visible()) { - set_process_unhandled_input(false); + set_process_shortcut_input(false); } } break; @@ -126,7 +126,7 @@ void EditorFileDialog::_notification(int p_what) { } } -void EditorFileDialog::unhandled_input(const Ref<InputEvent> &p_event) { +void EditorFileDialog::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); Ref<InputEventKey> k = p_event; @@ -327,7 +327,7 @@ void EditorFileDialog::_post_popup() { _update_favorites(); } - set_process_unhandled_input(true); + set_process_shortcut_input(true); } void EditorFileDialog::_thumbnail_result(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, const Variant &p_udata) { @@ -789,7 +789,7 @@ void EditorFileDialog::update_file_list() { } } else if (!dir_access->current_is_hidden()) { String full_path = cdir == "res://" ? item : dir_access->get_current_dir() + "/" + item; - if (dir_access->current_is_dir() && !EditorFileSystem::_should_skip_directory(full_path)) { + if (dir_access->current_is_dir() && (!EditorFileSystem::_should_skip_directory(full_path) || Engine::get_singleton()->is_project_manager_hint())) { dirs.push_back(item); } else { files.push_back(item); @@ -1065,7 +1065,6 @@ void EditorFileDialog::set_access(Access p_access) { if (access == p_access) { return; } - memdelete(dir_access); switch (p_access) { case ACCESS_FILESYSTEM: { dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); @@ -1099,16 +1098,18 @@ EditorFileDialog::Access EditorFileDialog::get_access() const { } void EditorFileDialog::_make_dir_confirm() { - if (EditorFileSystem::get_singleton()->get_filesystem_path(makedirname->get_text().strip_edges())) { + const String stripped_dirname = makedirname->get_text().strip_edges(); + + if (dir_access->dir_exists(stripped_dirname)) { error_dialog->set_text(TTR("Could not create folder. File with that name already exists.")); error_dialog->popup_centered(Size2(250, 50) * EDSCALE); makedirname->set_text(""); // Reset label. return; } - Error err = dir_access->make_dir(makedirname->get_text().strip_edges()); + Error err = dir_access->make_dir(stripped_dirname); if (err == OK) { - dir_access->change_dir(makedirname->get_text().strip_edges()); + dir_access->change_dir(stripped_dirname); invalidate(); update_filters(); update_dir(); @@ -1851,5 +1852,4 @@ EditorFileDialog::~EditorFileDialog() { if (unregister_func) { unregister_func(this); } - memdelete(dir_access); } diff --git a/editor/editor_file_dialog.h b/editor/editor_file_dialog.h index a747255ce8..db2a2ab09f 100644 --- a/editor/editor_file_dialog.h +++ b/editor/editor_file_dialog.h @@ -84,50 +84,50 @@ private: ITEM_MENU_SHOW_IN_EXPLORER }; - ConfirmationDialog *makedialog; - LineEdit *makedirname; + ConfirmationDialog *makedialog = nullptr; + LineEdit *makedirname = nullptr; - Button *makedir; + Button *makedir = nullptr; Access access; - VBoxContainer *vbox; + VBoxContainer *vbox = nullptr; FileMode mode; bool can_create_dir; - LineEdit *dir; - - Button *dir_prev; - Button *dir_next; - Button *dir_up; - - HBoxContainer *drives_container; - HBoxContainer *shortcuts_container; - OptionButton *drives; - ItemList *item_list; - PopupMenu *item_menu; - TextureRect *preview; - VBoxContainer *preview_vb; - HSplitContainer *list_hb; - HBoxContainer *file_box; - LineEdit *file; - OptionButton *filter; - AcceptDialog *error_dialog; - DirAccess *dir_access; - ConfirmationDialog *confirm_save; - DependencyRemoveDialog *dep_remove_dialog; - ConfirmationDialog *global_remove_dialog; - - Button *mode_thumbnails; - Button *mode_list; - - Button *refresh; - Button *favorite; - Button *show_hidden; - - Button *fav_up; - Button *fav_down; - - ItemList *favorites; - ItemList *recent; + LineEdit *dir = nullptr; + + Button *dir_prev = nullptr; + Button *dir_next = nullptr; + Button *dir_up = nullptr; + + HBoxContainer *drives_container = nullptr; + HBoxContainer *shortcuts_container = nullptr; + OptionButton *drives = nullptr; + ItemList *item_list = nullptr; + PopupMenu *item_menu = nullptr; + TextureRect *preview = nullptr; + VBoxContainer *preview_vb = nullptr; + HSplitContainer *list_hb = nullptr; + HBoxContainer *file_box = nullptr; + LineEdit *file = nullptr; + OptionButton *filter = nullptr; + AcceptDialog *error_dialog = nullptr; + Ref<DirAccess> dir_access; + ConfirmationDialog *confirm_save = nullptr; + DependencyRemoveDialog *dep_remove_dialog = nullptr; + ConfirmationDialog *global_remove_dialog = nullptr; + + Button *mode_thumbnails = nullptr; + Button *mode_list = nullptr; + + Button *refresh = nullptr; + Button *favorite = nullptr; + Button *show_hidden = nullptr; + + Button *fav_up = nullptr; + Button *fav_down = nullptr; + + ItemList *favorites = nullptr; + ItemList *recent = nullptr; Vector<String> local_history; int local_history_pos; @@ -201,7 +201,7 @@ private: void _thumbnail_done(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, const Variant &p_udata); void _request_single_thumbnail(const String &p_path); - virtual void unhandled_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; bool _is_open_should_be_disabled(); diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp index 2b98a4b02a..099dfe69d5 100644 --- a/editor/editor_file_system.cpp +++ b/editor/editor_file_system.cpp @@ -218,81 +218,80 @@ void EditorFileSystem::_scan_filesystem() { String project = ProjectSettings::get_singleton()->get_resource_path(); String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME); - FileAccess *f = FileAccess::open(fscache, FileAccess::READ); - - bool first = true; - if (f) { - //read the disk cache - while (!f->eof_reached()) { - String l = f->get_line().strip_edges(); - if (first) { - if (first_scan) { - // only use this on first scan, afterwards it gets ignored - // this is so on first reimport we synchronize versions, then - // we don't care until editor restart. This is for usability mainly so - // your workflow is not killed after changing a setting by forceful reimporting - // everything there is. - filesystem_settings_version_for_import = l.strip_edges(); - if (filesystem_settings_version_for_import != ResourceFormatImporter::get_singleton()->get_import_settings_hash()) { - revalidate_import_files = true; + { + Ref<FileAccess> f = FileAccess::open(fscache, FileAccess::READ); + + bool first = true; + if (f.is_valid()) { + //read the disk cache + while (!f->eof_reached()) { + String l = f->get_line().strip_edges(); + if (first) { + if (first_scan) { + // only use this on first scan, afterwards it gets ignored + // this is so on first reimport we synchronize versions, then + // we don't care until editor restart. This is for usability mainly so + // your workflow is not killed after changing a setting by forceful reimporting + // everything there is. + filesystem_settings_version_for_import = l.strip_edges(); + if (filesystem_settings_version_for_import != ResourceFormatImporter::get_singleton()->get_import_settings_hash()) { + revalidate_import_files = true; + } } + first = false; + continue; + } + if (l.is_empty()) { + continue; } - first = false; - continue; - } - if (l.is_empty()) { - continue; - } - if (l.begins_with("::")) { - Vector<String> split = l.split("::"); - ERR_CONTINUE(split.size() != 3); - String name = split[1]; + if (l.begins_with("::")) { + Vector<String> split = l.split("::"); + ERR_CONTINUE(split.size() != 3); + String name = split[1]; - cpath = name; + cpath = name; - } else { - Vector<String> split = l.split("::"); - ERR_CONTINUE(split.size() != 9); - String name = split[0]; - String file; - - file = name; - name = cpath.plus_file(name); - - FileCache fc; - fc.type = split[1]; - fc.uid = split[2].to_int(); - fc.modification_time = split[3].to_int(); - fc.import_modification_time = split[4].to_int(); - fc.import_valid = split[5].to_int() != 0; - fc.import_group_file = split[6].strip_edges(); - fc.script_class_name = split[7].get_slice("<>", 0); - fc.script_class_extends = split[7].get_slice("<>", 1); - fc.script_class_icon_path = split[7].get_slice("<>", 2); - - String deps = split[8].strip_edges(); - if (deps.length()) { - Vector<String> dp = deps.split("<>"); - for (int i = 0; i < dp.size(); i++) { - String path = dp[i]; - fc.deps.push_back(path); + } else { + Vector<String> split = l.split("::"); + ERR_CONTINUE(split.size() != 9); + String name = split[0]; + String file; + + file = name; + name = cpath.plus_file(name); + + FileCache fc; + fc.type = split[1]; + fc.uid = split[2].to_int(); + fc.modification_time = split[3].to_int(); + fc.import_modification_time = split[4].to_int(); + fc.import_valid = split[5].to_int() != 0; + fc.import_group_file = split[6].strip_edges(); + fc.script_class_name = split[7].get_slice("<>", 0); + fc.script_class_extends = split[7].get_slice("<>", 1); + fc.script_class_icon_path = split[7].get_slice("<>", 2); + + String deps = split[8].strip_edges(); + if (deps.length()) { + Vector<String> dp = deps.split("<>"); + for (int i = 0; i < dp.size(); i++) { + String path = dp[i]; + fc.deps.push_back(path); + } } - } - file_cache[name] = fc; + file_cache[name] = fc; + } } } - - f->close(); - memdelete(f); } String update_cache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4"); if (FileAccess::exists(update_cache)) { { - FileAccessRef f2 = FileAccess::open(update_cache, FileAccess::READ); + Ref<FileAccess> f2 = FileAccess::open(update_cache, FileAccess::READ); String l = f2->get_line().strip_edges(); while (!l.is_empty()) { file_cache.erase(l); //erase cache for this, so it gets updated @@ -300,7 +299,7 @@ void EditorFileSystem::_scan_filesystem() { } } - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); d->remove(update_cache); //bye bye update cache } @@ -314,14 +313,12 @@ void EditorFileSystem::_scan_filesystem() { new_filesystem = memnew(EditorFileSystemDirectory); new_filesystem->parent = nullptr; - DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES); d->change_dir("res://"); _scan_new_dir(new_filesystem, d, sp); file_cache.clear(); //clear caches, no longer needed - memdelete(d); - if (!first_scan) { //on the first scan this is done from the main thread after re-importing _save_filesystem_cache(); @@ -335,13 +332,11 @@ void EditorFileSystem::_save_filesystem_cache() { String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file(CACHE_FILE_NAME); - FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE); - ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions."); + Ref<FileAccess> f = FileAccess::open(fscache, FileAccess::WRITE); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + fscache + "'. Check user write permissions."); f->store_line(filesystem_settings_version_for_import); _save_filesystem_cache(filesystem, f); - f->close(); - memdelete(f); } void EditorFileSystem::_thread_func(void *_userdata) { @@ -364,9 +359,9 @@ bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_impo } Error err; - FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path + ".import", FileAccess::READ, &err); - if (!f) { //no import file, do reimport + if (f.is_null()) { //no import file, do reimport return true; } @@ -400,7 +395,6 @@ bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_impo break; } else if (err != OK) { ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import:" + itos(lines) + "' error '" + error_text + "'."); - memdelete(f); return false; //parse error, try reimport manually (Avoid reimport loop on broken file) } @@ -431,8 +425,6 @@ bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_impo } } - memdelete(f); - if (importer_name == "keep") { return false; //keep mode, do not reimport } @@ -453,8 +445,8 @@ bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_impo // Read the md5's from a separate file (so the import parameters aren't dependent on the file version String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_path); - FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::READ, &err); - if (!md5s) { // No md5's stored for this resource + Ref<FileAccess> md5s = FileAccess::open(base_path + ".md5", FileAccess::READ, &err); + if (md5s.is_null()) { // No md5's stored for this resource return true; } @@ -472,7 +464,6 @@ bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_impo break; } else if (err != OK) { ERR_PRINT("ResourceFormatImporter::load - '" + p_path + ".import.md5:" + itos(lines) + "' error '" + error_text + "'."); - memdelete(md5s); return false; // parse error } if (!assign.is_empty()) { @@ -485,7 +476,6 @@ bool EditorFileSystem::_test_for_reimport(const String &p_path, bool p_only_impo } } } - memdelete(md5s); //imported files are gone, reimport for (const String &E : to_check) { @@ -742,7 +732,7 @@ EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_cur return sp; } -void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress) { +void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, Ref<DirAccess> &da, const ScanProgress &p_progress) { List<String> dirs; List<String> files; @@ -967,7 +957,7 @@ void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const //then scan files and directories and check what's different - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); Error ret = da->change_dir(cd); ERR_FAIL_COND_MSG(ret != OK, "Cannot change to '" + cd + "' folder."); @@ -998,10 +988,9 @@ void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const efd->parent = p_dir; efd->name = f; - DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES); d->change_dir(cd.plus_file(f)); _scan_new_dir(efd, d, p_progress.get_sub(1, 1)); - memdelete(d); ItemAction ia; ia.action = ItemAction::ACTION_DIR_ADD; @@ -1137,7 +1126,7 @@ void EditorFileSystem::_delete_internal_files(String p_file) { if (FileAccess::exists(p_file + ".import")) { List<String> paths; ResourceFormatImporter::get_singleton()->get_internal_resource_path_list(p_file, &paths); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); for (const String &E : paths) { da->remove(E); } @@ -1282,7 +1271,7 @@ EditorFileSystemDirectory *EditorFileSystem::get_filesystem() { return filesystem; } -void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file) { +void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, Ref<FileAccess> p_file) { if (!p_dir) { return; //none } @@ -1467,8 +1456,8 @@ EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String &p void EditorFileSystem::_save_late_updated_files() { //files that already existed, and were modified, need re-scanning for dependencies upon project restart. This is done via saving this special file String fscache = EditorSettings::get_singleton()->get_project_settings_dir().plus_file("filesystem_update4"); - FileAccessRef f = FileAccess::open(fscache, FileAccess::WRITE); - ERR_FAIL_COND_MSG(!f, "Cannot create file '" + fscache + "'. Check user write permissions."); + Ref<FileAccess> f = FileAccess::open(fscache, FileAccess::WRITE); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + fscache + "'. Check user write permissions."); for (Set<String>::Element *E = late_update_files.front(); E; E = E->next()) { f->store_line(E->get()); } @@ -1713,78 +1702,78 @@ Error EditorFileSystem::_reimport_group(const String &p_group_file, const Vector for (const KeyValue<String, Map<StringName, Variant>> &E : source_file_options) { const String &file = E.key; String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(file); - FileAccessRef f = FileAccess::open(file + ".import", FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!f, ERR_FILE_CANT_OPEN, "Cannot open import file '" + file + ".import'."); - - //write manually, as order matters ([remap] has to go first for performance). - f->store_line("[remap]"); - f->store_line(""); - f->store_line("importer=\"" + importer->get_importer_name() + "\""); - int version = importer->get_format_version(); - if (version > 0) { - f->store_line("importer_version=" + itos(version)); - } - if (!importer->get_resource_type().is_empty()) { - f->store_line("type=\"" + importer->get_resource_type() + "\""); - } - Vector<String> dest_paths; + { + Ref<FileAccess> f = FileAccess::open(file + ".import", FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_FILE_CANT_OPEN, "Cannot open import file '" + file + ".import'."); + + //write manually, as order matters ([remap] has to go first for performance). + f->store_line("[remap]"); + f->store_line(""); + f->store_line("importer=\"" + importer->get_importer_name() + "\""); + int version = importer->get_format_version(); + if (version > 0) { + f->store_line("importer_version=" + itos(version)); + } + if (!importer->get_resource_type().is_empty()) { + f->store_line("type=\"" + importer->get_resource_type() + "\""); + } - if (err == OK) { - String path = base_path + "." + importer->get_save_extension(); - f->store_line("path=\"" + path + "\""); - dest_paths.push_back(path); - } - - f->store_line("group_file=" + Variant(p_group_file).get_construct_string()); - - if (err == OK) { - f->store_line("valid=true"); - } else { - f->store_line("valid=false"); - } - f->store_line("[deps]\n"); + if (err == OK) { + String path = base_path + "." + importer->get_save_extension(); + f->store_line("path=\"" + path + "\""); + dest_paths.push_back(path); + } - f->store_line(""); + f->store_line("group_file=" + Variant(p_group_file).get_construct_string()); - f->store_line("source_file=" + Variant(file).get_construct_string()); - if (dest_paths.size()) { - Array dp; - for (int i = 0; i < dest_paths.size(); i++) { - dp.push_back(dest_paths[i]); + if (err == OK) { + f->store_line("valid=true"); + } else { + f->store_line("valid=false"); } - f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); - } - f->store_line("[params]"); - f->store_line(""); + f->store_line("[deps]\n"); - //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. + f->store_line(""); - List<ResourceImporter::ImportOption> options; - importer->get_import_options(file, &options); - //set default values - for (const ResourceImporter::ImportOption &F : options) { - String base = F.option.name; - Variant v = F.default_value; - if (source_file_options[file].has(base)) { - v = source_file_options[file][base]; + f->store_line("source_file=" + Variant(file).get_construct_string()); + if (dest_paths.size()) { + Array dp; + for (int i = 0; i < dest_paths.size(); i++) { + dp.push_back(dest_paths[i]); + } + f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); + } + f->store_line("[params]"); + f->store_line(""); + + //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. + + List<ResourceImporter::ImportOption> options; + importer->get_import_options(file, &options); + //set default values + for (const ResourceImporter::ImportOption &F : options) { + String base = F.option.name; + Variant v = F.default_value; + if (source_file_options[file].has(base)) { + v = source_file_options[file][base]; + } + String value; + VariantWriter::write_to_string(v, value); + f->store_line(base + "=" + value); } - String value; - VariantWriter::write_to_string(v, value); - f->store_line(base + "=" + value); } - f->close(); - // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled. - FileAccessRef md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!md5s, ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'."); + { + Ref<FileAccess> md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(md5s.is_null(), ERR_FILE_CANT_OPEN, "Cannot open MD5 file '" + base_path + ".md5'."); - md5s->store_line("source_md5=\"" + FileAccess::get_md5(file) + "\""); - if (dest_paths.size()) { - md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); + md5s->store_line("source_md5=\"" + FileAccess::get_md5(file) + "\""); + if (dest_paths.size()) { + md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); + } } - md5s->close(); EditorFileSystemDirectory *fs = nullptr; int cpos = -1; @@ -1930,106 +1919,104 @@ void EditorFileSystem::_reimport_file(const String &p_file, const Map<StringName //as import is complete, save the .import file - FileAccess *f = FileAccess::open(p_file + ".import", FileAccess::WRITE); - ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + p_file + ".import'."); - - //write manually, as order matters ([remap] has to go first for performance). - f->store_line("[remap]"); - f->store_line(""); - f->store_line("importer=\"" + importer->get_importer_name() + "\""); - int version = importer->get_format_version(); - if (version > 0) { - f->store_line("importer_version=" + itos(version)); - } - if (!importer->get_resource_type().is_empty()) { - f->store_line("type=\"" + importer->get_resource_type() + "\""); - } - - if (uid == ResourceUID::INVALID_ID) { - uid = ResourceUID::get_singleton()->create_id(); - } + Vector<String> dest_paths; + { + Ref<FileAccess> f = FileAccess::open(p_file + ".import", FileAccess::WRITE); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file from path '" + p_file + ".import'."); - f->store_line("uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\""); //store in readable format + //write manually, as order matters ([remap] has to go first for performance). + f->store_line("[remap]"); + f->store_line(""); + f->store_line("importer=\"" + importer->get_importer_name() + "\""); + int version = importer->get_format_version(); + if (version > 0) { + f->store_line("importer_version=" + itos(version)); + } + if (!importer->get_resource_type().is_empty()) { + f->store_line("type=\"" + importer->get_resource_type() + "\""); + } - Vector<String> dest_paths; + if (uid == ResourceUID::INVALID_ID) { + uid = ResourceUID::get_singleton()->create_id(); + } - if (err == OK) { - if (importer->get_save_extension().is_empty()) { - //no path - } else if (import_variants.size()) { - //import with variants - for (const String &E : import_variants) { - String path = base_path.c_escape() + "." + E + "." + importer->get_save_extension(); + f->store_line("uid=\"" + ResourceUID::get_singleton()->id_to_text(uid) + "\""); //store in readable format - f->store_line("path." + E + "=\"" + path + "\""); + if (err == OK) { + if (importer->get_save_extension().is_empty()) { + //no path + } else if (import_variants.size()) { + //import with variants + for (const String &E : import_variants) { + String path = base_path.c_escape() + "." + E + "." + importer->get_save_extension(); + + f->store_line("path." + E + "=\"" + path + "\""); + dest_paths.push_back(path); + } + } else { + String path = base_path + "." + importer->get_save_extension(); + f->store_line("path=\"" + path + "\""); dest_paths.push_back(path); } + } else { - String path = base_path + "." + importer->get_save_extension(); - f->store_line("path=\"" + path + "\""); - dest_paths.push_back(path); + f->store_line("valid=false"); } - } else { - f->store_line("valid=false"); - } + if (metadata != Variant()) { + f->store_line("metadata=" + metadata.get_construct_string()); + } - if (metadata != Variant()) { - f->store_line("metadata=" + metadata.get_construct_string()); - } + f->store_line(""); - f->store_line(""); + f->store_line("[deps]\n"); - f->store_line("[deps]\n"); + if (gen_files.size()) { + Array genf; + for (const String &E : gen_files) { + genf.push_back(E); + dest_paths.push_back(E); + } - if (gen_files.size()) { - Array genf; - for (const String &E : gen_files) { - genf.push_back(E); - dest_paths.push_back(E); + String value; + VariantWriter::write_to_string(genf, value); + f->store_line("files=" + value); + f->store_line(""); } - String value; - VariantWriter::write_to_string(genf, value); - f->store_line("files=" + value); - f->store_line(""); - } - - f->store_line("source_file=" + Variant(p_file).get_construct_string()); + f->store_line("source_file=" + Variant(p_file).get_construct_string()); - if (dest_paths.size()) { - Array dp; - for (int i = 0; i < dest_paths.size(); i++) { - dp.push_back(dest_paths[i]); + if (dest_paths.size()) { + Array dp; + for (int i = 0; i < dest_paths.size(); i++) { + dp.push_back(dest_paths[i]); + } + f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); } - f->store_line("dest_files=" + Variant(dp).get_construct_string() + "\n"); - } - f->store_line("[params]"); - f->store_line(""); + f->store_line("[params]"); + f->store_line(""); - //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. + //store options in provided order, to avoid file changing. Order is also important because first match is accepted first. - for (const ResourceImporter::ImportOption &E : opts) { - String base = E.option.name; - String value; - VariantWriter::write_to_string(params[base], value); - f->store_line(base + "=" + value); + for (const ResourceImporter::ImportOption &E : opts) { + String base = E.option.name; + String value; + VariantWriter::write_to_string(params[base], value); + f->store_line(base + "=" + value); + } } - f->close(); - memdelete(f); - // Store the md5's of the various files. These are stored separately so that the .import files can be version controlled. - FileAccess *md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); - ERR_FAIL_COND_MSG(!md5s, "Cannot open MD5 file '" + base_path + ".md5'."); + { + Ref<FileAccess> md5s = FileAccess::open(base_path + ".md5", FileAccess::WRITE); + ERR_FAIL_COND_MSG(md5s.is_null(), "Cannot open MD5 file '" + base_path + ".md5'."); - md5s->store_line("source_md5=\"" + FileAccess::get_md5(p_file) + "\""); - if (dest_paths.size()) { - md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); + md5s->store_line("source_md5=\"" + FileAccess::get_md5(p_file) + "\""); + if (dest_paths.size()) { + md5s->store_line("dest_md5=\"" + FileAccess::get_multiple_md5(dest_paths) + "\"\n"); + } } - md5s->close(); - memdelete(md5s); //update modified times, to avoid reimport fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file); @@ -2342,14 +2329,14 @@ bool EditorFileSystem::_scan_extensions() { String extension_list_config_file = NativeExtension::get_extension_list_config_file(); if (extensions.size()) { if (extensions_added.size() || extensions_removed.size()) { //extensions were added or removed - FileAccessRef f = FileAccess::open(extension_list_config_file, FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open(extension_list_config_file, FileAccess::WRITE); for (const String &E : extensions) { f->store_line(E); } } } else { if (loaded_extensions.size() || FileAccess::exists(extension_list_config_file)) { //extensions were removed - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(extension_list_config_file); } } @@ -2438,7 +2425,7 @@ EditorFileSystem::EditorFileSystem() { new_filesystem = nullptr; // This should probably also work on Unix and use the string it returns for FAT32 or exFAT - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); using_fat32_or_exfat = (da->get_filesystem_type() == "FAT32" || da->get_filesystem_type() == "exFAT"); scan_total = 0; diff --git a/editor/editor_file_system.h b/editor/editor_file_system.h index 0ddac65839..81811d2eb0 100644 --- a/editor/editor_file_system.h +++ b/editor/editor_file_system.h @@ -49,7 +49,7 @@ class EditorFileSystemDirectory : public Object { uint64_t modified_time; bool verified = false; //used for checking changes - EditorFileSystemDirectory *parent; + EditorFileSystemDirectory *parent = nullptr; Vector<EditorFileSystemDirectory *> subdirs; struct FileInfo { @@ -167,7 +167,7 @@ class EditorFileSystem : public Node { Thread thread; static void _thread_func(void *_userdata); - EditorFileSystemDirectory *new_filesystem; + EditorFileSystemDirectory *new_filesystem = nullptr; bool abort_scan = false; bool scanning = false; @@ -184,7 +184,7 @@ class EditorFileSystem : public Node { void _save_late_updated_files(); - EditorFileSystemDirectory *filesystem; + EditorFileSystemDirectory *filesystem = nullptr; static EditorFileSystem *singleton; @@ -213,7 +213,7 @@ class EditorFileSystem : public Node { }; void _save_filesystem_cache(); - void _save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file); + void _save_filesystem_cache(EditorFileSystemDirectory *p_dir, Ref<FileAccess> p_file); bool _find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const; @@ -225,7 +225,7 @@ class EditorFileSystem : public Node { Set<String> valid_extensions; Set<String> import_extensions; - void _scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress); + void _scan_new_dir(EditorFileSystemDirectory *p_dir, Ref<DirAccess> &da, const ScanProgress &p_progress); Thread thread_sources; bool scanning_changes = false; diff --git a/editor/editor_folding.cpp b/editor/editor_folding.cpp index 8d6ebd1154..548f05217e 100644 --- a/editor/editor_folding.cpp +++ b/editor/editor_folding.cpp @@ -131,7 +131,7 @@ void EditorFolding::_fill_folds(const Node *p_root, const Node *p_node, Array &p void EditorFolding::save_scene_folding(const Node *p_scene, const String &p_path) { ERR_FAIL_NULL(p_scene); - FileAccessRef file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES); + Ref<FileAccess> file_check = FileAccess::create(FileAccess::ACCESS_RESOURCES); if (!file_check->file_exists(p_path)) { //This can happen when creating scene from FilesystemDock. It has path, but no file. return; } diff --git a/editor/editor_fonts.cpp b/editor/editor_fonts.cpp index 66fe3c4838..3e18499b97 100644 --- a/editor/editor_fonts.cpp +++ b/editor/editor_fonts.cpp @@ -218,7 +218,7 @@ Ref<FontData> load_cached_internal_font(const uint8_t *p_data, size_t p_size, Te } void editor_register_fonts(Ref<Theme> p_theme) { - DirAccessRef dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); /* Custom font */ diff --git a/editor/editor_help.h b/editor/editor_help.h index b40d1709b6..054fd84af6 100644 --- a/editor/editor_help.h +++ b/editor/editor_help.h @@ -47,14 +47,14 @@ class FindBar : public HBoxContainer { GDCLASS(FindBar, HBoxContainer); - LineEdit *search_text; - Button *find_prev; - Button *find_next; - Label *matches_label; - TextureButton *hide_button; + LineEdit *search_text = nullptr; + Button *find_prev = nullptr; + Button *find_next = nullptr; + Label *matches_label = nullptr; + TextureButton *hide_button = nullptr; String prev_search; - RichTextLabel *rich_text_label; + RichTextLabel *rich_text_label = nullptr; int results_count; @@ -114,15 +114,15 @@ class EditorHelp : public VBoxContainer { Map<String, Map<String, int>> enum_values_line; int description_line; - RichTextLabel *class_desc; - HSplitContainer *h_split; + RichTextLabel *class_desc = nullptr; + HSplitContainer *h_split = nullptr; static DocTools *doc; - ConfirmationDialog *search_dialog; - LineEdit *search; - FindBar *find_bar; - HBoxContainer *status_bar; - Button *toggle_scripts_button; + ConfirmationDialog *search_dialog = nullptr; + LineEdit *search = nullptr; + FindBar *find_bar = nullptr; + HBoxContainer *status_bar = nullptr; + Button *toggle_scripts_button = nullptr; String base_path; @@ -210,7 +210,7 @@ public: class EditorHelpBit : public MarginContainer { GDCLASS(EditorHelpBit, MarginContainer); - RichTextLabel *rich_text; + RichTextLabel *rich_text = nullptr; void _go_to_help(String p_what); void _meta_clicked(String p_select); diff --git a/editor/editor_help_search.cpp b/editor/editor_help_search.cpp index 8e03c55712..c747ae326f 100644 --- a/editor/editor_help_search.cpp +++ b/editor/editor_help_search.cpp @@ -331,7 +331,10 @@ bool EditorHelpSearch::Runner::_phase_match_classes() { // Match class name. if (search_flags & SEARCH_CLASSES) { - match.name = term.is_empty() || _match_string(term, class_doc.name); + // If the search term is empty, add any classes which are not script docs or which don't start with + // a double-quotation. This will ensure that only C++ classes and explictly named classes will + // be added. + match.name = (term.is_empty() && (!class_doc.is_script_doc || class_doc.name[0] != '\"')) || _match_string(term, class_doc.name); } // Match members if the term is long enough. @@ -398,6 +401,7 @@ bool EditorHelpSearch::Runner::_phase_match_classes() { } } } + matches[class_doc.name] = match; } iterator_doc = iterator_doc->next(); diff --git a/editor/editor_help_search.h b/editor/editor_help_search.h index bf69fe1693..d89bb0959c 100644 --- a/editor/editor_help_search.h +++ b/editor/editor_help_search.h @@ -55,11 +55,11 @@ class EditorHelpSearch : public ConfirmationDialog { SEARCH_SHOW_HIERARCHY = 1 << 30 }; - LineEdit *search_box; - Button *case_sensitive_button; - Button *hierarchy_button; - OptionButton *filter_combo; - Tree *results_tree; + LineEdit *search_box = nullptr; + Button *case_sensitive_button = nullptr; + Button *hierarchy_button = nullptr; + OptionButton *filter_combo = nullptr; + Tree *results_tree = nullptr; bool old_search = false; String old_term; @@ -114,8 +114,8 @@ class EditorHelpSearch::Runner : public RefCounted { } }; - Control *ui_service; - Tree *results_tree; + Control *ui_service = nullptr; + Tree *results_tree = nullptr; String term; int search_flags; diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp index 1449edb58f..d5085942c3 100644 --- a/editor/editor_inspector.cpp +++ b/editor/editor_inspector.cpp @@ -685,7 +685,7 @@ void EditorProperty::gui_input(const Ref<InputEvent> &p_event) { } } -void EditorProperty::unhandled_key_input(const Ref<InputEvent> &p_event) { +void EditorProperty::shortcut_input(const Ref<InputEvent> &p_event) { if (!selected || !p_event->is_pressed()) { return; } @@ -971,7 +971,7 @@ EditorProperty::EditorProperty() { label_reference = nullptr; bottom_editor = nullptr; menu = nullptr; - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); } void EditorProperty::_update_popup() { diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h index 87703564b9..c5bcbe0725 100644 --- a/editor/editor_inspector.h +++ b/editor/editor_inspector.h @@ -68,7 +68,7 @@ private: String label; int text_size; friend class EditorInspector; - Object *object; + Object *object = nullptr; StringName property; String property_path; @@ -111,9 +111,9 @@ private: float split_ratio; Vector<Control *> focusables; - Control *label_reference; - Control *bottom_editor; - PopupMenu *menu; + Control *label_reference = nullptr; + Control *bottom_editor = nullptr; + PopupMenu *menu = nullptr; mutable String tooltip_text; @@ -128,7 +128,7 @@ protected: virtual void _set_read_only(bool p_read_only); virtual void gui_input(const Ref<InputEvent> &p_event) override; - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; const Color *_get_property_colors(); public: @@ -269,14 +269,14 @@ class EditorInspectorSection : public Container { bool foldable = false; int indent_depth = 0; - Timer *dropping_unfold_timer; + Timer *dropping_unfold_timer = nullptr; bool dropping = false; void _test_unfold(); protected: Object *object = nullptr; - VBoxContainer *vbox; + VBoxContainer *vbox = nullptr; void _notification(int p_what); static void _bind_methods(); @@ -297,7 +297,7 @@ public: class EditorInspectorArray : public EditorInspectorSection { GDCLASS(EditorInspectorArray, EditorInspectorSection); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; enum Mode { MODE_NONE, @@ -309,16 +309,16 @@ class EditorInspectorArray : public EditorInspectorSection { int count = 0; - VBoxContainer *elements_vbox; + VBoxContainer *elements_vbox = nullptr; - Control *control_dropping; + Control *control_dropping = nullptr; bool dropping = false; - Button *add_button; + Button *add_button = nullptr; - AcceptDialog *resize_dialog; + AcceptDialog *resize_dialog = nullptr; int new_size = 0; - LineEdit *new_size_line_edit; + LineEdit *new_size_line_edit = nullptr; // Pagination int page_length = 5; @@ -337,14 +337,14 @@ class EditorInspectorArray : public EditorInspectorSection { OPTION_RESIZE_ARRAY, }; int popup_array_index_pressed = -1; - PopupMenu *rmb_popup; + PopupMenu *rmb_popup = nullptr; struct ArrayElement { - PanelContainer *panel; - MarginContainer *margin; - HBoxContainer *hbox; - TextureRect *move_texture_rect; - VBoxContainer *vbox; + PanelContainer *panel = nullptr; + MarginContainer *margin = nullptr; + HBoxContainer *hbox = nullptr; + TextureRect *move_texture_rect = nullptr; + VBoxContainer *vbox = nullptr; }; LocalVector<ArrayElement> array_elements; @@ -399,12 +399,12 @@ class EditorPaginator : public HBoxContainer { int page = 0; int max_page = 0; - Button *first_page_button; - Button *prev_page_button; - LineEdit *page_line_edit; - Label *page_count_label; - Button *next_page_button; - Button *last_page_button; + Button *first_page_button = nullptr; + Button *prev_page_button = nullptr; + LineEdit *page_line_edit = nullptr; + Label *page_count_label = nullptr; + Button *next_page_button = nullptr; + Button *last_page_button = nullptr; void _first_page_button_pressed(); void _prev_page_button_pressed(); @@ -425,14 +425,14 @@ public: class EditorInspector : public ScrollContainer { GDCLASS(EditorInspector, ScrollContainer); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; enum { MAX_PLUGINS = 1024 }; static Ref<EditorInspectorPlugin> inspector_plugins[MAX_PLUGINS]; static int inspector_plugin_count; - VBoxContainer *main_vbox; + VBoxContainer *main_vbox = nullptr; //map use to cache the instantiated editors Map<StringName, List<EditorProperty *>> editor_property_map; @@ -440,11 +440,11 @@ class EditorInspector : public ScrollContainer { Set<StringName> pending; void _clear(); - Object *object; + Object *object = nullptr; // - LineEdit *search_box; + LineEdit *search_box = nullptr; bool show_categories = false; bool hide_script = true; bool hide_metadata = true; diff --git a/editor/editor_layouts_dialog.h b/editor/editor_layouts_dialog.h index bbdffd6722..a597ac38cc 100644 --- a/editor/editor_layouts_dialog.h +++ b/editor/editor_layouts_dialog.h @@ -39,9 +39,9 @@ class ItemList; class EditorLayoutsDialog : public ConfirmationDialog { GDCLASS(EditorLayoutsDialog, ConfirmationDialog); - LineEdit *name; - ItemList *layout_names; - VBoxContainer *makevb; + LineEdit *name = nullptr; + ItemList *layout_names = nullptr; + VBoxContainer *makevb = nullptr; void _line_gui_input(const Ref<InputEvent> &p_event); diff --git a/editor/editor_log.cpp b/editor/editor_log.cpp index 54a55286e9..8d45f90ed6 100644 --- a/editor/editor_log.cpp +++ b/editor/editor_log.cpp @@ -38,7 +38,7 @@ #include "scene/resources/font.h" void EditorLog::_error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, bool p_editor_notify, ErrorHandlerType p_type) { - EditorLog *self = (EditorLog *)p_self; + EditorLog *self = static_cast<EditorLog *>(p_self); if (self->current != Thread::get_caller_id()) { return; } @@ -168,7 +168,7 @@ void EditorLog::_copy_request() { String text = log->get_selected_text(); if (text.is_empty()) { - text = log->get_text(); + text = log->get_parsed_text(); } if (!text.is_empty()) { @@ -216,7 +216,7 @@ void EditorLog::set_tool_button(Button *p_tool_button) { } void EditorLog::_undo_redo_cbk(void *p_self, const String &p_name) { - EditorLog *self = (EditorLog *)p_self; + EditorLog *self = static_cast<EditorLog *>(p_self); self->add_message(p_name, EditorLog::MSG_TYPE_EDITOR); } @@ -347,6 +347,7 @@ EditorLog::EditorLog() { log->set_focus_mode(FOCUS_CLICK); log->set_v_size_flags(SIZE_EXPAND_FILL); log->set_h_size_flags(SIZE_EXPAND_FILL); + log->set_deselect_on_focus_loss_enabled(false); vb_left->add_child(log); // Search box diff --git a/editor/editor_log.h b/editor/editor_log.h index e66b732ffe..267ad406d4 100644 --- a/editor/editor_log.h +++ b/editor/editor_log.h @@ -117,23 +117,23 @@ private: // Maps MessageTypes to LogFilters for convenient access and storage (don't need 1 member per filter). Map<MessageType, LogFilter *> type_filter_map; - RichTextLabel *log; + RichTextLabel *log = nullptr; - Button *clear_button; - Button *copy_button; + Button *clear_button = nullptr; + Button *copy_button = nullptr; - Button *collapse_button; + Button *collapse_button = nullptr; bool collapse = false; - Button *show_search_button; - LineEdit *search_box; + Button *show_search_button = nullptr; + LineEdit *search_box = nullptr; // Reference to the "Output" button on the toolbar so we can update it's icon when // Warnings or Errors are encounetered. - Button *tool_button; + Button *tool_button = nullptr; bool is_loading_state = false; // Used to disable saving requests while loading (some signals from buttons will try trigger a save, which happens during loading). - Timer *save_state_timer; + Timer *save_state_timer = nullptr; static void _error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, bool p_editor_notify, ErrorHandlerType p_type); diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 52f7366dd7..6fe6309eed 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -416,7 +416,7 @@ void EditorNode::_version_control_menu_option(int p_idx) { void EditorNode::_update_title() { const String appname = ProjectSettings::get_singleton()->get("application/config/name"); - String title = (appname.is_empty() ? "Unnamed Project" : appname) + String(" - ") + VERSION_NAME; + String title = (appname.is_empty() ? TTR("Unnamed Project") : appname) + String(" - ") + VERSION_NAME; const String edited = editor_data.get_edited_scene_root() ? editor_data.get_edited_scene_root()->get_scene_file_path() : String(); if (!edited.is_empty()) { // Display the edited scene name before the program name so that it can be seen in the OS task bar. @@ -430,7 +430,7 @@ void EditorNode::_update_title() { DisplayServer::get_singleton()->window_set_title(title); } -void EditorNode::unhandled_input(const Ref<InputEvent> &p_event) { +void EditorNode::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); Ref<InputEventKey> k = p_event; @@ -935,7 +935,7 @@ void EditorNode::_fs_changed() { } if (export_preset.is_null()) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->file_exists("res://export_presets.cfg")) { export_error = vformat( "Invalid export preset name: %s.\nThe following presets were detected in this project's `export_presets.cfg`:\n\n", @@ -1058,7 +1058,7 @@ void EditorNode::_scan_external_changes() { // Check if any edited scene has changed. for (int i = 0; i < editor_data.get_edited_scene_count(); i++) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (editor_data.get_scene_path(i) == "" || !da->file_exists(editor_data.get_scene_path(i))) { continue; } @@ -3854,7 +3854,7 @@ void EditorNode::add_io_error(const String &p_error) { } void EditorNode::_load_error_notify(void *p_ud, const String &p_text) { - EditorNode *en = (EditorNode *)p_ud; + EditorNode *en = static_cast<EditorNode *>(p_ud); en->load_errors->add_image(en->gui_base->get_theme_icon(SNAME("Error"), SNAME("EditorIcons"))); en->load_errors->add_text(p_text + "\n"); en->load_error_dialog->popup_centered_ratio(0.5); @@ -4261,7 +4261,7 @@ void EditorNode::_copy_warning(const String &p_str) { void EditorNode::_dock_floating_close_request(Control *p_control) { // Through the MarginContainer to the Window. - Window *window = (Window *)p_control->get_parent()->get_parent(); + Window *window = static_cast<Window *>(p_control->get_parent()->get_parent()); int window_slot = window->get_meta("dock_slot"); p_control->get_parent()->remove_child(p_control); @@ -5478,7 +5478,7 @@ void EditorNode::_global_menu_new_window(const Variant &p_tag) { } } -void EditorNode::_dropped_files(const Vector<String> &p_files, int p_screen) { +void EditorNode::_dropped_files(const Vector<String> &p_files) { String to_path = ProjectSettings::get_singleton()->globalize_path(FileSystemDock::get_singleton()->get_selected_path()); _add_dropped_files_recursive(p_files, to_path); @@ -5487,7 +5487,7 @@ void EditorNode::_dropped_files(const Vector<String> &p_files, int p_screen) { } void EditorNode::_add_dropped_files_recursive(const Vector<String> &p_files, String to_path) { - DirAccessRef dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); for (int i = 0; i < p_files.size(); i++) { String from = p_files[i]; @@ -5496,7 +5496,7 @@ void EditorNode::_add_dropped_files_recursive(const Vector<String> &p_files, Str if (dir->dir_exists(from)) { Vector<String> sub_files; - DirAccessRef sub_dir = DirAccess::open(from); + Ref<DirAccess> sub_dir = DirAccess::open(from); sub_dir->list_dir_begin(); String next_file = sub_dir->get_next(); @@ -5773,7 +5773,7 @@ static Node *_resource_get_edited_scene() { } void EditorNode::_print_handler(void *p_this, const String &p_string, bool p_error) { - EditorNode *en = (EditorNode *)p_this; + EditorNode *en = static_cast<EditorNode *>(p_this); en->log->add_message(p_string, p_error ? EditorLog::MSG_TYPE_ERROR : EditorLog::MSG_TYPE_STD); } @@ -5997,18 +5997,22 @@ EditorNode::EditorNode() { import_scene.instantiate(); ResourceFormatImporter::get_singleton()->add_importer(import_scene); + Ref<ResourceImporterScene> import_animation; + import_animation = Ref<ResourceImporterScene>(memnew(ResourceImporterScene(true))); + ResourceFormatImporter::get_singleton()->add_importer(import_animation); + { Ref<EditorSceneFormatImporterCollada> import_collada; import_collada.instantiate(); - import_scene->add_importer(import_collada); + ResourceImporterScene::add_importer(import_collada); Ref<EditorOBJImporter> import_obj2; import_obj2.instantiate(); - import_scene->add_importer(import_obj2); + ResourceImporterScene::add_importer(import_obj2); Ref<EditorSceneFormatImporterESCN> import_escn; import_escn.instantiate(); - import_scene->add_importer(import_escn); + ResourceImporterScene::add_importer(import_escn); } Ref<ResourceImporterBitMap> import_bitmap; @@ -7168,7 +7172,7 @@ EditorNode::EditorNode() { _update_recent_scenes(); editor_data.restore_editor_global_states(); - set_process_unhandled_input(true); + set_process_shortcut_input(true); load_errors = memnew(RichTextLabel); load_error_dialog = memnew(AcceptDialog); @@ -7245,6 +7249,7 @@ EditorNode::EditorNode() { EditorNode::~EditorNode() { EditorInspector::cleanup_plugins(); EditorTranslationParser::get_singleton()->clean_parsers(); + ResourceImporterScene::clean_up_importer_plugins(); remove_print_handler(&print_handler); EditorHelp::cleanup_doc(); diff --git a/editor/editor_node.h b/editor/editor_node.h index 7d24cfe758..c6c1f09938 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -275,161 +275,161 @@ private: bool _initializing_plugins = false; Map<String, EditorPlugin *> addon_name_to_plugin; - PanelContainer *scene_root_parent; - Control *theme_base; - Control *gui_base; - VBoxContainer *main_vbox; - OptionButton *rendering_driver; + PanelContainer *scene_root_parent = nullptr; + Control *theme_base = nullptr; + Control *gui_base = nullptr; + VBoxContainer *main_vbox = nullptr; + OptionButton *rendering_driver = nullptr; - ConfirmationDialog *video_restart_dialog; + ConfirmationDialog *video_restart_dialog = nullptr; int rendering_driver_current; String rendering_driver_request; // Split containers. - HSplitContainer *left_l_hsplit; - VSplitContainer *left_l_vsplit; - HSplitContainer *left_r_hsplit; - VSplitContainer *left_r_vsplit; - HSplitContainer *main_hsplit; - HSplitContainer *right_hsplit; - VSplitContainer *right_l_vsplit; - VSplitContainer *right_r_vsplit; - VSplitContainer *center_split; + HSplitContainer *left_l_hsplit = nullptr; + VSplitContainer *left_l_vsplit = nullptr; + HSplitContainer *left_r_hsplit = nullptr; + VSplitContainer *left_r_vsplit = nullptr; + HSplitContainer *main_hsplit = nullptr; + HSplitContainer *right_hsplit = nullptr; + VSplitContainer *right_l_vsplit = nullptr; + VSplitContainer *right_r_vsplit = nullptr; + VSplitContainer *center_split = nullptr; // To access those easily by index. Vector<VSplitContainer *> vsplits; Vector<HSplitContainer *> hsplits; // Main tabs. - TabBar *scene_tabs; - PopupMenu *scene_tabs_context_menu; - Panel *tab_preview_panel; - TextureRect *tab_preview; + TabBar *scene_tabs = nullptr; + PopupMenu *scene_tabs_context_menu = nullptr; + Panel *tab_preview_panel = nullptr; + TextureRect *tab_preview = nullptr; int tab_closing_idx; bool exiting = false; bool dimmed = false; int old_split_ofs; - VSplitContainer *top_split; - HBoxContainer *bottom_hb; - Control *vp_base; - - HBoxContainer *menu_hb; - Control *main_control; - MenuButton *file_menu; - MenuButton *project_menu; - MenuButton *debug_menu; - MenuButton *settings_menu; - MenuButton *help_menu; - PopupMenu *tool_menu; - Button *export_button; - Button *prev_scene; - Button *play_button; - Button *pause_button; - Button *stop_button; - Button *run_settings_button; - Button *play_scene_button; - Button *play_custom_scene_button; - Button *search_button; - TextureProgressBar *audio_vu; - - Timer *screenshot_timer; - - PluginConfigDialog *plugin_config_dialog; - - RichTextLabel *load_errors; - AcceptDialog *load_error_dialog; - - RichTextLabel *execute_outputs; - AcceptDialog *execute_output_dialog; + VSplitContainer *top_split = nullptr; + HBoxContainer *bottom_hb = nullptr; + Control *vp_base = nullptr; + + HBoxContainer *menu_hb = nullptr; + Control *main_control = nullptr; + MenuButton *file_menu = nullptr; + MenuButton *project_menu = nullptr; + MenuButton *debug_menu = nullptr; + MenuButton *settings_menu = nullptr; + MenuButton *help_menu = nullptr; + PopupMenu *tool_menu = nullptr; + Button *export_button = nullptr; + Button *prev_scene = nullptr; + Button *play_button = nullptr; + Button *pause_button = nullptr; + Button *stop_button = nullptr; + Button *run_settings_button = nullptr; + Button *play_scene_button = nullptr; + Button *play_custom_scene_button = nullptr; + Button *search_button = nullptr; + TextureProgressBar *audio_vu = nullptr; + + Timer *screenshot_timer = nullptr; + + PluginConfigDialog *plugin_config_dialog = nullptr; + + RichTextLabel *load_errors = nullptr; + AcceptDialog *load_error_dialog = nullptr; + + RichTextLabel *execute_outputs = nullptr; + AcceptDialog *execute_output_dialog = nullptr; Ref<Theme> theme; - PopupMenu *recent_scenes; + PopupMenu *recent_scenes = nullptr; String _recent_scene; List<String> previous_scenes; String defer_load_scene; - Node *_last_instantiated_scene; - - ConfirmationDialog *confirmation; - ConfirmationDialog *save_confirmation; - ConfirmationDialog *import_confirmation; - ConfirmationDialog *pick_main_scene; - Button *select_current_scene_button; - AcceptDialog *accept; - AcceptDialog *save_accept; - EditorAbout *about; - AcceptDialog *warning; + Node *_last_instantiated_scene = nullptr; + + ConfirmationDialog *confirmation = nullptr; + ConfirmationDialog *save_confirmation = nullptr; + ConfirmationDialog *import_confirmation = nullptr; + ConfirmationDialog *pick_main_scene = nullptr; + Button *select_current_scene_button = nullptr; + AcceptDialog *accept = nullptr; + AcceptDialog *save_accept = nullptr; + EditorAbout *about = nullptr; + AcceptDialog *warning = nullptr; int overridden_default_layout; Ref<ConfigFile> default_layout; - PopupMenu *editor_layouts; - EditorLayoutsDialog *layout_dialog; - - ConfirmationDialog *custom_build_manage_templates; - ConfirmationDialog *install_android_build_template; - ConfirmationDialog *remove_android_build_template; - - PopupMenu *vcs_actions_menu; - EditorFileDialog *file; - ExportTemplateManager *export_template_manager; - EditorFeatureProfileManager *feature_profile_manager; - EditorFileDialog *file_templates; - EditorFileDialog *file_export_lib; - EditorFileDialog *file_script; - EditorFileDialog *file_android_build_source; - CheckBox *file_export_lib_merge; - CheckBox *file_export_lib_apply_xforms; + PopupMenu *editor_layouts = nullptr; + EditorLayoutsDialog *layout_dialog = nullptr; + + ConfirmationDialog *custom_build_manage_templates = nullptr; + ConfirmationDialog *install_android_build_template = nullptr; + ConfirmationDialog *remove_android_build_template = nullptr; + + PopupMenu *vcs_actions_menu = nullptr; + EditorFileDialog *file = nullptr; + ExportTemplateManager *export_template_manager = nullptr; + EditorFeatureProfileManager *feature_profile_manager = nullptr; + EditorFileDialog *file_templates = nullptr; + EditorFileDialog *file_export_lib = nullptr; + EditorFileDialog *file_script = nullptr; + EditorFileDialog *file_android_build_source = nullptr; + CheckBox *file_export_lib_merge = nullptr; + CheckBox *file_export_lib_apply_xforms = nullptr; String current_path; - MenuButton *update_spinner; + MenuButton *update_spinner = nullptr; - HBoxContainer *main_editor_button_vb; + HBoxContainer *main_editor_button_vb = nullptr; Vector<Button *> main_editor_buttons; Vector<EditorPlugin *> editor_table; - AudioStreamPreviewGenerator *audio_preview_gen; - ProgressDialog *progress_dialog; - BackgroundProgress *progress_hb; + AudioStreamPreviewGenerator *audio_preview_gen = nullptr; + ProgressDialog *progress_dialog = nullptr; + BackgroundProgress *progress_hb = nullptr; - DependencyErrorDialog *dependency_error; + DependencyErrorDialog *dependency_error = nullptr; Map<String, Set<String>> dependency_errors; - DependencyEditor *dependency_fixer; - OrphanResourcesDialog *orphan_resources; - ConfirmationDialog *open_imported; - Button *new_inherited_button; + DependencyEditor *dependency_fixer = nullptr; + OrphanResourcesDialog *orphan_resources = nullptr; + ConfirmationDialog *open_imported = nullptr; + Button *new_inherited_button = nullptr; String open_import_request; Vector<Control *> floating_docks; - Button *dock_float; - Button *dock_tab_move_left; - Button *dock_tab_move_right; - Control *dock_select; - PopupPanel *dock_select_popup; + Button *dock_float = nullptr; + Button *dock_tab_move_left = nullptr; + Button *dock_tab_move_right = nullptr; + Control *dock_select = nullptr; + PopupPanel *dock_select_popup = nullptr; Rect2 dock_select_rect[DOCK_SLOT_MAX]; TabContainer *dock_slot[DOCK_SLOT_MAX]; - Timer *dock_drag_timer; + Timer *dock_drag_timer = nullptr; bool docks_visible = true; int dock_popup_selected_idx; int dock_select_rect_over_idx; - HBoxContainer *tabbar_container; - Button *distraction_free; - Button *scene_tab_add; - Control *scene_tab_add_ph; + HBoxContainer *tabbar_container = nullptr; + Button *distraction_free = nullptr; + Button *scene_tab_add = nullptr; + Control *scene_tab_add_ph = nullptr; Vector<BottomPanelItem> bottom_panel_items; - PanelContainer *bottom_panel; - HBoxContainer *bottom_panel_hb; - HBoxContainer *bottom_panel_hb_editors; - VBoxContainer *bottom_panel_vb; - EditorToaster *editor_toaster; - LinkButton *version_btn; - Button *bottom_panel_raise; + PanelContainer *bottom_panel = nullptr; + HBoxContainer *bottom_panel_hb = nullptr; + HBoxContainer *bottom_panel_hb_editors = nullptr; + VBoxContainer *bottom_panel_vb = nullptr; + EditorToaster *editor_toaster = nullptr; + LinkButton *version_btn = nullptr; + Button *bottom_panel_raise = nullptr; - Tree *disk_changed_list; - ConfirmationDialog *disk_changed; + Tree *disk_changed_list = nullptr; + ConfirmationDialog *disk_changed = nullptr; bool scene_distraction_free = false; bool script_distraction_free = false; @@ -447,8 +447,8 @@ private: int current_menu_option; - SubViewport *scene_root; // Root of the scene being edited. - Object *current; + SubViewport *scene_root = nullptr; // Root of the scene being edited. + Object *current = nullptr; Ref<Resource> saving_resource; @@ -464,8 +464,8 @@ private: uint64_t saved_version; uint64_t last_checked_version; - DynamicFontImportSettings *fontdata_import_settings; - SceneImportSettings *scene_import_settings; + DynamicFontImportSettings *fontdata_import_settings = nullptr; + SceneImportSettings *scene_import_settings = nullptr; String import_reload_fn; @@ -485,7 +485,7 @@ private: static Vector<EditorNodeInitCallback> _init_callbacks; static void _dependency_error_report(void *ud, const String &p_path, const String &p_dep, const String &p_type) { - EditorNode *en = (EditorNode *)ud; + EditorNode *en = static_cast<EditorNode *>(ud); if (!en->dependency_errors.has(p_path)) { en->dependency_errors[p_path] = Set<String>(); } @@ -575,7 +575,7 @@ private: void _open_recent_scene(int p_idx); void _global_menu_scene(const Variant &p_tag); void _global_menu_new_window(const Variant &p_tag); - void _dropped_files(const Vector<String> &p_files, int p_screen); + void _dropped_files(const Vector<String> &p_files); void _add_dropped_files_recursive(const Vector<String> &p_files, String to_path); void _update_from_settings(); @@ -585,7 +585,7 @@ private: void _exit_editor(int p_exit_code); - virtual void unhandled_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; bool has_main_screen() const { return true; } diff --git a/editor/editor_path.h b/editor/editor_path.h index 1e19344d9e..afc7a20bad 100644 --- a/editor/editor_path.h +++ b/editor/editor_path.h @@ -42,12 +42,12 @@ class EditorSelectionHistory; class EditorPath : public Button { GDCLASS(EditorPath, Button); - EditorSelectionHistory *history; + EditorSelectionHistory *history = nullptr; - TextureRect *current_object_icon; - Label *current_object_label; - TextureRect *sub_objects_icon; - PopupMenu *sub_objects_menu; + TextureRect *current_object_icon = nullptr; + Label *current_object_label = nullptr; + TextureRect *sub_objects_icon = nullptr; + PopupMenu *sub_objects_menu = nullptr; Vector<ObjectID> objects; diff --git a/editor/editor_paths.cpp b/editor/editor_paths.cpp index 7b454055e0..a5c2fe093c 100644 --- a/editor/editor_paths.cpp +++ b/editor/editor_paths.cpp @@ -97,7 +97,7 @@ EditorPaths::EditorPaths() { exe_path = exe_path.plus_file("../../..").simplify_path(); } { - DirAccessRef d = DirAccess::create_for_path(exe_path); + Ref<DirAccess> d = DirAccess::create_for_path(exe_path); if (d->file_exists(exe_path + "/._sc_")) { self_contained = true; @@ -141,7 +141,7 @@ EditorPaths::EditorPaths() { // Validate or create each dir and its relevant subdirectories. - DirAccessRef dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); // Data dir. { @@ -197,7 +197,7 @@ EditorPaths::EditorPaths() { // Nothing to create, use shared editor data dir for shader cache. Engine::get_singleton()->set_shader_cache_path(data_dir); } else { - DirAccessRef dir_res = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> dir_res = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (dir_res->change_dir(project_data_dir) != OK) { dir_res->make_dir_recursive(project_data_dir); if (dir_res->change_dir(project_data_dir) != OK) { @@ -210,10 +210,9 @@ EditorPaths::EditorPaths() { String project_data_gdignore_file_path = project_data_dir.plus_file(".gdignore"); if (!FileAccess::exists(project_data_gdignore_file_path)) { // Add an empty .gdignore file to avoid scan. - FileAccessRef f = FileAccess::open(project_data_gdignore_file_path, FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(project_data_gdignore_file_path, FileAccess::WRITE); + if (f.is_valid()) { f->store_line(""); - f->close(); } else { ERR_PRINT("Failed to create file " + project_data_gdignore_file_path); } diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp index 5166200ee3..6596c245bc 100644 --- a/editor/editor_plugin.cpp +++ b/editor/editor_plugin.cpp @@ -763,20 +763,20 @@ void EditorPlugin::remove_inspector_plugin(const Ref<EditorInspectorPlugin> &p_p void EditorPlugin::add_scene_format_importer_plugin(const Ref<EditorSceneFormatImporter> &p_importer, bool p_first_priority) { ERR_FAIL_COND(!p_importer.is_valid()); - ResourceImporterScene::get_singleton()->add_importer(p_importer, p_first_priority); + ResourceImporterScene::add_importer(p_importer, p_first_priority); } void EditorPlugin::remove_scene_format_importer_plugin(const Ref<EditorSceneFormatImporter> &p_importer) { ERR_FAIL_COND(!p_importer.is_valid()); - ResourceImporterScene::get_singleton()->remove_importer(p_importer); + ResourceImporterScene::remove_importer(p_importer); } void EditorPlugin::add_scene_post_import_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin, bool p_first_priority) { - ResourceImporterScene::get_singleton()->add_post_importer_plugin(p_plugin, p_first_priority); + ResourceImporterScene::add_post_importer_plugin(p_plugin, p_first_priority); } void EditorPlugin::remove_scene_post_import_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin) { - ResourceImporterScene::get_singleton()->remove_post_importer_plugin(p_plugin); + ResourceImporterScene::remove_post_importer_plugin(p_plugin); } int find(const PackedStringArray &a, const String &v) { diff --git a/editor/editor_plugin_settings.cpp b/editor/editor_plugin_settings.cpp index b6f48c7536..b728ce64c9 100644 --- a/editor/editor_plugin_settings.cpp +++ b/editor/editor_plugin_settings.cpp @@ -161,7 +161,7 @@ void EditorPluginSettings::_cell_button_pressed(Object *p_item, int p_column, in } Vector<String> EditorPluginSettings::_get_plugins(const String &p_dir) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); Error err = da->change_dir(p_dir); if (err != OK) { return Vector<String>(); diff --git a/editor/editor_plugin_settings.h b/editor/editor_plugin_settings.h index c239b735de..826bb8c00f 100644 --- a/editor/editor_plugin_settings.h +++ b/editor/editor_plugin_settings.h @@ -44,10 +44,10 @@ class EditorPluginSettings : public VBoxContainer { BUTTON_PLUGIN_EDIT }; - PluginConfigDialog *plugin_config_dialog; - Button *create_plugin; - Button *update_list; - Tree *plugin_list; + PluginConfigDialog *plugin_config_dialog = nullptr; + Button *create_plugin = nullptr; + Button *update_list = nullptr; + Tree *plugin_list = nullptr; bool updating = false; void _plugin_activity_changed(); diff --git a/editor/editor_properties.h b/editor/editor_properties.h index c21e0e0b4d..1f40a7fe7b 100644 --- a/editor/editor_properties.h +++ b/editor/editor_properties.h @@ -52,7 +52,7 @@ public: class EditorPropertyText : public EditorProperty { GDCLASS(EditorPropertyText, EditorProperty); - LineEdit *text; + LineEdit *text = nullptr; bool updating = false; bool string_name = false; @@ -72,11 +72,11 @@ public: class EditorPropertyMultilineText : public EditorProperty { GDCLASS(EditorPropertyMultilineText, EditorProperty); - TextEdit *text; + TextEdit *text = nullptr; - AcceptDialog *big_text_dialog; - TextEdit *big_text; - Button *open_big_text; + AcceptDialog *big_text_dialog = nullptr; + TextEdit *big_text = nullptr; + Button *open_big_text = nullptr; void _big_text_changed(); void _text_changed(); @@ -95,15 +95,15 @@ public: class EditorPropertyTextEnum : public EditorProperty { GDCLASS(EditorPropertyTextEnum, EditorProperty); - HBoxContainer *default_layout; - HBoxContainer *edit_custom_layout; + HBoxContainer *default_layout = nullptr; + HBoxContainer *edit_custom_layout = nullptr; - OptionButton *option_button; - Button *edit_button; + OptionButton *option_button = nullptr; + Button *edit_button = nullptr; - LineEdit *custom_value_edit; - Button *accept_button; - Button *cancel_button; + LineEdit *custom_value_edit = nullptr; + Button *accept_button = nullptr; + Button *cancel_button = nullptr; Vector<String> options; bool string_name = false; @@ -134,9 +134,9 @@ class EditorPropertyPath : public EditorProperty { bool folder = false; bool global = false; bool save_mode = false; - EditorFileDialog *dialog; - LineEdit *path; - Button *path_edit; + EditorFileDialog *dialog = nullptr; + LineEdit *path = nullptr; + Button *path_edit = nullptr; void _path_selected(const String &p_path); void _path_pressed(); @@ -156,9 +156,9 @@ public: class EditorPropertyLocale : public EditorProperty { GDCLASS(EditorPropertyLocale, EditorProperty); - EditorLocaleDialog *dialog; - LineEdit *locale; - Button *locale_edit; + EditorLocaleDialog *dialog = nullptr; + LineEdit *locale = nullptr; + Button *locale_edit = nullptr; void _locale_selected(const String &p_locale); void _locale_pressed(); @@ -178,8 +178,8 @@ class EditorPropertyClassName : public EditorProperty { GDCLASS(EditorPropertyClassName, EditorProperty); private: - CreateDialog *dialog; - Button *property; + CreateDialog *dialog = nullptr; + Button *property = nullptr; String selected_type; String base_type; void _property_selected(); @@ -212,8 +212,8 @@ public: private: Type hint; - PropertySelector *selector; - Button *property; + PropertySelector *selector = nullptr; + Button *property = nullptr; String hint_text; void _property_selected(const String &p_selected); @@ -231,7 +231,7 @@ public: class EditorPropertyCheck : public EditorProperty { GDCLASS(EditorPropertyCheck, EditorProperty); - CheckBox *checkbox; + CheckBox *checkbox = nullptr; void _checkbox_pressed(); @@ -246,7 +246,7 @@ public: class EditorPropertyEnum : public EditorProperty { GDCLASS(EditorPropertyEnum, EditorProperty); - OptionButton *options; + OptionButton *options = nullptr; void _option_selected(int p_which); @@ -263,7 +263,7 @@ public: class EditorPropertyFlags : public EditorProperty { GDCLASS(EditorPropertyFlags, EditorProperty); - VBoxContainer *vbox; + VBoxContainer *vbox = nullptr; Vector<CheckBox *> flags; Vector<int> flag_indices; @@ -293,9 +293,9 @@ private: int hovered_index = -1; bool read_only = false; int renamed_layer_index = -1; - PopupMenu *layer_rename; - ConfirmationDialog *rename_dialog; - LineEdit *rename_dialog_text; + PopupMenu *layer_rename = nullptr; + ConfirmationDialog *rename_dialog = nullptr; + LineEdit *rename_dialog_text = nullptr; void _rename_pressed(int p_menu); void _rename_operation_confirm(); @@ -334,12 +334,12 @@ public: }; private: - EditorPropertyLayersGrid *grid; + EditorPropertyLayersGrid *grid = nullptr; void _grid_changed(uint32_t p_grid); String basename; LayerType layer_type; - PopupMenu *layers; - Button *button; + PopupMenu *layers = nullptr; + Button *button = nullptr; void _button_pressed(); void _menu_pressed(int p_menu); @@ -358,7 +358,7 @@ public: class EditorPropertyInteger : public EditorProperty { GDCLASS(EditorPropertyInteger, EditorProperty); - EditorSpinSlider *spin; + EditorSpinSlider *spin = nullptr; bool setting = false; void _value_changed(int64_t p_val); @@ -374,7 +374,7 @@ public: class EditorPropertyObjectID : public EditorProperty { GDCLASS(EditorPropertyObjectID, EditorProperty); - Button *edit; + Button *edit = nullptr; String base_type; void _edit_pressed(); @@ -390,7 +390,7 @@ public: class EditorPropertyFloat : public EditorProperty { GDCLASS(EditorPropertyFloat, EditorProperty); - EditorSpinSlider *spin; + EditorSpinSlider *spin = nullptr; bool setting = false; bool angle_in_radians = false; void _value_changed(double p_val); @@ -407,9 +407,9 @@ public: class EditorPropertyEasing : public EditorProperty { GDCLASS(EditorPropertyEasing, EditorProperty); - Control *easing_draw; - PopupMenu *preset; - EditorSpinSlider *spin; + Control *easing_draw = nullptr; + PopupMenu *preset = nullptr; + EditorSpinSlider *spin = nullptr; bool setting = false; bool dragging = false; @@ -657,7 +657,7 @@ public: class EditorPropertyColor : public EditorProperty { GDCLASS(EditorPropertyColor, EditorProperty); - ColorPickerButton *picker; + ColorPickerButton *picker = nullptr; void _color_changed(const Color &p_color); void _popup_closed(); void _picker_created(); @@ -677,9 +677,9 @@ public: class EditorPropertyNodePath : public EditorProperty { GDCLASS(EditorPropertyNodePath, EditorProperty); - Button *assign; - Button *clear; - SceneTreeDialog *scene_tree; + Button *assign = nullptr; + Button *clear = nullptr; + SceneTreeDialog *scene_tree = nullptr; NodePath base_hint; bool use_path_from_scene_root = false; @@ -705,7 +705,7 @@ public: class EditorPropertyRID : public EditorProperty { GDCLASS(EditorPropertyRID, EditorProperty); - Label *label; + Label *label = nullptr; public: virtual void update_property() override; diff --git a/editor/editor_properties_array_dict.h b/editor/editor_properties_array_dict.h index 3d9fe90b20..070353c538 100644 --- a/editor/editor_properties_array_dict.h +++ b/editor/editor_properties_array_dict.h @@ -80,7 +80,7 @@ public: class EditorPropertyArray : public EditorProperty { GDCLASS(EditorPropertyArray, EditorProperty); - PopupMenu *change_type; + PopupMenu *change_type = nullptr; bool updating = false; bool dropping = false; @@ -88,12 +88,12 @@ class EditorPropertyArray : public EditorProperty { int page_length = 20; int page_index = 0; int changing_type_index; - Button *edit; - VBoxContainer *vbox; - VBoxContainer *property_vbox; - EditorSpinSlider *size_slider; - Button *button_add_item; - EditorPaginator *paginator; + Button *edit = nullptr; + VBoxContainer *vbox = nullptr; + VBoxContainer *property_vbox = nullptr; + EditorSpinSlider *size_slider = nullptr; + Button *button_add_item = nullptr; + EditorPaginator *paginator = nullptr; Variant::Type array_type; Variant::Type subtype; PropertyHint subtype_hint; @@ -138,19 +138,19 @@ public: class EditorPropertyDictionary : public EditorProperty { GDCLASS(EditorPropertyDictionary, EditorProperty); - PopupMenu *change_type; + PopupMenu *change_type = nullptr; bool updating = false; Ref<EditorPropertyDictionaryObject> object; int page_length = 20; int page_index = 0; int changing_type_index; - Button *edit; - VBoxContainer *vbox; - VBoxContainer *property_vbox; - EditorSpinSlider *size_slider; - Button *button_add_item; - EditorPaginator *paginator; + Button *edit = nullptr; + VBoxContainer *vbox = nullptr; + VBoxContainer *property_vbox = nullptr; + EditorSpinSlider *size_slider = nullptr; + Button *button_add_item = nullptr; + EditorPaginator *paginator = nullptr; void _page_changed(int p_page); void _edit_pressed(); @@ -173,19 +173,19 @@ public: class EditorPropertyLocalizableString : public EditorProperty { GDCLASS(EditorPropertyLocalizableString, EditorProperty); - EditorLocaleDialog *locale_select; + EditorLocaleDialog *locale_select = nullptr; bool updating; Ref<EditorPropertyDictionaryObject> object; int page_length = 20; int page_index = 0; - Button *edit; - VBoxContainer *vbox; - VBoxContainer *property_vbox; - EditorSpinSlider *size_slider; - Button *button_add_item; - EditorPaginator *paginator; + Button *edit = nullptr; + VBoxContainer *vbox = nullptr; + VBoxContainer *property_vbox = nullptr; + EditorSpinSlider *size_slider = nullptr; + Button *button_add_item = nullptr; + EditorPaginator *paginator = nullptr; void _page_changed(int p_page); void _edit_pressed(); diff --git a/editor/editor_resource_picker.h b/editor/editor_resource_picker.h index a6eff760e7..cd7e507984 100644 --- a/editor/editor_resource_picker.h +++ b/editor/editor_resource_picker.h @@ -52,9 +52,9 @@ class EditorResourcePicker : public HBoxContainer { Vector<String> inheritors_array; - Button *assign_button; - TextureRect *preview_rect; - Button *edit_button; + Button *assign_button = nullptr; + TextureRect *preview_rect = nullptr; + Button *edit_button = nullptr; EditorFileDialog *file_dialog = nullptr; EditorQuickOpen *quick_open = nullptr; diff --git a/editor/editor_resource_preview.cpp b/editor/editor_resource_preview.cpp index 2bc92427e5..8541918e88 100644 --- a/editor/editor_resource_preview.cpp +++ b/editor/editor_resource_preview.cpp @@ -199,14 +199,12 @@ void EditorResourcePreview::_generate_preview(Ref<ImageTexture> &r_texture, Ref< if (has_small_texture) { ResourceSaver::save(cache_base + "_small.png", r_small_texture); } - FileAccess *f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE); - ERR_FAIL_COND_MSG(!f, "Cannot create file '" + cache_base + ".txt'. Check user write permissions."); + Ref<FileAccess> f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + cache_base + ".txt'. Check user write permissions."); f->store_line(itos(thumbnail_size)); f->store_line(itos(has_small_texture)); f->store_line(itos(FileAccess::get_modified_time(p_item.path))); f->store_line(FileAccess::get_md5(p_item.path)); - f->close(); - memdelete(f); } } } @@ -251,8 +249,8 @@ void EditorResourcePreview::_iterate() { //does not have it, try to load a cached thumbnail String file = cache_base + ".txt"; - FileAccess *f = FileAccess::open(file, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(file, FileAccess::READ); + if (f.is_null()) { // No cache found, generate _generate_preview(texture, small_texture, item, cache_base); } else { @@ -265,33 +263,31 @@ void EditorResourcePreview::_iterate() { if (tsize != thumbnail_size) { cache_valid = false; - memdelete(f); + f.unref(); } else if (last_modtime != modtime) { String last_md5 = f->get_line(); String md5 = FileAccess::get_md5(item.path); - memdelete(f); + f.unref(); if (last_md5 != md5) { cache_valid = false; - } else { //update modified time - f = FileAccess::open(file, FileAccess::WRITE); - if (!f) { + Ref<FileAccess> f2 = FileAccess::open(file, FileAccess::WRITE); + if (f2.is_null()) { // Not returning as this would leave the thread hanging and would require // some proper cleanup/disabling of resource preview generation. ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions."); } else { - f->store_line(itos(thumbnail_size)); - f->store_line(itos(has_small_texture)); - f->store_line(itos(modtime)); - f->store_line(md5); - memdelete(f); + f2->store_line(itos(thumbnail_size)); + f2->store_line(itos(has_small_texture)); + f2->store_line(itos(modtime)); + f2->store_line(md5); } } } else { - memdelete(f); + f.unref(); } if (cache_valid) { diff --git a/editor/editor_run.cpp b/editor/editor_run.cpp index 4743294967..574acdff1c 100644 --- a/editor/editor_run.cpp +++ b/editor/editor_run.cpp @@ -110,9 +110,10 @@ Error EditorRun::run(const String &p_scene) { } int window_placement = EditorSettings::get_singleton()->get("run/window_placement/rect"); - bool hidpi_proj = ProjectSettings::get_singleton()->get("display/window/dpi/allow_hidpi"); - int display_scale = 1; if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_HIDPI)) { + bool hidpi_proj = ProjectSettings::get_singleton()->get("display/window/dpi/allow_hidpi"); + int display_scale = 1; + if (OS::get_singleton()->is_hidpi_allowed()) { if (hidpi_proj) { display_scale = 1; // Both editor and project runs in hiDPI mode, do not scale. diff --git a/editor/editor_run_script.h b/editor/editor_run_script.h index 28a854aaeb..a2399bd780 100644 --- a/editor/editor_run_script.h +++ b/editor/editor_run_script.h @@ -39,7 +39,7 @@ class EditorNode; class EditorScript : public RefCounted { GDCLASS(EditorScript, RefCounted); - EditorNode *editor; + EditorNode *editor = nullptr; protected: static void _bind_methods(); diff --git a/editor/editor_sectioned_inspector.h b/editor/editor_sectioned_inspector.h index 7c21e00c03..0ccffa0048 100644 --- a/editor/editor_sectioned_inspector.h +++ b/editor/editor_sectioned_inspector.h @@ -42,11 +42,11 @@ class SectionedInspector : public HSplitContainer { ObjectID obj; - Tree *sections; - SectionedInspectorFilter *filter; + Tree *sections = nullptr; + SectionedInspectorFilter *filter = nullptr; Map<String, TreeItem *> section_map; - EditorInspector *inspector; + EditorInspector *inspector = nullptr; LineEdit *search_box = nullptr; String selected_category; diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp index 66bbb79de8..48f04694aa 100644 --- a/editor/editor_settings.cpp +++ b/editor/editor_settings.cpp @@ -722,7 +722,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) { /* Extra config */ - EDITOR_SETTING(Variant::INT, PROPERTY_HINT_ENUM, "project_manager/sorting_order", 0, "Name,Path,Last Edited") + EDITOR_SETTING(Variant::INT, PROPERTY_HINT_ENUM, "project_manager/sorting_order", 0, "Last Edited,Name,Path") if (p_extra_config.is_valid()) { if (p_extra_config->has_section("init_projects") && p_extra_config->has_section_key("init_projects", "list")) { @@ -842,7 +842,7 @@ void EditorSettings::create() { if (EditorPaths::get_singleton()->are_paths_valid()) { // Validate editor config file. - DirAccessRef dir = DirAccess::open(EditorPaths::get_singleton()->get_config_dir()); + Ref<DirAccess> dir = DirAccess::open(EditorPaths::get_singleton()->get_config_dir()); String config_file_name = "editor_settings-" + itos(VERSION_MAJOR) + ".tres"; config_file_path = EditorPaths::get_singleton()->get_config_dir().plus_file(config_file_name); if (!dir->file_exists(config_file_name)) { @@ -1151,12 +1151,11 @@ void EditorSettings::set_favorites(const Vector<String> &p_favorites) { } else { favorites_file = get_project_settings_dir().plus_file("favorites"); } - FileAccess *f = FileAccess::open(favorites_file, FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(favorites_file, FileAccess::WRITE); + if (f.is_valid()) { for (int i = 0; i < favorites.size(); i++) { f->store_line(favorites[i]); } - memdelete(f); } } @@ -1172,12 +1171,11 @@ void EditorSettings::set_recent_dirs(const Vector<String> &p_recent_dirs) { } else { recent_dirs_file = get_project_settings_dir().plus_file("recent_dirs"); } - FileAccess *f = FileAccess::open(recent_dirs_file, FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(recent_dirs_file, FileAccess::WRITE); + if (f.is_valid()) { for (int i = 0; i < recent_dirs.size(); i++) { f->store_line(recent_dirs[i]); } - memdelete(f); } } @@ -1195,24 +1193,22 @@ void EditorSettings::load_favorites_and_recent_dirs() { favorites_file = get_project_settings_dir().plus_file("favorites"); recent_dirs_file = get_project_settings_dir().plus_file("recent_dirs"); } - FileAccess *f = FileAccess::open(favorites_file, FileAccess::READ); - if (f) { + Ref<FileAccess> f = FileAccess::open(favorites_file, FileAccess::READ); + if (f.is_valid()) { String line = f->get_line().strip_edges(); while (!line.is_empty()) { favorites.push_back(line); line = f->get_line().strip_edges(); } - memdelete(f); } f = FileAccess::open(recent_dirs_file, FileAccess::READ); - if (f) { + if (f.is_valid()) { String line = f->get_line().strip_edges(); while (!line.is_empty()) { recent_dirs.push_back(line); line = f->get_line().strip_edges(); } - memdelete(f); } } @@ -1227,8 +1223,8 @@ bool EditorSettings::is_dark_theme() { void EditorSettings::list_text_editor_themes() { String themes = "Default,Godot 2,Custom"; - DirAccessRef d = DirAccess::open(get_text_editor_themes_dir()); - if (d) { + Ref<DirAccess> d = DirAccess::open(get_text_editor_themes_dir()); + if (d.is_valid()) { List<String> custom_themes; d->list_dir_begin(); String file = d->get_next(); @@ -1293,8 +1289,8 @@ bool EditorSettings::import_text_editor_theme(String p_file) { return false; } - DirAccessRef d = DirAccess::open(get_text_editor_themes_dir()); - if (d) { + Ref<DirAccess> d = DirAccess::open(get_text_editor_themes_dir()); + if (d.is_valid()) { d->copy(p_file, get_text_editor_themes_dir().plus_file(p_file.get_file())); return true; } @@ -1345,8 +1341,8 @@ Vector<String> EditorSettings::get_script_templates(const String &p_extension, c if (!p_custom_path.is_empty()) { template_dir = p_custom_path; } - DirAccessRef d = DirAccess::open(template_dir); - if (d) { + Ref<DirAccess> d = DirAccess::open(template_dir); + if (d.is_valid()) { d->list_dir_begin(); String file = d->get_next(); while (!file.is_empty()) { @@ -1365,7 +1361,7 @@ String EditorSettings::get_editor_layouts_config() const { } float EditorSettings::get_auto_display_scale() const { -#ifdef OSX_ENABLED +#if defined(OSX_ENABLED) || defined(ANDROID_ENABLED) return DisplayServer::get_singleton()->screen_get_max_scale(); #else const int screen = DisplayServer::get_singleton()->window_get_current_screen(); @@ -1389,7 +1385,7 @@ float EditorSettings::get_auto_display_scale() const { // Shortcuts -void EditorSettings::add_shortcut(const String &p_name, Ref<Shortcut> &p_shortcut) { +void EditorSettings::add_shortcut(const String &p_name, const Ref<Shortcut> &p_shortcut) { shortcuts[p_name] = p_shortcut; } diff --git a/editor/editor_settings.h b/editor/editor_settings.h index 4f25259a01..d1b9cabfb7 100644 --- a/editor/editor_settings.h +++ b/editor/editor_settings.h @@ -179,7 +179,7 @@ public: String get_editor_layouts_config() const; float get_auto_display_scale() const; - void add_shortcut(const String &p_name, Ref<Shortcut> &p_shortcut); + void add_shortcut(const String &p_name, const Ref<Shortcut> &p_shortcut); bool is_shortcut(const String &p_name, const Ref<InputEvent> &p_event) const; Ref<Shortcut> get_shortcut(const String &p_name) const; void get_shortcut_list(List<String> *r_shortcuts); diff --git a/editor/editor_settings_dialog.cpp b/editor/editor_settings_dialog.cpp index 285b909b66..dcbe91bd7f 100644 --- a/editor/editor_settings_dialog.cpp +++ b/editor/editor_settings_dialog.cpp @@ -92,7 +92,7 @@ void EditorSettingsDialog::popup_edit_settings() { search_box->grab_focus(); _update_shortcuts(); - set_process_unhandled_input(true); + set_process_shortcut_input(true); // Restore valid window bounds or pop up at default size. Rect2 saved_size = EditorSettings::get_singleton()->get_project_metadata("dialog_bounds", "editor_settings", Rect2()); @@ -119,7 +119,7 @@ void EditorSettingsDialog::_notification(int p_what) { case NOTIFICATION_VISIBILITY_CHANGED: { if (!is_visible()) { EditorSettings::get_singleton()->set_project_metadata("dialog_bounds", "editor_settings", Rect2(get_position(), get_size())); - set_process_unhandled_input(false); + set_process_shortcut_input(false); } } break; @@ -148,7 +148,7 @@ void EditorSettingsDialog::_notification(int p_what) { } } -void EditorSettingsDialog::unhandled_input(const Ref<InputEvent> &p_event) { +void EditorSettingsDialog::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); const Ref<InputEventKey> k = p_event; diff --git a/editor/editor_settings_dialog.h b/editor/editor_settings_dialog.h index e3139bb07a..9a34eac7ef 100644 --- a/editor/editor_settings_dialog.h +++ b/editor/editor_settings_dialog.h @@ -45,13 +45,13 @@ class EditorSettingsDialog : public AcceptDialog { bool updating = false; - TabContainer *tabs; - Control *tab_general; - Control *tab_shortcuts; + TabContainer *tabs = nullptr; + Control *tab_general = nullptr; + Control *tab_shortcuts = nullptr; - LineEdit *search_box; - LineEdit *shortcut_search_box; - SectionedInspector *inspector; + LineEdit *search_box = nullptr; + LineEdit *shortcut_search_box = nullptr; + SectionedInspector *inspector = nullptr; // Shortcuts enum ShortcutButton { @@ -61,19 +61,19 @@ class EditorSettingsDialog : public AcceptDialog { SHORTCUT_REVERT }; - Tree *shortcuts; + Tree *shortcuts = nullptr; String shortcut_filter; - InputEventConfigurationDialog *shortcut_editor; + InputEventConfigurationDialog *shortcut_editor = nullptr; bool is_editing_action = false; String current_edited_identifier; Array current_events; int current_event_index = -1; - Timer *timer; + Timer *timer = nullptr; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; virtual void cancel_pressed() override; virtual void ok_pressed() override; @@ -82,7 +82,7 @@ class EditorSettingsDialog : public AcceptDialog { void _settings_property_edited(const String &p_name); void _settings_save(); - virtual void unhandled_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; void _notification(int p_what); void _update_icons(); @@ -110,10 +110,10 @@ class EditorSettingsDialog : public AcceptDialog { static void _undo_redo_callback(void *p_self, const String &p_name); - Label *restart_label; - TextureRect *restart_icon; - PanelContainer *restart_container; - Button *restart_close_button; + Label *restart_label = nullptr; + TextureRect *restart_icon = nullptr; + PanelContainer *restart_container = nullptr; + Button *restart_close_button = nullptr; void _editor_restart_request(); void _editor_restart(); diff --git a/editor/editor_spin_slider.h b/editor/editor_spin_slider.h index 405c3bfc22..fc9f6b8722 100644 --- a/editor/editor_spin_slider.h +++ b/editor/editor_spin_slider.h @@ -44,7 +44,7 @@ class EditorSpinSlider : public Range { bool hover_updown = false; bool mouse_hover = false; - TextureRect *grabber; + TextureRect *grabber = nullptr; int grabber_range; bool mouse_over_spin = false; diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp index 1fea759a90..f4082746d8 100644 --- a/editor/editor_themes.cpp +++ b/editor/editor_themes.cpp @@ -1220,10 +1220,6 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { theme->set_icon("breakpoint", "CodeEdit", theme->get_icon(SNAME("Breakpoint"), SNAME("EditorIcons"))); theme->set_constant("line_spacing", "CodeEdit", EDITOR_GET("text_editor/appearance/whitespace/line_spacing")); - // H/VSplitContainer - theme->set_stylebox("bg", "VSplitContainer", make_stylebox(theme->get_icon(SNAME("GuiVsplitBg"), SNAME("EditorIcons")), 1, 1, 1, 1)); - theme->set_stylebox("bg", "HSplitContainer", make_stylebox(theme->get_icon(SNAME("GuiHsplitBg"), SNAME("EditorIcons")), 1, 1, 1, 1)); - theme->set_icon("grabber", "VSplitContainer", theme->get_icon(SNAME("GuiVsplitter"), SNAME("EditorIcons"))); theme->set_icon("grabber", "HSplitContainer", theme->get_icon(SNAME("GuiHsplitter"), SNAME("EditorIcons"))); diff --git a/editor/editor_toaster.h b/editor/editor_toaster.h index 059245ce66..791a146a8d 100644 --- a/editor/editor_toaster.h +++ b/editor/editor_toaster.h @@ -61,11 +61,11 @@ private: Ref<StyleBoxFlat> warning_panel_style_progress; Ref<StyleBoxFlat> error_panel_style_progress; - Button *main_button; - PanelContainer *disable_notifications_panel; - Button *disable_notifications_button; + Button *main_button = nullptr; + PanelContainer *disable_notifications_panel = nullptr; + Button *disable_notifications_button = nullptr; - VBoxContainer *vbox_container; + VBoxContainer *vbox_container = nullptr; const int max_temporary_count = 5; struct Toast { Severity severity = SEVERITY_INFO; diff --git a/editor/editor_translation.cpp b/editor/editor_translation.cpp index f64adcf0a1..b08e5807e7 100644 --- a/editor/editor_translation.cpp +++ b/editor/editor_translation.cpp @@ -59,7 +59,8 @@ void load_editor_translations(const String &p_locale) { int ret = Compression::decompress(data.ptrw(), etl->uncomp_size, etl->data, etl->comp_size, Compression::MODE_DEFLATE); ERR_FAIL_COND_MSG(ret == -1, "Compressed file is corrupt."); - FileAccessMemory *fa = memnew(FileAccessMemory); + Ref<FileAccessMemory> fa; + fa.instantiate(); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa); @@ -84,7 +85,8 @@ void load_doc_translations(const String &p_locale) { int ret = Compression::decompress(data.ptrw(), dtl->uncomp_size, dtl->data, dtl->comp_size, Compression::MODE_DEFLATE); ERR_FAIL_COND_MSG(ret == -1, "Compressed file is corrupt."); - FileAccessMemory *fa = memnew(FileAccessMemory); + Ref<FileAccessMemory> fa; + fa.instantiate(); fa->open_custom(data.ptr(), data.size()); Ref<Translation> tr = TranslationLoaderPO::load_translation(fa); diff --git a/editor/editor_vcs_interface.cpp b/editor/editor_vcs_interface.cpp index 0954779300..3f2012cc16 100644 --- a/editor/editor_vcs_interface.cpp +++ b/editor/editor_vcs_interface.cpp @@ -168,21 +168,19 @@ void EditorVCSInterface::set_singleton(EditorVCSInterface *p_singleton) { void EditorVCSInterface::create_vcs_metadata_files(VCSMetadata p_vcs_metadata_type, String &p_dir) { if (p_vcs_metadata_type == VCSMetadata::GIT) { - FileAccess *f = FileAccess::open(p_dir.plus_file(".gitignore"), FileAccess::WRITE); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_dir.plus_file(".gitignore"), FileAccess::WRITE); + if (f.is_null()) { ERR_FAIL_MSG(TTR("Couldn't create .gitignore in project path.")); } else { f->store_line("# Godot 4+ specific ignores"); f->store_line(".godot/"); - memdelete(f); } f = FileAccess::open(p_dir.plus_file(".gitattributes"), FileAccess::WRITE); - if (!f) { + if (f.is_null()) { ERR_FAIL_MSG(TTR("Couldn't create .gitattributes in project path.")); } else { f->store_line("# Normalize EOL for all files that Git considers text files."); f->store_line("* text=auto eol=lf"); - memdelete(f); } } } diff --git a/editor/editor_zoom_widget.h b/editor/editor_zoom_widget.h index bf8358ff1a..4690a57a2b 100644 --- a/editor/editor_zoom_widget.h +++ b/editor/editor_zoom_widget.h @@ -37,9 +37,9 @@ class EditorZoomWidget : public HBoxContainer { GDCLASS(EditorZoomWidget, HBoxContainer); - Button *zoom_minus; - Button *zoom_reset; - Button *zoom_plus; + Button *zoom_minus = nullptr; + Button *zoom_reset = nullptr; + Button *zoom_plus = nullptr; float zoom = 1.0; void _update_zoom_label(); diff --git a/editor/export_template_manager.cpp b/editor/export_template_manager.cpp index 7320f957c9..06c179e77c 100644 --- a/editor/export_template_manager.cpp +++ b/editor/export_template_manager.cpp @@ -44,7 +44,7 @@ void ExportTemplateManager::_update_template_status() { // Fetch installed templates from the file system. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); const String &templates_dir = EditorSettings::get_singleton()->get_templates_dir(); Error err = da->change_dir(templates_dir); @@ -194,7 +194,7 @@ void ExportTemplateManager::_download_template_completed(int p_status, int p_cod bool ret = _install_file_selected(path, true); if (ret) { // Clean up downloaded file. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = da->remove(path); if (err != OK) { EditorNode::get_singleton()->add_io_error(TTR("Cannot remove temporary file:") + "\n" + path + "\n"); @@ -374,10 +374,7 @@ void ExportTemplateManager::_install_file() { } bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_skip_progress) { - // unzClose() will take care of closing the file stored in the unzFile, - // so we don't need to `memdelete(fa)` in this method. - FileAccess *fa = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&fa); + zlib_filefunc_def io = zipio_create_io(); unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io); if (!pkg) { @@ -395,6 +392,9 @@ bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_ unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String file = String::utf8(fname); if (file.ends_with("version.txt")) { @@ -404,6 +404,9 @@ bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_ // Read. unzOpenCurrentFile(pkg); ret = unzReadCurrentFile(pkg, data.ptrw(), data.size()); + if (ret != UNZ_OK) { + break; + } unzCloseCurrentFile(pkg); String data_str; @@ -435,7 +438,7 @@ bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_ return false; } - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version); Error err = d->make_dir_recursive(template_path); if (err != OK) { @@ -455,7 +458,10 @@ bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_ // Get filename. unz_file_info info; char fname[16384]; - unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String file_path(String::utf8(fname).simplify_path()); @@ -471,7 +477,10 @@ bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_ // Read unzOpenCurrentFile(pkg); - unzReadCurrentFile(pkg, data.ptrw(), data.size()); + ret = unzReadCurrentFile(pkg, data.ptrw(), data.size()); + if (ret != UNZ_OK) { + break; + } unzCloseCurrentFile(pkg); String base_dir = file_path.get_base_dir().trim_suffix("/"); @@ -480,8 +489,8 @@ bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_ base_dir = base_dir.substr(contents_dir.length(), file_path.length()).trim_prefix("/"); file = base_dir.plus_file(file); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_CONTINUE(!da); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_CONTINUE(da.is_null()); String output_dir = template_path.plus_file(base_dir); @@ -496,16 +505,16 @@ bool ExportTemplateManager::_install_file_selected(const String &p_file, bool p_ } String to_write = template_path.plus_file(file); - FileAccessRef f = FileAccess::open(to_write, FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open(to_write, FileAccess::WRITE); - if (!f) { + if (f.is_null()) { ret = unzGoToNextFile(pkg); fc++; ERR_CONTINUE_MSG(true, "Can't open file from path '" + String(to_write) + "'."); } f->store_buffer(data.ptr(), data.size()); - + f.unref(); // close file. #ifndef WINDOWS_ENABLED FileAccess::set_unix_permissions(to_write, (info.external_fa >> 16) & 0x01FF); #endif @@ -530,7 +539,7 @@ void ExportTemplateManager::_uninstall_template(const String &p_version) { } void ExportTemplateManager::_uninstall_template_confirmed() { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); const String &templates_dir = EditorSettings::get_singleton()->get_templates_dir(); Error err = da->change_dir(templates_dir); @@ -644,17 +653,16 @@ Error ExportTemplateManager::install_android_template_from_file(const String &p_ // To support custom Android builds, we install the Java source code and buildsystem // from android_source.zip to the project's res://android folder. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - ERR_FAIL_COND_V(!da, ERR_CANT_CREATE); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE); // Make res://android dir (if it does not exist). da->make_dir("android"); { // Add version, to ensure building won't work if template and Godot version don't match. - FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::WRITE); - ERR_FAIL_COND_V(!f, ERR_CANT_CREATE); + Ref<FileAccess> f = FileAccess::open("res://android/.build_version", FileAccess::WRITE); + ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE); f->store_line(VERSION_FULL_CONFIG); - f->close(); } // Create the android plugins directory. @@ -665,16 +673,14 @@ Error ExportTemplateManager::install_android_template_from_file(const String &p_ ERR_FAIL_COND_V(err != OK, err); { // Add an empty .gdignore file to avoid scan. - FileAccessRef f = FileAccess::open("res://android/build/.gdignore", FileAccess::WRITE); - ERR_FAIL_COND_V(!f, ERR_CANT_CREATE); + Ref<FileAccess> f = FileAccess::open("res://android/build/.gdignore", FileAccess::WRITE); + ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE); f->store_line(""); - f->close(); } // Uncompress source template. - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io); ERR_FAIL_COND_V_MSG(!pkg, ERR_CANT_OPEN, "Android sources not in ZIP format."); @@ -697,6 +703,9 @@ Error ExportTemplateManager::install_android_template_from_file(const String &p_ unz_file_info info; char fpath[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fpath, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String path = String::utf8(fpath); String base_dir = path.get_base_dir(); @@ -716,10 +725,10 @@ Error ExportTemplateManager::install_android_template_from_file(const String &p_ } String to_write = String("res://android/build").plus_file(path); - FileAccess *f = FileAccess::open(to_write, FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(to_write, FileAccess::WRITE); + if (f.is_valid()) { f->store_buffer(data.ptr(), data.size()); - memdelete(f); + f.unref(); // close file. #ifndef WINDOWS_ENABLED FileAccess::set_unix_permissions(to_write, (info.external_fa >> 16) & 0x01FF); #endif diff --git a/editor/export_template_manager.h b/editor/export_template_manager.h index cf7585635d..61df212f1f 100644 --- a/editor/export_template_manager.h +++ b/editor/export_template_manager.h @@ -51,42 +51,42 @@ class ExportTemplateManager : public AcceptDialog { bool is_downloading_templates = false; float update_countdown = 0; - Label *current_value; - Label *current_missing_label; - Label *current_installed_label; + Label *current_value = nullptr; + Label *current_missing_label = nullptr; + Label *current_installed_label = nullptr; - HBoxContainer *current_installed_hb; - LineEdit *current_installed_path; - Button *current_open_button; - Button *current_uninstall_button; + HBoxContainer *current_installed_hb = nullptr; + LineEdit *current_installed_path = nullptr; + Button *current_open_button = nullptr; + Button *current_uninstall_button = nullptr; - VBoxContainer *install_options_vb; - OptionButton *mirrors_list; + VBoxContainer *install_options_vb = nullptr; + OptionButton *mirrors_list = nullptr; enum MirrorAction { VISIT_WEB_MIRROR, COPY_MIRROR_URL, }; - MenuButton *mirror_options_button; - HBoxContainer *download_progress_hb; - ProgressBar *download_progress_bar; - Label *download_progress_label; - HTTPRequest *download_templates; - Button *install_file_button; - HTTPRequest *request_mirrors; + MenuButton *mirror_options_button = nullptr; + HBoxContainer *download_progress_hb = nullptr; + ProgressBar *download_progress_bar = nullptr; + Label *download_progress_label = nullptr; + HTTPRequest *download_templates = nullptr; + Button *install_file_button = nullptr; + HTTPRequest *request_mirrors = nullptr; enum TemplatesAction { OPEN_TEMPLATE_FOLDER, UNINSTALL_TEMPLATE, }; - Tree *installed_table; + Tree *installed_table = nullptr; - ConfirmationDialog *uninstall_confirm; + ConfirmationDialog *uninstall_confirm = nullptr; String uninstall_version; - FileDialog *install_file_dialog; - AcceptDialog *hide_dialog_accept; + FileDialog *install_file_dialog = nullptr; + AcceptDialog *hide_dialog_accept = nullptr; void _update_template_status(); diff --git a/editor/fileserver/editor_file_server.cpp b/editor/fileserver/editor_file_server.cpp index df0af69359..46fb767c00 100644 --- a/editor/fileserver/editor_file_server.cpp +++ b/editor/fileserver/editor_file_server.cpp @@ -46,14 +46,13 @@ void EditorFileServer::_close_client(ClientData *cd) { cd->efs->to_wait.insert(cd->thread); } while (cd->files.size()) { - memdelete(cd->files.front()->get()); cd->files.erase(cd->files.front()); } memdelete(cd); } void EditorFileServer::_subthread_start(void *s) { - ClientData *cd = (ClientData *)s; + ClientData *cd = static_cast<ClientData *>(s); cd->connection->set_no_delay(true); uint8_t buf4[8]; @@ -181,8 +180,8 @@ void EditorFileServer::_subthread_start(void *s) { break; } - FileAccess *fa = FileAccess::open(s2, FileAccess::READ); - if (!fa) { + Ref<FileAccess> fa = FileAccess::open(s2, FileAccess::READ); + if (fa.is_null()) { //not found, continue encode_uint32(id, buf4); cd->connection->put_data(buf4, 4); @@ -249,7 +248,6 @@ void EditorFileServer::_subthread_start(void *s) { case FileAccessNetwork::COMMAND_CLOSE: { print_verbose("CLOSED"); ERR_CONTINUE(!cd->files.has(id)); - memdelete(cd->files[id]); cd->files.erase(id); } break; } @@ -259,7 +257,7 @@ void EditorFileServer::_subthread_start(void *s) { } void EditorFileServer::_thread_start(void *s) { - EditorFileServer *self = (EditorFileServer *)s; + EditorFileServer *self = static_cast<EditorFileServer *>(s); while (!self->quit) { if (self->cmd == CMD_ACTIVATE) { self->server->listen(self->port); diff --git a/editor/fileserver/editor_file_server.h b/editor/fileserver/editor_file_server.h index 7807e72800..ccebd1465d 100644 --- a/editor/fileserver/editor_file_server.h +++ b/editor/fileserver/editor_file_server.h @@ -47,9 +47,9 @@ class EditorFileServer : public Object { }; struct ClientData { - Thread *thread; + Thread *thread = nullptr; Ref<StreamPeerTCP> connection; - Map<int, FileAccess *> files; + Map<int, Ref<FileAccess>> files; EditorFileServer *efs = nullptr; bool quit = false; }; diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp index ee7ed77957..778c5c33ff 100644 --- a/editor/filesystem_dock.cpp +++ b/editor/filesystem_dock.cpp @@ -225,13 +225,14 @@ void FileSystemDock::_update_tree(const Vector<String> &p_uncollapsed_paths, boo Vector<String> favorite_paths = EditorSettings::get_singleton()->get_favorites(); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); bool fav_changed = false; for (int i = favorite_paths.size() - 1; i >= 0; i--) { - if (!da->dir_exists(favorite_paths[i])) { - favorite_paths.remove_at(i); - fav_changed = true; + if (da->dir_exists(favorite_paths[i]) || da->file_exists(favorite_paths[i])) { + continue; } + favorite_paths.remove_at(i); + fav_changed = true; } if (fav_changed) { EditorSettings::get_singleton()->set_favorites(favorite_paths); @@ -538,7 +539,7 @@ void FileSystemDock::_navigate_to_path(const String &p_path, bool p_select_in_fa if (target_path.ends_with("/")) { target_path = target_path.substr(0, target_path.length() - 1); } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->file_exists(p_path)) { path = target_path; } else if (da->dir_exists(p_path)) { @@ -988,7 +989,7 @@ void FileSystemDock::_select_file(const String &p_path, bool p_select_in_favorit { List<String> importer_exts; - ResourceImporterScene::get_singleton()->get_recognized_extensions(&importer_exts); + ResourceImporterScene::get_scene_singleton()->get_recognized_extensions(&importer_exts); String extension = fpath.get_extension(); for (const String &E : importer_exts) { if (extension.nocasecmp_to(E) == 0) { @@ -999,7 +1000,27 @@ void FileSystemDock::_select_file(const String &p_path, bool p_select_in_favorit } if (is_imported) { - ResourceImporterScene::get_singleton()->show_advanced_options(fpath); + ResourceImporterScene::get_scene_singleton()->show_advanced_options(fpath); + } else { + EditorNode::get_singleton()->open_request(fpath); + } + } else if (ResourceLoader::get_resource_type(fpath) == "AnimationLibrary") { + bool is_imported = false; + + { + List<String> importer_exts; + ResourceImporterScene::get_animation_singleton()->get_recognized_extensions(&importer_exts); + String extension = fpath.get_extension(); + for (const String &E : importer_exts) { + if (extension.nocasecmp_to(E) == 0) { + is_imported = true; + break; + } + } + } + + if (is_imported) { + ResourceImporterScene::get_animation_singleton()->show_advanced_options(fpath); } else { EditorNode::get_singleton()->open_request(fpath); } @@ -1182,7 +1203,7 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_ _get_all_items_in_dir(EditorFileSystem::get_singleton()->get_filesystem_path(old_path), file_changed_paths, folder_changed_paths); } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); print_verbose("Moving " + old_path + " -> " + new_path); Error err = da->rename(old_path, new_path); if (err == OK) { @@ -1240,7 +1261,7 @@ void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const Strin return; } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); print_verbose("Duplicating " + old_path + " -> " + new_path); Error err = p_item.is_file ? da->copy(old_path, new_path) : da->copy_dir(old_path, new_path); if (err == OK) { @@ -1259,7 +1280,7 @@ void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const Strin cfg->save(new_path + ".import"); } else if (p_item.is_file && (old_path.get_extension() == "tscn" || old_path.get_extension() == "tres")) { // FIXME: Quick hack to fix text resources. This should be fixed properly. - FileAccessRef file = FileAccess::open(old_path, FileAccess::READ, &err); + Ref<FileAccess> file = FileAccess::open(old_path, FileAccess::READ, &err); if (err == OK) { PackedStringArray lines = file->get_as_utf8_string().split("\n"); String line = lines[0]; @@ -1268,7 +1289,7 @@ void FileSystemDock::_try_duplicate_item(const FileOrFolder &p_item, const Strin line = line.substr(0, line.find(" uid")) + "]"; lines.write[0] = line; - FileAccessRef file2 = FileAccess::open(new_path, FileAccess::WRITE, &err); + Ref<FileAccess> file2 = FileAccess::open(new_path, FileAccess::WRITE, &err); if (err == OK) { file2->store_string(String("\n").join(lines)); } @@ -1427,17 +1448,17 @@ void FileSystemDock::_make_dir_confirm() { directory = directory.get_base_dir(); } - if (EditorFileSystem::get_singleton()->get_filesystem_path(directory + dir_name)) { + print_verbose("Making folder " + dir_name + " in " + directory); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Error err = da->change_dir(directory); + ERR_FAIL_COND_MSG(err != OK, "Cannot open directory '" + directory + "'."); + + if (da->dir_exists(dir_name)) { EditorNode::get_singleton()->show_warning(TTR("Could not create folder. File with that name already exists.")); return; } - print_verbose("Making folder " + dir_name + " in " + directory); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - Error err = da->change_dir(directory); - if (err == OK) { - err = da->make_dir(dir_name); - } + err = da->make_dir(dir_name); if (err == OK) { print_verbose("FileSystem: calling rescan."); @@ -1478,7 +1499,7 @@ void FileSystemDock::_make_scene_confirm() { scene_name = directory.plus_file(scene_name); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->file_exists(scene_name)) { EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists.")); return; @@ -1493,7 +1514,7 @@ void FileSystemDock::_file_removed(String p_file) { // Find the closest parent directory available, in case multiple items were deleted along the same path. path = p_file.get_base_dir(); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); while (!da->dir_exists(path)) { path = path.get_base_dir(); } @@ -1506,7 +1527,7 @@ void FileSystemDock::_folder_removed(String p_folder) { // Find the closest parent directory available, in case multiple items were deleted along the same path. path = p_folder.get_base_dir(); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); while (!da->dir_exists(path)) { path = path.get_base_dir(); } @@ -1545,7 +1566,7 @@ void FileSystemDock::_rename_operation_confirm() { } // Present a more user friendly warning for name conflict. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); #if defined(WINDOWS_ENABLED) || defined(UWP_ENABLED) // Workaround case insensitivity on Windows. if ((da->file_exists(new_path) || da->dir_exists(new_path)) && new_path.to_lower() != old_path.to_lower()) { @@ -1598,7 +1619,7 @@ void FileSystemDock::_duplicate_operation_confirm() { String new_path = base_dir.plus_file(new_name); // Present a more user friendly warning for name conflict - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->file_exists(new_path) || da->dir_exists(new_path)) { EditorNode::get_singleton()->show_warning(TTR("A file or folder with this name already exists.")); return; @@ -2353,7 +2374,7 @@ void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data, } int exist_counter = 1; - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); while (da->file_exists(new_path) || da->dir_exists(new_path)) { exist_counter++; new_path = vformat(new_path_base, exist_counter); @@ -2830,7 +2851,7 @@ void FileSystemDock::_get_imported_files(const String &p_path, Vector<String> &f return; } - DirAccessRef da = DirAccess::open(p_path); + Ref<DirAccess> da = DirAccess::open(p_path); da->list_dir_begin(); String n = da->get_next(); while (!n.is_empty()) { diff --git a/editor/filesystem_dock.h b/editor/filesystem_dock.h index 92dac374ec..15fade2d95 100644 --- a/editor/filesystem_dock.h +++ b/editor/filesystem_dock.h @@ -102,57 +102,57 @@ private: FileSortOption file_sort = FILE_SORT_NAME; - VBoxContainer *scanning_vb; - ProgressBar *scanning_progress; - VSplitContainer *split_box; - VBoxContainer *file_list_vb; + VBoxContainer *scanning_vb = nullptr; + ProgressBar *scanning_progress = nullptr; + VSplitContainer *split_box = nullptr; + VBoxContainer *file_list_vb = nullptr; Set<String> favorites; - Button *button_toggle_display_mode; - Button *button_reload; - Button *button_file_list_display_mode; - Button *button_hist_next; - Button *button_hist_prev; - LineEdit *current_path; + Button *button_toggle_display_mode = nullptr; + Button *button_reload = nullptr; + Button *button_file_list_display_mode = nullptr; + Button *button_hist_next = nullptr; + Button *button_hist_prev = nullptr; + LineEdit *current_path = nullptr; - HBoxContainer *toolbar2_hbc; - LineEdit *tree_search_box; - MenuButton *tree_button_sort; + HBoxContainer *toolbar2_hbc = nullptr; + LineEdit *tree_search_box = nullptr; + MenuButton *tree_button_sort = nullptr; - LineEdit *file_list_search_box; - MenuButton *file_list_button_sort; + LineEdit *file_list_search_box = nullptr; + MenuButton *file_list_button_sort = nullptr; String searched_string; Vector<String> uncollapsed_paths_before_search; - TextureRect *search_icon; - HBoxContainer *path_hb; + TextureRect *search_icon = nullptr; + HBoxContainer *path_hb = nullptr; FileListDisplayMode file_list_display_mode; DisplayMode display_mode; DisplayMode old_display_mode; - PopupMenu *file_list_popup; - PopupMenu *tree_popup; - - DependencyEditor *deps_editor; - DependencyEditorOwners *owners_editor; - DependencyRemoveDialog *remove_dialog; - - EditorDirDialog *move_dialog; - ConfirmationDialog *rename_dialog; - LineEdit *rename_dialog_text; - ConfirmationDialog *duplicate_dialog; - LineEdit *duplicate_dialog_text; - ConfirmationDialog *make_dir_dialog; - LineEdit *make_dir_dialog_text; - ConfirmationDialog *make_scene_dialog; - LineEdit *make_scene_dialog_text; - ConfirmationDialog *overwrite_dialog; - ScriptCreateDialog *make_script_dialog; - ShaderCreateDialog *make_shader_dialog; - CreateDialog *new_resource_dialog; + PopupMenu *file_list_popup = nullptr; + PopupMenu *tree_popup = nullptr; + + DependencyEditor *deps_editor = nullptr; + DependencyEditorOwners *owners_editor = nullptr; + DependencyRemoveDialog *remove_dialog = nullptr; + + EditorDirDialog *move_dialog = nullptr; + ConfirmationDialog *rename_dialog = nullptr; + LineEdit *rename_dialog_text = nullptr; + ConfirmationDialog *duplicate_dialog = nullptr; + LineEdit *duplicate_dialog_text = nullptr; + ConfirmationDialog *make_dir_dialog = nullptr; + LineEdit *make_dir_dialog_text = nullptr; + ConfirmationDialog *make_scene_dialog = nullptr; + LineEdit *make_scene_dialog_text = nullptr; + ConfirmationDialog *overwrite_dialog = nullptr; + ScriptCreateDialog *make_script_dialog = nullptr; + ShaderCreateDialog *make_shader_dialog = nullptr; + CreateDialog *new_resource_dialog = nullptr; bool always_show_folders = false; @@ -181,8 +181,8 @@ private: bool updating_tree = false; int tree_update_id; - Tree *tree; - ItemList *files; + Tree *tree = nullptr; + ItemList *files = nullptr; bool import_dock_needs_update = false; bool holding_branch = false; diff --git a/editor/find_in_files.cpp b/editor/find_in_files.cpp index 1ce363c651..41191271a1 100644 --- a/editor/find_in_files.cpp +++ b/editor/find_in_files.cpp @@ -211,8 +211,8 @@ float FindInFiles::get_progress() const { } void FindInFiles::_scan_dir(String path, PackedStringArray &out_folders) { - DirAccessRef dir = DirAccess::open(path); - if (!dir) { + Ref<DirAccess> dir = DirAccess::open(path); + if (dir.is_null()) { print_verbose("Cannot open directory! " + path); return; } @@ -253,8 +253,8 @@ void FindInFiles::_scan_dir(String path, PackedStringArray &out_folders) { } void FindInFiles::_scan_file(String fpath) { - FileAccessRef f = FileAccess::open(fpath, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ); + if (f.is_null()) { print_verbose(String("Cannot open file ") + fpath); return; } @@ -274,8 +274,6 @@ void FindInFiles::_scan_file(String fpath) { emit_signal(SNAME(SIGNAL_RESULT_FOUND), fpath, line_number, begin, end, line); } } - - f->close(); } void FindInFiles::_bind_methods() { @@ -449,7 +447,7 @@ Set<String> FindInFilesDialog::get_filter() const { // Could check the _filters_preferences but it might not have been generated yet. Set<String> filters; for (int i = 0; i < _filters_container->get_child_count(); ++i) { - CheckBox *cb = (CheckBox *)_filters_container->get_child(i); + CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i)); if (cb->is_pressed()) { filters.insert(cb->get_text()); } @@ -489,7 +487,7 @@ void FindInFilesDialog::_on_folder_button_pressed() { void FindInFilesDialog::custom_action(const String &p_action) { for (int i = 0; i < _filters_container->get_child_count(); ++i) { - CheckBox *cb = (CheckBox *)_filters_container->get_child(i); + CheckBox *cb = static_cast<CheckBox *>(_filters_container->get_child(i)); _filters_preferences[cb->get_text()] = cb->is_pressed(); } @@ -873,7 +871,7 @@ void FindInFilesPanel::_on_replace_all_clicked() { // Same as get_line, but preserves line ending characters. class ConservativeGetLine { public: - String get_line(FileAccess *f) { + String get_line(Ref<FileAccess> f) { _line_buffer.clear(); char32_t c = f->get_8(); @@ -908,8 +906,8 @@ void FindInFilesPanel::apply_replaces_in_file(String fpath, const Vector<Result> // If there are unsaved changes, the user will be asked on focus, // however that means either losing changes or losing replaces. - FileAccessRef f = FileAccess::open(fpath, FileAccess::READ); - ERR_FAIL_COND_MSG(!f, "Cannot open file from path '" + fpath + "'."); + Ref<FileAccess> f = FileAccess::open(fpath, FileAccess::READ); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file from path '" + fpath + "'."); String buffer; int current_line = 1; @@ -958,8 +956,6 @@ void FindInFilesPanel::apply_replaces_in_file(String fpath, const Vector<Result> ERR_FAIL_COND_MSG(err != OK, "Cannot create file in path '" + fpath + "'."); f->store_string(buffer); - - f->close(); } String FindInFilesPanel::get_replace_text() { diff --git a/editor/find_in_files.h b/editor/find_in_files.h index cf14f3d5c3..9def190b5b 100644 --- a/editor/find_in_files.h +++ b/editor/find_in_files.h @@ -132,18 +132,18 @@ private: void _on_replace_text_submitted(String text); FindInFilesMode _mode; - LineEdit *_search_text_line_edit; - - Label *_replace_label; - LineEdit *_replace_text_line_edit; - - LineEdit *_folder_line_edit; - CheckBox *_match_case_checkbox; - CheckBox *_whole_words_checkbox; - Button *_find_button; - Button *_replace_button; - FileDialog *_folder_dialog; - HBoxContainer *_filters_container; + LineEdit *_search_text_line_edit = nullptr; + + Label *_replace_label = nullptr; + LineEdit *_replace_text_line_edit = nullptr; + + LineEdit *_folder_line_edit = nullptr; + CheckBox *_match_case_checkbox = nullptr; + CheckBox *_whole_words_checkbox = nullptr; + Button *_find_button = nullptr; + Button *_replace_button = nullptr; + FileDialog *_folder_dialog = nullptr; + HBoxContainer *_filters_container = nullptr; HashMap<String, bool> _filters_preferences; }; @@ -201,20 +201,20 @@ private: void set_progress_visible(bool visible); void clear(); - FindInFiles *_finder; - Label *_search_text_label; - Tree *_results_display; - Label *_status_label; - Button *_refresh_button; - Button *_cancel_button; - ProgressBar *_progress_bar; + FindInFiles *_finder = nullptr; + Label *_search_text_label = nullptr; + Tree *_results_display = nullptr; + Label *_status_label = nullptr; + Button *_refresh_button = nullptr; + Button *_cancel_button = nullptr; + ProgressBar *_progress_bar = nullptr; Map<String, TreeItem *> _file_items; Map<TreeItem *, Result> _result_items; bool _with_replace = false; - HBoxContainer *_replace_container; - LineEdit *_replace_line_edit; - Button *_replace_all_button; + HBoxContainer *_replace_container = nullptr; + LineEdit *_replace_line_edit = nullptr; + Button *_replace_all_button = nullptr; }; #endif // FIND_IN_FILES_H diff --git a/editor/groups_editor.h b/editor/groups_editor.h index aa70ac5bc4..b6a6204013 100644 --- a/editor/groups_editor.h +++ b/editor/groups_editor.h @@ -43,32 +43,32 @@ class GroupDialog : public AcceptDialog { GDCLASS(GroupDialog, AcceptDialog); - ConfirmationDialog *error; + ConfirmationDialog *error = nullptr; - SceneTree *scene_tree; - TreeItem *groups_root; + SceneTree *scene_tree = nullptr; + TreeItem *groups_root = nullptr; - LineEdit *add_group_text; - Button *add_group_button; + LineEdit *add_group_text = nullptr; + Button *add_group_button = nullptr; - Tree *groups; + Tree *groups = nullptr; - Tree *nodes_to_add; - TreeItem *add_node_root; - LineEdit *add_filter; + Tree *nodes_to_add = nullptr; + TreeItem *add_node_root = nullptr; + LineEdit *add_filter = nullptr; - Tree *nodes_to_remove; - TreeItem *remove_node_root; - LineEdit *remove_filter; + Tree *nodes_to_remove = nullptr; + TreeItem *remove_node_root = nullptr; + LineEdit *remove_filter = nullptr; - Label *group_empty; + Label *group_empty = nullptr; - Button *add_button; - Button *remove_button; + Button *add_button = nullptr; + Button *remove_button = nullptr; String selected_group; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; void _group_selected(); @@ -111,15 +111,15 @@ public: class GroupsEditor : public VBoxContainer { GDCLASS(GroupsEditor, VBoxContainer); - Node *node; + Node *node = nullptr; - GroupDialog *group_dialog; + GroupDialog *group_dialog = nullptr; - LineEdit *group_name; - Button *add; - Tree *tree; + LineEdit *group_name = nullptr; + Button *add = nullptr; + Tree *tree = nullptr; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; void update_tree(); void _add_group(const String &p_group = ""); diff --git a/editor/icons/AnimationLibrary.svg b/editor/icons/AnimationLibrary.svg new file mode 100644 index 0000000000..0bac67d302 --- /dev/null +++ b/editor/icons/AnimationLibrary.svg @@ -0,0 +1 @@ +<svg height="16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="M14.519 2.006A6 6 0 0 0 8.599 8a6 6 0 0 0 5.92 5.994v-1.01a1 1 0 0 1-.92-.984 1 1 0 0 1 .92-.984V4.984a1 1 0 0 1-.92-.984 1 1 0 0 1 .92-.984Zm-3.432 2.996a1 1 0 0 1 .547.133 1 1 0 0 1 .367 1.365 1 1 0 0 1-1.367.365A1 1 0 0 1 10.27 5.5a1 1 0 0 1 .818-.498ZM11.111 9a1 1 0 0 1 .89.5 1 1 0 0 1-.367 1.365 1 1 0 0 1-1.365-.365 1 1 0 0 1 .365-1.365A1 1 0 0 1 11.111 9Z" style="fill:#e0e0e0;fill-opacity:1"/><path d="M11.094 2.104a6 6 0 0 0-5.92 5.994 6 6 0 0 0 5.92 5.994v-.023a5.795 6.506 0 0 1-2.89-3.104 1 1 0 0 1-1.36-.367 1 1 0 0 1 .365-1.365 1 1 0 0 1 .475-.135 5.795 6.506 0 0 1-.076-.984 5.795 6.506 0 0 1 .082-1.027 1 1 0 0 1-.48-.124 1 1 0 0 1-.366-1.365 1 1 0 0 1 .818-.498 1 1 0 0 1 .547.133 1 1 0 0 1 .004.002 5.795 6.506 0 0 1 2.881-3.076z" style="fill:#e0e0e0;fill-opacity:1"/><path d="M7.616 2.104a6 6 0 0 0-5.92 5.994 6 6 0 0 0 5.92 5.994v-.023a5.795 6.506 0 0 1-2.89-3.104 1 1 0 0 1-1.36-.367 1 1 0 0 1 .366-1.365 1 1 0 0 1 .474-.135 5.795 6.506 0 0 1-.076-.984 5.795 6.506 0 0 1 .082-1.027 1 1 0 0 1-.48-.124 1 1 0 0 1-.366-1.365 1 1 0 0 1 .819-.498 1 1 0 0 1 .547.133 1 1 0 0 1 .003.002 5.795 6.506 0 0 1 2.881-3.076z" style="fill:#e0e0e0;fill-opacity:1"/></svg> diff --git a/editor/icons/ArrayOccluder3D.svg b/editor/icons/ArrayOccluder3D.svg new file mode 100644 index 0000000000..ac45821897 --- /dev/null +++ b/editor/icons/ArrayOccluder3D.svg @@ -0,0 +1 @@ +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m13 1c-1.104569 0-2 .8954305-2 2s.895431 2 2 2 2-.8954305 2-2-.895431-2-2-2zm-2 7v3h-3v2h3v3h2v-3h3v-2h-3v-3zm-8 3c-1.1045695 0-2 .895431-2 2s.8954305 2 2 2 2-.895431 2-2-.8954305-2-2-2z" fill="#ffca5f"/></svg> diff --git a/editor/icons/BoxOccluder3D.svg b/editor/icons/BoxOccluder3D.svg new file mode 100644 index 0000000000..3cee3db532 --- /dev/null +++ b/editor/icons/BoxOccluder3D.svg @@ -0,0 +1 @@ +<svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="m8 .88867188-.5058594.25390622a4.5 4.5 0 0 1 1.3789063 2.2988281l3.0664061 1.5332032-3.5546874 1.7753906a4.5 4.5 0 0 1 -1.6796875 1.6601562l.2949219.1464844v3.9414064l-4-2.001953v-1.7636721a4.5 4.5 0 0 1 -2-1.4179688v4.2968749l7 3.5 7-3.5v-7.2226561zm5 5.66796872v3.9394534l-4 2.001953v-3.9414064z"/><path d="m8 .88867188-.5058594.25390622a4.5 4.5 0 0 1 1.5058594 3.3574219 4.5 4.5 0 0 1 -4.5 4.5 4.5 4.5 0 0 1 -3.5-1.6855469v4.2968749l7 3.5 7-3.5v-7.2226561z" fill="#ffca5f"/></svg> diff --git a/editor/icons/GuiVsplitBg.svg b/editor/icons/GuiVsplitBg.svg deleted file mode 100644 index 9844fc2018..0000000000 --- a/editor/icons/GuiVsplitBg.svg +++ /dev/null @@ -1 +0,0 @@ -<svg height="8" viewBox="0 0 8 7.9999995" width="8" xmlns="http://www.w3.org/2000/svg"><path d="m0 0h8v8h-8z" fill-opacity=".098039"/></svg> diff --git a/editor/icons/Occluder3D.svg b/editor/icons/Occluder3D.svg index 850e2651af..c91a77781b 100644 --- a/editor/icons/Occluder3D.svg +++ b/editor/icons/Occluder3D.svg @@ -1 +1 @@ -<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7.90625 1a7 7 0 0 0 -1.2988281.1386719 4.5 4.5 0 0 1 3.3925781 4.3613281 4.5 4.5 0 0 1 -4.5 4.5 4.5 4.5 0 0 1 -4.359375-3.3886719 7 7 0 0 0 -.140625 1.3886719 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0 -7-7 7 7 0 0 0 -.09375 0z" fill="#ffca5f" stroke-width=".365215"/></svg> +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m13 1a2 2 0 0 0 -1.730469 1h-3.0273435a4.5 4.5 0 0 1 .7285156 2h2.3007809a2 2 0 0 0 .728516.7304688v5.8554692l-3.6933594-3.6933599a4.5 4.5 0 0 1 -1.4140625 1.4140625l3.6933599 3.6933594h-5.8574224a2 2 0 0 0 -.7285156-.730469v-2.3046872a4.5 4.5 0 0 1 -2-.7285157v3.0351559a2 2 0 0 0 -1 1.728516 2 2 0 0 0 2 2 2 2 0 0 0 1.7304688-1h6.5410152a2 2 0 0 0 1.728516 1 2 2 0 0 0 2-2 2 2 0 0 0 -1.03125-1.75h.03125v-6.5214844a2 2 0 0 0 1-1.7285156 2 2 0 0 0 -2-2z" fill="#ffca5f"/></svg> diff --git a/editor/icons/PolygonOccluder3D.svg b/editor/icons/PolygonOccluder3D.svg new file mode 100644 index 0000000000..fc87e5e086 --- /dev/null +++ b/editor/icons/PolygonOccluder3D.svg @@ -0,0 +1 @@ +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><g fill="#ffca5f" stroke-linejoin="round"><path d="m8.2421875 2a4.5 4.5 0 0 1 .7578125 2.5 4.5 4.5 0 0 1 -4.5 4.5 4.5 4.5 0 0 1 -2.5-.7636719v5.7636719h12l-6-6 6-6z" stroke-width="2"/><path d="m7.328125 1c.6472144.5230929 1.136703 1.2154082 1.4140625 2h2.8437505l-2.7675786 2.767578c-.2943505.9927946-.9220914 1.8536963-1.7773438 2.4375.0343146.1879491.1217471.3621363.2519532.501953l4.2929692 4.292969h-8.585938v-4.267578c-.785054-.2784421-1.4774185-.7693178-2-1.417969v6.685547c.0000552.552262.4477381.999945 1 1h12c.890637-.00035 1.336587-1.077036.707031-1.707031l-5.2929685-5.292969 5.2929685-5.292969c.629556-.6299945.183606-1.7066812-.707031-1.707031z"/></g></svg> diff --git a/editor/icons/QuadOccluder3D.svg b/editor/icons/QuadOccluder3D.svg new file mode 100644 index 0000000000..16da6f420f --- /dev/null +++ b/editor/icons/QuadOccluder3D.svg @@ -0,0 +1 @@ +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7.328125 1c.6472144.5230929 1.136703 1.2154082 1.4140625 2h4.2578125v8.585938l-4.6933594-4.6933599c-.3593282.5714479-.8426146 1.0547343-1.4140625 1.4140625l4.6933599 4.6933594h-8.585938v-4.2675781c-.785054-.2784421-1.4774185-.7693176-2-1.4179688v7.6855469h14v-14z" fill="#ffca5f"/></svg> diff --git a/editor/icons/SphereOccluder3D.svg b/editor/icons/SphereOccluder3D.svg new file mode 100644 index 0000000000..850e2651af --- /dev/null +++ b/editor/icons/SphereOccluder3D.svg @@ -0,0 +1 @@ +<svg height="16" viewBox="0 0 16 16" width="16" xmlns="http://www.w3.org/2000/svg"><path d="m7.90625 1a7 7 0 0 0 -1.2988281.1386719 4.5 4.5 0 0 1 3.3925781 4.3613281 4.5 4.5 0 0 1 -4.5 4.5 4.5 4.5 0 0 1 -4.359375-3.3886719 7 7 0 0 0 -.140625 1.3886719 7 7 0 0 0 7 7 7 7 0 0 0 7-7 7 7 0 0 0 -7-7 7 7 0 0 0 -.09375 0z" fill="#ffca5f" stroke-width=".365215"/></svg> diff --git a/editor/import/dynamic_font_import_settings.h b/editor/import/dynamic_font_import_settings.h index 7b2a9184a4..c1e868403f 100644 --- a/editor/import/dynamic_font_import_settings.h +++ b/editor/import/dynamic_font_import_settings.h @@ -66,7 +66,7 @@ class DynamicFontImportSettings : public ConfirmationDialog { List<ResourceImporter::ImportOption> options_variations; List<ResourceImporter::ImportOption> options_general; - EditorLocaleDialog *locale_select; + EditorLocaleDialog *locale_select = nullptr; Vector<String> script_codes; // Root layout diff --git a/editor/import/editor_import_collada.cpp b/editor/import/editor_import_collada.cpp index 69fa64c24c..013dcb5deb 100644 --- a/editor/import/editor_import_collada.cpp +++ b/editor/import/editor_import_collada.cpp @@ -1801,7 +1801,14 @@ Node *EditorSceneFormatImporterCollada::import_scene(const String &p_path, uint3 name = state.animations[i]->get_name(); } - ap->add_animation(name, state.animations[i]); + Ref<AnimationLibrary> library; + if (!ap->has_animation_library("")) { + library.instantiate(); + ap->add_animation_library("", library); + } else { + library = ap->get_animation_library(""); + } + library->add_animation(name, state.animations[i]); } state.scene->add_child(ap, true); ap->set_owner(state.scene); @@ -1810,26 +1817,5 @@ Node *EditorSceneFormatImporterCollada::import_scene(const String &p_path, uint3 return state.scene; } -Ref<Animation> EditorSceneFormatImporterCollada::import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) { - ColladaImport state; - - state.use_mesh_builtin_materials = false; - - Error err = state.load(p_path, Collada::IMPORT_FLAG_ANIMATION, p_flags & EditorSceneFormatImporter::IMPORT_GENERATE_TANGENT_ARRAYS); - ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load animation from file '" + p_path + "'."); - - state.create_animations(true); - if (state.scene) { - memdelete(state.scene); - } - - if (state.animations.size() == 0) { - return Ref<Animation>(); - } - Ref<Animation> anim = state.animations[0]; - - return anim; -} - EditorSceneFormatImporterCollada::EditorSceneFormatImporterCollada() { } diff --git a/editor/import/editor_import_collada.h b/editor/import/editor_import_collada.h index c32d785d1c..be3f74d821 100644 --- a/editor/import/editor_import_collada.h +++ b/editor/import/editor_import_collada.h @@ -40,7 +40,6 @@ public: virtual uint32_t get_import_flags() const override; virtual void get_extensions(List<String> *r_extensions) const override; virtual Node *import_scene(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps, List<String> *r_missing_deps = nullptr, Error *r_err = nullptr) override; - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) override; EditorSceneFormatImporterCollada(); }; diff --git a/editor/import/resource_importer_csv_translation.cpp b/editor/import/resource_importer_csv_translation.cpp index f0ee14bdcb..ee6500a643 100644 --- a/editor/import/resource_importer_csv_translation.cpp +++ b/editor/import/resource_importer_csv_translation.cpp @@ -88,9 +88,8 @@ Error ResourceImporterCSVTranslation::import(const String &p_source_file, const break; } - FileAccessRef f = FileAccess::open(p_source_file, FileAccess::READ); - - ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open file from path '" + p_source_file + "'."); + Ref<FileAccess> f = FileAccess::open(p_source_file, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot open file from path '" + p_source_file + "'."); Vector<String> line = f->get_csv_line(delimiter); ERR_FAIL_COND_V(line.size() <= 1, ERR_PARSE_ERROR); diff --git a/editor/import/resource_importer_image.cpp b/editor/import/resource_importer_image.cpp index e6a822d827..8514df76bb 100644 --- a/editor/import/resource_importer_image.cpp +++ b/editor/import/resource_importer_image.cpp @@ -71,10 +71,9 @@ void ResourceImporterImage::get_import_options(const String &p_path, List<Import } Error ResourceImporterImage::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) { - FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ); - - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot open file from path '" + p_source_file + "'."); + Ref<FileAccess> f = FileAccess::open(p_source_file, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, "Cannot open file from path '" + p_source_file + "'."); uint64_t len = f->get_length(); Vector<uint8_t> data; @@ -82,10 +81,8 @@ Error ResourceImporterImage::import(const String &p_source_file, const String &p f->get_buffer(data.ptrw(), len); - memdelete(f); - f = FileAccess::open(p_save_path + ".image", FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_CREATE, "Cannot create file in path '" + p_save_path + ".image'."); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_CREATE, "Cannot create file in path '" + p_save_path + ".image'."); //save the header GDIM const uint8_t header[4] = { 'G', 'D', 'I', 'M' }; @@ -95,8 +92,6 @@ Error ResourceImporterImage::import(const String &p_source_file, const String &p //SAVE the actual image f->store_buffer(data.ptr(), len); - memdelete(f); - return OK; } diff --git a/editor/import/resource_importer_layered_texture.cpp b/editor/import/resource_importer_layered_texture.cpp index 9ddee9c058..7c0c99cd29 100644 --- a/editor/import/resource_importer_layered_texture.cpp +++ b/editor/import/resource_importer_layered_texture.cpp @@ -257,7 +257,7 @@ void ResourceImporterLayeredTexture::_save_tex(Vector<Ref<Image>> p_images, cons } } - FileAccessRef f = FileAccess::open(p_to_path, FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open(p_to_path, FileAccess::WRITE); f->store_8('G'); f->store_8('S'); f->store_8('T'); @@ -280,8 +280,6 @@ void ResourceImporterLayeredTexture::_save_tex(Vector<Ref<Image>> p_images, cons for (int i = 0; i < mipmap_images.size(); i++) { ResourceImporterTexture::save_to_ctex_format(f, mipmap_images[i], ResourceImporterTexture::CompressMode(p_compress_mode), used_channels, p_vram_compression, p_lossy); } - - f->close(); } Error ResourceImporterLayeredTexture::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) { diff --git a/editor/import/resource_importer_obj.cpp b/editor/import/resource_importer_obj.cpp index 9042f1e32c..88837d089a 100644 --- a/editor/import/resource_importer_obj.cpp +++ b/editor/import/resource_importer_obj.cpp @@ -44,8 +44,8 @@ uint32_t EditorOBJImporter::get_import_flags() const { } static Error _parse_material_library(const String &p_path, Map<String, Ref<StandardMaterial3D>> &material_map, List<String> *r_missing_deps) { - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path)); Ref<StandardMaterial3D> current; String current_name; @@ -203,8 +203,8 @@ static Error _parse_material_library(const String &p_path, Map<String, Ref<Stand } static Error _parse_obj(const String &p_path, List<Ref<Mesh>> &r_meshes, bool p_single_mesh, bool p_generate_tangents, bool p_optimize, Vector3 p_scale_mesh, Vector3 p_offset_mesh, List<String> *r_missing_deps) { - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path)); Ref<ArrayMesh> mesh; mesh.instantiate(); @@ -457,10 +457,6 @@ Node *EditorOBJImporter::import_scene(const String &p_path, uint32_t p_flags, co return scene; } -Ref<Animation> EditorOBJImporter::import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) { - return Ref<Animation>(); -} - void EditorOBJImporter::get_extensions(List<String> *r_extensions) const { r_extensions->push_back("obj"); } diff --git a/editor/import/resource_importer_obj.h b/editor/import/resource_importer_obj.h index d7e3f0209d..1b5e8bbdc1 100644 --- a/editor/import/resource_importer_obj.h +++ b/editor/import/resource_importer_obj.h @@ -40,7 +40,6 @@ public: virtual uint32_t get_import_flags() const override; virtual void get_extensions(List<String> *r_extensions) const override; virtual Node *import_scene(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr) override; - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) override; EditorOBJImporter(); }; diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp index e7c605aaf0..bdb0c3c493 100644 --- a/editor/import/resource_importer_scene.cpp +++ b/editor/import/resource_importer_scene.cpp @@ -87,26 +87,13 @@ Node *EditorSceneFormatImporter::import_scene(const String &p_path, uint32_t p_f ERR_FAIL_V(nullptr); } -Ref<Animation> EditorSceneFormatImporter::import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) { - Dictionary options_dict; - for (const KeyValue<StringName, Variant> &elem : p_options) { - options_dict[elem.key] = elem.value; - } - Ref<Animation> ret; - if (GDVIRTUAL_CALL(_import_animation, p_path, p_flags, options_dict, p_bake_fps, ret)) { - return ret; - } - - ERR_FAIL_V(nullptr); -} - void EditorSceneFormatImporter::get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options) { GDVIRTUAL_CALL(_get_import_options, p_path); } -Variant EditorSceneFormatImporter::get_option_visibility(const String &p_path, const String &p_option, const Map<StringName, Variant> &p_options) { +Variant EditorSceneFormatImporter::get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) { Variant ret; - GDVIRTUAL_CALL(_get_option_visibility, p_path, p_option, ret); + GDVIRTUAL_CALL(_get_option_visibility, p_path, p_for_animation, p_option, ret); return ret; } @@ -114,15 +101,15 @@ void EditorSceneFormatImporter::_bind_methods() { GDVIRTUAL_BIND(_get_import_flags); GDVIRTUAL_BIND(_get_extensions); GDVIRTUAL_BIND(_import_scene, "path", "flags", "options", "bake_fps"); - GDVIRTUAL_BIND(_import_animation, "path", "flags", "options", "bake_fps"); GDVIRTUAL_BIND(_get_import_options, "path"); - GDVIRTUAL_BIND(_get_option_visibility, "path", "option"); + GDVIRTUAL_BIND(_get_option_visibility, "path", "for_animation", "option"); BIND_CONSTANT(IMPORT_SCENE); BIND_CONSTANT(IMPORT_ANIMATION); BIND_CONSTANT(IMPORT_FAIL_ON_MISSING_DEPENDENCIES); BIND_CONSTANT(IMPORT_GENERATE_TANGENT_ARRAYS); BIND_CONSTANT(IMPORT_USE_NAMED_SKIN_BINDS); + BIND_CONSTANT(IMPORT_DISCARD_MESHES_AND_MATERIALS); } ///////////////////////////////// @@ -179,10 +166,10 @@ void EditorScenePostImportPlugin::get_internal_import_options(InternalImportCate GDVIRTUAL_CALL(_get_internal_import_options, p_category); current_option_list = nullptr; } -Variant EditorScenePostImportPlugin::get_internal_option_visibility(InternalImportCategory p_category, const String &p_option, const Map<StringName, Variant> &p_options) const { +Variant EditorScenePostImportPlugin::get_internal_option_visibility(InternalImportCategory p_category, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) const { current_options = &p_options; Variant ret; - GDVIRTUAL_CALL(_get_internal_option_visibility, p_category, p_option, ret); + GDVIRTUAL_CALL(_get_internal_option_visibility, p_category, p_for_animation, p_option, ret); current_options = nullptr; return ret; } @@ -205,10 +192,10 @@ void EditorScenePostImportPlugin::get_import_options(const String &p_path, List< GDVIRTUAL_CALL(_get_import_options, p_path); current_option_list = nullptr; } -Variant EditorScenePostImportPlugin::get_option_visibility(const String &p_path, const String &p_option, const Map<StringName, Variant> &p_options) const { +Variant EditorScenePostImportPlugin::get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) const { current_options = &p_options; Variant ret; - GDVIRTUAL_CALL(_get_option_visibility, p_path, p_option, ret); + GDVIRTUAL_CALL(_get_option_visibility, p_path, p_for_animation, p_option, ret); current_options = nullptr; return ret; } @@ -231,11 +218,11 @@ void EditorScenePostImportPlugin::_bind_methods() { ClassDB::bind_method(D_METHOD("add_import_option_advanced", "type", "name", "default_value", "hint", "hint_string", "usage_flags"), &EditorScenePostImportPlugin::add_import_option_advanced, DEFVAL(PROPERTY_HINT_NONE), DEFVAL(""), DEFVAL(PROPERTY_USAGE_DEFAULT)); GDVIRTUAL_BIND(_get_internal_import_options, "category"); - GDVIRTUAL_BIND(_get_internal_option_visibility, "category", "option"); + GDVIRTUAL_BIND(_get_internal_option_visibility, "category", "for_animation", "option"); GDVIRTUAL_BIND(_get_internal_option_update_view_required, "category", "option"); GDVIRTUAL_BIND(_internal_process, "category", "base_node", "node", "resource"); GDVIRTUAL_BIND(_get_import_options, "path"); - GDVIRTUAL_BIND(_get_option_visibility, "path", "option"); + GDVIRTUAL_BIND(_get_option_visibility, "path", "for_animation", "option"); GDVIRTUAL_BIND(_pre_process, "scene"); GDVIRTUAL_BIND(_post_process, "scene"); @@ -251,11 +238,11 @@ void EditorScenePostImportPlugin::_bind_methods() { ///////////////////////////////////////////////////////// String ResourceImporterScene::get_importer_name() const { - return "scene"; + return animation_importer ? "animation_library" : "scene"; } String ResourceImporterScene::get_visible_name() const { - return "Scene"; + return animation_importer ? "Animation Library" : "Scene"; } void ResourceImporterScene::get_recognized_extensions(List<String> *p_extensions) const { @@ -265,11 +252,11 @@ void ResourceImporterScene::get_recognized_extensions(List<String> *p_extensions } String ResourceImporterScene::get_save_extension() const { - return "scn"; + return animation_importer ? "res" : "scn"; } String ResourceImporterScene::get_resource_type() const { - return "PackedScene"; + return animation_importer ? "AnimationLibrary" : "PackedScene"; } int ResourceImporterScene::get_format_version() const { @@ -277,26 +264,34 @@ int ResourceImporterScene::get_format_version() const { } bool ResourceImporterScene::get_option_visibility(const String &p_path, const String &p_option, const Map<StringName, Variant> &p_options) const { - if (p_option.begins_with("animation/")) { + if (animation_importer) { + if (p_option == "animation/import") { // Option ignored, animation always imported. + return false; + } + } else if (p_option.begins_with("animation/")) { if (p_option != "animation/import" && !bool(p_options["animation/import"])) { return false; } } + if (animation_importer && (p_option.begins_with("nodes/") || p_option.begins_with("meshes/") || p_option.begins_with("skins/"))) { + return false; // Nothing to do here for animations. + } + if (p_option == "meshes/lightmap_texel_size" && int(p_options["meshes/light_baking"]) != 2) { // Only display the lightmap texel size import option when using the Static Lightmaps light baking mode. return false; } for (int i = 0; i < post_importer_plugins.size(); i++) { - Variant ret = post_importer_plugins.write[i]->get_option_visibility(p_path, p_option, p_options); + Variant ret = post_importer_plugins.write[i]->get_option_visibility(p_path, animation_importer, p_option, p_options); if (ret.get_type() == Variant::BOOL) { return ret; } } for (Ref<EditorSceneFormatImporter> importer : importers) { - Variant ret = importer->get_option_visibility(p_path, p_option, p_options); + Variant ret = importer->get_option_visibility(p_path, animation_importer, p_option, p_options); if (ret.get_type() == Variant::BOOL) { return ret; } @@ -473,7 +468,9 @@ Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, Map<Ref<I if (_teststr(animname, loop_strings[i])) { anim->set_loop_mode(Animation::LoopMode::LOOP_LINEAR); animname = _fixstr(animname, loop_strings[i]); - ap->rename_animation(E, animname); + + Ref<AnimationLibrary> library = ap->get_animation_library(ap->find_animation_library(anim)); + library->rename_animation(E, animname); } } } @@ -1019,7 +1016,8 @@ Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, Map<Ref< Ref<Animation> saved_anim = _save_animation_to_file(anim, save, path, keep_custom); if (saved_anim != anim) { - ap->add_animation(name, saved_anim); //replace + Ref<AnimationLibrary> al = ap->get_animation_library(ap->find_animation_library(anim)); + al->add_animation(name, saved_anim); //replace } } } @@ -1109,6 +1107,7 @@ void ResourceImporterScene::_create_clips(AnimationPlayer *anim, const Array &p_ } Ref<Animation> default_anim = anim->get_animation("default"); + Ref<AnimationLibrary> al = anim->get_animation_library(anim->find_animation(default_anim)); for (int i = 0; i < p_clips.size(); i += 7) { String name = p_clips[i]; @@ -1246,15 +1245,16 @@ void ResourceImporterScene::_create_clips(AnimationPlayer *anim, const Array &p_ new_anim->set_loop_mode(loop_mode); new_anim->set_length(to - from); - anim->add_animation(name, new_anim); + + al->add_animation(name, new_anim); Ref<Animation> saved_anim = _save_animation_to_file(new_anim, save_to_file, save_to_path, keep_current); if (saved_anim != new_anim) { - anim->add_animation(name, saved_anim); + al->add_animation(name, saved_anim); } } - anim->remove_animation("default"); //remove default (no longer needed) + al->remove_animation("default"); // Remove default (no longer needed). } void ResourceImporterScene::_optimize_animations(AnimationPlayer *anim, float p_max_lin_error, float p_max_ang_error, float p_max_angle) { @@ -1477,7 +1477,7 @@ bool ResourceImporterScene::get_internal_option_visibility(InternalImportCategor } for (int i = 0; i < post_importer_plugins.size(); i++) { - Variant ret = post_importer_plugins.write[i]->get_internal_option_visibility(EditorScenePostImportPlugin::InternalImportCategory(p_category), p_option, p_options); + Variant ret = post_importer_plugins.write[i]->get_internal_option_visibility(EditorScenePostImportPlugin::InternalImportCategory(p_category), animation_importer, p_option, p_options); if (ret.get_type() == Variant::BOOL) { return ret; } @@ -1969,8 +1969,13 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p int import_flags = 0; - if (bool(p_options["animation/import"])) { + if (animation_importer) { import_flags |= EditorSceneFormatImporter::IMPORT_ANIMATION; + import_flags |= EditorSceneFormatImporter::IMPORT_DISCARD_MESHES_AND_MATERIALS; + } else { + if (bool(p_options["animation/import"])) { + import_flags |= EditorSceneFormatImporter::IMPORT_ANIMATION; + } } if (bool(p_options["skins/use_named_skins"])) { @@ -2086,14 +2091,13 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p _generate_meshes(scene, mesh_data, gen_lods, create_shadow_meshes, LightBakeMode(light_bake_mode), lightmap_texel_size, src_lightmap_cache, mesh_lightmap_caches); if (mesh_lightmap_caches.size()) { - FileAccessRef f = FileAccess::open(p_source_file + ".unwrap_cache", FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(p_source_file + ".unwrap_cache", FileAccess::WRITE); + if (f.is_valid()) { f->store_32(mesh_lightmap_caches.size()); for (int i = 0; i < mesh_lightmap_caches.size(); i++) { String md5 = String::md5(mesh_lightmap_caches[i].ptr()); f->store_buffer(mesh_lightmap_caches[i].ptr(), mesh_lightmap_caches[i].size()); } - f->close(); } } err = OK; @@ -2135,11 +2139,35 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p progress.step(TTR("Saving..."), 104); - Ref<PackedScene> packer = memnew(PackedScene); - packer->pack(scene); - print_verbose("Saving scene to: " + p_save_path + ".scn"); - err = ResourceSaver::save(p_save_path + ".scn", packer); //do not take over, let the changed files reload themselves - ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save scene to file '" + p_save_path + ".scn'."); + if (animation_importer) { + Ref<AnimationLibrary> library; + for (int i = 0; i < scene->get_child_count(); i++) { + AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(scene->get_child(i)); + if (ap) { + List<StringName> libs; + ap->get_animation_library_list(&libs); + if (libs.size()) { + library = ap->get_animation_library(libs.front()->get()); + break; + } + } + } + + if (!library.is_valid()) { + library.instantiate(); // Will be empty + } + + print_verbose("Saving animation to: " + p_save_path + ".scn"); + err = ResourceSaver::save(p_save_path + ".res", library); //do not take over, let the changed files reload themselves + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save animation to file '" + p_save_path + ".res'."); + + } else { + Ref<PackedScene> packer = memnew(PackedScene); + packer->pack(scene); + print_verbose("Saving scene to: " + p_save_path + ".scn"); + err = ResourceSaver::save(p_save_path + ".scn", packer); //do not take over, let the changed files reload themselves + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save scene to file '" + p_save_path + ".scn'."); + } memdelete(scene); @@ -2149,17 +2177,26 @@ Error ResourceImporterScene::import(const String &p_source_file, const String &p return OK; } -ResourceImporterScene *ResourceImporterScene::singleton = nullptr; +ResourceImporterScene *ResourceImporterScene::scene_singleton = nullptr; +ResourceImporterScene *ResourceImporterScene::animation_singleton = nullptr; + +Vector<Ref<EditorSceneFormatImporter>> ResourceImporterScene::importers; +Vector<Ref<EditorScenePostImportPlugin>> ResourceImporterScene::post_importer_plugins; bool ResourceImporterScene::ResourceImporterScene::has_advanced_options() const { return true; } void ResourceImporterScene::ResourceImporterScene::show_advanced_options(const String &p_path) { - SceneImportSettings::get_singleton()->open_settings(p_path); + SceneImportSettings::get_singleton()->open_settings(p_path, animation_importer); } -ResourceImporterScene::ResourceImporterScene() { - singleton = this; +ResourceImporterScene::ResourceImporterScene(bool p_animation_import) { + if (p_animation_import) { + animation_singleton = this; + } else { + scene_singleton = this; + } + animation_importer = p_animation_import; } void ResourceImporterScene::add_importer(Ref<EditorSceneFormatImporter> p_importer, bool p_first_priority) { @@ -2188,6 +2225,11 @@ void ResourceImporterScene::remove_importer(Ref<EditorSceneFormatImporter> p_imp importers.erase(p_importer); } +void ResourceImporterScene::clean_up_importer_plugins() { + importers.clear(); + post_importer_plugins.clear(); +} + /////////////////////////////////////// uint32_t EditorSceneFormatImporterESCN::get_import_flags() const { @@ -2208,7 +2250,3 @@ Node *EditorSceneFormatImporterESCN::import_scene(const String &p_path, uint32_t return scene; } - -Ref<Animation> EditorSceneFormatImporterESCN::import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) { - ERR_FAIL_V(Ref<Animation>()); -} diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h index a819be682d..368f68ae8f 100644 --- a/editor/import/resource_importer_scene.h +++ b/editor/import/resource_importer_scene.h @@ -56,9 +56,8 @@ protected: GDVIRTUAL0RC(int, _get_import_flags) GDVIRTUAL0RC(Vector<String>, _get_extensions) GDVIRTUAL4R(Object *, _import_scene, String, uint32_t, Dictionary, uint32_t) - GDVIRTUAL4R(Ref<Animation>, _import_animation, String, uint32_t, Dictionary, uint32_t) GDVIRTUAL1(_get_import_options, String) - GDVIRTUAL2RC(Variant, _get_option_visibility, String, String) + GDVIRTUAL3RC(Variant, _get_option_visibility, String, bool, String) public: enum ImportFlags { @@ -67,14 +66,14 @@ public: IMPORT_FAIL_ON_MISSING_DEPENDENCIES = 4, IMPORT_GENERATE_TANGENT_ARRAYS = 8, IMPORT_USE_NAMED_SKIN_BINDS = 16, + IMPORT_DISCARD_MESHES_AND_MATERIALS = 32, //used for optimizing animation import }; virtual uint32_t get_import_flags() const; virtual void get_extensions(List<String> *r_extensions) const; virtual Node *import_scene(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr); - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps); virtual void get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options); - virtual Variant get_option_visibility(const String &p_path, const String &p_option, const Map<StringName, Variant> &p_options); + virtual Variant get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options); EditorSceneFormatImporter() {} }; @@ -118,11 +117,11 @@ private: protected: GDVIRTUAL1(_get_internal_import_options, int) - GDVIRTUAL2RC(Variant, _get_internal_option_visibility, int, String) + GDVIRTUAL3RC(Variant, _get_internal_option_visibility, int, bool, String) GDVIRTUAL2RC(Variant, _get_internal_option_update_view_required, int, String) GDVIRTUAL4(_internal_process, int, Node *, Node *, RES) GDVIRTUAL1(_get_import_options, String) - GDVIRTUAL2RC(Variant, _get_option_visibility, String, String) + GDVIRTUAL3RC(Variant, _get_option_visibility, String, bool, String) GDVIRTUAL1(_pre_process, Node *) GDVIRTUAL1(_post_process, Node *) @@ -134,13 +133,13 @@ public: void add_import_option_advanced(Variant::Type p_type, const String &p_name, Variant p_default_value, PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_string = String(), int p_usage_flags = PROPERTY_USAGE_DEFAULT); virtual void get_internal_import_options(InternalImportCategory p_category, List<ResourceImporter::ImportOption> *r_options); - virtual Variant get_internal_option_visibility(InternalImportCategory p_category, const String &p_option, const Map<StringName, Variant> &p_options) const; + virtual Variant get_internal_option_visibility(InternalImportCategory p_category, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) const; virtual Variant get_internal_option_update_view_required(InternalImportCategory p_category, const String &p_option, const Map<StringName, Variant> &p_options) const; virtual void internal_process(InternalImportCategory p_category, Node *p_base_scene, Node *p_node, RES p_resource, const Dictionary &p_options); virtual void get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options); - virtual Variant get_option_visibility(const String &p_path, const String &p_option, const Map<StringName, Variant> &p_options) const; + virtual Variant get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) const; virtual void pre_process(Node *p_scene, const Map<StringName, Variant> &p_options); virtual void post_process(Node *p_scene, const Map<StringName, Variant> &p_options); @@ -153,9 +152,11 @@ VARIANT_ENUM_CAST(EditorScenePostImportPlugin::InternalImportCategory) class ResourceImporterScene : public ResourceImporter { GDCLASS(ResourceImporterScene, ResourceImporter); - Vector<Ref<EditorSceneFormatImporter>> importers; + static Vector<Ref<EditorSceneFormatImporter>> importers; + static Vector<Ref<EditorScenePostImportPlugin>> post_importer_plugins; - static ResourceImporterScene *singleton; + static ResourceImporterScene *scene_singleton; + static ResourceImporterScene *animation_singleton; enum LightBakeMode { LIGHT_BAKE_DISABLED, @@ -225,18 +226,21 @@ class ResourceImporterScene : public ResourceImporter { void _optimize_track_usage(AnimationPlayer *p_player, AnimationImportTracks *p_track_actions); - mutable Vector<Ref<EditorScenePostImportPlugin>> post_importer_plugins; + bool animation_importer = false; public: - static ResourceImporterScene *get_singleton() { return singleton; } + static ResourceImporterScene *get_scene_singleton() { return scene_singleton; } + static ResourceImporterScene *get_animation_singleton() { return animation_singleton; } - void add_post_importer_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin, bool p_first_priority = false); - void remove_post_importer_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin); + static void add_post_importer_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin, bool p_first_priority = false); + static void remove_post_importer_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin); const Vector<Ref<EditorSceneFormatImporter>> &get_importers() const { return importers; } - void add_importer(Ref<EditorSceneFormatImporter> p_importer, bool p_first_priority = false); - void remove_importer(Ref<EditorSceneFormatImporter> p_importer); + static void add_importer(Ref<EditorSceneFormatImporter> p_importer, bool p_first_priority = false); + static void remove_importer(Ref<EditorSceneFormatImporter> p_importer); + + static void clean_up_importer_plugins(); virtual String get_importer_name() const override; virtual String get_visible_name() const override; @@ -283,7 +287,7 @@ public: virtual bool can_import_threaded() const override { return false; } - ResourceImporterScene(); + ResourceImporterScene(bool p_animation_import = false); template <class M> static Vector<Ref<Shape3D>> get_collision_shapes(const Ref<Mesh> &p_mesh, const M &p_options); @@ -299,7 +303,6 @@ public: virtual uint32_t get_import_flags() const override; virtual void get_extensions(List<String> *r_extensions) const override; virtual Node *import_scene(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr) override; - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) override; }; #include "scene/resources/box_shape_3d.h" diff --git a/editor/import/resource_importer_shader_file.cpp b/editor/import/resource_importer_shader_file.cpp index cc34259a2d..1d70a47daa 100644 --- a/editor/import/resource_importer_shader_file.cpp +++ b/editor/import/resource_importer_shader_file.cpp @@ -82,7 +82,7 @@ static String _include_function(const String &p_path, void *userpointer) { include = base_path->plus_file(include); } - FileAccessRef file_inc = FileAccess::open(include, FileAccess::READ, &err); + Ref<FileAccess> file_inc = FileAccess::open(include, FileAccess::READ, &err); if (err != OK) { return String(); } @@ -93,7 +93,7 @@ Error ResourceImporterShaderFile::import(const String &p_source_file, const Stri /* STEP 1, Read shader code */ Error err; - FileAccessRef file = FileAccess::open(p_source_file, FileAccess::READ, &err); + Ref<FileAccess> file = FileAccess::open(p_source_file, FileAccess::READ, &err); ERR_FAIL_COND_V(err != OK, ERR_CANT_OPEN); ERR_FAIL_COND_V(!file.operator->(), ERR_CANT_OPEN); diff --git a/editor/import/resource_importer_texture.cpp b/editor/import/resource_importer_texture.cpp index e2fa624fc6..de51a28c5a 100644 --- a/editor/import/resource_importer_texture.cpp +++ b/editor/import/resource_importer_texture.cpp @@ -229,7 +229,7 @@ void ResourceImporterTexture::get_import_options(const String &p_path, List<Impo } } -void ResourceImporterTexture::save_to_ctex_format(FileAccess *f, const Ref<Image> &p_image, CompressMode p_compress_mode, Image::UsedChannels p_channels, Image::CompressMode p_compress_format, float p_lossy_quality) { +void ResourceImporterTexture::save_to_ctex_format(Ref<FileAccess> f, const Ref<Image> &p_image, CompressMode p_compress_mode, Image::UsedChannels p_channels, Image::CompressMode p_compress_format, float p_lossy_quality) { switch (p_compress_mode) { case COMPRESS_LOSSLESS: { bool lossless_force_png = ProjectSettings::get_singleton()->get("rendering/textures/lossless_compression/force_png") || @@ -322,8 +322,8 @@ void ResourceImporterTexture::save_to_ctex_format(FileAccess *f, const Ref<Image } void ResourceImporterTexture::_save_ctex(const Ref<Image> &p_image, const String &p_to_path, CompressMode p_compress_mode, float p_lossy_quality, Image::CompressMode p_vram_compression, bool p_mipmaps, bool p_streamable, bool p_detect_3d, bool p_detect_roughness, bool p_detect_normal, bool p_force_normal, bool p_srgb_friendly, bool p_force_po2_for_compressed, uint32_t p_limit_mipmap, const Ref<Image> &p_normal, Image::RoughnessChannel p_roughness_channel) { - FileAccess *f = FileAccess::open(p_to_path, FileAccess::WRITE); - ERR_FAIL_NULL(f); + Ref<FileAccess> f = FileAccess::open(p_to_path, FileAccess::WRITE); + ERR_FAIL_COND(f.is_null()); f->store_8('G'); f->store_8('S'); f->store_8('T'); @@ -399,8 +399,6 @@ void ResourceImporterTexture::_save_ctex(const Ref<Image> &p_image, const String Image::UsedChannels used_channels = image->detect_used_channels(csource); save_to_ctex_format(f, image, p_compress_mode, used_channels, p_vram_compression, p_lossy_quality); - - memdelete(f); } Error ResourceImporterTexture::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) { diff --git a/editor/import/resource_importer_texture.h b/editor/import/resource_importer_texture.h index b3a68260fc..b932c598a2 100644 --- a/editor/import/resource_importer_texture.h +++ b/editor/import/resource_importer_texture.h @@ -77,7 +77,7 @@ protected: void _save_ctex(const Ref<Image> &p_image, const String &p_to_path, CompressMode p_compress_mode, float p_lossy_quality, Image::CompressMode p_vram_compression, bool p_mipmaps, bool p_streamable, bool p_detect_3d, bool p_detect_srgb, bool p_detect_normal, bool p_force_normal, bool p_srgb_friendly, bool p_force_po2_for_compressed, uint32_t p_limit_mipmap, const Ref<Image> &p_normal, Image::RoughnessChannel p_roughness_channel); public: - static void save_to_ctex_format(FileAccess *f, const Ref<Image> &p_image, CompressMode p_compress_mode, Image::UsedChannels p_channels, Image::CompressMode p_compress_format, float p_lossy_quality); + static void save_to_ctex_format(Ref<FileAccess> f, const Ref<Image> &p_image, CompressMode p_compress_mode, Image::UsedChannels p_channels, Image::CompressMode p_compress_format, float p_lossy_quality); static ResourceImporterTexture *get_singleton() { return singleton; } virtual String get_importer_name() const override; diff --git a/editor/import/resource_importer_wav.cpp b/editor/import/resource_importer_wav.cpp index 68d1d23dd8..154970f7ed 100644 --- a/editor/import/resource_importer_wav.cpp +++ b/editor/import/resource_importer_wav.cpp @@ -97,7 +97,7 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s /* STEP 1, READ WAVE FILE */ Error err; - FileAccess *file = FileAccess::open(p_source_file, FileAccess::READ, &err); + Ref<FileAccess> file = FileAccess::open(p_source_file, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_OPEN, "Cannot open file '" + p_source_file + "'."); @@ -107,8 +107,6 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s file->get_buffer((uint8_t *)&riff, 4); //RIFF if (riff[0] != 'R' || riff[1] != 'I' || riff[2] != 'F' || riff[3] != 'F') { - file->close(); - memdelete(file); ERR_FAIL_V(ERR_FILE_UNRECOGNIZED); } @@ -122,8 +120,6 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s file->get_buffer((uint8_t *)&wave, 4); //RIFF if (wave[0] != 'W' || wave[1] != 'A' || wave[2] != 'V' || wave[3] != 'E') { - file->close(); - memdelete(file); ERR_FAIL_V_MSG(ERR_FILE_UNRECOGNIZED, "Not a WAV file (no WAVE RIFF header)."); } @@ -166,15 +162,11 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s //Consider revision for engine version 3.0 compression_code = file->get_16(); if (compression_code != 1 && compression_code != 3) { - file->close(); - memdelete(file); ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Format not supported for WAVE file (not PCM). Save WAVE files as uncompressed PCM instead."); } format_channels = file->get_16(); if (format_channels != 1 && format_channels != 2) { - file->close(); - memdelete(file); ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Format not supported for WAVE file (not stereo or mono)."); } @@ -185,8 +177,6 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s format_bits = file->get_16(); // bits per sample if (format_bits % 8 || format_bits == 0) { - file->close(); - memdelete(file); ERR_FAIL_V_MSG(ERR_INVALID_DATA, "Invalid amount of bits in the sample (should be one of 8, 16, 24 or 32)."); } @@ -206,8 +196,6 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s frames = chunksize; if (format_channels == 0) { - file->close(); - memdelete(file); ERR_FAIL_COND_V(format_channels == 0, ERR_INVALID_DATA); } frames /= format_channels; @@ -254,8 +242,6 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s } if (file->eof_reached()) { - file->close(); - memdelete(file); ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Premature end of file."); } } @@ -295,9 +281,6 @@ Error ResourceImporterWAV::import(const String &p_source_file, const String &p_s file->seek(file_pos + chunksize); } - file->close(); - memdelete(file); - // STEP 2, APPLY CONVERSIONS bool is16 = format_bits != 8; diff --git a/editor/import/scene_import_settings.cpp b/editor/import/scene_import_settings.cpp index 302bc98499..4e53a644ee 100644 --- a/editor/import/scene_import_settings.cpp +++ b/editor/import/scene_import_settings.cpp @@ -47,6 +47,8 @@ class SceneImportSettingsData : public Object { Map<StringName, Variant> current; Map<StringName, Variant> defaults; List<ResourceImporter::ImportOption> options; + bool hide_options = false; + String path; ResourceImporterScene::InternalImportCategory category = ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX; @@ -60,8 +62,26 @@ class SceneImportSettingsData : public Object { current[p_name] = p_value; - if (ResourceImporterScene::get_singleton()->get_internal_option_update_view_required(category, p_name, current)) { - SceneImportSettings::get_singleton()->update_view(); + if (SceneImportSettings::get_singleton()->is_editing_animation()) { + if (category == ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX) { + if (ResourceImporterScene::get_animation_singleton()->get_option_visibility(path, p_name, current)) { + SceneImportSettings::get_singleton()->update_view(); + } + } else { + if (ResourceImporterScene::get_animation_singleton()->get_internal_option_update_view_required(category, p_name, current)) { + SceneImportSettings::get_singleton()->update_view(); + } + } + } else { + if (category == ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX) { + if (ResourceImporterScene::get_scene_singleton()->get_option_visibility(path, p_name, current)) { + SceneImportSettings::get_singleton()->update_view(); + } + } else { + if (ResourceImporterScene::get_scene_singleton()->get_internal_option_update_view_required(category, p_name, current)) { + SceneImportSettings::get_singleton()->update_view(); + } + } } return true; @@ -82,9 +102,30 @@ class SceneImportSettingsData : public Object { return false; } void _get_property_list(List<PropertyInfo> *p_list) const { + if (hide_options) { + return; + } for (const ResourceImporter::ImportOption &E : options) { - if (ResourceImporterScene::get_singleton()->get_internal_option_visibility(category, E.option.name, current)) { - p_list->push_back(E.option); + if (SceneImportSettings::get_singleton()->is_editing_animation()) { + if (category == ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX) { + if (ResourceImporterScene::get_animation_singleton()->get_option_visibility(path, E.option.name, current)) { + p_list->push_back(E.option); + } + } else { + if (ResourceImporterScene::get_animation_singleton()->get_internal_option_visibility(category, E.option.name, current)) { + p_list->push_back(E.option); + } + } + } else { + if (category == ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX) { + if (ResourceImporterScene::get_scene_singleton()->get_option_visibility(path, E.option.name, current)) { + p_list->push_back(E.option); + } + } else { + if (ResourceImporterScene::get_scene_singleton()->get_internal_option_visibility(category, E.option.name, current)) { + p_list->push_back(E.option); + } + } } } } @@ -326,7 +367,9 @@ void SceneImportSettings::_fill_scene(Node *p_node, TreeItem *p_parent_item) { } MeshInstance3D *mesh_node = Object::cast_to<MeshInstance3D>(p_node); if (mesh_node && mesh_node->get_mesh().is_valid()) { - _fill_mesh(scene_tree, mesh_node->get_mesh(), item); + if (!editing_animation) { + _fill_mesh(scene_tree, mesh_node->get_mesh(), item); + } // Add the collider view. MeshInstance3D *collider_view = memnew(MeshInstance3D); @@ -365,6 +408,9 @@ void SceneImportSettings::_update_scene() { } void SceneImportSettings::_update_view_gizmos() { + if (!is_visible()) { + return; + } for (const KeyValue<String, NodeData> &e : node_map) { bool generate_collider = false; if (e.value.settings.has(SNAME("generate/physics"))) { @@ -378,6 +424,7 @@ void SceneImportSettings::_update_view_gizmos() { } TypedArray<Node> descendants = mesh_node->find_nodes("collider_view", "MeshInstance3D"); + CRASH_COND_MSG(descendants.is_empty(), "This is unreachable, since the collider view is always created even when the collision is not used! If this is triggered there is a bug on the function `_fill_scene`."); MeshInstance3D *collider_view = static_cast<MeshInstance3D *>(descendants[0].operator Object *()); @@ -460,7 +507,11 @@ void SceneImportSettings::_load_default_subresource_settings(Map<StringName, Var if (d.has(p_import_id)) { d = d[p_import_id]; List<ResourceImporterScene::ImportOption> options; - ResourceImporterScene::get_singleton()->get_internal_import_options(p_category, &options); + if (editing_animation) { + ResourceImporterScene::get_animation_singleton()->get_internal_import_options(p_category, &options); + } else { + ResourceImporterScene::get_scene_singleton()->get_internal_import_options(p_category, &options); + } for (const ResourceImporterScene::ImportOption &E : options) { String key = E.option.name; if (d.has(key)) { @@ -472,21 +523,32 @@ void SceneImportSettings::_load_default_subresource_settings(Map<StringName, Var } void SceneImportSettings::update_view() { - _update_view_gizmos(); + update_view_timer->start(); } -void SceneImportSettings::open_settings(const String &p_path) { +void SceneImportSettings::open_settings(const String &p_path, bool p_for_animation) { if (scene) { memdelete(scene); scene = nullptr; } + + editing_animation = p_for_animation; scene_import_settings_data->settings = nullptr; - scene = ResourceImporterScene::get_singleton()->pre_import(p_path); + scene_import_settings_data->path = p_path; + + scene = ResourceImporterScene::get_scene_singleton()->pre_import(p_path); // Use the scene singleton here because we want to see the full thing. if (scene == nullptr) { EditorNode::get_singleton()->show_warning(TTR("Error opening scene")); return; } + // Visibility + data_mode->set_tab_hidden(1, p_for_animation); + data_mode->set_tab_hidden(2, p_for_animation); + + action_menu->get_popup()->set_item_disabled(action_menu->get_popup()->get_item_id(ACTION_EXTRACT_MATERIALS), p_for_animation); + action_menu->get_popup()->set_item_disabled(action_menu->get_popup()->get_item_id(ACTION_CHOOSE_MESH_SAVE_PATHS), p_for_animation); + base_path = p_path; material_set.clear(); @@ -540,7 +602,11 @@ void SceneImportSettings::open_settings(const String &p_path) { _update_view_gizmos(); _update_camera(); - set_title(vformat(TTR("Advanced Import Settings for '%s'"), base_path.get_file())); + if (p_for_animation) { + set_title(vformat(TTR("Advanced Import Settings for AnimationLibrary '%s'"), base_path.get_file())); + } else { + set_title(vformat(TTR("Advanced Import Settings for Scene '%s'"), base_path.get_file())); + } } SceneImportSettings *SceneImportSettings::singleton = nullptr; @@ -551,6 +617,7 @@ SceneImportSettings *SceneImportSettings::get_singleton() { void SceneImportSettings::_select(Tree *p_from, String p_type, String p_id) { selecting = true; + scene_import_settings_data->hide_options = false; if (p_type == "Node") { node_selected->hide(); //always hide just in case @@ -585,10 +652,12 @@ void SceneImportSettings::_select(Tree *p_from, String p_type, String p_id) { scene_import_settings_data->settings = &nd.settings; if (mi) { scene_import_settings_data->category = ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE; + scene_import_settings_data->hide_options = editing_animation; } else if (Object::cast_to<AnimationPlayer>(nd.node)) { scene_import_settings_data->category = ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE; } else { scene_import_settings_data->category = ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_NODE; + scene_import_settings_data->hide_options = editing_animation; } } } else if (p_type == "Animation") { @@ -671,24 +740,36 @@ void SceneImportSettings::_select(Tree *p_from, String p_type, String p_id) { List<ResourceImporter::ImportOption> options; - if (scene_import_settings_data->category == ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX) { - ResourceImporterScene::get_singleton()->get_import_options(base_path, &options); + if (editing_animation) { + if (scene_import_settings_data->category == ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX) { + ResourceImporterScene::get_animation_singleton()->get_import_options(base_path, &options); + } else { + ResourceImporterScene::get_animation_singleton()->get_internal_import_options(scene_import_settings_data->category, &options); + } + } else { - ResourceImporterScene::get_singleton()->get_internal_import_options(scene_import_settings_data->category, &options); + if (scene_import_settings_data->category == ResourceImporterScene::INTERNAL_IMPORT_CATEGORY_MAX) { + ResourceImporterScene::get_scene_singleton()->get_import_options(base_path, &options); + } else { + ResourceImporterScene::get_scene_singleton()->get_internal_import_options(scene_import_settings_data->category, &options); + } } scene_import_settings_data->defaults.clear(); scene_import_settings_data->current.clear(); - for (const ResourceImporter::ImportOption &E : options) { - scene_import_settings_data->defaults[E.option.name] = E.default_value; - //needed for visibility toggling (fails if something is missing) - if (scene_import_settings_data->settings->has(E.option.name)) { - scene_import_settings_data->current[E.option.name] = (*scene_import_settings_data->settings)[E.option.name]; - } else { - scene_import_settings_data->current[E.option.name] = E.default_value; + if (scene_import_settings_data->settings) { + for (const ResourceImporter::ImportOption &E : options) { + scene_import_settings_data->defaults[E.option.name] = E.default_value; + //needed for visibility toggling (fails if something is missing) + if (scene_import_settings_data->settings->has(E.option.name)) { + scene_import_settings_data->current[E.option.name] = (*scene_import_settings_data->settings)[E.option.name]; + } else { + scene_import_settings_data->current[E.option.name] = E.default_value; + } } } + scene_import_settings_data->options = options; inspector->edit(scene_import_settings_data); scene_import_settings_data->notify_property_list_changed(); @@ -836,7 +917,7 @@ void SceneImportSettings::_re_import() { main_settings["_subresources"] = subresources; } - EditorFileSystem::get_singleton()->reimport_file_with_custom_parameters(base_path, "scene", main_settings); + EditorFileSystem::get_singleton()->reimport_file_with_custom_parameters(base_path, editing_animation ? "animation_library" : "scene", main_settings); } void SceneImportSettings::_notification(int p_what) { @@ -1282,6 +1363,11 @@ SceneImportSettings::SceneImportSettings() { item_save_path->connect("file_selected", callable_mp(this, &SceneImportSettings::_save_path_changed)); save_path->connect("dir_selected", callable_mp(this, &SceneImportSettings::_save_dir_callback)); + + update_view_timer = memnew(Timer); + update_view_timer->set_wait_time(0.2); + update_view_timer->connect("timeout", callable_mp(this, &SceneImportSettings::_update_view_gizmos)); + add_child(update_view_timer); } SceneImportSettings::~SceneImportSettings() { diff --git a/editor/import/scene_import_settings.h b/editor/import/scene_import_settings.h index b51f342729..55cfba3275 100644 --- a/editor/import/scene_import_settings.h +++ b/editor/import/scene_import_settings.h @@ -62,26 +62,26 @@ class SceneImportSettings : public ConfirmationDialog { Node *scene = nullptr; - HSplitContainer *tree_split; - HSplitContainer *property_split; - TabContainer *data_mode; - Tree *scene_tree; - Tree *mesh_tree; - Tree *material_tree; + HSplitContainer *tree_split = nullptr; + HSplitContainer *property_split = nullptr; + TabContainer *data_mode = nullptr; + Tree *scene_tree = nullptr; + Tree *mesh_tree = nullptr; + Tree *material_tree = nullptr; - EditorInspector *inspector; + EditorInspector *inspector = nullptr; - SubViewport *base_viewport; + SubViewport *base_viewport = nullptr; - Camera3D *camera; + Camera3D *camera = nullptr; bool first_aabb = false; AABB contents_aabb; - DirectionalLight3D *light; + DirectionalLight3D *light = nullptr; Ref<ArrayMesh> selection_mesh; - MeshInstance3D *node_selected; + MeshInstance3D *node_selected = nullptr; - MeshInstance3D *mesh_preview; + MeshInstance3D *mesh_preview = nullptr; Ref<SphereMesh> material_preview; Ref<StandardMaterial3D> collider_mat; @@ -95,9 +95,9 @@ class SceneImportSettings : public ConfirmationDialog { struct MaterialData { bool has_import_id; Ref<Material> material; - TreeItem *scene_node; - TreeItem *mesh_node; - TreeItem *material_node; + TreeItem *scene_node = nullptr; + TreeItem *mesh_node = nullptr; + TreeItem *material_node = nullptr; float cam_rot_x = -Math_PI / 4; float cam_rot_y = -Math_PI / 4; @@ -110,8 +110,8 @@ class SceneImportSettings : public ConfirmationDialog { struct MeshData { bool has_import_id; Ref<Mesh> mesh; - TreeItem *scene_node; - TreeItem *mesh_node; + TreeItem *scene_node = nullptr; + TreeItem *mesh_node = nullptr; float cam_rot_x = -Math_PI / 4; float cam_rot_y = -Math_PI / 4; @@ -122,14 +122,14 @@ class SceneImportSettings : public ConfirmationDialog { struct AnimationData { Ref<Animation> animation; - TreeItem *scene_node; + TreeItem *scene_node = nullptr; Map<StringName, Variant> settings; }; Map<String, AnimationData> animation_map; struct NodeData { - Node *node; - TreeItem *scene_node; + Node *node = nullptr; + TreeItem *scene_node = nullptr; Map<StringName, Variant> settings; }; Map<String, NodeData> node_map; @@ -158,20 +158,20 @@ class SceneImportSettings : public ConfirmationDialog { Map<StringName, Variant> defaults; - SceneImportSettingsData *scene_import_settings_data; + SceneImportSettingsData *scene_import_settings_data = nullptr; void _re_import(); String base_path; - MenuButton *action_menu; + MenuButton *action_menu = nullptr; - ConfirmationDialog *external_paths; - Tree *external_path_tree; - EditorFileDialog *save_path; - OptionButton *external_extension_type; + ConfirmationDialog *external_paths = nullptr; + Tree *external_path_tree = nullptr; + EditorFileDialog *save_path = nullptr; + OptionButton *external_extension_type = nullptr; - EditorFileDialog *item_save_path; + EditorFileDialog *item_save_path = nullptr; void _menu_callback(int p_id); void _save_dir_callback(const String &p_path); @@ -189,12 +189,17 @@ class SceneImportSettings : public ConfirmationDialog { void _load_default_subresource_settings(Map<StringName, Variant> &settings, const String &p_type, const String &p_import_id, ResourceImporterScene::InternalImportCategory p_category); + bool editing_animation = false; + + Timer *update_view_timer; + protected: void _notification(int p_what); public: + bool is_editing_animation() const { return editing_animation; } void update_view(); - void open_settings(const String &p_path); + void open_settings(const String &p_path, bool p_for_animation = false); static SceneImportSettings *get_singleton(); SceneImportSettings(); ~SceneImportSettings(); diff --git a/editor/import_defaults_editor.h b/editor/import_defaults_editor.h index ed94fe6156..f0433f6065 100644 --- a/editor/import_defaults_editor.h +++ b/editor/import_defaults_editor.h @@ -41,13 +41,13 @@ class EditorInspector; class ImportDefaultsEditor : public VBoxContainer { GDCLASS(ImportDefaultsEditor, VBoxContainer) - OptionButton *importers; - Button *save_defaults; - Button *reset_defaults; + OptionButton *importers = nullptr; + Button *save_defaults = nullptr; + Button *reset_defaults = nullptr; - EditorInspector *inspector; + EditorInspector *inspector = nullptr; - ImportDefaultsEditorSettings *settings; + ImportDefaultsEditorSettings *settings = nullptr; void _update_importer(); void _importer_selected(int p_index); diff --git a/editor/import_dock.h b/editor/import_dock.h index c5cdc4ac40..f522b0bced 100644 --- a/editor/import_dock.h +++ b/editor/import_dock.h @@ -45,25 +45,25 @@ class ImportDockParameters; class ImportDock : public VBoxContainer { GDCLASS(ImportDock, VBoxContainer); - Label *imported; - OptionButton *import_as; - MenuButton *preset; - EditorInspector *import_opts; + Label *imported = nullptr; + OptionButton *import_as = nullptr; + MenuButton *preset = nullptr; + EditorInspector *import_opts = nullptr; List<PropertyInfo> properties; Map<StringName, Variant> property_values; - ConfirmationDialog *reimport_confirm; - Label *label_warning; - Button *import; + ConfirmationDialog *reimport_confirm = nullptr; + Label *label_warning = nullptr; + Button *import = nullptr; - Control *advanced_spacer; - Button *advanced; + Control *advanced_spacer = nullptr; + Button *advanced = nullptr; - ImportDockParameters *params; + ImportDockParameters *params = nullptr; - VBoxContainer *content; - Label *select_a_resource; + VBoxContainer *content = nullptr; + Label *select_a_resource = nullptr; void _preset_selected(int p_idx); void _importer_selected(int i_idx); diff --git a/editor/inspector_dock.h b/editor/inspector_dock.h index 7e653c4750..86733c992d 100644 --- a/editor/inspector_dock.h +++ b/editor/inspector_dock.h @@ -70,34 +70,34 @@ class InspectorDock : public VBoxContainer { OBJECT_METHOD_BASE = 500 }; - EditorData *editor_data; + EditorData *editor_data = nullptr; - EditorInspector *inspector; + EditorInspector *inspector = nullptr; - Object *current; + Object *current = nullptr; - Button *backward_button; - Button *forward_button; + Button *backward_button = nullptr; + Button *forward_button = nullptr; - EditorFileDialog *load_resource_dialog; - CreateDialog *new_resource_dialog; - Button *resource_new_button; - Button *resource_load_button; - MenuButton *resource_save_button; - MenuButton *resource_extra_button; - MenuButton *history_menu; - LineEdit *search; + EditorFileDialog *load_resource_dialog = nullptr; + CreateDialog *new_resource_dialog = nullptr; + Button *resource_new_button = nullptr; + Button *resource_load_button = nullptr; + MenuButton *resource_save_button = nullptr; + MenuButton *resource_extra_button = nullptr; + MenuButton *history_menu = nullptr; + LineEdit *search = nullptr; - Button *open_docs_button; - MenuButton *object_menu; - EditorPath *editor_path; + Button *open_docs_button = nullptr; + MenuButton *object_menu = nullptr; + EditorPath *editor_path = nullptr; - Button *warning; - AcceptDialog *warning_dialog; + Button *warning = nullptr; + AcceptDialog *warning_dialog = nullptr; int current_option = -1; - ConfirmationDialog *unique_resources_confirmation; - Tree *unique_resources_list_tree; + ConfirmationDialog *unique_resources_confirmation = nullptr; + Tree *unique_resources_list_tree = nullptr; EditorPropertyNameProcessor::Style property_name_style; diff --git a/editor/localization_editor.h b/editor/localization_editor.h index 3424ba7c55..966ef0f36e 100644 --- a/editor/localization_editor.h +++ b/editor/localization_editor.h @@ -40,22 +40,22 @@ class EditorFileDialog; class LocalizationEditor : public VBoxContainer { GDCLASS(LocalizationEditor, VBoxContainer); - Tree *translation_list; + Tree *translation_list = nullptr; - EditorLocaleDialog *locale_select; - EditorFileDialog *translation_file_open; + EditorLocaleDialog *locale_select = nullptr; + EditorFileDialog *translation_file_open = nullptr; - Button *translation_res_option_add_button; - EditorFileDialog *translation_res_file_open_dialog; - EditorFileDialog *translation_res_option_file_open_dialog; - Tree *translation_remap; - Tree *translation_remap_options; + Button *translation_res_option_add_button = nullptr; + EditorFileDialog *translation_res_file_open_dialog = nullptr; + EditorFileDialog *translation_res_option_file_open_dialog = nullptr; + Tree *translation_remap = nullptr; + Tree *translation_remap_options = nullptr; - Tree *translation_pot_list; - EditorFileDialog *pot_file_open_dialog; - EditorFileDialog *pot_generate_dialog; + Tree *translation_pot_list = nullptr; + EditorFileDialog *pot_file_open_dialog = nullptr; + EditorFileDialog *pot_generate_dialog = nullptr; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; bool updating_translations = false; String localization_changed; diff --git a/editor/node_dock.h b/editor/node_dock.h index 4c814ab65f..35af1a8121 100644 --- a/editor/node_dock.h +++ b/editor/node_dock.h @@ -38,15 +38,15 @@ class ConnectionsDock; class NodeDock : public VBoxContainer { GDCLASS(NodeDock, VBoxContainer); - Button *connections_button; - Button *groups_button; + Button *connections_button = nullptr; + Button *groups_button = nullptr; - ConnectionsDock *connections; - GroupsEditor *groups; + ConnectionsDock *connections = nullptr; + GroupsEditor *groups = nullptr; - HBoxContainer *mode_hb; + HBoxContainer *mode_hb = nullptr; - Label *select_a_node; + Label *select_a_node = nullptr; private: static NodeDock *singleton; diff --git a/editor/plugin_config_dialog.cpp b/editor/plugin_config_dialog.cpp index 02cc95e14a..755bf7ce07 100644 --- a/editor/plugin_config_dialog.cpp +++ b/editor/plugin_config_dialog.cpp @@ -50,8 +50,8 @@ void PluginConfigDialog::_on_confirmed() { String path = "res://addons/" + subfolder_edit->get_text(); if (!_edit_mode) { - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_RESOURCES); - if (!d || d->make_dir_recursive(path) != OK) { + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES); + if (d.is_null() || d->make_dir_recursive(path) != OK) { return; } } @@ -137,7 +137,7 @@ void PluginConfigDialog::_on_required_text_changed(const String &) { subfolder_validation->set_texture(invalid_icon); subfolder_validation->set_tooltip(TTR("Subfolder name is not a valid folder name.")); } else { - DirAccessRef dir = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_RESOURCES); String path = "res://addons/" + subfolder_edit->get_text(); if (dir->dir_exists(path) && !_edit_mode) { // Only show this error if in "create" mode. is_valid = false; diff --git a/editor/plugin_config_dialog.h b/editor/plugin_config_dialog.h index 0dc2e84a98..76fec636f3 100644 --- a/editor/plugin_config_dialog.h +++ b/editor/plugin_config_dialog.h @@ -41,18 +41,18 @@ class PluginConfigDialog : public ConfirmationDialog { GDCLASS(PluginConfigDialog, ConfirmationDialog); - LineEdit *name_edit; - LineEdit *subfolder_edit; - TextEdit *desc_edit; - LineEdit *author_edit; - LineEdit *version_edit; - OptionButton *script_option_edit; - LineEdit *script_edit; - CheckBox *active_edit; + LineEdit *name_edit = nullptr; + LineEdit *subfolder_edit = nullptr; + TextEdit *desc_edit = nullptr; + LineEdit *author_edit = nullptr; + LineEdit *version_edit = nullptr; + OptionButton *script_option_edit = nullptr; + LineEdit *script_edit = nullptr; + CheckBox *active_edit = nullptr; - TextureRect *name_validation; - TextureRect *subfolder_validation; - TextureRect *script_validation; + TextureRect *name_validation = nullptr; + TextureRect *subfolder_validation = nullptr; + TextureRect *script_validation = nullptr; bool _edit_mode; diff --git a/editor/plugins/abstract_polygon_2d_editor.h b/editor/plugins/abstract_polygon_2d_editor.h index c0e7c1be2e..b0483cbb62 100644 --- a/editor/plugins/abstract_polygon_2d_editor.h +++ b/editor/plugins/abstract_polygon_2d_editor.h @@ -40,9 +40,9 @@ class CanvasItemEditor; class AbstractPolygon2DEditor : public HBoxContainer { GDCLASS(AbstractPolygon2DEditor, HBoxContainer); - Button *button_create; - Button *button_edit; - Button *button_delete; + Button *button_create = nullptr; + Button *button_edit = nullptr; + Button *button_delete = nullptr; struct Vertex { Vertex() {} @@ -85,9 +85,9 @@ class AbstractPolygon2DEditor : public HBoxContainer { bool _polygon_editing_enabled; - CanvasItemEditor *canvas_item_editor; - Panel *panel; - ConfirmationDialog *create_resource; + CanvasItemEditor *canvas_item_editor = nullptr; + Panel *panel = nullptr; + ConfirmationDialog *create_resource = nullptr; protected: enum { @@ -99,7 +99,7 @@ protected: int mode; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; virtual void _menu_option(int p_option); void _wip_changed(); @@ -149,7 +149,7 @@ public: class AbstractPolygon2DEditorPlugin : public EditorPlugin { GDCLASS(AbstractPolygon2DEditorPlugin, EditorPlugin); - AbstractPolygon2DEditor *polygon_editor; + AbstractPolygon2DEditor *polygon_editor = nullptr; String klass; public: diff --git a/editor/plugins/animation_blend_space_1d_editor.h b/editor/plugins/animation_blend_space_1d_editor.h index 54cded6048..816c2555ca 100644 --- a/editor/plugins/animation_blend_space_1d_editor.h +++ b/editor/plugins/animation_blend_space_1d_editor.h @@ -45,36 +45,36 @@ class AnimationNodeBlendSpace1DEditor : public AnimationTreeNodeEditorPlugin { Ref<AnimationNodeBlendSpace1D> blend_space; - HBoxContainer *goto_parent_hb; - Button *goto_parent; - - PanelContainer *panel; - Button *tool_blend; - Button *tool_select; - Button *tool_create; - VSeparator *tool_erase_sep; - Button *tool_erase; - Button *snap; - SpinBox *snap_value; - - LineEdit *label_value; - SpinBox *max_value; - SpinBox *min_value; - - HBoxContainer *edit_hb; - SpinBox *edit_value; - Button *open_editor; + HBoxContainer *goto_parent_hb = nullptr; + Button *goto_parent = nullptr; + + PanelContainer *panel = nullptr; + Button *tool_blend = nullptr; + Button *tool_select = nullptr; + Button *tool_create = nullptr; + VSeparator *tool_erase_sep = nullptr; + Button *tool_erase = nullptr; + Button *snap = nullptr; + SpinBox *snap_value = nullptr; + + LineEdit *label_value = nullptr; + SpinBox *max_value = nullptr; + SpinBox *min_value = nullptr; + + HBoxContainer *edit_hb = nullptr; + SpinBox *edit_value = nullptr; + Button *open_editor = nullptr; int selected_point; - Control *blend_space_draw; + Control *blend_space_draw = nullptr; - PanelContainer *error_panel; - Label *error_label; + PanelContainer *error_panel = nullptr; + Label *error_label = nullptr; bool updating; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; static AnimationNodeBlendSpace1DEditor *singleton; @@ -87,8 +87,8 @@ class AnimationNodeBlendSpace1DEditor : public AnimationTreeNodeEditorPlugin { void _labels_changed(String); void _snap_toggled(); - PopupMenu *menu; - PopupMenu *animations_menu; + PopupMenu *menu = nullptr; + PopupMenu *animations_menu = nullptr; Vector<String> animations_to_add; float add_point_pos; Vector<real_t> points; @@ -108,7 +108,7 @@ class AnimationNodeBlendSpace1DEditor : public AnimationTreeNodeEditorPlugin { void _edit_point_pos(double); void _open_editor(); - EditorFileDialog *open_file; + EditorFileDialog *open_file = nullptr; Ref<AnimationNode> file_loaded; void _file_opened(const String &p_file); diff --git a/editor/plugins/animation_blend_space_2d_editor.h b/editor/plugins/animation_blend_space_2d_editor.h index 933d2bd96d..db54e84254 100644 --- a/editor/plugins/animation_blend_space_2d_editor.h +++ b/editor/plugins/animation_blend_space_2d_editor.h @@ -45,43 +45,43 @@ class AnimationNodeBlendSpace2DEditor : public AnimationTreeNodeEditorPlugin { Ref<AnimationNodeBlendSpace2D> blend_space; - PanelContainer *panel; - Button *tool_blend; - Button *tool_select; - Button *tool_create; - Button *tool_triangle; - VSeparator *tool_erase_sep; - Button *tool_erase; - Button *snap; - SpinBox *snap_x; - SpinBox *snap_y; - OptionButton *interpolation; - - Button *auto_triangles; - - LineEdit *label_x; - LineEdit *label_y; - SpinBox *max_x_value; - SpinBox *min_x_value; - SpinBox *max_y_value; - SpinBox *min_y_value; - - HBoxContainer *edit_hb; - SpinBox *edit_x; - SpinBox *edit_y; - Button *open_editor; + PanelContainer *panel = nullptr; + Button *tool_blend = nullptr; + Button *tool_select = nullptr; + Button *tool_create = nullptr; + Button *tool_triangle = nullptr; + VSeparator *tool_erase_sep = nullptr; + Button *tool_erase = nullptr; + Button *snap = nullptr; + SpinBox *snap_x = nullptr; + SpinBox *snap_y = nullptr; + OptionButton *interpolation = nullptr; + + Button *auto_triangles = nullptr; + + LineEdit *label_x = nullptr; + LineEdit *label_y = nullptr; + SpinBox *max_x_value = nullptr; + SpinBox *min_x_value = nullptr; + SpinBox *max_y_value = nullptr; + SpinBox *min_y_value = nullptr; + + HBoxContainer *edit_hb = nullptr; + SpinBox *edit_x = nullptr; + SpinBox *edit_y = nullptr; + Button *open_editor = nullptr; int selected_point; int selected_triangle; - Control *blend_space_draw; + Control *blend_space_draw = nullptr; - PanelContainer *error_panel; - Label *error_label; + PanelContainer *error_panel = nullptr; + Label *error_label = nullptr; bool updating; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; static AnimationNodeBlendSpace2DEditor *singleton; @@ -94,8 +94,8 @@ class AnimationNodeBlendSpace2DEditor : public AnimationTreeNodeEditorPlugin { void _labels_changed(String); void _snap_toggled(); - PopupMenu *menu; - PopupMenu *animations_menu; + PopupMenu *menu = nullptr; + PopupMenu *animations_menu = nullptr; Vector<String> animations_to_add; Vector2 add_point_pos; Vector<Vector2> points; @@ -123,7 +123,7 @@ class AnimationNodeBlendSpace2DEditor : public AnimationTreeNodeEditorPlugin { StringName get_blend_position_path() const; - EditorFileDialog *open_file; + EditorFileDialog *open_file = nullptr; Ref<AnimationNode> file_loaded; void _file_opened(const String &p_file); diff --git a/editor/plugins/animation_blend_tree_editor_plugin.h b/editor/plugins/animation_blend_tree_editor_plugin.h index c111f9245e..cacf8379f9 100644 --- a/editor/plugins/animation_blend_tree_editor_plugin.h +++ b/editor/plugins/animation_blend_tree_editor_plugin.h @@ -47,19 +47,19 @@ class AnimationNodeBlendTreeEditor : public AnimationTreeNodeEditorPlugin { GDCLASS(AnimationNodeBlendTreeEditor, AnimationTreeNodeEditorPlugin); Ref<AnimationNodeBlendTree> blend_tree; - GraphEdit *graph; - MenuButton *add_node; + GraphEdit *graph = nullptr; + MenuButton *add_node = nullptr; Vector2 position_from_popup_menu; bool use_position_from_popup_menu; - PanelContainer *error_panel; - Label *error_label; + PanelContainer *error_panel = nullptr; + Label *error_label = nullptr; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; - AcceptDialog *filter_dialog; - Tree *filters; - CheckBox *filter_enabled; + AcceptDialog *filter_dialog = nullptr; + Tree *filters = nullptr; + CheckBox *filter_enabled = nullptr; Map<StringName, ProgressBar *> animations; Vector<EditorProperty *> visible_properties; @@ -122,7 +122,7 @@ class AnimationNodeBlendTreeEditor : public AnimationTreeNodeEditorPlugin { void _update_editor_settings(); void _update_theme(); - EditorFileDialog *open_file; + EditorFileDialog *open_file = nullptr; Ref<AnimationNode> file_loaded; void _file_opened(const String &p_file); diff --git a/editor/plugins/animation_library_editor.cpp b/editor/plugins/animation_library_editor.cpp new file mode 100644 index 0000000000..2e9a82a7c2 --- /dev/null +++ b/editor/plugins/animation_library_editor.cpp @@ -0,0 +1,689 @@ +/*************************************************************************/ +/* animation_library_editor.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "animation_library_editor.h" +#include "editor/editor_file_dialog.h" +#include "editor/editor_node.h" +#include "editor/editor_scale.h" + +void AnimationLibraryEditor::set_animation_player(Object *p_player) { + player = p_player; +} + +void AnimationLibraryEditor::_add_library() { + add_library_dialog->set_title(TTR("Library Name:")); + add_library_name->set_text(""); + add_library_dialog->popup_centered(); + add_library_name->grab_focus(); + adding_animation = false; + adding_animation_to_library = StringName(); + _add_library_validate(""); +} + +void AnimationLibraryEditor::_add_library_validate(const String &p_name) { + String error; + + if (adding_animation) { + Ref<AnimationLibrary> al = player->call("get_animation_library", adding_animation_to_library); + ERR_FAIL_COND(al.is_null()); + if (p_name == "") { + error = TTR("Animation name can't be empty."); + + } else if (String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("[")) { + error = TTR("Animation name contains invalid characters: '/', ':', ',' or '['."); + } else if (al->has_animation(p_name)) { + error = TTR("Animation with the same name already exists."); + } + + } else { + if (p_name == "" && bool(player->call("has_animation_library", ""))) { + error = TTR("Enter a library name."); + } else if (String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("[")) { + error = TTR("Library name contains invalid characters: '/', ':', ',' or '['."); + } else if (bool(player->call("has_animation_library", p_name))) { + error = TTR("Library with the same name already exists."); + } + } + + if (error != "") { + add_library_validate->add_theme_color_override("font_color", get_theme_color(SNAME("error_color"), SNAME("Editor"))); + add_library_validate->set_text(error); + add_library_dialog->get_ok_button()->set_disabled(true); + } else { + add_library_validate->add_theme_color_override("font_color", get_theme_color(SNAME("success_color"), SNAME("Editor"))); + if (p_name == "") { + add_library_validate->set_text(TTR("Global library will be created.")); + } else { + add_library_validate->set_text(TTR("Library name is valid.")); + } + add_library_dialog->get_ok_button()->set_disabled(false); + } +} + +void AnimationLibraryEditor::_add_library_confirm() { + if (adding_animation) { + String anim_name = add_library_name->get_text(); + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + Ref<AnimationLibrary> al = player->call("get_animation_library", adding_animation_to_library); + ERR_FAIL_COND(!al.is_valid()); + + Ref<Animation> anim; + anim.instantiate(); + + undo_redo->create_action(vformat(TTR("Add Animation to Library: %s"), anim_name)); + undo_redo->add_do_method(al.ptr(), "add_animation", anim_name, anim); + undo_redo->add_undo_method(al.ptr(), "remove_animation", anim_name); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + + } else { + String lib_name = add_library_name->get_text(); + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + Ref<AnimationLibrary> al; + al.instantiate(); + + undo_redo->create_action(vformat(TTR("Add Animation Library: %s"), lib_name)); + undo_redo->add_do_method(player, "add_animation_library", lib_name, al); + undo_redo->add_undo_method(player, "remove_animation_library", lib_name); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } +} + +void AnimationLibraryEditor::_load_library() { + List<String> extensions; + ResourceLoader::get_recognized_extensions_for_type("AnimationLibrary", &extensions); + + file_dialog->set_title(TTR("Load Animation")); + file_dialog->clear_filters(); + for (const String &K : extensions) { + file_dialog->add_filter("*." + K); + } + + file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE); + file_dialog->set_current_file(""); + file_dialog->popup_centered_ratio(); + + file_dialog_action = FILE_DIALOG_ACTION_OPEN_LIBRARY; +} + +void AnimationLibraryEditor::_file_popup_selected(int p_id) { + Ref<AnimationLibrary> al = player->call("get_animation_library", file_dialog_library); + Ref<Animation> anim; + if (file_dialog_animation != StringName()) { + anim = al->get_animation(file_dialog_animation); + ERR_FAIL_COND(anim.is_null()); + } + switch (p_id) { + case FILE_MENU_SAVE_LIBRARY: { + if (al->get_path().is_resource_file()) { + EditorNode::get_singleton()->save_resource(al); + break; + } + [[fallthrough]]; + } + case FILE_MENU_SAVE_AS_LIBRARY: { + file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE); + file_dialog->set_title(TTR("Save Library")); + if (al->get_path().is_resource_file()) { + file_dialog->set_current_path(al->get_path()); + } else { + file_dialog->set_current_file(String(file_dialog_library) + ".res"); + } + file_dialog->clear_filters(); + List<String> exts; + ResourceLoader::get_recognized_extensions_for_type("AnimationLibrary", &exts); + for (const String &K : exts) { + file_dialog->add_filter("*." + K); + } + + file_dialog->popup_centered_ratio(); + file_dialog_action = FILE_DIALOG_ACTION_SAVE_LIBRARY; + } break; + case FILE_MENU_MAKE_LIBRARY_UNIQUE: { + StringName lib_name = file_dialog_library; + + Ref<AnimationLibrary> ald = al->duplicate(); + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action(vformat(TTR("Make Animation Library Unique: %s"), lib_name)); + undo_redo->add_do_method(player, "remove_animation_library", lib_name); + undo_redo->add_do_method(player, "add_animation_library", lib_name, ald); + undo_redo->add_undo_method(player, "remove_animation_library", lib_name); + undo_redo->add_undo_method(player, "add_animation_library", lib_name, al); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + + } break; + case FILE_MENU_EDIT_LIBRARY: { + EditorNode::get_singleton()->push_item(al.ptr()); + } break; + + case FILE_MENU_SAVE_ANIMATION: { + if (anim->get_path().is_resource_file()) { + EditorNode::get_singleton()->save_resource(anim); + break; + } + [[fallthrough]]; + } + case FILE_MENU_SAVE_AS_ANIMATION: { + file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE); + file_dialog->set_title(TTR("Save Animation")); + if (anim->get_path().is_resource_file()) { + file_dialog->set_current_path(anim->get_path()); + } else { + file_dialog->set_current_file(String(file_dialog_animation) + ".res"); + } + file_dialog->clear_filters(); + List<String> exts; + ResourceLoader::get_recognized_extensions_for_type("Animation", &exts); + for (const String &K : exts) { + file_dialog->add_filter("*." + K); + } + + file_dialog->popup_centered_ratio(); + file_dialog_action = FILE_DIALOG_ACTION_SAVE_ANIMATION; + } break; + case FILE_MENU_MAKE_ANIMATION_UNIQUE: { + StringName anim_name = file_dialog_animation; + + Ref<Animation> animd = anim->duplicate(); + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action(vformat(TTR("Make Animation Unique: %s"), anim_name)); + undo_redo->add_do_method(al.ptr(), "remove_animation", anim_name); + undo_redo->add_do_method(al.ptr(), "add_animation", anim_name, animd); + undo_redo->add_undo_method(al.ptr(), "remove_animation", anim_name); + undo_redo->add_undo_method(al.ptr(), "add_animation", anim_name, anim); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } break; + case FILE_MENU_EDIT_ANIMATION: { + EditorNode::get_singleton()->push_item(anim.ptr()); + } break; + } +} +void AnimationLibraryEditor::_load_file(String p_path) { + switch (file_dialog_action) { + case FILE_DIALOG_ACTION_OPEN_LIBRARY: { + Ref<AnimationLibrary> al = ResourceLoader::load(p_path); + if (al.is_null()) { + error_dialog->set_text(TTR("Invalid AnimationLibrary file.")); + error_dialog->popup_centered(); + return; + } + + TypedArray<StringName> libs = player->call("get_animation_library_list"); + for (int i = 0; i < libs.size(); i++) { + const StringName K = libs[i]; + Ref<AnimationLibrary> al2 = player->call("get_animation_library", K); + if (al2 == al) { + error_dialog->set_text(TTR("This library is already added to the player.")); + error_dialog->popup_centered(); + + return; + } + } + + String name = p_path.get_file().get_basename(); + + int attempt = 1; + + while (bool(player->call("has_animation_library", name))) { + attempt++; + name = p_path.get_file().get_basename() + " " + itos(attempt); + } + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + undo_redo->create_action(vformat(TTR("Add Animation Library: %s"), name)); + undo_redo->add_do_method(player, "add_animation_library", name, al); + undo_redo->add_undo_method(player, "remove_animation_library", name); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } break; + case FILE_DIALOG_ACTION_OPEN_ANIMATION: { + Ref<Animation> anim = ResourceLoader::load(p_path); + if (anim.is_null()) { + error_dialog->set_text(TTR("Invalid Animation file.")); + error_dialog->popup_centered(); + return; + } + + Ref<AnimationLibrary> al = player->call("get_animation_library", adding_animation_to_library); + List<StringName> anims; + al->get_animation_list(&anims); + for (const StringName &K : anims) { + Ref<Animation> a2 = al->get_animation(K); + if (a2 == anim) { + error_dialog->set_text(TTR("This animation is already added to the library.")); + error_dialog->popup_centered(); + return; + } + } + + String name = p_path.get_file().get_basename(); + + int attempt = 1; + + while (al->has_animation(name)) { + attempt++; + name = p_path.get_file().get_basename() + " " + itos(attempt); + } + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + undo_redo->create_action(vformat(TTR("Load Animation into Library: %s"), name)); + undo_redo->add_do_method(al.ptr(), "add_animation", name, anim); + undo_redo->add_undo_method(al.ptr(), "remove_animation", name); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } break; + + case FILE_DIALOG_ACTION_SAVE_LIBRARY: { + Ref<AnimationLibrary> al = player->call("get_animation_library", file_dialog_library); + String prev_path = al->get_path(); + EditorNode::get_singleton()->save_resource_in_path(al, p_path); + + if (al->get_path() != prev_path) { // Save successful. + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + undo_redo->create_action(vformat(TTR("Save Animation library to File: %s"), file_dialog_library)); + undo_redo->add_do_method(al.ptr(), "set_path", al->get_path()); + undo_redo->add_undo_method(al.ptr(), "set_path", prev_path); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } + + } break; + case FILE_DIALOG_ACTION_SAVE_ANIMATION: { + Ref<AnimationLibrary> al = player->call("get_animation_library", file_dialog_library); + Ref<Animation> anim; + if (file_dialog_animation != StringName()) { + anim = al->get_animation(file_dialog_animation); + ERR_FAIL_COND(anim.is_null()); + } + String prev_path = anim->get_path(); + EditorNode::get_singleton()->save_resource_in_path(anim, p_path); + if (anim->get_path() != prev_path) { // Save successful. + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + undo_redo->create_action(vformat(TTR("Save Animation to File: %s"), file_dialog_animation)); + undo_redo->add_do_method(anim.ptr(), "set_path", anim->get_path()); + undo_redo->add_undo_method(anim.ptr(), "set_path", prev_path); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } + } break; + } +} + +void AnimationLibraryEditor::_item_renamed() { + TreeItem *ti = tree->get_edited(); + String text = ti->get_text(0); + String old_text = ti->get_metadata(0); + bool restore_text = false; + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + if (String(text).contains("/") || String(text).contains(":") || String(text).contains(",") || String(text).contains("[")) { + restore_text = true; + } else { + if (ti->get_parent() == tree->get_root()) { + // Renamed library + + if (player->call("has_animation_library", text)) { + restore_text = true; + } else { + undo_redo->create_action(vformat(TTR("Rename Animation Library: %s"), text)); + undo_redo->add_do_method(player, "rename_animation_library", old_text, text); + undo_redo->add_undo_method(player, "rename_animation_library", text, old_text); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + updating = true; + undo_redo->commit_action(); + updating = false; + ti->set_metadata(0, text); + if (text == "") { + ti->set_suffix(0, TTR("[Global]")); + } else { + ti->set_suffix(0, ""); + } + } + } else { + // Renamed anim + StringName library = ti->get_parent()->get_metadata(0); + Ref<AnimationLibrary> al = player->call("get_animation_library", library); + + if (al.is_valid()) { + if (al->has_animation(text)) { + restore_text = true; + } else { + undo_redo->create_action(vformat(TTR("Rename Animation: %s"), text)); + undo_redo->add_do_method(al.ptr(), "rename_animation", old_text, text); + undo_redo->add_undo_method(al.ptr(), "rename_animation", text, old_text); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + updating = true; + undo_redo->commit_action(); + updating = false; + + ti->set_metadata(0, text); + } + } else { + restore_text = true; + } + } + } + + if (restore_text) { + ti->set_text(0, old_text); + } +} + +void AnimationLibraryEditor::_button_pressed(TreeItem *p_item, int p_column, int p_button) { + if (p_item->get_parent() == tree->get_root()) { + // Library + StringName lib_name = p_item->get_metadata(0); + Ref<AnimationLibrary> al = player->call("get_animation_library", lib_name); + switch (p_button) { + case LIB_BUTTON_ADD: { + add_library_dialog->set_title(TTR("Animation Name:")); + add_library_name->set_text(""); + add_library_dialog->popup_centered(); + add_library_name->grab_focus(); + adding_animation = true; + adding_animation_to_library = p_item->get_metadata(0); + _add_library_validate(""); + } break; + case LIB_BUTTON_LOAD: { + adding_animation_to_library = p_item->get_metadata(0); + List<String> extensions; + ResourceLoader::get_recognized_extensions_for_type("Animation", &extensions); + + file_dialog->clear_filters(); + for (const String &K : extensions) { + file_dialog->add_filter("*." + K); + } + + file_dialog->set_title(TTR("Load Animation")); + file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE); + file_dialog->set_current_file(""); + file_dialog->popup_centered_ratio(); + + file_dialog_action = FILE_DIALOG_ACTION_OPEN_ANIMATION; + + } break; + case LIB_BUTTON_PASTE: { + Ref<Animation> anim = EditorSettings::get_singleton()->get_resource_clipboard(); + if (!anim.is_valid()) { + error_dialog->set_text(TTR("No animation resource in clipboard!")); + error_dialog->popup_centered(); + return; + } + + anim = anim->duplicate(); // Users simply dont care about referencing, so making a copy works better here. + + String base_name; + if (anim->get_name() != "") { + base_name = anim->get_name(); + } else { + base_name = TTR("Pasted Animation"); + } + + String name = base_name; + int attempt = 1; + while (al->has_animation(name)) { + attempt++; + name = base_name + " " + itos(attempt); + } + + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + + undo_redo->create_action(vformat(TTR("Add Animation to Library: %s"), name)); + undo_redo->add_do_method(al.ptr(), "add_animation", name, anim); + undo_redo->add_undo_method(al.ptr(), "remove_animation", name); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + + } break; + case LIB_BUTTON_FILE: { + file_popup->clear(); + file_popup->add_item(TTR("Save"), FILE_MENU_SAVE_LIBRARY); + file_popup->add_item(TTR("Save As"), FILE_MENU_SAVE_AS_LIBRARY); + file_popup->add_separator(); + file_popup->add_item(TTR("Make Unique"), FILE_MENU_MAKE_LIBRARY_UNIQUE); + file_popup->add_separator(); + file_popup->add_item(TTR("Open in Inspector"), FILE_MENU_EDIT_LIBRARY); + Rect2 pos = tree->get_item_rect(p_item, 1, 0); + Vector2 popup_pos = tree->get_screen_position() + pos.position + Vector2(0, pos.size.height); + file_popup->popup(Rect2(popup_pos, Size2())); + + file_dialog_animation = StringName(); + file_dialog_library = lib_name; + } break; + case LIB_BUTTON_DELETE: { + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action(vformat(TTR("Remove Animation Library: %s"), lib_name)); + undo_redo->add_do_method(player, "remove_animation_library", lib_name); + undo_redo->add_undo_method(player, "add_animation_library", lib_name, al); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } break; + } + + } else { + // Animation + StringName lib_name = p_item->get_parent()->get_metadata(0); + StringName anim_name = p_item->get_metadata(0); + Ref<AnimationLibrary> al = player->call("get_animation_library", lib_name); + Ref<Animation> anim = al->get_animation(anim_name); + ERR_FAIL_COND(!anim.is_valid()); + switch (p_button) { + case ANIM_BUTTON_COPY: { + if (anim->get_name() == "") { + anim->set_name(anim_name); // Keep the name around + } + EditorSettings::get_singleton()->set_resource_clipboard(anim); + } break; + case ANIM_BUTTON_FILE: { + file_popup->clear(); + file_popup->add_item(TTR("Save"), FILE_MENU_SAVE_ANIMATION); + file_popup->add_item(TTR("Save As"), FILE_MENU_SAVE_AS_ANIMATION); + file_popup->add_separator(); + file_popup->add_item(TTR("Make Unique"), FILE_MENU_MAKE_ANIMATION_UNIQUE); + file_popup->add_separator(); + file_popup->add_item(TTR("Open in Inspector"), FILE_MENU_EDIT_ANIMATION); + Rect2 pos = tree->get_item_rect(p_item, 1, 0); + Vector2 popup_pos = tree->get_screen_position() + pos.position + Vector2(0, pos.size.height); + file_popup->popup(Rect2(popup_pos, Size2())); + + file_dialog_animation = anim_name; + file_dialog_library = lib_name; + + } break; + case ANIM_BUTTON_DELETE: { + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action(vformat(TTR("Remove Animation from Library: %s"), anim_name)); + undo_redo->add_do_method(al.ptr(), "remove_animation", anim_name); + undo_redo->add_undo_method(al.ptr(), "add_animation", anim_name, anim); + undo_redo->add_do_method(this, "_update_editor", player); + undo_redo->add_undo_method(this, "_update_editor", player); + undo_redo->commit_action(); + } break; + } + } +} + +void AnimationLibraryEditor::update_tree() { + if (updating) { + return; + } + + tree->clear(); + ERR_FAIL_COND(!player); + + Color ss_color = get_theme_color(SNAME("prop_subsection"), SNAME("Editor")); + + TreeItem *root = tree->create_item(); + TypedArray<StringName> libs = player->call("get_animation_library_list"); + + for (int i = 0; i < libs.size(); i++) { + const StringName K = libs[i]; + TreeItem *libitem = tree->create_item(root); + libitem->set_text(0, K); + if (K == StringName()) { + libitem->set_suffix(0, TTR("[Global]")); + } else { + libitem->set_suffix(0, ""); + } + libitem->set_editable(0, true); + libitem->set_metadata(0, K); + libitem->set_icon(0, get_theme_icon("AnimationLibrary", "EditorIcons")); + libitem->add_button(0, get_theme_icon("Add", "EditorIcons"), LIB_BUTTON_ADD, false, TTR("Add Animation to Library")); + libitem->add_button(0, get_theme_icon("Load", "EditorIcons"), LIB_BUTTON_LOAD, false, TTR("Load animation from file and add to library")); + libitem->add_button(0, get_theme_icon("ActionPaste", "EditorIcons"), LIB_BUTTON_PASTE, false, TTR("Paste Animation to Library from clipboard")); + Ref<AnimationLibrary> al = player->call("get_animation_library", K); + if (al->get_path().is_resource_file()) { + libitem->set_text(1, al->get_path().get_file()); + libitem->set_tooltip(1, al->get_path()); + } else { + libitem->set_text(1, TTR("[built-in]")); + } + libitem->add_button(1, get_theme_icon("Save", "EditorIcons"), LIB_BUTTON_FILE, false, TTR("Save animation library to resource on disk")); + libitem->add_button(1, get_theme_icon("Remove", "EditorIcons"), LIB_BUTTON_DELETE, false, TTR("Remove animation library")); + + libitem->set_custom_bg_color(0, ss_color); + + List<StringName> animations; + al->get_animation_list(&animations); + for (const StringName &L : animations) { + TreeItem *anitem = tree->create_item(libitem); + anitem->set_text(0, L); + anitem->set_editable(0, true); + anitem->set_metadata(0, L); + anitem->set_icon(0, get_theme_icon("Animation", "EditorIcons")); + anitem->add_button(0, get_theme_icon("ActionCopy", "EditorIcons"), ANIM_BUTTON_COPY, false, TTR("Copy animation to clipboard")); + Ref<Animation> anim = al->get_animation(L); + + if (anim->get_path().is_resource_file()) { + anitem->set_text(1, anim->get_path().get_file()); + anitem->set_tooltip(1, anim->get_path()); + } else { + anitem->set_text(1, TTR("[built-in]")); + } + anitem->add_button(1, get_theme_icon("Save", "EditorIcons"), ANIM_BUTTON_FILE, false, TTR("Save animation to resource on disk")); + anitem->add_button(1, get_theme_icon("Remove", "EditorIcons"), ANIM_BUTTON_DELETE, false, TTR("Remove animation from Library")); + } + } +} + +void AnimationLibraryEditor::show_dialog() { + update_tree(); + popup_centered_ratio(0.5); +} + +void AnimationLibraryEditor::_update_editor(Object *p_player) { + emit_signal("update_editor", p_player); +} + +void AnimationLibraryEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("_update_editor", "player"), &AnimationLibraryEditor::_update_editor); + ADD_SIGNAL(MethodInfo("update_editor")); +} + +AnimationLibraryEditor::AnimationLibraryEditor() { + set_title(TTR("Edit Animation Libraries")); + + file_dialog = memnew(EditorFileDialog); + add_child(file_dialog); + file_dialog->connect("file_selected", callable_mp(this, &AnimationLibraryEditor::_load_file)); + + add_library_dialog = memnew(ConfirmationDialog); + VBoxContainer *dialog_vb = memnew(VBoxContainer); + add_library_name = memnew(LineEdit); + dialog_vb->add_child(add_library_name); + add_library_name->connect("text_changed", callable_mp(this, &AnimationLibraryEditor::_add_library_validate)); + add_child(add_library_dialog); + + add_library_validate = memnew(Label); + dialog_vb->add_child(add_library_validate); + add_library_dialog->add_child(dialog_vb); + add_library_dialog->connect("confirmed", callable_mp(this, &AnimationLibraryEditor::_add_library_confirm)); + add_library_dialog->register_text_enter(add_library_name); + + VBoxContainer *vb = memnew(VBoxContainer); + HBoxContainer *hb = memnew(HBoxContainer); + hb->add_spacer(true); + Button *b = memnew(Button(TTR("Add Library"))); + b->connect("pressed", callable_mp(this, &AnimationLibraryEditor::_add_library)); + hb->add_child(b); + b = memnew(Button(TTR("Load Library"))); + b->connect("pressed", callable_mp(this, &AnimationLibraryEditor::_load_library)); + hb->add_child(b); + vb->add_child(hb); + tree = memnew(Tree); + vb->add_child(tree); + + tree->set_columns(2); + tree->set_column_titles_visible(true); + tree->set_column_title(0, TTR("Resource")); + tree->set_column_title(1, TTR("Storage")); + tree->set_column_expand(0, true); + tree->set_column_custom_minimum_width(1, EDSCALE * 250); + tree->set_column_expand(1, false); + tree->set_hide_root(true); + tree->set_hide_folding(true); + tree->set_v_size_flags(Control::SIZE_EXPAND_FILL); + + tree->connect("item_edited", callable_mp(this, &AnimationLibraryEditor::_item_renamed)); + tree->connect("button_pressed", callable_mp(this, &AnimationLibraryEditor::_button_pressed)); + + file_popup = memnew(PopupMenu); + add_child(file_popup); + file_popup->connect("id_pressed", callable_mp(this, &AnimationLibraryEditor::_file_popup_selected)); + + add_child(vb); + + error_dialog = memnew(AcceptDialog); + error_dialog->set_title(TTR("Error:")); + add_child(error_dialog); +} diff --git a/tests/scene/test_gui.h b/editor/plugins/animation_library_editor.h index a1807ed15c..5bd4e8d9e2 100644 --- a/tests/scene/test_gui.h +++ b/editor/plugins/animation_library_editor.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* test_gui.h */ +/* animation_library_editor.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,14 +28,92 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef TEST_GUI_H -#define TEST_GUI_H +#ifndef ANIMATION_LIBRARY_EDITOR_H +#define ANIMATION_LIBRARY_EDITOR_H -class MainLoop; +#include "editor/animation_track_editor.h" +#include "editor/editor_plugin.h" +#include "scene/animation/animation_player.h" +#include "scene/gui/dialogs.h" +#include "scene/gui/tree.h" -namespace TestGUI { +class EditorFileDialog; -MainLoop *test(); -} +class AnimationLibraryEditor : public AcceptDialog { + GDCLASS(AnimationLibraryEditor, AcceptDialog) -#endif + enum { + LIB_BUTTON_ADD, + LIB_BUTTON_LOAD, + LIB_BUTTON_PASTE, + LIB_BUTTON_FILE, + LIB_BUTTON_DELETE, + }; + enum { + ANIM_BUTTON_COPY, + ANIM_BUTTON_FILE, + ANIM_BUTTON_DELETE, + }; + + enum FileMenuAction { + FILE_MENU_SAVE_LIBRARY, + FILE_MENU_SAVE_AS_LIBRARY, + FILE_MENU_MAKE_LIBRARY_UNIQUE, + FILE_MENU_EDIT_LIBRARY, + + FILE_MENU_SAVE_ANIMATION, + FILE_MENU_SAVE_AS_ANIMATION, + FILE_MENU_MAKE_ANIMATION_UNIQUE, + FILE_MENU_EDIT_ANIMATION, + }; + + enum FileDialogAction { + FILE_DIALOG_ACTION_OPEN_LIBRARY, + FILE_DIALOG_ACTION_SAVE_LIBRARY, + FILE_DIALOG_ACTION_OPEN_ANIMATION, + FILE_DIALOG_ACTION_SAVE_ANIMATION, + }; + + FileDialogAction file_dialog_action = FILE_DIALOG_ACTION_OPEN_ANIMATION; + + StringName file_dialog_animation; + StringName file_dialog_library; + + AcceptDialog *error_dialog = nullptr; + bool adding_animation = false; + StringName adding_animation_to_library; + EditorFileDialog *file_dialog = nullptr; + ConfirmationDialog *add_library_dialog = nullptr; + LineEdit *add_library_name = nullptr; + Label *add_library_validate = nullptr; + PopupMenu *file_popup = nullptr; + + Tree *tree = nullptr; + + Object *player = nullptr; + + void _add_library(); + void _add_library_validate(const String &p_name); + void _add_library_confirm(); + void _load_library(); + void _load_file(String p_path); + + void _item_renamed(); + void _button_pressed(TreeItem *p_item, int p_column, int p_button); + + void _file_popup_selected(int p_id); + + bool updating = false; + +protected: + void _update_editor(Object *p_player); + static void _bind_methods(); + +public: + void set_animation_player(Object *p_player); + void show_dialog(); + void update_tree(); + AnimationLibraryEditor(); +}; + +#endif // ANIMATIONPLAYERLIBRARYEDITOR_H diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp index ab8e2ca54a..17a1bd1048 100644 --- a/editor/plugins/animation_player_editor_plugin.cpp +++ b/editor/plugins/animation_player_editor_plugin.cpp @@ -47,6 +47,8 @@ #include "scene/scene_string_names.h" #include "servers/rendering_server.h" +/////////////////////////////////// + void AnimationPlayerEditor::_node_removed(Node *p_node) { if (player && player == p_node) { player = nullptr; @@ -148,9 +150,7 @@ void AnimationPlayerEditor::_notification(int p_what) { #define ITEM_ICON(m_item, m_icon) tool_anim->get_popup()->set_item_icon(tool_anim->get_popup()->get_item_index(m_item), get_theme_icon(SNAME(m_icon), SNAME("EditorIcons"))) ITEM_ICON(TOOL_NEW_ANIM, "New"); - ITEM_ICON(TOOL_LOAD_ANIM, "Load"); - ITEM_ICON(TOOL_SAVE_ANIM, "Save"); - ITEM_ICON(TOOL_SAVE_AS_ANIM, "Save"); + ITEM_ICON(TOOL_ANIM_LIBRARY, "AnimationLibrary"); ITEM_ICON(TOOL_DUPLICATE_ANIM, "Duplicate"); ITEM_ICON(TOOL_RENAME_ANIM, "Rename"); ITEM_ICON(TOOL_EDIT_TRANSITIONS, "Blend"); @@ -166,7 +166,7 @@ void AnimationPlayerEditor::_autoplay_pressed() { if (updating) { return; } - if (animation->get_item_count() == 0) { + if (animation->has_selectable_items() == 0) { return; } @@ -192,10 +192,7 @@ void AnimationPlayerEditor::_autoplay_pressed() { } void AnimationPlayerEditor::_play_pressed() { - String current; - if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) { - current = animation->get_item_text(animation->get_selected()); - } + String current = _get_current(); if (!current.is_empty()) { if (current == player->get_assigned_animation()) { @@ -209,10 +206,7 @@ void AnimationPlayerEditor::_play_pressed() { } void AnimationPlayerEditor::_play_from_pressed() { - String current; - if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) { - current = animation->get_item_text(animation->get_selected()); - } + String current = _get_current(); if (!current.is_empty()) { float time = player->get_current_animation_position(); @@ -229,12 +223,15 @@ void AnimationPlayerEditor::_play_from_pressed() { stop->set_pressed(false); } -void AnimationPlayerEditor::_play_bw_pressed() { +String AnimationPlayerEditor::_get_current() const { String current; - if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) { + if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count() && !animation->is_item_separator(animation->get_selected())) { current = animation->get_item_text(animation->get_selected()); } - + return current; +} +void AnimationPlayerEditor::_play_bw_pressed() { + String current = _get_current(); if (!current.is_empty()) { if (current == player->get_assigned_animation()) { player->stop(); //so it won't blend with itself @@ -247,10 +244,7 @@ void AnimationPlayerEditor::_play_bw_pressed() { } void AnimationPlayerEditor::_play_bw_from_pressed() { - String current; - if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) { - current = animation->get_item_text(animation->get_selected()); - } + String current = _get_current(); if (!current.is_empty()) { float time = player->get_current_animation_position(); @@ -282,10 +276,7 @@ void AnimationPlayerEditor::_animation_selected(int p_which) { } // when selecting an animation, the idea is that the only interesting behavior // ui-wise is that it should play/blend the next one if currently playing - String current; - if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) { - current = animation->get_item_text(animation->get_selected()); - } + String current = _get_current(); if (!current.is_empty()) { player->set_assigned_animation(current); @@ -330,6 +321,20 @@ void AnimationPlayerEditor::_animation_new() { break; } + List<StringName> libraries; + player->get_animation_library_list(&libraries); + library->clear(); + for (const StringName &K : libraries) { + library->add_item((K == StringName()) ? String(TTR("[Global]")) : String(K)); + library->set_item_metadata(0, String(K)); + } + + if (libraries.size() > 1) { + library->show(); + } else { + library->hide(); + } + name->set_text(base); name_dialog->popup_centered(Size2(300, 90)); name->select_all(); @@ -337,7 +342,7 @@ void AnimationPlayerEditor::_animation_new() { } void AnimationPlayerEditor::_animation_rename() { - if (animation->get_item_count() == 0) { + if (!animation->has_selectable_items()) { return; } int selected = animation->get_selected(); @@ -349,84 +354,11 @@ void AnimationPlayerEditor::_animation_rename() { name_dialog->popup_centered(Size2(300, 90)); name->select_all(); name->grab_focus(); -} - -void AnimationPlayerEditor::_animation_load() { - ERR_FAIL_COND(!player); - file->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILES); - file->clear_filters(); - List<String> extensions; - - ResourceLoader::get_recognized_extensions_for_type("Animation", &extensions); - for (const String &E : extensions) { - file->add_filter("*." + E + " ; " + E.to_upper()); - } - - file->popup_file_dialog(); -} - -void AnimationPlayerEditor::_animation_save_in_path(const Ref<Resource> &p_resource, const String &p_path) { - int flg = 0; - if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources")) { - flg |= ResourceSaver::FLAG_COMPRESS; - } - - String path = ProjectSettings::get_singleton()->localize_path(p_path); - Error err = ResourceSaver::save(path, p_resource, flg | ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS); - - if (err != OK) { - EditorNode::get_singleton()->show_warning(TTR("Error saving resource!")); - return; - } - - ((Resource *)p_resource.ptr())->set_path(path); - EditorNode::get_singleton()->emit_signal(SNAME("resource_saved"), p_resource); -} - -void AnimationPlayerEditor::_animation_save(const Ref<Resource> &p_resource) { - if (p_resource->get_path().is_resource_file()) { - _animation_save_in_path(p_resource, p_resource->get_path()); - } else { - _animation_save_as(p_resource); - } -} - -void AnimationPlayerEditor::_animation_save_as(const Ref<Resource> &p_resource) { - file->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE); - - List<String> extensions; - ResourceSaver::get_recognized_extensions(p_resource, &extensions); - file->clear_filters(); - for (int i = 0; i < extensions.size(); i++) { - file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); - } - - String path; - //file->set_current_path(current_path); - if (!p_resource->get_path().is_empty()) { - path = p_resource->get_path(); - if (extensions.size()) { - if (extensions.find(p_resource->get_path().get_extension().to_lower()) == nullptr) { - path = p_resource->get_path().get_base_dir() + p_resource->get_name() + "." + extensions.front()->get(); - } - } - } else { - if (extensions.size()) { - if (!p_resource->get_name().is_empty()) { - path = p_resource->get_name() + "." + extensions.front()->get().to_lower(); - } else { - String resource_name_snake_case = p_resource->get_class().camelcase_to_underscore(); - path = "new_" + resource_name_snake_case + "." + extensions.front()->get().to_lower(); - } - } - } - file->set_current_path(path); - file->set_title(TTR("Save Resource As...")); - file->popup_file_dialog(); + library->hide(); } void AnimationPlayerEditor::_animation_remove() { - if (animation->get_item_count() == 0) { + if (!animation->has_selectable_items()) { return; } @@ -440,6 +372,9 @@ void AnimationPlayerEditor::_animation_remove_confirmed() { String current = animation->get_item_text(animation->get_selected()); Ref<Animation> anim = player->get_animation(current); + Ref<AnimationLibrary> al = player->get_animation_library(player->find_animation_library(anim)); + ERR_FAIL_COND(al.is_null()); + undo_redo->create_action(TTR("Remove Animation")); if (player->get_autoplay() == current) { undo_redo->add_do_method(player, "set_autoplay", ""); @@ -447,11 +382,11 @@ void AnimationPlayerEditor::_animation_remove_confirmed() { // Avoid having the autoplay icon linger around if there is only one animation in the player. undo_redo->add_do_method(this, "_animation_player_changed", player); } - undo_redo->add_do_method(player, "remove_animation", current); - undo_redo->add_undo_method(player, "add_animation", current, anim); + undo_redo->add_do_method(al.ptr(), "remove_animation", current); + undo_redo->add_undo_method(al.ptr(), "add_animation", current, anim); undo_redo->add_do_method(this, "_animation_player_changed", player); undo_redo->add_undo_method(this, "_animation_player_changed", player); - if (animation->get_item_count() == 1) { + if (animation->has_selectable_items() && animation->get_selectable_item(false) == animation->get_selectable_item(true)) { // Last item remaining. undo_redo->add_do_method(this, "_stop_onion_skinning"); undo_redo->add_undo_method(this, "_start_onion_skinning"); } @@ -498,7 +433,7 @@ void AnimationPlayerEditor::_animation_name_edited() { return; } - if (name_dialog_op == TOOL_RENAME_ANIM && animation->get_item_count() > 0 && animation->get_item_text(animation->get_selected()) == new_name) { + if (name_dialog_op == TOOL_RENAME_ANIM && animation->has_selectable_items() && animation->get_item_text(animation->get_selected()) == new_name) { name_dialog->hide(); return; } @@ -514,10 +449,13 @@ void AnimationPlayerEditor::_animation_name_edited() { String current = animation->get_item_text(animation->get_selected()); Ref<Animation> anim = player->get_animation(current); + Ref<AnimationLibrary> al = player->get_animation_library(player->find_animation_library(anim)); + ERR_FAIL_COND(al.is_null()); + undo_redo->create_action(TTR("Rename Animation")); - undo_redo->add_do_method(player, "rename_animation", current, new_name); + undo_redo->add_do_method(al.ptr(), "rename_animation", current, new_name); undo_redo->add_do_method(anim.ptr(), "set_name", new_name); - undo_redo->add_undo_method(player, "rename_animation", new_name, current); + undo_redo->add_undo_method(al.ptr(), "rename_animation", new_name, current); undo_redo->add_undo_method(anim.ptr(), "set_name", current); undo_redo->add_do_method(this, "_animation_player_changed", player); undo_redo->add_undo_method(this, "_animation_player_changed", player); @@ -530,15 +468,35 @@ void AnimationPlayerEditor::_animation_name_edited() { Ref<Animation> new_anim = Ref<Animation>(memnew(Animation)); new_anim->set_name(new_name); + Ref<AnimationLibrary> al; + if (library->is_visible()) { + al = player->get_animation_library(library->get_item_metadata(library->get_selected())); + } else { + if (player->has_animation_library("")) { + al = player->get_animation_library(""); + } + } + undo_redo->create_action(TTR("Add Animation")); - undo_redo->add_do_method(player, "add_animation", new_name, new_anim); - undo_redo->add_undo_method(player, "remove_animation", new_name); + + bool lib_added = false; + if (al.is_null()) { + al.instantiate(); + lib_added = true; + undo_redo->add_do_method(player, "add_animation_library", "", al); + } + + undo_redo->add_do_method(al.ptr(), "add_animation", new_name, new_anim); + undo_redo->add_undo_method(al.ptr(), "remove_animation", new_name); undo_redo->add_do_method(this, "_animation_player_changed", player); undo_redo->add_undo_method(this, "_animation_player_changed", player); - if (animation->get_item_count() == 0) { + if (!animation->has_selectable_items()) { undo_redo->add_do_method(this, "_start_onion_skinning"); undo_redo->add_undo_method(this, "_stop_onion_skinning"); } + if (lib_added) { + undo_redo->add_undo_method(player, "remove_animation_library", ""); + } undo_redo->commit_action(); _select_anim_by_name(new_name); @@ -551,9 +509,11 @@ void AnimationPlayerEditor::_animation_name_edited() { Ref<Animation> new_anim = _animation_clone(anim); new_anim->set_name(new_name); + Ref<AnimationLibrary> library = player->get_animation_library(player->find_animation_library(anim)); + undo_redo->create_action(TTR("Duplicate Animation")); - undo_redo->add_do_method(player, "add_animation", new_name, new_anim); - undo_redo->add_undo_method(player, "remove_animation", new_name); + undo_redo->add_do_method(library.ptr(), "add_animation", new_name, new_anim); + undo_redo->add_undo_method(library.ptr(), "remove_animation", new_name); undo_redo->add_do_method(player, "animation_set_next", new_name, player->animation_get_next(current)); undo_redo->add_do_method(this, "_animation_player_changed", player); undo_redo->add_undo_method(this, "_animation_player_changed", player); @@ -567,7 +527,7 @@ void AnimationPlayerEditor::_animation_name_edited() { } void AnimationPlayerEditor::_blend_editor_next_changed(const int p_idx) { - if (animation->get_item_count() == 0) { + if (!animation->has_selectable_items()) { return; } @@ -588,7 +548,7 @@ void AnimationPlayerEditor::_animation_blend() { blend_editor.tree->clear(); - if (animation->get_item_count() == 0) { + if (!animation->has_selectable_items()) { return; } @@ -643,7 +603,7 @@ void AnimationPlayerEditor::_blend_edited() { return; } - if (animation->get_item_count() == 0) { + if (!animation->has_selectable_items()) { return; } @@ -722,16 +682,16 @@ void AnimationPlayerEditor::set_state(const Dictionary &p_state) { } void AnimationPlayerEditor::_animation_resource_edit() { - if (animation->get_item_count()) { - String current = animation->get_item_text(animation->get_selected()); + String current = _get_current(); + if (current != String()) { Ref<Animation> anim = player->get_animation(current); EditorNode::get_singleton()->edit_resource(anim); } } void AnimationPlayerEditor::_animation_edit() { - if (animation->get_item_count()) { - String current = animation->get_item_text(animation->get_selected()); + String current = _get_current(); + if (current != String()) { Ref<Animation> anim = player->get_animation(current); track_editor->set_animation(anim); @@ -745,51 +705,6 @@ void AnimationPlayerEditor::_animation_edit() { } } -void AnimationPlayerEditor::_save_animation(String p_file) { - String current = animation->get_item_text(animation->get_selected()); - if (!current.is_empty()) { - Ref<Animation> anim = player->get_animation(current); - - ERR_FAIL_COND(!Object::cast_to<Resource>(*anim)); - - RES current_res = RES(Object::cast_to<Resource>(*anim)); - - _animation_save_in_path(current_res, p_file); - } -} - -void AnimationPlayerEditor::_load_animations(Vector<String> p_files) { - ERR_FAIL_COND(!player); - - for (int i = 0; i < p_files.size(); i++) { - String file = p_files[i]; - - Ref<Resource> res = ResourceLoader::load(file, "Animation"); - ERR_FAIL_COND_MSG(res.is_null(), "Cannot load Animation from file '" + file + "'."); - ERR_FAIL_COND_MSG(!res->is_class("Animation"), "Loaded resource from file '" + file + "' is not Animation."); - if (file.rfind("/") != -1) { - file = file.substr(file.rfind("/") + 1, file.length()); - } - if (file.rfind("\\") != -1) { - file = file.substr(file.rfind("\\") + 1, file.length()); - } - - if (file.contains(".")) { - file = file.substr(0, file.find(".")); - } - - undo_redo->create_action(TTR("Load Animation")); - undo_redo->add_do_method(player, "add_animation", file, res); - undo_redo->add_undo_method(player, "remove_animation", file); - if (player->has_animation(file)) { - undo_redo->add_undo_method(player, "add_animation", file, player->get_animation(file)); - } - undo_redo->add_do_method(this, "_animation_player_changed", player); - undo_redo->add_undo_method(this, "_animation_player_changed", player); - undo_redo->commit_action(); - } -} - void AnimationPlayerEditor::_scale_changed(const String &p_scale) { player->set_speed_scale(p_scale.to_float()); } @@ -824,49 +739,67 @@ void AnimationPlayerEditor::_update_animation() { void AnimationPlayerEditor::_update_player() { updating = true; - List<StringName> animlist; - if (player) { - player->get_animation_list(&animlist); - } animation->clear(); -#define ITEM_DISABLED(m_item, m_disabled) tool_anim->get_popup()->set_item_disabled(tool_anim->get_popup()->get_item_index(m_item), m_disabled) - - ITEM_DISABLED(TOOL_SAVE_ANIM, animlist.size() == 0); - ITEM_DISABLED(TOOL_SAVE_AS_ANIM, animlist.size() == 0); - ITEM_DISABLED(TOOL_DUPLICATE_ANIM, animlist.size() == 0); - ITEM_DISABLED(TOOL_RENAME_ANIM, animlist.size() == 0); - ITEM_DISABLED(TOOL_EDIT_TRANSITIONS, animlist.size() == 0); - ITEM_DISABLED(TOOL_COPY_ANIM, animlist.size() == 0); - ITEM_DISABLED(TOOL_REMOVE_ANIM, animlist.size() == 0); - - stop->set_disabled(animlist.size() == 0); - play->set_disabled(animlist.size() == 0); - play_bw->set_disabled(animlist.size() == 0); - play_bw_from->set_disabled(animlist.size() == 0); - play_from->set_disabled(animlist.size() == 0); - frame->set_editable(animlist.size() != 0); - animation->set_disabled(animlist.size() == 0); - autoplay->set_disabled(animlist.size() == 0); - tool_anim->set_disabled(player == nullptr); - onion_toggle->set_disabled(animlist.size() == 0); - onion_skinning->set_disabled(animlist.size() == 0); - pin->set_disabled(player == nullptr); - if (!player) { AnimationPlayerEditor::get_singleton()->get_track_editor()->update_keying(); return; } + List<StringName> libraries; + if (player) { + player->get_animation_library_list(&libraries); + } + int active_idx = -1; - for (const StringName &E : animlist) { - animation->add_item(E); + bool no_anims_found = true; - if (player->get_assigned_animation() == E) { - active_idx = animation->get_item_count() - 1; + for (const StringName &K : libraries) { + if (K != StringName()) { + animation->add_separator(K); + } + + Ref<AnimationLibrary> library = player->get_animation_library(K); + List<StringName> animlist; + library->get_animation_list(&animlist); + + for (const StringName &E : animlist) { + String path = K; + if (path != "") { + path += "/"; + } + path += E; + animation->add_item(path); + if (player->get_assigned_animation() == path) { + active_idx = animation->get_selectable_item(true); + } + no_anims_found = false; } } +#define ITEM_CHECK_DISABLED(m_item) tool_anim->get_popup()->set_item_disabled(tool_anim->get_popup()->get_item_index(m_item), no_anims_found) + + ITEM_CHECK_DISABLED(TOOL_DUPLICATE_ANIM); + ITEM_CHECK_DISABLED(TOOL_RENAME_ANIM); + ITEM_CHECK_DISABLED(TOOL_EDIT_TRANSITIONS); + ITEM_CHECK_DISABLED(TOOL_REMOVE_ANIM); + ITEM_CHECK_DISABLED(TOOL_EDIT_RESOURCE); + +#undef ITEM_CHECK_DISABLED + + stop->set_disabled(no_anims_found); + play->set_disabled(no_anims_found); + play_bw->set_disabled(no_anims_found); + play_bw_from->set_disabled(no_anims_found); + play_from->set_disabled(no_anims_found); + frame->set_editable(!no_anims_found); + animation->set_disabled(no_anims_found); + autoplay->set_disabled(no_anims_found); + tool_anim->set_disabled(player == nullptr); + onion_toggle->set_disabled(no_anims_found); + onion_skinning->set_disabled(no_anims_found); + pin->set_disabled(player == nullptr); + _update_animation_list_icons(); updating = false; @@ -874,16 +807,16 @@ void AnimationPlayerEditor::_update_player() { animation->select(active_idx); autoplay->set_pressed(animation->get_item_text(active_idx) == player->get_autoplay()); _animation_selected(active_idx); - - } else if (animation->get_item_count() > 0) { - animation->select(0); - autoplay->set_pressed(animation->get_item_text(0) == player->get_autoplay()); - _animation_selected(0); + } else if (animation->has_selectable_items()) { + int item = animation->get_selectable_item(); + animation->select(item); + autoplay->set_pressed(animation->get_item_text(item) == player->get_autoplay()); + _animation_selected(item); } else { _animation_selected(0); } - if (animation->get_item_count()) { + if (!no_anims_found) { String current = animation->get_item_text(animation->get_selected()); Ref<Animation> anim = player->get_animation(current); track_editor->set_animation(anim); @@ -899,6 +832,9 @@ void AnimationPlayerEditor::_update_player() { void AnimationPlayerEditor::_update_animation_list_icons() { for (int i = 0; i < animation->get_item_count(); i++) { String name = animation->get_item_text(i); + if (animation->is_item_disabled(i) || animation->is_item_separator(i)) { + continue; + } Ref<Texture2D> icon; if (name == player->get_autoplay()) { @@ -925,7 +861,7 @@ void AnimationPlayerEditor::edit(AnimationPlayer *p_player) { _update_player(); if (onion.enabled) { - if (animation->get_item_count() > 0) { + if (animation->has_selectable_items()) { _start_onion_skinning(); } else { _stop_onion_skinning(); @@ -940,6 +876,8 @@ void AnimationPlayerEditor::edit(AnimationPlayer *p_player) { track_editor->show_select_node_warning(true); } + + library_editor->set_animation_player(player); } void AnimationPlayerEditor::forward_force_draw_over_viewport(Control *p_overlay) { @@ -993,7 +931,7 @@ void AnimationPlayerEditor::forward_force_draw_over_viewport(Control *p_overlay) } void AnimationPlayerEditor::_animation_duplicate() { - if (!animation->get_item_count()) { + if (!animation->has_selectable_items()) { return; } @@ -1031,29 +969,6 @@ Ref<Animation> AnimationPlayerEditor::_animation_clone(Ref<Animation> p_anim) { return new_anim; } -void AnimationPlayerEditor::_animation_paste(Ref<Animation> p_anim) { - String name = p_anim->get_name(); - if (name.is_empty()) { - name = TTR("Pasted Animation"); - } - - int idx = 1; - String base = name; - while (player->has_animation(name)) { - idx++; - name = base + " " + itos(idx); - } - - undo_redo->create_action(TTR("Paste Animation")); - undo_redo->add_do_method(player, "add_animation", name, p_anim); - undo_redo->add_undo_method(player, "remove_animation", name); - undo_redo->add_do_method(this, "_animation_player_changed", player); - undo_redo->add_undo_method(this, "_animation_player_changed", player); - undo_redo->commit_action(); - - _select_anim_by_name(name); -} - void AnimationPlayerEditor::_seek_value_changed(float p_value, bool p_set, bool p_timeline_only) { if (updating || !player || player->is_playing()) { return; @@ -1095,6 +1010,9 @@ void AnimationPlayerEditor::_animation_player_changed(Object *p_pl) { if (blend_editor.dialog->is_visible()) { _animation_blend(); // Update. } + if (library_editor->is_visible()) { + library_editor->update_tree(); + } } } @@ -1134,10 +1052,7 @@ void AnimationPlayerEditor::_animation_key_editor_seek(float p_pos, bool p_drag, } void AnimationPlayerEditor::_animation_tool_menu(int p_option) { - String current; - if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) { - current = animation->get_item_text(animation->get_selected()); - } + String current = _get_current(); Ref<Animation> anim; if (!current.is_empty()) { @@ -1148,18 +1063,9 @@ void AnimationPlayerEditor::_animation_tool_menu(int p_option) { case TOOL_NEW_ANIM: { _animation_new(); } break; - case TOOL_LOAD_ANIM: { - _animation_load(); - } break; - case TOOL_SAVE_ANIM: { - if (anim.is_valid()) { - _animation_save(anim); - } - } break; - case TOOL_SAVE_AS_ANIM: { - if (anim.is_valid()) { - _animation_save_as(anim); - } + case TOOL_ANIM_LIBRARY: { + library_editor->set_animation_player(player); + library_editor->show_dialog(); } break; case TOOL_DUPLICATE_ANIM: { _animation_duplicate(); @@ -1173,47 +1079,10 @@ void AnimationPlayerEditor::_animation_tool_menu(int p_option) { case TOOL_REMOVE_ANIM: { _animation_remove(); } break; - case TOOL_COPY_ANIM: { - if (!animation->get_item_count()) { - error_dialog->set_text(TTR("No animation to copy!")); - error_dialog->popup_centered(); - return; - } - - String current2 = animation->get_item_text(animation->get_selected()); - Ref<Animation> anim2 = player->get_animation(current2); - EditorSettings::get_singleton()->set_resource_clipboard(anim2); - } break; - case TOOL_PASTE_ANIM: { - Ref<Animation> anim2 = EditorSettings::get_singleton()->get_resource_clipboard(); - if (!anim2.is_valid()) { - error_dialog->set_text(TTR("No animation resource in clipboard!")); - error_dialog->popup_centered(); - return; - } - Ref<Animation> new_anim = _animation_clone(anim2); - _animation_paste(new_anim); - } break; - case TOOL_PASTE_ANIM_REF: { - Ref<Animation> anim2 = EditorSettings::get_singleton()->get_resource_clipboard(); - if (!anim2.is_valid()) { - error_dialog->set_text(TTR("No animation resource in clipboard!")); - error_dialog->popup_centered(); - return; - } - - _animation_paste(anim2); - } break; case TOOL_EDIT_RESOURCE: { - if (!animation->get_item_count()) { - error_dialog->set_text(TTR("No animation to edit!")); - error_dialog->popup_centered(); - return; + if (anim.is_valid()) { + EditorNode::get_singleton()->edit_resource(anim); } - - String current2 = animation->get_item_text(animation->get_selected()); - Ref<Animation> anim2 = player->get_animation(current2); - EditorNode::get_singleton()->edit_resource(anim2); } break; } } @@ -1267,7 +1136,7 @@ void AnimationPlayerEditor::_onion_skinning_menu(int p_option) { } } -void AnimationPlayerEditor::unhandled_key_input(const Ref<InputEvent> &p_ev) { +void AnimationPlayerEditor::shortcut_input(const Ref<InputEvent> &p_ev) { ERR_FAIL_COND(p_ev.is_null()); Ref<InputEventKey> k = p_ev; @@ -1300,7 +1169,7 @@ void AnimationPlayerEditor::unhandled_key_input(const Ref<InputEvent> &p_ev) { } void AnimationPlayerEditor::_editor_visibility_changed() { - if (is_visible() && animation->get_item_count() > 0) { + if (is_visible() && animation->has_selectable_items()) { _start_onion_skinning(); } } @@ -1536,7 +1405,6 @@ void AnimationPlayerEditor::_pin_pressed() { void AnimationPlayerEditor::_bind_methods() { ClassDB::bind_method(D_METHOD("_animation_new"), &AnimationPlayerEditor::_animation_new); ClassDB::bind_method(D_METHOD("_animation_rename"), &AnimationPlayerEditor::_animation_rename); - ClassDB::bind_method(D_METHOD("_animation_load"), &AnimationPlayerEditor::_animation_load); ClassDB::bind_method(D_METHOD("_animation_remove"), &AnimationPlayerEditor::_animation_remove); ClassDB::bind_method(D_METHOD("_animation_blend"), &AnimationPlayerEditor::_animation_blend); ClassDB::bind_method(D_METHOD("_animation_edit"), &AnimationPlayerEditor::_animation_edit); @@ -1623,13 +1491,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(AnimationPlayerEditorPlugin *p_plug tool_anim->set_text(TTR("Animation")); tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/new_animation", TTR("New")), TOOL_NEW_ANIM); tool_anim->get_popup()->add_separator(); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/open_animation", TTR("Load")), TOOL_LOAD_ANIM); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/save_animation", TTR("Save")), TOOL_SAVE_ANIM); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/save_as_animation", TTR("Save As...")), TOOL_SAVE_AS_ANIM); - tool_anim->get_popup()->add_separator(); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/copy_animation", TTR("Copy")), TOOL_COPY_ANIM); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/paste_animation", TTR("Paste")), TOOL_PASTE_ANIM); - tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/paste_animation_as_reference", TTR("Paste As Reference")), TOOL_PASTE_ANIM_REF); + tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/animation_libraries", TTR("Manage Animations...")), TOOL_ANIM_LIBRARY); tool_anim->get_popup()->add_separator(); tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/duplicate_animation", TTR("Duplicate...")), TOOL_DUPLICATE_ANIM); tool_anim->get_popup()->add_separator(); @@ -1638,6 +1500,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(AnimationPlayerEditorPlugin *p_plug tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/open_animation_in_inspector", TTR("Open in Inspector")), TOOL_EDIT_RESOURCE); tool_anim->get_popup()->add_separator(); tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/remove_animation", TTR("Remove")), TOOL_REMOVE_ANIM); + tool_anim->set_disabled(true); hb->add_child(tool_anim); animation = memnew(OptionButton); @@ -1705,8 +1568,14 @@ AnimationPlayerEditor::AnimationPlayerEditor(AnimationPlayerEditorPlugin *p_plug name_title = memnew(Label(TTR("Animation Name:"))); vb->add_child(name_title); + HBoxContainer *name_hb = memnew(HBoxContainer); name = memnew(LineEdit); - vb->add_child(name); + name_hb->add_child(name); + name->set_h_size_flags(SIZE_EXPAND_FILL); + library = memnew(OptionButton); + name_hb->add_child(library); + library->hide(); + vb->add_child(name_hb); name_dialog->register_text_enter(name); error_dialog = memnew(ConfirmationDialog); @@ -1742,15 +1611,13 @@ AnimationPlayerEditor::AnimationPlayerEditor(AnimationPlayerEditorPlugin *p_plug animation->connect("item_selected", callable_mp(this, &AnimationPlayerEditor::_animation_selected)); - file->connect("file_selected", callable_mp(this, &AnimationPlayerEditor::_save_animation)); - file->connect("files_selected", callable_mp(this, &AnimationPlayerEditor::_load_animations)); frame->connect("value_changed", callable_mp(this, &AnimationPlayerEditor::_seek_value_changed), make_binds(true, false)); scale->connect("text_submitted", callable_mp(this, &AnimationPlayerEditor::_scale_changed)); last_active = false; timeline_position = 0; - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); add_child(track_editor); track_editor->set_v_size_flags(SIZE_EXPAND_FILL); @@ -1759,6 +1626,10 @@ AnimationPlayerEditor::AnimationPlayerEditor(AnimationPlayerEditorPlugin *p_plug _update_player(); + library_editor = memnew(AnimationLibraryEditor); + add_child(library_editor); + library_editor->connect("update_editor", callable_mp(this, &AnimationPlayerEditor::_animation_player_changed)); + // Onion skinning. track_editor->connect("visibility_changed", callable_mp(this, &AnimationPlayerEditor::_editor_visibility_changed)); diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h index 5bb32e25e6..0cc04460ca 100644 --- a/editor/plugins/animation_player_editor_plugin.h +++ b/editor/plugins/animation_player_editor_plugin.h @@ -33,6 +33,7 @@ #include "editor/animation_track_editor.h" #include "editor/editor_plugin.h" +#include "editor/plugins/animation_library_editor.h" #include "scene/animation/animation_player.h" #include "scene/gui/dialogs.h" #include "scene/gui/slider.h" @@ -40,27 +41,21 @@ #include "scene/gui/texture_button.h" #include "scene/gui/tree.h" -class EditorFileDialog; class AnimationPlayerEditorPlugin; class AnimationPlayerEditor : public VBoxContainer { GDCLASS(AnimationPlayerEditor, VBoxContainer); - AnimationPlayerEditorPlugin *plugin; - AnimationPlayer *player; + AnimationPlayerEditorPlugin *plugin = nullptr; + AnimationPlayer *player = nullptr; enum { TOOL_NEW_ANIM, - TOOL_LOAD_ANIM, - TOOL_SAVE_ANIM, - TOOL_SAVE_AS_ANIM, + TOOL_ANIM_LIBRARY, TOOL_DUPLICATE_ANIM, TOOL_RENAME_ANIM, TOOL_EDIT_TRANSITIONS, TOOL_REMOVE_ANIM, - TOOL_COPY_ANIM, - TOOL_PASTE_ANIM, - TOOL_PASTE_ANIM_REF, TOOL_EDIT_RESOURCE }; @@ -88,31 +83,35 @@ class AnimationPlayerEditor : public VBoxContainer { RESOURCE_SAVE }; - OptionButton *animation; - Button *stop; - Button *play; - Button *play_from; - Button *play_bw; - Button *play_bw_from; - Button *autoplay; - - MenuButton *tool_anim; - Button *onion_toggle; - MenuButton *onion_skinning; - Button *pin; - SpinBox *frame; - LineEdit *scale; - LineEdit *name; - Label *name_title; - UndoRedo *undo_redo; + OptionButton *animation = nullptr; + Button *stop = nullptr; + Button *play = nullptr; + Button *play_from = nullptr; + Button *play_bw = nullptr; + Button *play_bw_from = nullptr; + Button *autoplay = nullptr; + + MenuButton *tool_anim = nullptr; + Button *onion_toggle = nullptr; + MenuButton *onion_skinning = nullptr; + Button *pin = nullptr; + SpinBox *frame = nullptr; + LineEdit *scale = nullptr; + LineEdit *name = nullptr; + OptionButton *library = nullptr; + Label *name_title = nullptr; + UndoRedo *undo_redo = nullptr; + Ref<Texture2D> autoplay_icon; Ref<Texture2D> reset_icon; Ref<ImageTexture> autoplay_reset_icon; bool last_active; float timeline_position; - EditorFileDialog *file; - ConfirmationDialog *delete_dialog; + EditorFileDialog *file = nullptr; + ConfirmationDialog *delete_dialog = nullptr; + + AnimationLibraryEditor *library_editor = nullptr; struct BlendEditor { AcceptDialog *dialog = nullptr; @@ -121,14 +120,14 @@ class AnimationPlayerEditor : public VBoxContainer { } blend_editor; - ConfirmationDialog *name_dialog; - ConfirmationDialog *error_dialog; + ConfirmationDialog *name_dialog = nullptr; + ConfirmationDialog *error_dialog = nullptr; int name_dialog_op = TOOL_NEW_ANIM; bool updating; bool updating_blends; - AnimationTrackEditor *track_editor; + AnimationTrackEditor *track_editor = nullptr; static AnimationPlayerEditor *singleton; // Onion skinning. @@ -173,11 +172,6 @@ class AnimationPlayerEditor : public VBoxContainer { void _animation_new(); void _animation_rename(); void _animation_name_edited(); - void _animation_load(); - - void _animation_save_in_path(const Ref<Resource> &p_resource, const String &p_path); - void _animation_save(const Ref<Resource> &p_resource); - void _animation_save_as(const Ref<Resource> &p_resource); void _animation_remove(); void _animation_remove_confirmed(); @@ -185,11 +179,8 @@ class AnimationPlayerEditor : public VBoxContainer { void _animation_edit(); void _animation_duplicate(); Ref<Animation> _animation_clone(const Ref<Animation> p_anim); - void _animation_paste(const Ref<Animation> p_anim); void _animation_resource_edit(); void _scale_changed(const String &p_scale); - void _save_animation(String p_file); - void _load_animations(Vector<String> p_files); void _seek_value_changed(float p_value, bool p_set = false, bool p_timeline_only = false); void _blend_editor_next_changed(const int p_idx); @@ -204,7 +195,7 @@ class AnimationPlayerEditor : public VBoxContainer { void _animation_key_editor_seek(float p_pos, bool p_drag, bool p_timeline_only = false); void _animation_key_editor_anim_len_changed(float p_len); - virtual void unhandled_key_input(const Ref<InputEvent> &p_ev) override; + virtual void shortcut_input(const Ref<InputEvent> &p_ev) override; void _animation_tool_menu(int p_option); void _onion_skinning_menu(int p_option); @@ -219,6 +210,7 @@ class AnimationPlayerEditor : public VBoxContainer { void _stop_onion_skinning(); void _pin_pressed(); + String _get_current() const; ~AnimationPlayerEditor(); @@ -250,7 +242,7 @@ public: class AnimationPlayerEditorPlugin : public EditorPlugin { GDCLASS(AnimationPlayerEditorPlugin, EditorPlugin); - AnimationPlayerEditor *anim_editor; + AnimationPlayerEditor *anim_editor = nullptr; protected: void _notification(int p_what); diff --git a/editor/plugins/animation_state_machine_editor.cpp b/editor/plugins/animation_state_machine_editor.cpp index bd0c1afd19..f0dabed652 100644 --- a/editor/plugins/animation_state_machine_editor.cpp +++ b/editor/plugins/animation_state_machine_editor.cpp @@ -499,7 +499,7 @@ void AnimationNodeStateMachineEditor::_connection_draw(const Vector2 &p_from, co accent.a *= 0.6; } - Ref<Texture2D> icons[6] = { + const Ref<Texture2D> icons[6] = { get_theme_icon(SNAME("TransitionImmediateBig"), SNAME("EditorIcons")), get_theme_icon(SNAME("TransitionSyncBig"), SNAME("EditorIcons")), get_theme_icon(SNAME("TransitionEndBig"), SNAME("EditorIcons")), diff --git a/editor/plugins/animation_state_machine_editor.h b/editor/plugins/animation_state_machine_editor.h index 03991d00f9..bf3f7e93cf 100644 --- a/editor/plugins/animation_state_machine_editor.h +++ b/editor/plugins/animation_state_machine_editor.h @@ -47,36 +47,36 @@ class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin { Ref<AnimationNodeStateMachine> state_machine; - Button *tool_select; - Button *tool_create; - Button *tool_connect; - Popup *name_edit_popup; - LineEdit *name_edit; + Button *tool_select = nullptr; + Button *tool_create = nullptr; + Button *tool_connect = nullptr; + Popup *name_edit_popup = nullptr; + LineEdit *name_edit = nullptr; - HBoxContainer *tool_erase_hb; - Button *tool_erase; - Button *tool_autoplay; - Button *tool_end; + HBoxContainer *tool_erase_hb = nullptr; + Button *tool_erase = nullptr; + Button *tool_autoplay = nullptr; + Button *tool_end = nullptr; - OptionButton *transition_mode; - OptionButton *play_mode; + OptionButton *transition_mode = nullptr; + OptionButton *play_mode = nullptr; - PanelContainer *panel; + PanelContainer *panel = nullptr; StringName selected_node; - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; - Control *state_machine_draw; - Control *state_machine_play_pos; + Control *state_machine_draw = nullptr; + Control *state_machine_play_pos = nullptr; - PanelContainer *error_panel; - Label *error_label; + PanelContainer *error_panel = nullptr; + Label *error_label = nullptr; bool updating; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; static AnimationNodeStateMachineEditor *singleton; @@ -87,8 +87,8 @@ class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin { void _update_graph(); - PopupMenu *menu; - PopupMenu *animations_menu; + PopupMenu *menu = nullptr; + PopupMenu *animations_menu = nullptr; Vector<String> animations_to_add; Vector2 add_node_pos; @@ -166,7 +166,7 @@ class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin { float error_time; String error_text; - EditorFileDialog *open_file; + EditorFileDialog *open_file = nullptr; Ref<AnimationNode> file_loaded; void _file_opened(const String &p_file); diff --git a/editor/plugins/animation_tree_editor_plugin.h b/editor/plugins/animation_tree_editor_plugin.h index 5442584a40..ab4ef5a001 100644 --- a/editor/plugins/animation_tree_editor_plugin.h +++ b/editor/plugins/animation_tree_editor_plugin.h @@ -52,11 +52,11 @@ public: class AnimationTreeEditor : public VBoxContainer { GDCLASS(AnimationTreeEditor, VBoxContainer); - ScrollContainer *path_edit; - HBoxContainer *path_hb; + ScrollContainer *path_edit = nullptr; + HBoxContainer *path_hb = nullptr; - AnimationTree *tree; - MarginContainer *editor_base; + AnimationTree *tree = nullptr; + MarginContainer *editor_base = nullptr; Vector<String> button_path; Vector<String> edited_path; @@ -96,8 +96,8 @@ public: class AnimationTreeEditorPlugin : public EditorPlugin { GDCLASS(AnimationTreeEditorPlugin, EditorPlugin); - AnimationTreeEditor *anim_tree_editor; - Button *button; + AnimationTreeEditor *anim_tree_editor = nullptr; + Button *button = nullptr; public: virtual String get_name() const override { return "AnimationTree"; } diff --git a/editor/plugins/asset_library_editor_plugin.cpp b/editor/plugins/asset_library_editor_plugin.cpp index 20bd145299..157eed02f4 100644 --- a/editor/plugins/asset_library_editor_plugin.cpp +++ b/editor/plugins/asset_library_editor_plugin.cpp @@ -640,7 +640,7 @@ void EditorAssetLibrary::_update_repository_options() { } } -void EditorAssetLibrary::unhandled_key_input(const Ref<InputEvent> &p_event) { +void EditorAssetLibrary::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); const Ref<InputEventKey> key = p_event; @@ -729,9 +729,8 @@ void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PackedB if (use_cache) { String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().plus_file("assetimage_" + image_queue[p_queue_id].image_url.md5_text()); - FileAccess *file = FileAccess::open(cache_filename_base + ".data", FileAccess::READ); - - if (file) { + Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".data", FileAccess::READ); + if (file.is_valid()) { PackedByteArray cached_data; int len = file->get_32(); cached_data.resize(len); @@ -740,8 +739,6 @@ void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PackedB file->get_buffer(w, len); image_data = cached_data; - file->close(); - memdelete(file); } } @@ -808,23 +805,17 @@ void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, cons if (headers[i].findn("ETag:") == 0) { // Save etag String cache_filename_base = EditorPaths::get_singleton()->get_cache_dir().plus_file("assetimage_" + image_queue[p_queue_id].image_url.md5_text()); String new_etag = headers[i].substr(headers[i].find(":") + 1, headers[i].length()).strip_edges(); - FileAccess *file; - - file = FileAccess::open(cache_filename_base + ".etag", FileAccess::WRITE); - if (file) { + Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".etag", FileAccess::WRITE); + if (file.is_valid()) { file->store_line(new_etag); - file->close(); - memdelete(file); } int len = p_data.size(); const uint8_t *r = p_data.ptr(); file = FileAccess::open(cache_filename_base + ".data", FileAccess::WRITE); - if (file) { + if (file.is_valid()) { file->store_32(len); file->store_buffer(r, len); - file->close(); - memdelete(file); } break; @@ -858,11 +849,9 @@ void EditorAssetLibrary::_update_image_queue() { Vector<String> headers; if (FileAccess::exists(cache_filename_base + ".etag") && FileAccess::exists(cache_filename_base + ".data")) { - FileAccess *file = FileAccess::open(cache_filename_base + ".etag", FileAccess::READ); - if (file) { + Ref<FileAccess> file = FileAccess::open(cache_filename_base + ".etag", FileAccess::READ); + if (file.is_valid()) { headers.push_back("If-None-Match: " + file->get_line()); - file->close(); - memdelete(file); } } @@ -1541,7 +1530,7 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) { description = nullptr; set_process(true); - set_process_unhandled_key_input(true); // Global shortcuts since there is no main element to be focused. + set_process_shortcut_input(true); // Global shortcuts since there is no main element to be focused. downloads_scroll = memnew(ScrollContainer); downloads_scroll->set_vertical_scroll_mode(ScrollContainer::SCROLL_MODE_DISABLED); diff --git a/editor/plugins/asset_library_editor_plugin.h b/editor/plugins/asset_library_editor_plugin.h index 493ffc4033..96830c31fd 100644 --- a/editor/plugins/asset_library_editor_plugin.h +++ b/editor/plugins/asset_library_editor_plugin.h @@ -53,12 +53,12 @@ class EditorAssetLibraryItem : public PanelContainer { GDCLASS(EditorAssetLibraryItem, PanelContainer); - TextureButton *icon; - LinkButton *title; - LinkButton *category; - LinkButton *author; + TextureButton *icon = nullptr; + LinkButton *title = nullptr; + LinkButton *category = nullptr; + LinkButton *author = nullptr; TextureRect *stars[5]; - Label *price; + Label *price = nullptr; int asset_id; int category_id; @@ -83,11 +83,11 @@ public: class EditorAssetLibraryItemDescription : public ConfirmationDialog { GDCLASS(EditorAssetLibraryItemDescription, ConfirmationDialog); - EditorAssetLibraryItem *item; - RichTextLabel *description; - ScrollContainer *previews; - HBoxContainer *preview_hb; - PanelContainer *previews_bg; + EditorAssetLibraryItem *item = nullptr; + RichTextLabel *description = nullptr; + ScrollContainer *previews = nullptr; + HBoxContainer *preview_hb = nullptr; + PanelContainer *previews_bg = nullptr; struct Preview { int id = 0; @@ -98,7 +98,7 @@ class EditorAssetLibraryItemDescription : public ConfirmationDialog { }; Vector<Preview> preview_images; - TextureRect *preview; + TextureRect *preview = nullptr; void set_image(int p_type, int p_index, const Ref<Texture2D> &p_image); @@ -130,19 +130,19 @@ public: class EditorAssetLibraryItemDownload : public MarginContainer { GDCLASS(EditorAssetLibraryItemDownload, MarginContainer); - PanelContainer *panel; - TextureRect *icon; - Label *title; - ProgressBar *progress; - Button *install_button; - Button *retry_button; - TextureButton *dismiss_button; + PanelContainer *panel = nullptr; + TextureRect *icon = nullptr; + Label *title = nullptr; + ProgressBar *progress = nullptr; + Button *install_button = nullptr; + Button *retry_button = nullptr; + TextureButton *dismiss_button = nullptr; - AcceptDialog *download_error; - HTTPRequest *download; + AcceptDialog *download_error = nullptr; + HTTPRequest *download = nullptr; String host; String sha256; - Label *status; + Label *status = nullptr; int prev_status; @@ -150,7 +150,7 @@ class EditorAssetLibraryItemDownload : public MarginContainer { bool external_install; - EditorAssetInstaller *asset_installer; + EditorAssetInstaller *asset_installer = nullptr; void _close(); void _make_request(); @@ -176,35 +176,35 @@ class EditorAssetLibrary : public PanelContainer { String host; - EditorFileDialog *asset_open; - EditorAssetInstaller *asset_installer; + EditorFileDialog *asset_open = nullptr; + EditorAssetInstaller *asset_installer = nullptr; void _asset_open(); void _asset_file_selected(const String &p_file); void _update_repository_options(); - PanelContainer *library_scroll_bg; - ScrollContainer *library_scroll; - VBoxContainer *library_vb; - Label *library_loading; - Label *library_error; - LineEdit *filter; - Timer *filter_debounce_timer; - OptionButton *categories; - OptionButton *repository; - OptionButton *sort; - HBoxContainer *error_hb; - TextureRect *error_tr; - Label *error_label; - MenuButton *support; - - HBoxContainer *contents; - - HBoxContainer *asset_top_page; - GridContainer *asset_items; - HBoxContainer *asset_bottom_page; - - HTTPRequest *request; + PanelContainer *library_scroll_bg = nullptr; + ScrollContainer *library_scroll = nullptr; + VBoxContainer *library_vb = nullptr; + Label *library_loading = nullptr; + Label *library_error = nullptr; + LineEdit *filter = nullptr; + Timer *filter_debounce_timer = nullptr; + OptionButton *categories = nullptr; + OptionButton *repository = nullptr; + OptionButton *sort = nullptr; + HBoxContainer *error_hb = nullptr; + TextureRect *error_tr = nullptr; + Label *error_label = nullptr; + MenuButton *support = nullptr; + + HBoxContainer *contents = nullptr; + + HBoxContainer *asset_top_page = nullptr; + GridContainer *asset_items = nullptr; + HBoxContainer *asset_bottom_page = nullptr; + + HTTPRequest *request = nullptr; bool templates_only; bool initial_loading; @@ -260,7 +260,7 @@ class EditorAssetLibrary : public PanelContainer { HBoxContainer *_make_pages(int p_page, int p_page_count, int p_page_len, int p_total_items, int p_current_items); // - EditorAssetLibraryItemDescription *description; + EditorAssetLibraryItemDescription *description = nullptr; // enum RequestType { @@ -273,8 +273,8 @@ class EditorAssetLibrary : public PanelContainer { RequestType requesting; Dictionary category_map; - ScrollContainer *downloads_scroll; - HBoxContainer *downloads_hb; + ScrollContainer *downloads_scroll = nullptr; + HBoxContainer *downloads_hb = nullptr; void _install_asset(); @@ -304,7 +304,7 @@ class EditorAssetLibrary : public PanelContainer { protected: static void _bind_methods(); void _notification(int p_what); - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; public: void disable_community_support(); @@ -315,7 +315,7 @@ public: class AssetLibraryEditorPlugin : public EditorPlugin { GDCLASS(AssetLibraryEditorPlugin, EditorPlugin); - EditorAssetLibrary *addon_library; + EditorAssetLibrary *addon_library = nullptr; public: virtual String get_name() const override { return "AssetLib"; } diff --git a/editor/plugins/audio_stream_editor_plugin.h b/editor/plugins/audio_stream_editor_plugin.h index 2478210430..0d927bddd5 100644 --- a/editor/plugins/audio_stream_editor_plugin.h +++ b/editor/plugins/audio_stream_editor_plugin.h @@ -75,7 +75,7 @@ public: class AudioStreamEditorPlugin : public EditorPlugin { GDCLASS(AudioStreamEditorPlugin, EditorPlugin); - AudioStreamEditor *audio_editor; + AudioStreamEditor *audio_editor = nullptr; public: virtual String get_name() const override { return "Audio"; } diff --git a/editor/plugins/camera_3d_editor_plugin.h b/editor/plugins/camera_3d_editor_plugin.h index c1f71d3b1b..a8164f9b85 100644 --- a/editor/plugins/camera_3d_editor_plugin.h +++ b/editor/plugins/camera_3d_editor_plugin.h @@ -37,9 +37,9 @@ class Camera3DEditor : public Control { GDCLASS(Camera3DEditor, Control); - Panel *panel; - Button *preview; - Node *node; + Panel *panel = nullptr; + Button *preview = nullptr; + Node *node = nullptr; void _pressed(); diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp index 764f467192..8d0db697e2 100644 --- a/editor/plugins/canvas_item_editor_plugin.cpp +++ b/editor/plugins/canvas_item_editor_plugin.cpp @@ -475,7 +475,7 @@ real_t CanvasItemEditor::snap_angle(real_t p_target, real_t p_start) const { } } -void CanvasItemEditor::unhandled_key_input(const Ref<InputEvent> &p_ev) { +void CanvasItemEditor::shortcut_input(const Ref<InputEvent> &p_ev) { ERR_FAIL_COND(p_ev.is_null()); Ref<InputEventKey> k = p_ev; @@ -860,7 +860,7 @@ void CanvasItemEditor::_commit_canvas_item_state(List<CanvasItem *> p_canvas_ite } void CanvasItemEditor::_snap_changed() { - ((SnapDialog *)snap_dialog)->get_fields(grid_offset, grid_step, primary_grid_steps, snap_rotation_offset, snap_rotation_step, snap_scale_step); + static_cast<SnapDialog *>(snap_dialog)->get_fields(grid_offset, grid_step, primary_grid_steps, snap_rotation_offset, snap_rotation_step, snap_scale_step); grid_step_multiplier = 0; viewport->update(); } @@ -1504,7 +1504,7 @@ bool CanvasItemEditor::_gui_input_anchors(const Ref<InputEvent> &p_event) { } } - DragType dragger[] = { + const DragType dragger[] = { DRAG_ANCHOR_TOP_LEFT, DRAG_ANCHOR_TOP_RIGHT, DRAG_ANCHOR_BOTTOM_RIGHT, @@ -1635,14 +1635,14 @@ bool CanvasItemEditor::_gui_input_resize(const Ref<InputEvent> &p_event) { Rect2 rect = canvas_item->_edit_get_rect(); Transform2D xform = transform * canvas_item->get_global_transform_with_canvas(); - Vector2 endpoints[4] = { + const Vector2 endpoints[4] = { xform.xform(rect.position), xform.xform(rect.position + Vector2(rect.size.x, 0)), xform.xform(rect.position + rect.size), xform.xform(rect.position + Vector2(0, rect.size.y)) }; - DragType dragger[] = { + const DragType dragger[] = { DRAG_TOP_LEFT, DRAG_TOP, DRAG_TOP_RIGHT, @@ -2298,7 +2298,7 @@ bool CanvasItemEditor::_gui_input_select(const Ref<InputEvent> &p_event) { } add_node_menu->reset_size(); - add_node_menu->set_position(get_screen_transform().xform(b->get_position())); + add_node_menu->set_position(viewport->get_screen_transform().xform(b->get_position())); add_node_menu->popup(); node_create_position = transform.affine_inverse().xform(b->get_position()); return true; @@ -2318,7 +2318,6 @@ bool CanvasItemEditor::_gui_input_select(const Ref<InputEvent> &p_event) { Vector<_SelectResult> selection = Vector<_SelectResult>(); // Retrieve the canvas items - selection = Vector<_SelectResult>(); _get_canvas_items_at_pos(click, selection); if (!selection.is_empty()) { canvas_item = selection[0].item; @@ -2572,7 +2571,7 @@ void CanvasItemEditor::_gui_input_viewport(const Ref<InputEvent> &p_event) { void CanvasItemEditor::_update_cursor() { // Compute an eventual rotation of the cursor - CursorShape rotation_array[4] = { CURSOR_HSIZE, CURSOR_BDIAGSIZE, CURSOR_VSIZE, CURSOR_FDIAGSIZE }; + const CursorShape rotation_array[4] = { CURSOR_HSIZE, CURSOR_BDIAGSIZE, CURSOR_VSIZE, CURSOR_FDIAGSIZE }; int rotation_array_index = 0; List<CanvasItem *> selection = _get_edited_canvas_items(); @@ -3150,7 +3149,6 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { if (dragged_anchor >= 0) { // Draw the 4 lines when dragged - bool anchor_snapped; Color color_snapped = Color(0.64, 0.93, 0.67, 0.5); Vector2 corners_pos[4]; @@ -3164,7 +3162,7 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { real_t anchor_val = (i >= 2) ? ANCHOR_END - anchors_values[i] : anchors_values[i]; line_starts[i] = corners_pos[i].lerp(corners_pos[(i + 1) % 4], anchor_val); line_ends[i] = corners_pos[(i + 3) % 4].lerp(corners_pos[(i + 2) % 4], anchor_val); - anchor_snapped = anchors_values[i] == 0.0 || anchors_values[i] == 0.5 || anchors_values[i] == 1.0; + bool anchor_snapped = anchors_values[i] == 0.0 || anchors_values[i] == 0.5 || anchors_values[i] == 1.0; viewport->draw_line(line_starts[i], line_ends[i], anchor_snapped ? color_snapped : color_base, (i == dragged_anchor || (i + 3) % 4 == dragged_anchor) ? 2 : 1); } @@ -3328,7 +3326,7 @@ void CanvasItemEditor::_draw_selection() { // Draw the selected items position / surrounding boxes if (canvas_item->_edit_use_rect()) { Rect2 rect = canvas_item->_edit_get_rect(); - Vector2 endpoints[4] = { + const Vector2 endpoints[4] = { xform.xform(rect.position), xform.xform(rect.position + Vector2(rect.size.x, 0)), xform.xform(rect.position + rect.size), @@ -4103,7 +4101,7 @@ void CanvasItemEditor::_button_tool_select(int p_index) { } void CanvasItemEditor::_insert_animation_keys(bool p_location, bool p_rotation, bool p_scale, bool p_on_existing) { - Map<Node *, Object *> &selection = editor_selection->get_selection(); + const Map<Node *, Object *> &selection = editor_selection->get_selection(); for (const KeyValue<Node *, Object *> &E : selection) { CanvasItem *canvas_item = Object::cast_to<CanvasItem>(E.key); @@ -4269,7 +4267,7 @@ void CanvasItemEditor::_popup_callback(int p_op) { snap_config_menu->get_popup()->set_item_checked(idx, snap_pixel); } break; case SNAP_CONFIGURE: { - ((SnapDialog *)snap_dialog)->set_fields(grid_offset, grid_step, primary_grid_steps, snap_rotation_offset, snap_rotation_step, snap_scale_step); + static_cast<SnapDialog *>(snap_dialog)->set_fields(grid_offset, grid_step, primary_grid_steps, snap_rotation_offset, snap_rotation_step, snap_scale_step); snap_dialog->popup_centered(Size2(220, 160) * EDSCALE); } break; case SKELETON_SHOW_BONES: { @@ -4414,7 +4412,7 @@ void CanvasItemEditor::_popup_callback(int p_op) { case ANIM_COPY_POSE: { pose_clipboard.clear(); - Map<Node *, Object *> &selection = editor_selection->get_selection(); + const Map<Node *, Object *> &selection = editor_selection->get_selection(); for (const KeyValue<Node *, Object *> &E : selection) { CanvasItem *canvas_item = Object::cast_to<CanvasItem>(E.key); @@ -5322,7 +5320,7 @@ CanvasItemEditor::CanvasItemEditor() { ED_SHORTCUT("canvas_item_editor/zoom_800_percent", TTR("Zoom to 800%"), Key::KEY_4); ED_SHORTCUT("canvas_item_editor/zoom_1600_percent", TTR("Zoom to 1600%"), Key::KEY_5); - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); // Update the menus' checkboxes call_deferred(SNAME("set_state"), get_state()); @@ -5735,7 +5733,6 @@ void CanvasItemEditorViewport::drop_data(const Point2 &p_point, const Variant &p if (root_node) { target_node = root_node; } else { - drop_pos = p_point; target_node = nullptr; } } diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h index 1a9d49a4a8..26852ea8ed 100644 --- a/editor/plugins/canvas_item_editor_plugin.h +++ b/editor/plugins/canvas_item_editor_plugin.h @@ -183,16 +183,16 @@ private: bool selection_menu_additive_selection; Tool tool = TOOL_SELECT; - Control *viewport; - Control *viewport_scrollable; + Control *viewport = nullptr; + Control *viewport_scrollable = nullptr; - HScrollBar *h_scroll; - VScrollBar *v_scroll; - HBoxContainer *hb; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; + HBoxContainer *hb = nullptr; // Used for secondary menu items which are displayed depending on the currently selected node // (such as MeshInstance's "Mesh" menu). - PanelContainer *context_menu_container; - HBoxContainer *hbc_context_menu; + PanelContainer *context_menu_container = nullptr; + HBoxContainer *hbc_context_menu = nullptr; Transform2D transform; GridVisibility grid_visibility = GRID_VISIBILITY_SHOW_WHEN_SNAPPING; @@ -293,47 +293,47 @@ private: }; List<PoseClipboard> pose_clipboard; - Button *select_button; + Button *select_button = nullptr; - Button *move_button; - Button *scale_button; - Button *rotate_button; + Button *move_button = nullptr; + Button *scale_button = nullptr; + Button *rotate_button = nullptr; - Button *list_select_button; - Button *pivot_button; - Button *pan_button; + Button *list_select_button = nullptr; + Button *pivot_button = nullptr; + Button *pan_button = nullptr; - Button *ruler_button; + Button *ruler_button = nullptr; - Button *smart_snap_button; - Button *grid_snap_button; - MenuButton *snap_config_menu; - PopupMenu *smartsnap_config_popup; + Button *smart_snap_button = nullptr; + Button *grid_snap_button = nullptr; + MenuButton *snap_config_menu = nullptr; + PopupMenu *smartsnap_config_popup = nullptr; - Button *lock_button; - Button *unlock_button; + Button *lock_button = nullptr; + Button *unlock_button = nullptr; - Button *group_button; - Button *ungroup_button; + Button *group_button = nullptr; + Button *ungroup_button = nullptr; - MenuButton *skeleton_menu; - Button *override_camera_button; - MenuButton *view_menu; - PopupMenu *grid_menu; - HBoxContainer *animation_hb; - MenuButton *animation_menu; + MenuButton *skeleton_menu = nullptr; + Button *override_camera_button = nullptr; + MenuButton *view_menu = nullptr; + PopupMenu *grid_menu = nullptr; + HBoxContainer *animation_hb = nullptr; + MenuButton *animation_menu = nullptr; - Button *key_loc_button; - Button *key_rot_button; - Button *key_scale_button; - Button *key_insert_button; - Button *key_auto_insert_button; + Button *key_loc_button = nullptr; + Button *key_rot_button = nullptr; + Button *key_scale_button = nullptr; + Button *key_insert_button = nullptr; + Button *key_auto_insert_button = nullptr; - PopupMenu *selection_menu; - PopupMenu *add_node_menu; + PopupMenu *selection_menu = nullptr; + PopupMenu *add_node_menu = nullptr; - Control *top_ruler; - Control *left_ruler; + Control *top_ruler = nullptr; + Control *left_ruler = nullptr; Point2 drag_start_origin; DragType drag_type = DRAG_NONE; @@ -374,9 +374,9 @@ private: void _find_canvas_items_in_rect(const Rect2 &p_rect, Node *p_node, List<CanvasItem *> *r_items, const Transform2D &p_parent_xform = Transform2D(), const Transform2D &p_canvas_xform = Transform2D()); bool _select_click_on_item(CanvasItem *item, Point2 p_click_pos, bool p_append); - ConfirmationDialog *snap_dialog; + ConfirmationDialog *snap_dialog = nullptr; - CanvasItem *ref_item; + CanvasItem *ref_item = nullptr; void _save_canvas_item_state(List<CanvasItem *> p_canvas_items, bool save_bones = false); void _restore_canvas_item_state(List<CanvasItem *> p_canvas_items, bool restore_bones = false); @@ -400,7 +400,7 @@ private: void _prepare_grid_menu(); void _on_grid_menu_id_pressed(int p_id); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; List<CanvasItem *> _get_edited_canvas_items(bool retrieve_locked = false, bool remove_canvas_item_if_parent_in_selection = true); Rect2 _get_encompassing_rect_from_list(List<CanvasItem *> p_list); @@ -413,7 +413,7 @@ private: void _keying_changed(); - virtual void unhandled_key_input(const Ref<InputEvent> &p_ev) override; + virtual void shortcut_input(const Ref<InputEvent> &p_ev) override; void _draw_text_at_position(Point2 p_position, String p_string, Side p_side); void _draw_margin_at_position(int p_value, Point2 p_position, Side p_side); @@ -476,8 +476,8 @@ private: const SnapTarget p_snap_target, List<const CanvasItem *> p_exceptions, const Node *p_current); - VBoxContainer *controls_vb; - EditorZoomWidget *zoom_widget; + VBoxContainer *controls_vb = nullptr; + EditorZoomWidget *zoom_widget = nullptr; void _update_zoom(real_t p_zoom); void _shortcut_zoom_set(real_t p_zoom); void _zoom_on_position(real_t p_zoom, Point2 p_position = Point2()); @@ -488,9 +488,9 @@ private: void _update_override_camera_button(bool p_game_running); - HSplitContainer *left_panel_split; - HSplitContainer *right_panel_split; - VSplitContainer *bottom_split; + HSplitContainer *left_panel_split = nullptr; + HSplitContainer *right_panel_split = nullptr; + VSplitContainer *bottom_split = nullptr; void _update_context_menu_stylebox(); @@ -555,7 +555,7 @@ public: void focus_selection(); - EditorSelection *editor_selection; + EditorSelection *editor_selection = nullptr; CanvasItemEditor(); }; @@ -563,7 +563,7 @@ public: class CanvasItemEditorPlugin : public EditorPlugin { GDCLASS(CanvasItemEditorPlugin, EditorPlugin); - CanvasItemEditor *canvas_item_editor; + CanvasItemEditor *canvas_item_editor = nullptr; public: virtual String get_name() const override { return "2D"; } @@ -589,18 +589,18 @@ class CanvasItemEditorViewport : public Control { Vector<String> texture_node_types; Vector<String> selected_files; - Node *target_node; + Node *target_node = nullptr; Point2 drop_pos; - EditorData *editor_data; - CanvasItemEditor *canvas_item_editor; - Control *preview_node; - AcceptDialog *accept; - AcceptDialog *selector; - Label *selector_label; - Label *label; - Label *label_desc; - VBoxContainer *btn_group; + EditorData *editor_data = nullptr; + CanvasItemEditor *canvas_item_editor = nullptr; + Control *preview_node = nullptr; + AcceptDialog *accept = nullptr; + AcceptDialog *selector = nullptr; + Label *selector_label = nullptr; + Label *label = nullptr; + Label *label_desc = nullptr; + VBoxContainer *btn_group = nullptr; Ref<ButtonGroup> button_group; void _on_mouse_exit(); diff --git a/editor/plugins/collision_polygon_2d_editor_plugin.cpp b/editor/plugins/collision_polygon_2d_editor_plugin.cpp index 5d769e7987..f018376e4b 100644 --- a/editor/plugins/collision_polygon_2d_editor_plugin.cpp +++ b/editor/plugins/collision_polygon_2d_editor_plugin.cpp @@ -38,10 +38,7 @@ void CollisionPolygon2DEditor::_set_node(Node *p_polygon) { node = Object::cast_to<CollisionPolygon2D>(p_polygon); } -CollisionPolygon2DEditor::CollisionPolygon2DEditor() : - AbstractPolygon2DEditor() { - node = nullptr; -} +CollisionPolygon2DEditor::CollisionPolygon2DEditor() {} CollisionPolygon2DEditorPlugin::CollisionPolygon2DEditorPlugin() : AbstractPolygon2DEditorPlugin(memnew(CollisionPolygon2DEditor), "CollisionPolygon2D") { diff --git a/editor/plugins/collision_polygon_2d_editor_plugin.h b/editor/plugins/collision_polygon_2d_editor_plugin.h index bdd4228b3b..0225d5d620 100644 --- a/editor/plugins/collision_polygon_2d_editor_plugin.h +++ b/editor/plugins/collision_polygon_2d_editor_plugin.h @@ -37,7 +37,7 @@ class CollisionPolygon2DEditor : public AbstractPolygon2DEditor { GDCLASS(CollisionPolygon2DEditor, AbstractPolygon2DEditor); - CollisionPolygon2D *node; + CollisionPolygon2D *node = nullptr; protected: virtual Node2D *_get_node() const override; diff --git a/editor/plugins/collision_shape_2d_editor_plugin.h b/editor/plugins/collision_shape_2d_editor_plugin.h index 033ea3db93..da9e9f339f 100644 --- a/editor/plugins/collision_shape_2d_editor_plugin.h +++ b/editor/plugins/collision_shape_2d_editor_plugin.h @@ -61,9 +61,9 @@ class CollisionShape2DEditor : public Control { Point2(1, -1), }; - UndoRedo *undo_redo; - CanvasItemEditor *canvas_item_editor; - CollisionShape2D *node; + UndoRedo *undo_redo = nullptr; + CanvasItemEditor *canvas_item_editor = nullptr; + CollisionShape2D *node = nullptr; Vector<Point2> handles; @@ -96,7 +96,7 @@ public: class CollisionShape2DEditorPlugin : public EditorPlugin { GDCLASS(CollisionShape2DEditorPlugin, EditorPlugin); - CollisionShape2DEditor *collision_shape_2d_editor; + CollisionShape2DEditor *collision_shape_2d_editor = nullptr; public: virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return collision_shape_2d_editor->forward_canvas_gui_input(p_event); } diff --git a/editor/plugins/control_editor_plugin.h b/editor/plugins/control_editor_plugin.h index 37d218abb9..96451f7dcf 100644 --- a/editor/plugins/control_editor_plugin.h +++ b/editor/plugins/control_editor_plugin.h @@ -70,7 +70,7 @@ public: class EditorPropertyAnchorsPreset : public EditorProperty { GDCLASS(EditorPropertyAnchorsPreset, EditorProperty); - OptionButton *options; + OptionButton *options = nullptr; void _option_selected(int p_which); @@ -94,9 +94,9 @@ class EditorPropertySizeFlags : public EditorProperty { SIZE_FLAGS_PRESET_CUSTOM, }; - OptionButton *flag_presets; - CheckBox *flag_expand; - VBoxContainer *flag_options; + OptionButton *flag_presets = nullptr; + CheckBox *flag_expand = nullptr; + VBoxContainer *flag_options = nullptr; Vector<CheckBox *> flag_checks; bool vertical = false; @@ -128,8 +128,8 @@ public: class ControlEditorToolbar : public HBoxContainer { GDCLASS(ControlEditorToolbar, HBoxContainer); - UndoRedo *undo_redo; - EditorSelection *editor_selection; + UndoRedo *undo_redo = nullptr; + EditorSelection *editor_selection = nullptr; enum MenuOption { ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT, @@ -198,12 +198,12 @@ class ControlEditorToolbar : public HBoxContainer { CONTAINERS_V_PRESET_SHRINK_END, }; - MenuButton *anchor_presets_menu; - PopupMenu *anchors_popup; - MenuButton *container_h_presets_menu; - MenuButton *container_v_presets_menu; + MenuButton *anchor_presets_menu = nullptr; + PopupMenu *anchors_popup = nullptr; + MenuButton *container_h_presets_menu = nullptr; + MenuButton *container_v_presets_menu = nullptr; - Button *anchor_mode_button; + Button *anchor_mode_button = nullptr; bool anchors_mode = false; @@ -239,7 +239,7 @@ public: class ControlEditorPlugin : public EditorPlugin { GDCLASS(ControlEditorPlugin, EditorPlugin); - ControlEditorToolbar *toolbar; + ControlEditorToolbar *toolbar = nullptr; public: virtual String get_name() const override { return "Control"; } diff --git a/editor/plugins/cpu_particles_2d_editor_plugin.h b/editor/plugins/cpu_particles_2d_editor_plugin.h index b10ed73e38..cc59bc924f 100644 --- a/editor/plugins/cpu_particles_2d_editor_plugin.h +++ b/editor/plugins/cpu_particles_2d_editor_plugin.h @@ -55,22 +55,22 @@ class CPUParticles2DEditorPlugin : public EditorPlugin { EMISSION_MODE_BORDER_DIRECTED }; - CPUParticles2D *particles; + CPUParticles2D *particles = nullptr; - EditorFileDialog *file; + EditorFileDialog *file = nullptr; - HBoxContainer *toolbar; - MenuButton *menu; + HBoxContainer *toolbar = nullptr; + MenuButton *menu = nullptr; - SpinBox *epoints; + SpinBox *epoints = nullptr; - ConfirmationDialog *emission_mask; - OptionButton *emission_mask_mode; - CheckBox *emission_colors; + ConfirmationDialog *emission_mask = nullptr; + OptionButton *emission_mask_mode = nullptr; + CheckBox *emission_colors = nullptr; String source_emission_file; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; void _file_selected(const String &p_file); void _menu_callback(int p_idx); void _generate_emission_mask(); diff --git a/editor/plugins/cpu_particles_3d_editor_plugin.h b/editor/plugins/cpu_particles_3d_editor_plugin.h index 0501936574..70f2da4b2d 100644 --- a/editor/plugins/cpu_particles_3d_editor_plugin.h +++ b/editor/plugins/cpu_particles_3d_editor_plugin.h @@ -44,7 +44,7 @@ class CPUParticles3DEditor : public GPUParticles3DEditorBase { }; - CPUParticles3D *node; + CPUParticles3D *node = nullptr; void _menu_option(int); @@ -65,7 +65,7 @@ public: class CPUParticles3DEditorPlugin : public EditorPlugin { GDCLASS(CPUParticles3DEditorPlugin, EditorPlugin); - CPUParticles3DEditor *particles_editor; + CPUParticles3DEditor *particles_editor = nullptr; public: virtual String get_name() const override { return "CPUParticles3D"; } diff --git a/editor/plugins/curve_editor_plugin.h b/editor/plugins/curve_editor_plugin.h index 4aba2fffd0..5cf3b16a06 100644 --- a/editor/plugins/curve_editor_plugin.h +++ b/editor/plugins/curve_editor_plugin.h @@ -99,8 +99,8 @@ private: Transform2D _world_to_view; Ref<Curve> _curve_ref; - PopupMenu *_context_menu; - PopupMenu *_presets_menu; + PopupMenu *_context_menu = nullptr; + PopupMenu *_presets_menu = nullptr; Array _undo_data; bool _has_undo_data; diff --git a/editor/plugins/debugger_editor_plugin.h b/editor/plugins/debugger_editor_plugin.h index c024526285..10e1a27933 100644 --- a/editor/plugins/debugger_editor_plugin.h +++ b/editor/plugins/debugger_editor_plugin.h @@ -41,9 +41,9 @@ class DebuggerEditorPlugin : public EditorPlugin { GDCLASS(DebuggerEditorPlugin, EditorPlugin); private: - MenuButton *debug_menu; - EditorFileServer *file_server; - PopupMenu *instances_menu; + MenuButton *debug_menu = nullptr; + EditorFileServer *file_server = nullptr; + PopupMenu *instances_menu = nullptr; enum MenuOptions { RUN_FILE_SERVER, diff --git a/editor/plugins/gpu_particles_2d_editor_plugin.h b/editor/plugins/gpu_particles_2d_editor_plugin.h index f94ce632e9..75f68617d1 100644 --- a/editor/plugins/gpu_particles_2d_editor_plugin.h +++ b/editor/plugins/gpu_particles_2d_editor_plugin.h @@ -56,26 +56,26 @@ class GPUParticles2DEditorPlugin : public EditorPlugin { EMISSION_MODE_BORDER_DIRECTED }; - GPUParticles2D *particles; + GPUParticles2D *particles = nullptr; List<GPUParticles2D *> selected_particles; - EditorFileDialog *file; + EditorFileDialog *file = nullptr; - HBoxContainer *toolbar; - MenuButton *menu; + HBoxContainer *toolbar = nullptr; + MenuButton *menu = nullptr; - SpinBox *epoints; + SpinBox *epoints = nullptr; - ConfirmationDialog *generate_visibility_rect; - SpinBox *generate_seconds; + ConfirmationDialog *generate_visibility_rect = nullptr; + SpinBox *generate_seconds = nullptr; - ConfirmationDialog *emission_mask; - OptionButton *emission_mask_mode; - CheckBox *emission_colors; + ConfirmationDialog *emission_mask = nullptr; + OptionButton *emission_mask_mode = nullptr; + CheckBox *emission_colors = nullptr; String source_emission_file; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; void _file_selected(const String &p_file); void _menu_callback(int p_idx); void _generate_visibility_rect(); diff --git a/editor/plugins/gpu_particles_3d_editor_plugin.h b/editor/plugins/gpu_particles_3d_editor_plugin.h index 39aa596ece..190fb9954b 100644 --- a/editor/plugins/gpu_particles_3d_editor_plugin.h +++ b/editor/plugins/gpu_particles_3d_editor_plugin.h @@ -41,16 +41,16 @@ class GPUParticles3DEditorBase : public Control { GDCLASS(GPUParticles3DEditorBase, Control); protected: - Node3D *base_node; - Panel *panel; - MenuButton *options; - HBoxContainer *particles_editor_hb; + Node3D *base_node = nullptr; + Panel *panel = nullptr; + MenuButton *options = nullptr; + HBoxContainer *particles_editor_hb = nullptr; - SceneTreeDialog *emission_tree_dialog; + SceneTreeDialog *emission_tree_dialog = nullptr; - ConfirmationDialog *emission_dialog; - SpinBox *emission_amount; - OptionButton *emission_fill; + ConfirmationDialog *emission_dialog = nullptr; + SpinBox *emission_amount = nullptr; + OptionButton *emission_fill = nullptr; Vector<Face3> geometry; @@ -67,9 +67,9 @@ public: class GPUParticles3DEditor : public GPUParticles3DEditorBase { GDCLASS(GPUParticles3DEditor, GPUParticles3DEditorBase); - ConfirmationDialog *generate_aabb; - SpinBox *generate_seconds; - GPUParticles3D *node; + ConfirmationDialog *generate_aabb = nullptr; + SpinBox *generate_seconds = nullptr; + GPUParticles3D *node = nullptr; enum Menu { MENU_OPTION_GENERATE_AABB, @@ -101,7 +101,7 @@ public: class GPUParticles3DEditorPlugin : public EditorPlugin { GDCLASS(GPUParticles3DEditorPlugin, EditorPlugin); - GPUParticles3DEditor *particles_editor; + GPUParticles3DEditor *particles_editor = nullptr; public: virtual String get_name() const override { return "GPUParticles3D"; } diff --git a/editor/plugins/gpu_particles_collision_sdf_editor_plugin.h b/editor/plugins/gpu_particles_collision_sdf_editor_plugin.h index f6e4fd3dec..684279039a 100644 --- a/editor/plugins/gpu_particles_collision_sdf_editor_plugin.h +++ b/editor/plugins/gpu_particles_collision_sdf_editor_plugin.h @@ -41,12 +41,12 @@ class EditorFileDialog; class GPUParticlesCollisionSDF3DEditorPlugin : public EditorPlugin { GDCLASS(GPUParticlesCollisionSDF3DEditorPlugin, EditorPlugin); - GPUParticlesCollisionSDF3D *col_sdf; + GPUParticlesCollisionSDF3D *col_sdf = nullptr; - HBoxContainer *bake_hb; - Button *bake; + HBoxContainer *bake_hb = nullptr; + Button *bake = nullptr; - EditorFileDialog *probe_file; + EditorFileDialog *probe_file = nullptr; static EditorProgress *tmp_progress; static void bake_func_begin(int p_steps); diff --git a/editor/plugins/gradient_editor_plugin.h b/editor/plugins/gradient_editor_plugin.h index 9857ea018d..26bf76fecd 100644 --- a/editor/plugins/gradient_editor_plugin.h +++ b/editor/plugins/gradient_editor_plugin.h @@ -65,9 +65,9 @@ class GradientReverseButton : public BaseButton { class EditorInspectorPluginGradient : public EditorInspectorPlugin { GDCLASS(EditorInspectorPluginGradient, EditorInspectorPlugin); - GradientEditor *editor; - HBoxContainer *gradient_tools_hbox; - GradientReverseButton *reverse_btn; + GradientEditor *editor = nullptr; + HBoxContainer *gradient_tools_hbox = nullptr; + GradientReverseButton *reverse_btn = nullptr; void _reverse_button_pressed(); diff --git a/editor/plugins/input_event_editor_plugin.cpp b/editor/plugins/input_event_editor_plugin.cpp index b4a7081ebc..fb0e260388 100644 --- a/editor/plugins/input_event_editor_plugin.cpp +++ b/editor/plugins/input_event_editor_plugin.cpp @@ -33,6 +33,15 @@ void InputEventConfigContainer::_bind_methods() { } +void InputEventConfigContainer::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_TREE: + case NOTIFICATION_THEME_CHANGED: { + open_config_button->set_icon(get_theme_icon(SNAME("Edit"), SNAME("EditorIcons"))); + } break; + } +} + void InputEventConfigContainer::_configure_pressed() { config_dialog->popup_and_configure(input_event); } @@ -47,12 +56,6 @@ void InputEventConfigContainer::_config_dialog_confirmed() { _event_changed(); } -Size2 InputEventConfigContainer::get_minimum_size() const { - // Don't bother with a minimum x size for the control - we don't want the inspector - // to jump in size if a long text is placed in the label (e.g. Joypad Axis description) - return Size2(0, HBoxContainer::get_minimum_size().y); -} - void InputEventConfigContainer::set_event(const Ref<InputEvent> &p_event) { Ref<InputEventKey> k = p_event; Ref<InputEventMouseButton> m = p_event; @@ -75,29 +78,26 @@ void InputEventConfigContainer::set_event(const Ref<InputEvent> &p_event) { } InputEventConfigContainer::InputEventConfigContainer() { - MarginContainer *mc = memnew(MarginContainer); - mc->add_theme_constant_override("margin_left", 10); - mc->add_theme_constant_override("margin_right", 10); - mc->add_theme_constant_override("margin_top", 10); - mc->add_theme_constant_override("margin_bottom", 10); - add_child(mc); - - HBoxContainer *hb = memnew(HBoxContainer); - mc->add_child(hb); + input_event_text = memnew(Label); + input_event_text->set_h_size_flags(SIZE_EXPAND_FILL); + input_event_text->set_autowrap_mode(Label::AutowrapMode::AUTOWRAP_WORD_SMART); + input_event_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER); + add_child(input_event_text); open_config_button = memnew(Button); open_config_button->set_text(TTR("Configure")); open_config_button->connect("pressed", callable_mp(this, &InputEventConfigContainer::_configure_pressed)); - hb->add_child(open_config_button); + add_child(open_config_button); - input_event_text = memnew(Label); - hb->add_child(input_event_text); + add_child(memnew(Control)); config_dialog = memnew(InputEventConfigurationDialog); config_dialog->connect("confirmed", callable_mp(this, &InputEventConfigContainer::_config_dialog_confirmed)); add_child(config_dialog); } +/////////////////////// + bool EditorInspectorPluginInputEvent::can_handle(Object *p_object) { Ref<InputEventKey> k = Ref<InputEventKey>(p_object); Ref<InputEventMouseButton> m = Ref<InputEventMouseButton>(p_object); @@ -115,6 +115,8 @@ void EditorInspectorPluginInputEvent::parse_begin(Object *p_object) { add_custom_control(picker_controls); } +/////////////////////// + InputEventEditorPlugin::InputEventEditorPlugin() { Ref<EditorInspectorPluginInputEvent> plugin; plugin.instantiate(); diff --git a/editor/plugins/input_event_editor_plugin.h b/editor/plugins/input_event_editor_plugin.h index ab948462ab..344f176e78 100644 --- a/editor/plugins/input_event_editor_plugin.h +++ b/editor/plugins/input_event_editor_plugin.h @@ -35,14 +35,14 @@ #include "editor/editor_inspector.h" #include "editor/editor_plugin.h" -class InputEventConfigContainer : public HBoxContainer { - GDCLASS(InputEventConfigContainer, HBoxContainer); +class InputEventConfigContainer : public VBoxContainer { + GDCLASS(InputEventConfigContainer, VBoxContainer); - Label *input_event_text; - Button *open_config_button; + Label *input_event_text = nullptr; + Button *open_config_button = nullptr; Ref<InputEvent> input_event; - InputEventConfigurationDialog *config_dialog; + InputEventConfigurationDialog *config_dialog = nullptr; void _config_dialog_confirmed(); void _configure_pressed(); @@ -50,10 +50,10 @@ class InputEventConfigContainer : public HBoxContainer { void _event_changed(); protected: + void _notification(int p_what); static void _bind_methods(); public: - virtual Size2 get_minimum_size() const override; void set_event(const Ref<InputEvent> &p_event); InputEventConfigContainer(); diff --git a/editor/plugins/light_occluder_2d_editor_plugin.cpp b/editor/plugins/light_occluder_2d_editor_plugin.cpp index 6a5ead58d0..4fbc8188b9 100644 --- a/editor/plugins/light_occluder_2d_editor_plugin.cpp +++ b/editor/plugins/light_occluder_2d_editor_plugin.cpp @@ -102,10 +102,7 @@ void LightOccluder2DEditor::_create_resource() { _menu_option(MODE_CREATE); } -LightOccluder2DEditor::LightOccluder2DEditor() : - AbstractPolygon2DEditor() { - node = nullptr; -} +LightOccluder2DEditor::LightOccluder2DEditor() {} LightOccluder2DEditorPlugin::LightOccluder2DEditorPlugin() : AbstractPolygon2DEditorPlugin(memnew(LightOccluder2DEditor), "LightOccluder2D") { diff --git a/editor/plugins/light_occluder_2d_editor_plugin.h b/editor/plugins/light_occluder_2d_editor_plugin.h index 557e8bf292..aeee12b5b6 100644 --- a/editor/plugins/light_occluder_2d_editor_plugin.h +++ b/editor/plugins/light_occluder_2d_editor_plugin.h @@ -37,7 +37,7 @@ class LightOccluder2DEditor : public AbstractPolygon2DEditor { GDCLASS(LightOccluder2DEditor, AbstractPolygon2DEditor); - LightOccluder2D *node; + LightOccluder2D *node = nullptr; Ref<OccluderPolygon2D> _ensure_occluder() const; diff --git a/editor/plugins/lightmap_gi_editor_plugin.h b/editor/plugins/lightmap_gi_editor_plugin.h index e658230181..1202efe8fc 100644 --- a/editor/plugins/lightmap_gi_editor_plugin.h +++ b/editor/plugins/lightmap_gi_editor_plugin.h @@ -41,11 +41,11 @@ class EditorFileDialog; class LightmapGIEditorPlugin : public EditorPlugin { GDCLASS(LightmapGIEditorPlugin, EditorPlugin); - LightmapGI *lightmap; + LightmapGI *lightmap = nullptr; - Button *bake; + Button *bake = nullptr; - EditorFileDialog *file_dialog; + EditorFileDialog *file_dialog = nullptr; static EditorProgress *tmp_progress; static bool bake_func_step(float p_progress, const String &p_description, void *, bool p_refresh); static void bake_func_end(uint64_t p_time_started); diff --git a/editor/plugins/line_2d_editor_plugin.cpp b/editor/plugins/line_2d_editor_plugin.cpp index 0f81b17cb3..31053f90b8 100644 --- a/editor/plugins/line_2d_editor_plugin.cpp +++ b/editor/plugins/line_2d_editor_plugin.cpp @@ -56,10 +56,7 @@ void Line2DEditor::_action_set_polygon(int p_idx, const Variant &p_previous, con undo_redo->add_undo_method(node, "set_points", p_previous); } -Line2DEditor::Line2DEditor() : - AbstractPolygon2DEditor() { - node = nullptr; -} +Line2DEditor::Line2DEditor() {} Line2DEditorPlugin::Line2DEditorPlugin() : AbstractPolygon2DEditorPlugin(memnew(Line2DEditor), "Line2D") { diff --git a/editor/plugins/line_2d_editor_plugin.h b/editor/plugins/line_2d_editor_plugin.h index 307cf11207..0d407b3150 100644 --- a/editor/plugins/line_2d_editor_plugin.h +++ b/editor/plugins/line_2d_editor_plugin.h @@ -37,7 +37,7 @@ class Line2DEditor : public AbstractPolygon2DEditor { GDCLASS(Line2DEditor, AbstractPolygon2DEditor); - Line2D *node; + Line2D *node = nullptr; protected: virtual Node2D *_get_node() const override; diff --git a/editor/plugins/material_editor_plugin.cpp b/editor/plugins/material_editor_plugin.cpp index daa864cfa1..eb004568d0 100644 --- a/editor/plugins/material_editor_plugin.cpp +++ b/editor/plugins/material_editor_plugin.cpp @@ -270,7 +270,7 @@ void EditorInspectorPluginMaterial::_undo_redo_inspector_callback(Object *p_undo Texture2D *texture = Object::cast_to<Texture2D>(p_new_value); if (texture) { if (p_property == "roughness_texture") { - if (base_material->get_texture(StandardMaterial3D::TEXTURE_ROUGHNESS).is_null() && texture) { + if (base_material->get_texture(StandardMaterial3D::TEXTURE_ROUGHNESS).is_null()) { undo_redo->add_do_property(p_edited, "roughness", 1.0); bool valid = false; @@ -280,7 +280,7 @@ void EditorInspectorPluginMaterial::_undo_redo_inspector_callback(Object *p_undo } } } else if (p_property == "metallic_texture") { - if (base_material->get_texture(StandardMaterial3D::TEXTURE_METALLIC).is_null() && texture) { + if (base_material->get_texture(StandardMaterial3D::TEXTURE_METALLIC).is_null()) { undo_redo->add_do_property(p_edited, "metallic", 1.0); bool valid = false; diff --git a/editor/plugins/mesh_editor_plugin.h b/editor/plugins/mesh_editor_plugin.h index 37464c98fe..3554b3c1e9 100644 --- a/editor/plugins/mesh_editor_plugin.h +++ b/editor/plugins/mesh_editor_plugin.h @@ -44,17 +44,17 @@ class MeshEditor : public SubViewportContainer { float rot_x; float rot_y; - SubViewport *viewport; - MeshInstance3D *mesh_instance; - Node3D *rotation; - DirectionalLight3D *light1; - DirectionalLight3D *light2; - Camera3D *camera; + SubViewport *viewport = nullptr; + MeshInstance3D *mesh_instance = nullptr; + Node3D *rotation = nullptr; + DirectionalLight3D *light1 = nullptr; + DirectionalLight3D *light2 = nullptr; + Camera3D *camera = nullptr; Ref<Mesh> mesh; - TextureButton *light_1_switch; - TextureButton *light_2_switch; + TextureButton *light_1_switch = nullptr; + TextureButton *light_2_switch = nullptr; void _button_pressed(Node *p_button); bool first_enter; diff --git a/editor/plugins/mesh_instance_3d_editor_plugin.h b/editor/plugins/mesh_instance_3d_editor_plugin.h index 9c59c5fb9f..36d8eacd98 100644 --- a/editor/plugins/mesh_instance_3d_editor_plugin.h +++ b/editor/plugins/mesh_instance_3d_editor_plugin.h @@ -51,17 +51,17 @@ class MeshInstance3DEditor : public Control { MENU_OPTION_DEBUG_UV2, }; - MeshInstance3D *node; + MeshInstance3D *node = nullptr; - MenuButton *options; + MenuButton *options = nullptr; - ConfirmationDialog *outline_dialog; - SpinBox *outline_size; + ConfirmationDialog *outline_dialog = nullptr; + SpinBox *outline_size = nullptr; - AcceptDialog *err_dialog; + AcceptDialog *err_dialog = nullptr; - AcceptDialog *debug_uv_dialog; - Control *debug_uv; + AcceptDialog *debug_uv_dialog = nullptr; + Control *debug_uv = nullptr; Vector<Vector2> uv_lines; void _menu_option(int p_option); @@ -84,7 +84,7 @@ public: class MeshInstance3DEditorPlugin : public EditorPlugin { GDCLASS(MeshInstance3DEditorPlugin, EditorPlugin); - MeshInstance3DEditor *mesh_editor; + MeshInstance3DEditor *mesh_editor = nullptr; public: virtual String get_name() const override { return "MeshInstance3D"; } diff --git a/editor/plugins/mesh_library_editor_plugin.h b/editor/plugins/mesh_library_editor_plugin.h index 6bc992869b..85ead35534 100644 --- a/editor/plugins/mesh_library_editor_plugin.h +++ b/editor/plugins/mesh_library_editor_plugin.h @@ -43,10 +43,10 @@ class MeshLibraryEditor : public Control { Ref<MeshLibrary> mesh_library; - MenuButton *menu; - ConfirmationDialog *cd_remove; - ConfirmationDialog *cd_update; - EditorFileDialog *file; + MenuButton *menu = nullptr; + ConfirmationDialog *cd_remove = nullptr; + ConfirmationDialog *cd_update = nullptr; + EditorFileDialog *file = nullptr; bool apply_xforms; int to_erase; @@ -81,7 +81,7 @@ public: class MeshLibraryEditorPlugin : public EditorPlugin { GDCLASS(MeshLibraryEditorPlugin, EditorPlugin); - MeshLibraryEditor *mesh_library_editor; + MeshLibraryEditor *mesh_library_editor = nullptr; public: virtual String get_name() const override { return "MeshLibrary"; } diff --git a/editor/plugins/multimesh_editor_plugin.h b/editor/plugins/multimesh_editor_plugin.h index 846e6d17f3..9f5e85216c 100644 --- a/editor/plugins/multimesh_editor_plugin.h +++ b/editor/plugins/multimesh_editor_plugin.h @@ -43,26 +43,26 @@ class MultiMeshEditor : public Control { friend class MultiMeshEditorPlugin; - AcceptDialog *err_dialog; - MenuButton *options; - MultiMeshInstance3D *_last_pp_node; + AcceptDialog *err_dialog = nullptr; + MenuButton *options = nullptr; + MultiMeshInstance3D *_last_pp_node = nullptr; bool browsing_source; - Panel *panel; - MultiMeshInstance3D *node; + Panel *panel = nullptr; + MultiMeshInstance3D *node = nullptr; - LineEdit *surface_source; - LineEdit *mesh_source; + LineEdit *surface_source = nullptr; + LineEdit *mesh_source = nullptr; - SceneTreeDialog *std; + SceneTreeDialog *std = nullptr; - ConfirmationDialog *populate_dialog; - OptionButton *populate_axis; - HSlider *populate_rotate_random; - HSlider *populate_tilt_random; - SpinBox *populate_scale_random; - SpinBox *populate_scale; - SpinBox *populate_amount; + ConfirmationDialog *populate_dialog = nullptr; + OptionButton *populate_axis = nullptr; + HSlider *populate_rotate_random = nullptr; + HSlider *populate_tilt_random = nullptr; + SpinBox *populate_scale_random = nullptr; + SpinBox *populate_scale = nullptr; + SpinBox *populate_amount = nullptr; enum Menu { MENU_OPTION_POPULATE @@ -85,7 +85,7 @@ public: class MultiMeshEditorPlugin : public EditorPlugin { GDCLASS(MultiMeshEditorPlugin, EditorPlugin); - MultiMeshEditor *multimesh_editor; + MultiMeshEditor *multimesh_editor = nullptr; public: virtual String get_name() const override { return "MultiMesh"; } diff --git a/editor/plugins/navigation_polygon_editor_plugin.cpp b/editor/plugins/navigation_polygon_editor_plugin.cpp index fe31f254df..17eaf45bb5 100644 --- a/editor/plugins/navigation_polygon_editor_plugin.cpp +++ b/editor/plugins/navigation_polygon_editor_plugin.cpp @@ -112,10 +112,7 @@ void NavigationPolygonEditor::_create_resource() { _menu_option(MODE_CREATE); } -NavigationPolygonEditor::NavigationPolygonEditor() : - AbstractPolygon2DEditor() { - node = nullptr; -} +NavigationPolygonEditor::NavigationPolygonEditor() {} NavigationPolygonEditorPlugin::NavigationPolygonEditorPlugin() : AbstractPolygon2DEditorPlugin(memnew(NavigationPolygonEditor), "NavigationRegion2D") { diff --git a/editor/plugins/navigation_polygon_editor_plugin.h b/editor/plugins/navigation_polygon_editor_plugin.h index 16fbb241e9..7550b75fa3 100644 --- a/editor/plugins/navigation_polygon_editor_plugin.h +++ b/editor/plugins/navigation_polygon_editor_plugin.h @@ -37,7 +37,7 @@ class NavigationPolygonEditor : public AbstractPolygon2DEditor { GDCLASS(NavigationPolygonEditor, AbstractPolygon2DEditor); - NavigationRegion2D *node; + NavigationRegion2D *node = nullptr; Ref<NavigationPolygon> _ensure_navpoly() const; diff --git a/editor/plugins/node_3d_editor_gizmos.h b/editor/plugins/node_3d_editor_gizmos.h index fa55651d26..3b67b898e3 100644 --- a/editor/plugins/node_3d_editor_gizmos.h +++ b/editor/plugins/node_3d_editor_gizmos.h @@ -70,14 +70,14 @@ class EditorNode3DGizmo : public Node3DGizmo { bool valid; bool hidden; Vector<Instance> instances; - Node3D *spatial_node; + Node3D *spatial_node = nullptr; void _set_spatial_node(Node *p_node) { set_spatial_node(Object::cast_to<Node3D>(p_node)); } protected: static void _bind_methods(); - EditorNode3DGizmoPlugin *gizmo_plugin; + EditorNode3DGizmoPlugin *gizmo_plugin = nullptr; GDVIRTUAL0(_redraw) GDVIRTUAL2RC(String, _get_handle_name, int, bool) @@ -618,7 +618,7 @@ public: class Joint3DGizmoPlugin : public EditorNode3DGizmoPlugin { GDCLASS(Joint3DGizmoPlugin, EditorNode3DGizmoPlugin); - Timer *update_timer; + Timer *update_timer = nullptr; uint64_t update_idx = 0; void incremental_update_gizmos(); diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp index eab477adb7..f2ca1fcfeb 100644 --- a/editor/plugins/node_3d_editor_plugin.cpp +++ b/editor/plugins/node_3d_editor_plugin.cpp @@ -369,7 +369,7 @@ Transform3D Node3DEditorViewport::to_camera_transform(const Cursor &p_cursor) co } int Node3DEditorViewport::get_selected_count() const { - Map<Node *, Object *> &selection = editor_selection->get_selection(); + const Map<Node *, Object *> &selection = editor_selection->get_selection(); int count = 0; @@ -2467,7 +2467,7 @@ void Node3DEditorViewport::_notification(int p_what) { _update_camera(delta); - Map<Node *, Object *> &selection = editor_selection->get_selection(); + const Map<Node *, Object *> &selection = editor_selection->get_selection(); bool changed = false; bool exist = false; @@ -6848,7 +6848,7 @@ void Node3DEditor::snap_selected_nodes_to_floor() { } } -void Node3DEditor::unhandled_key_input(const Ref<InputEvent> &p_event) { +void Node3DEditor::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (!is_visible_in_tree()) { @@ -7120,7 +7120,9 @@ void Node3DEditor::_request_gizmo(Object *p_obj) { } } } - sp->update_gizmos(); + if (!sp->get_gizmos().is_empty()) { + sp->update_gizmos(); + } } } @@ -7893,7 +7895,7 @@ Node3DEditor::Node3DEditor() { selected = nullptr; - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); add_to_group("_spatial_editor_group"); EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80); diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h index 5c0bfab34e..d5d50c743c 100644 --- a/editor/plugins/node_3d_editor_plugin.h +++ b/editor/plugins/node_3d_editor_plugin.h @@ -190,27 +190,27 @@ private: ViewType view_type; void _menu_option(int p_option); void _set_auto_orthogonal(); - Node3D *preview_node; - AABB *preview_bounds; + Node3D *preview_node = nullptr; + AABB *preview_bounds = nullptr; Vector<String> selected_files; - AcceptDialog *accept; + AcceptDialog *accept = nullptr; - Node *target_node; + Node *target_node = nullptr; Point2 drop_pos; - EditorData *editor_data; - EditorSelection *editor_selection; - UndoRedo *undo_redo; + EditorData *editor_data = nullptr; + EditorSelection *editor_selection = nullptr; + UndoRedo *undo_redo = nullptr; - CheckBox *preview_camera; - SubViewportContainer *subviewport_container; + CheckBox *preview_camera = nullptr; + SubViewportContainer *subviewport_container = nullptr; - MenuButton *view_menu; - PopupMenu *display_submenu; + MenuButton *view_menu = nullptr; + PopupMenu *display_submenu = nullptr; - Control *surface; - SubViewport *viewport; - Camera3D *camera; + Control *surface = nullptr; + SubViewport *viewport = nullptr; + Camera3D *camera = nullptr; bool transforming; bool orthogonal; bool auto_orthogonal; @@ -221,17 +221,17 @@ private: real_t freelook_speed; Vector2 previous_mouse_position; - Label *info_label; - Label *cinema_label; - Label *locked_label; - Label *zoom_limit_label; + Label *info_label = nullptr; + Label *cinema_label = nullptr; + Label *locked_label = nullptr; + Label *zoom_limit_label = nullptr; - VBoxContainer *top_right_vbox; - ViewportRotationControl *rotation_control; - Gradient *frame_time_gradient; - Label *cpu_time_label; - Label *gpu_time_label; - Label *fps_label; + VBoxContainer *top_right_vbox = nullptr; + ViewportRotationControl *rotation_control = nullptr; + Gradient *frame_time_gradient = nullptr; + Label *cpu_time_label = nullptr; + Label *gpu_time_label = nullptr; + Label *fps_label = nullptr; struct _RayResult { Node3D *item = nullptr; @@ -274,7 +274,7 @@ private: bool clicked_wants_append; bool selection_in_progress = false; - PopupMenu *selection_menu; + PopupMenu *selection_menu = nullptr; enum NavigationZoomStyle { NAVIGATION_ZOOM_VERTICAL, @@ -375,9 +375,9 @@ private: void _sinput(const Ref<InputEvent> &p_event); void _update_freelook(real_t delta); - Node3DEditor *spatial_editor; + Node3DEditor *spatial_editor = nullptr; - Camera3D *previewing; + Camera3D *previewing = nullptr; Camera3D *preview = nullptr; bool previewing_cinema; @@ -455,7 +455,7 @@ public: Transform3D original_local; Transform3D last_xform; // last transform bool last_xform_dirty; - Node3D *sp; + Node3D *sp = nullptr; RID sbox_instance; RID sbox_instance_offset; RID sbox_instance_xray; @@ -537,13 +537,13 @@ public: }; private: - EditorSelection *editor_selection; + EditorSelection *editor_selection = nullptr; - Node3DEditorViewportContainer *viewport_base; + Node3DEditorViewportContainer *viewport_base = nullptr; Node3DEditorViewport *viewports[VIEWPORTS_COUNT]; - VSplitContainer *shader_split; - HSplitContainer *left_panel_split; - HSplitContainer *right_panel_split; + VSplitContainer *shader_split = nullptr; + HSplitContainer *left_panel_split = nullptr; + HSplitContainer *right_panel_split = nullptr; ///// @@ -588,7 +588,7 @@ private: Ref<StandardMaterial3D> cursor_material; // Scene drag and drop support - Node3D *preview_node; + Node3D *preview_node = nullptr; AABB preview_bounds; struct Gizmo { @@ -628,31 +628,31 @@ private: Button *tool_button[TOOL_MAX]; Button *tool_option_button[TOOL_OPT_MAX]; - MenuButton *transform_menu; - PopupMenu *gizmos_menu; - MenuButton *view_menu; + MenuButton *transform_menu = nullptr; + PopupMenu *gizmos_menu = nullptr; + MenuButton *view_menu = nullptr; - AcceptDialog *accept; + AcceptDialog *accept = nullptr; - ConfirmationDialog *snap_dialog; - ConfirmationDialog *xform_dialog; - ConfirmationDialog *settings_dialog; + ConfirmationDialog *snap_dialog = nullptr; + ConfirmationDialog *xform_dialog = nullptr; + ConfirmationDialog *settings_dialog = nullptr; bool snap_enabled; bool snap_key_enabled; - LineEdit *snap_translate; - LineEdit *snap_rotate; - LineEdit *snap_scale; + LineEdit *snap_translate = nullptr; + LineEdit *snap_rotate = nullptr; + LineEdit *snap_scale = nullptr; LineEdit *xform_translate[3]; LineEdit *xform_rotate[3]; LineEdit *xform_scale[3]; - OptionButton *xform_type; + OptionButton *xform_type = nullptr; - VBoxContainer *settings_vbc; - SpinBox *settings_fov; - SpinBox *settings_znear; - SpinBox *settings_zfar; + VBoxContainer *settings_vbc = nullptr; + SpinBox *settings_fov = nullptr; + SpinBox *settings_znear = nullptr; + SpinBox *settings_zfar = nullptr; void _snap_changed(); void _snap_update(); @@ -662,14 +662,14 @@ private: void _menu_gizmo_toggled(int p_option); void _update_camera_override_button(bool p_game_running); void _update_camera_override_viewport(Object *p_viewport); - HBoxContainer *hbc_menu; + HBoxContainer *hbc_menu = nullptr; // Used for secondary menu items which are displayed depending on the currently selected node // (such as MeshInstance's "Mesh" menu). - PanelContainer *context_menu_container; - HBoxContainer *hbc_context_menu; + PanelContainer *context_menu_container = nullptr; + HBoxContainer *hbc_context_menu = nullptr; void _generate_selection_boxes(); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; int camera_override_viewport_id; @@ -683,13 +683,13 @@ private: void _toggle_maximize_view(Object *p_viewport); - Node *custom_camera; + Node *custom_camera = nullptr; Object *_get_editor_data(Object *p_what); Ref<Environment> viewport_environment; - Node3D *selected; + Node3D *selected = nullptr; void _request_gizmo(Object *p_obj); void _set_subgizmo_selection(Object *p_obj, Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform = Transform3D()); @@ -712,18 +712,18 @@ private: uint32_t world_env_count = 0; uint32_t directional_light_count = 0; - Button *sun_button; - Label *sun_state; - Label *sun_title; - VBoxContainer *sun_vb; - Popup *sun_environ_popup; - Control *sun_direction; - EditorSpinSlider *sun_angle_altitude; - EditorSpinSlider *sun_angle_azimuth; - ColorPickerButton *sun_color; - EditorSpinSlider *sun_energy; - EditorSpinSlider *sun_max_distance; - Button *sun_add_to_scene; + Button *sun_button = nullptr; + Label *sun_state = nullptr; + Label *sun_title = nullptr; + VBoxContainer *sun_vb = nullptr; + Popup *sun_environ_popup = nullptr; + Control *sun_direction = nullptr; + EditorSpinSlider *sun_angle_altitude = nullptr; + EditorSpinSlider *sun_angle_azimuth = nullptr; + ColorPickerButton *sun_color = nullptr; + EditorSpinSlider *sun_energy = nullptr; + EditorSpinSlider *sun_max_distance = nullptr; + Button *sun_add_to_scene = nullptr; void _sun_direction_draw(); void _sun_direction_input(const Ref<InputEvent> &p_event); @@ -734,23 +734,23 @@ private: Ref<Shader> sun_direction_shader; Ref<ShaderMaterial> sun_direction_material; - Button *environ_button; - Label *environ_state; - Label *environ_title; - VBoxContainer *environ_vb; - ColorPickerButton *environ_sky_color; - ColorPickerButton *environ_ground_color; - EditorSpinSlider *environ_energy; - Button *environ_ao_button; - Button *environ_glow_button; - Button *environ_tonemap_button; - Button *environ_gi_button; - Button *environ_add_to_scene; - - Button *sun_environ_settings; - - DirectionalLight3D *preview_sun; - WorldEnvironment *preview_environment; + Button *environ_button = nullptr; + Label *environ_state = nullptr; + Label *environ_title = nullptr; + VBoxContainer *environ_vb = nullptr; + ColorPickerButton *environ_sky_color = nullptr; + ColorPickerButton *environ_ground_color = nullptr; + EditorSpinSlider *environ_energy = nullptr; + Button *environ_ao_button = nullptr; + Button *environ_glow_button = nullptr; + Button *environ_tonemap_button = nullptr; + Button *environ_gi_button = nullptr; + Button *environ_add_to_scene = nullptr; + + Button *sun_environ_settings = nullptr; + + DirectionalLight3D *preview_sun = nullptr; + WorldEnvironment *preview_environment = nullptr; Ref<Environment> environment; Ref<ProceduralSkyMaterial> sky_material; @@ -770,7 +770,7 @@ private: protected: void _notification(int p_what); //void _gui_input(InputEvent p_event); - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; static void _bind_methods(); @@ -868,7 +868,7 @@ public: class Node3DEditorPlugin : public EditorPlugin { GDCLASS(Node3DEditorPlugin, EditorPlugin); - Node3DEditor *spatial_editor; + Node3DEditor *spatial_editor = nullptr; public: Node3DEditor *get_spatial_editor() { return spatial_editor; } diff --git a/editor/plugins/occluder_instance_3d_editor_plugin.h b/editor/plugins/occluder_instance_3d_editor_plugin.h index 24f31b2ea8..360b7297cf 100644 --- a/editor/plugins/occluder_instance_3d_editor_plugin.h +++ b/editor/plugins/occluder_instance_3d_editor_plugin.h @@ -40,11 +40,11 @@ class EditorFileDialog; class OccluderInstance3DEditorPlugin : public EditorPlugin { GDCLASS(OccluderInstance3DEditorPlugin, EditorPlugin); - OccluderInstance3D *occluder_instance; + OccluderInstance3D *occluder_instance = nullptr; - Button *bake; + Button *bake = nullptr; - EditorFileDialog *file_dialog; + EditorFileDialog *file_dialog = nullptr; void _bake_select_file(const String &p_file); void _bake(); diff --git a/editor/plugins/ot_features_plugin.cpp b/editor/plugins/ot_features_plugin.cpp index 27b35d803c..936eb747b0 100644 --- a/editor/plugins/ot_features_plugin.cpp +++ b/editor/plugins/ot_features_plugin.cpp @@ -145,8 +145,11 @@ void OpenTypeFeaturesAdd::setup(Object *p_object) { void OpenTypeFeaturesAdd::_notification(int p_what) { switch (p_what) { - case NOTIFICATION_THEME_CHANGED: case NOTIFICATION_ENTER_TREE: { + connect("pressed", callable_mp(this, &OpenTypeFeaturesAdd::_features_menu)); + [[fallthrough]]; + } + case NOTIFICATION_THEME_CHANGED: { set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons"))); } break; } @@ -173,7 +176,6 @@ OpenTypeFeaturesAdd::OpenTypeFeaturesAdd() { menu_cu->set_name("CUMenu"); menu->add_child(menu_cu); - connect("pressed", callable_mp(this, &OpenTypeFeaturesAdd::_features_menu)); menu->connect("id_pressed", callable_mp(this, &OpenTypeFeaturesAdd::_add_feature)); menu_cv->connect("id_pressed", callable_mp(this, &OpenTypeFeaturesAdd::_add_feature)); menu_ss->connect("id_pressed", callable_mp(this, &OpenTypeFeaturesAdd::_add_feature)); diff --git a/editor/plugins/ot_features_plugin.h b/editor/plugins/ot_features_plugin.h index fcbc8692ca..6639148080 100644 --- a/editor/plugins/ot_features_plugin.h +++ b/editor/plugins/ot_features_plugin.h @@ -38,7 +38,7 @@ class OpenTypeFeaturesEditor : public EditorProperty { GDCLASS(OpenTypeFeaturesEditor, EditorProperty); - EditorSpinSlider *spin; + EditorSpinSlider *spin = nullptr; bool setting = true; void _value_changed(double p_val); Button *button = nullptr; diff --git a/editor/plugins/path_2d_editor_plugin.h b/editor/plugins/path_2d_editor_plugin.h index 926a859f8b..ff74aeedf7 100644 --- a/editor/plugins/path_2d_editor_plugin.h +++ b/editor/plugins/path_2d_editor_plugin.h @@ -40,14 +40,14 @@ class CanvasItemEditor; class Path2DEditor : public HBoxContainer { GDCLASS(Path2DEditor, HBoxContainer); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; - CanvasItemEditor *canvas_item_editor; - Panel *panel; - Path2D *node; + CanvasItemEditor *canvas_item_editor = nullptr; + Panel *panel = nullptr; + Path2D *node = nullptr; - HBoxContainer *base_hb; - Separator *sep; + HBoxContainer *base_hb = nullptr; + Separator *sep = nullptr; enum Mode { MODE_CREATE, @@ -58,12 +58,12 @@ class Path2DEditor : public HBoxContainer { }; Mode mode; - Button *curve_create; - Button *curve_edit; - Button *curve_edit_curve; - Button *curve_del; - Button *curve_close; - MenuButton *handle_menu; + Button *curve_create = nullptr; + Button *curve_edit = nullptr; + Button *curve_edit_curve = nullptr; + Button *curve_del = nullptr; + Button *curve_close = nullptr; + MenuButton *handle_menu = nullptr; bool mirror_handle_angle; bool mirror_handle_length; @@ -110,7 +110,7 @@ public: class Path2DEditorPlugin : public EditorPlugin { GDCLASS(Path2DEditorPlugin, EditorPlugin); - Path2DEditor *path2d_editor; + Path2DEditor *path2d_editor = nullptr; public: virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return path2d_editor->forward_gui_input(p_event); } diff --git a/editor/plugins/path_3d_editor_plugin.h b/editor/plugins/path_3d_editor_plugin.h index 3c6ca65437..72c24732c0 100644 --- a/editor/plugins/path_3d_editor_plugin.h +++ b/editor/plugins/path_3d_editor_plugin.h @@ -40,7 +40,7 @@ class Path3DGizmo : public EditorNode3DGizmo { GDCLASS(Path3DGizmo, EditorNode3DGizmo); - Path3D *path; + Path3D *path = nullptr; mutable Vector3 original; mutable float orig_in_length; mutable float orig_out_length; @@ -70,14 +70,14 @@ public: class Path3DEditorPlugin : public EditorPlugin { GDCLASS(Path3DEditorPlugin, EditorPlugin); - Separator *sep; - Button *curve_create; - Button *curve_edit; - Button *curve_del; - Button *curve_close; - MenuButton *handle_menu; + Separator *sep = nullptr; + Button *curve_create = nullptr; + Button *curve_edit = nullptr; + Button *curve_del = nullptr; + Button *curve_close = nullptr; + MenuButton *handle_menu = nullptr; - Path3D *path; + Path3D *path = nullptr; void _update_theme(); diff --git a/editor/plugins/physical_bone_3d_editor_plugin.cpp b/editor/plugins/physical_bone_3d_editor_plugin.cpp index e815a9c9f6..9dc89133c4 100644 --- a/editor/plugins/physical_bone_3d_editor_plugin.cpp +++ b/editor/plugins/physical_bone_3d_editor_plugin.cpp @@ -82,8 +82,7 @@ void PhysicalBone3DEditor::show() { spatial_editor_hb->show(); } -PhysicalBone3DEditorPlugin::PhysicalBone3DEditorPlugin() : - physical_bone_editor() {} +PhysicalBone3DEditorPlugin::PhysicalBone3DEditorPlugin() {} void PhysicalBone3DEditorPlugin::make_visible(bool p_visible) { if (p_visible) { diff --git a/editor/plugins/physical_bone_3d_editor_plugin.h b/editor/plugins/physical_bone_3d_editor_plugin.h index 4051644b54..93e722a432 100644 --- a/editor/plugins/physical_bone_3d_editor_plugin.h +++ b/editor/plugins/physical_bone_3d_editor_plugin.h @@ -39,8 +39,8 @@ class PhysicalBone3DEditor : public Object { GDCLASS(PhysicalBone3DEditor, Object); - HBoxContainer *spatial_editor_hb; - Button *button_transform_joint; + HBoxContainer *spatial_editor_hb = nullptr; + Button *button_transform_joint = nullptr; PhysicalBone3D *selected = nullptr; diff --git a/editor/plugins/polygon_2d_editor_plugin.cpp b/editor/plugins/polygon_2d_editor_plugin.cpp index 2812c4aaaf..8566e92b22 100644 --- a/editor/plugins/polygon_2d_editor_plugin.cpp +++ b/editor/plugins/polygon_2d_editor_plugin.cpp @@ -1228,9 +1228,7 @@ Vector2 Polygon2DEditor::snap_point(Vector2 p_target) const { return p_target; } -Polygon2DEditor::Polygon2DEditor() : - AbstractPolygon2DEditor() { - node = nullptr; +Polygon2DEditor::Polygon2DEditor() { snap_offset = EditorSettings::get_singleton()->get_project_metadata("polygon_2d_uv_editor", "snap_offset", Vector2()); snap_step = EditorSettings::get_singleton()->get_project_metadata("polygon_2d_uv_editor", "snap_step", Vector2(10, 10)); use_snap = EditorSettings::get_singleton()->get_project_metadata("polygon_2d_uv_editor", "snap_enabled", false); diff --git a/editor/plugins/polygon_2d_editor_plugin.h b/editor/plugins/polygon_2d_editor_plugin.h index 0a5def902c..4403d1e9c7 100644 --- a/editor/plugins/polygon_2d_editor_plugin.h +++ b/editor/plugins/polygon_2d_editor_plugin.h @@ -68,38 +68,38 @@ class Polygon2DEditor : public AbstractPolygon2DEditor { Button *uv_edit_mode[4]; Ref<ButtonGroup> uv_edit_group; - Polygon2D *node; + Polygon2D *node = nullptr; UVMode uv_mode; - AcceptDialog *uv_edit; + AcceptDialog *uv_edit = nullptr; Button *uv_button[UV_MODE_MAX]; - Button *b_snap_enable; - Button *b_snap_grid; - Panel *uv_edit_draw; - HSlider *uv_zoom; - SpinBox *uv_zoom_value; - HScrollBar *uv_hscroll; - VScrollBar *uv_vscroll; - MenuButton *uv_menu; - TextureRect *uv_icon_zoom; + Button *b_snap_enable = nullptr; + Button *b_snap_grid = nullptr; + Panel *uv_edit_draw = nullptr; + HSlider *uv_zoom = nullptr; + SpinBox *uv_zoom_value = nullptr; + HScrollBar *uv_hscroll = nullptr; + VScrollBar *uv_vscroll = nullptr; + MenuButton *uv_menu = nullptr; + TextureRect *uv_icon_zoom = nullptr; Ref<ViewPanner> uv_panner; void _uv_scroll_callback(Vector2 p_scroll_vec, bool p_alt); void _uv_pan_callback(Vector2 p_scroll_vec); void _uv_zoom_callback(Vector2 p_scroll_vec, Vector2 p_origin, bool p_alt); - VBoxContainer *bone_scroll_main_vb; - ScrollContainer *bone_scroll; - VBoxContainer *bone_scroll_vb; - Button *sync_bones; - HSlider *bone_paint_strength; - SpinBox *bone_paint_radius; - Label *bone_paint_radius_label; + VBoxContainer *bone_scroll_main_vb = nullptr; + ScrollContainer *bone_scroll = nullptr; + VBoxContainer *bone_scroll_vb = nullptr; + Button *sync_bones = nullptr; + HSlider *bone_paint_strength = nullptr; + SpinBox *bone_paint_radius = nullptr; + Label *bone_paint_radius_label = nullptr; bool bone_painting; int bone_painting_bone; Vector<float> prev_weights; Vector2 bone_paint_pos; - AcceptDialog *grid_settings; + AcceptDialog *grid_settings = nullptr; void _sync_bones(); void _update_bone_list(); @@ -123,9 +123,9 @@ class Polygon2DEditor : public AbstractPolygon2DEditor { Vector2 uv_drag_from; bool updating_uv_scroll; - AcceptDialog *error; + AcceptDialog *error = nullptr; - Button *button_uv; + Button *button_uv = nullptr; bool use_snap; bool snap_show_grid; diff --git a/editor/plugins/polygon_3d_editor_plugin.h b/editor/plugins/polygon_3d_editor_plugin.h index e92dcaf319..3ad7a4df58 100644 --- a/editor/plugins/polygon_3d_editor_plugin.h +++ b/editor/plugins/polygon_3d_editor_plugin.h @@ -41,7 +41,7 @@ class CanvasItemEditor; class Polygon3DEditor : public HBoxContainer { GDCLASS(Polygon3DEditor, HBoxContainer); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; enum Mode { MODE_CREATE, MODE_EDIT, @@ -50,21 +50,21 @@ class Polygon3DEditor : public HBoxContainer { Mode mode; - Button *button_create; - Button *button_edit; + Button *button_create = nullptr; + Button *button_edit = nullptr; Ref<StandardMaterial3D> line_material; Ref<StandardMaterial3D> handle_material; - Panel *panel; - Node3D *node; + Panel *panel = nullptr; + Node3D *node = nullptr; Ref<Resource> node_resource; Ref<ImmediateMesh> imesh; - MeshInstance3D *imgeom; - MeshInstance3D *pointsm; + MeshInstance3D *imgeom = nullptr; + MeshInstance3D *pointsm = nullptr; Ref<ArrayMesh> m; - MenuButton *options; + MenuButton *options = nullptr; int edited_point; Vector2 edited_point_pos; @@ -98,7 +98,7 @@ public: class Polygon3DEditorPlugin : public EditorPlugin { GDCLASS(Polygon3DEditorPlugin, EditorPlugin); - Polygon3DEditor *polygon_editor; + Polygon3DEditor *polygon_editor = nullptr; public: virtual EditorPlugin::AfterGUIInput forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) override { return polygon_editor->forward_spatial_gui_input(p_camera, p_event); } diff --git a/editor/plugins/replication_editor_plugin.h b/editor/plugins/replication_editor_plugin.h index 46274d188c..08e86d1617 100644 --- a/editor/plugins/replication_editor_plugin.h +++ b/editor/plugins/replication_editor_plugin.h @@ -51,7 +51,7 @@ private: Ref<SceneReplicationConfig> config; NodePath deleting; - Tree *tree; + Tree *tree = nullptr; bool keying = false; Ref<Texture2D> _get_class_icon(const Node *p_node); @@ -84,7 +84,7 @@ class ReplicationEditorPlugin : public EditorPlugin { GDCLASS(ReplicationEditorPlugin, EditorPlugin); private: - ReplicationEditor *repl_editor; + ReplicationEditor *repl_editor = nullptr; void _node_removed(Node *p_node); void _keying_changed(); diff --git a/editor/plugins/resource_preloader_editor_plugin.h b/editor/plugins/resource_preloader_editor_plugin.h index 8e81239f1b..0b799c13c6 100644 --- a/editor/plugins/resource_preloader_editor_plugin.h +++ b/editor/plugins/resource_preloader_editor_plugin.h @@ -47,16 +47,16 @@ class ResourcePreloaderEditor : public PanelContainer { BUTTON_REMOVE }; - Button *load; - Button *paste; - Tree *tree; + Button *load = nullptr; + Button *paste = nullptr; + Tree *tree = nullptr; bool loading_scene; - EditorFileDialog *file; + EditorFileDialog *file = nullptr; - AcceptDialog *dialog; + AcceptDialog *dialog = nullptr; - ResourcePreloader *preloader; + ResourcePreloader *preloader = nullptr; void _load_pressed(); void _files_load_request(const Vector<String> &p_paths); @@ -66,7 +66,7 @@ class ResourcePreloaderEditor : public PanelContainer { void _cell_button_pressed(Object *p_item, int p_column, int p_id); void _item_edited(); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; Variant get_drag_data_fw(const Point2 &p_point, Control *p_from); bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const; @@ -87,8 +87,8 @@ public: class ResourcePreloaderEditorPlugin : public EditorPlugin { GDCLASS(ResourcePreloaderEditorPlugin, EditorPlugin); - ResourcePreloaderEditor *preloader_editor; - Button *button; + ResourcePreloaderEditor *preloader_editor = nullptr; + Button *button = nullptr; public: virtual String get_name() const override { return "ResourcePreloader"; } diff --git a/editor/plugins/root_motion_editor_plugin.h b/editor/plugins/root_motion_editor_plugin.h index c2866f269b..5b8c1d77b3 100644 --- a/editor/plugins/root_motion_editor_plugin.h +++ b/editor/plugins/root_motion_editor_plugin.h @@ -38,12 +38,12 @@ class EditorPropertyRootMotion : public EditorProperty { GDCLASS(EditorPropertyRootMotion, EditorProperty); - Button *assign; - Button *clear; + Button *assign = nullptr; + Button *clear = nullptr; NodePath base_hint; - ConfirmationDialog *filter_dialog; - Tree *filters; + ConfirmationDialog *filter_dialog = nullptr; + Tree *filters = nullptr; void _confirmed(); void _node_assign(); diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index 677b55bb88..906edb006c 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -1091,13 +1091,13 @@ void ScriptEditor::_file_dialog_action(String p_file) { switch (file_dialog_option) { case FILE_NEW_TEXTFILE: { Error err; - FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err); - if (err) { - EditorNode::get_singleton()->show_warning(TTR("Error writing TextFile:") + "\n" + p_file, TTR("Error!")); - break; + { + Ref<FileAccess> file = FileAccess::open(p_file, FileAccess::WRITE, &err); + if (err) { + EditorNode::get_singleton()->show_warning(TTR("Error writing TextFile:") + "\n" + p_file, TTR("Error!")); + break; + } } - file->close(); - memdelete(file); if (EditorFileSystem::get_singleton()) { if (textfile_extensions.has(p_file.get_extension())) { @@ -2211,17 +2211,16 @@ Error ScriptEditor::_save_text_file(Ref<TextFile> p_text_file, const String &p_p String source = sqscr->get_text(); Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); + { + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V_MSG(err, err, "Cannot save text file '" + p_path + "'."); + ERR_FAIL_COND_V_MSG(err, err, "Cannot save text file '" + p_path + "'."); - file->store_string(source); - if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { - memdelete(file); - return ERR_CANT_CREATE; + file->store_string(source); + if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { + return ERR_CANT_CREATE; + } } - file->close(); - memdelete(file); if (ResourceSaver::get_timestamp_on_save()) { p_text_file->set_last_modified_time(FileAccess::get_modified_time(p_path)); @@ -3019,7 +3018,7 @@ void ScriptEditor::input(const Ref<InputEvent> &p_event) { } } -void ScriptEditor::unhandled_key_input(const Ref<InputEvent> &p_event) { +void ScriptEditor::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (!is_visible_in_tree() || !p_event->is_pressed() || p_event->is_echo()) { @@ -3291,15 +3290,8 @@ void ScriptEditor::_help_class_open(const String &p_class) { void ScriptEditor::_help_class_goto(const String &p_desc) { String cname = p_desc.get_slice(":", 1); - for (int i = 0; i < tab_container->get_tab_count(); i++) { - EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i)); - - if (eh && eh->get_class() == cname) { - _go_to_tab(i); - eh->go_to_help(p_desc); - _update_script_names(); - return; - } + if (_help_tab_goto(cname, p_desc)) { + return; } EditorHelp *eh = memnew(EditorHelp); @@ -3313,6 +3305,22 @@ void ScriptEditor::_help_class_goto(const String &p_desc) { _sort_list_on_update = true; _update_script_names(); _save_layout(); + + call_deferred("_help_tab_goto", cname, p_desc); +} + +bool ScriptEditor::_help_tab_goto(const String &p_name, const String &p_desc) { + for (int i = 0; i < tab_container->get_tab_count(); i++) { + EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_tab_control(i)); + + if (eh && eh->get_class() == p_name) { + _go_to_tab(i); + eh->go_to_help(p_desc); + _update_script_names(); + return true; + } + } + return false; } void ScriptEditor::update_doc(const String &p_name) { @@ -3601,6 +3609,7 @@ void ScriptEditor::_bind_methods() { ClassDB::bind_method("_update_script_connections", &ScriptEditor::_update_script_connections); ClassDB::bind_method("_help_class_open", &ScriptEditor::_help_class_open); + ClassDB::bind_method("_help_tab_goto", &ScriptEditor::_help_tab_goto); ClassDB::bind_method("_live_auto_reload_running_scripts", &ScriptEditor::_live_auto_reload_running_scripts); ClassDB::bind_method("_update_members_overview", &ScriptEditor::_update_members_overview); ClassDB::bind_method("_update_recent_scripts", &ScriptEditor::_update_recent_scripts); @@ -3740,7 +3749,7 @@ ScriptEditor::ScriptEditor() { ED_SHORTCUT("script_editor/next_script", TTR("Next Script"), KeyModifierMask::CMD | KeyModifierMask::SHIFT | Key::PERIOD); ED_SHORTCUT("script_editor/prev_script", TTR("Previous Script"), KeyModifierMask::CMD | KeyModifierMask::SHIFT | Key::COMMA); set_process_input(true); - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); file_menu = memnew(MenuButton); file_menu->set_text(TTR("File")); diff --git a/editor/plugins/script_editor_plugin.h b/editor/plugins/script_editor_plugin.h index a99e269d46..7885ffe2c5 100644 --- a/editor/plugins/script_editor_plugin.h +++ b/editor/plugins/script_editor_plugin.h @@ -102,8 +102,8 @@ public: class ScriptEditorQuickOpen : public ConfirmationDialog { GDCLASS(ScriptEditorQuickOpen, ConfirmationDialog); - LineEdit *search_box; - Tree *search_options; + LineEdit *search_box = nullptr; + Tree *search_options = nullptr; String function; void _update_search(); @@ -242,55 +242,55 @@ class ScriptEditor : public PanelContainer { DISPLAY_FULL_PATH, }; - HBoxContainer *menu_hb; - MenuButton *file_menu; - MenuButton *edit_menu; - MenuButton *script_search_menu; - MenuButton *debug_menu; - PopupMenu *context_menu; - Timer *autosave_timer; + HBoxContainer *menu_hb = nullptr; + MenuButton *file_menu = nullptr; + MenuButton *edit_menu = nullptr; + MenuButton *script_search_menu = nullptr; + MenuButton *debug_menu = nullptr; + PopupMenu *context_menu = nullptr; + Timer *autosave_timer = nullptr; uint64_t idle; - PopupMenu *recent_scripts; - PopupMenu *theme_submenu; - - Button *help_search; - Button *site_search; - EditorHelpSearch *help_search_dialog; - - ItemList *script_list; - HSplitContainer *script_split; - ItemList *members_overview; - LineEdit *filter_scripts; - LineEdit *filter_methods; - VBoxContainer *scripts_vbox; - VBoxContainer *overview_vbox; - HBoxContainer *buttons_hbox; - Label *filename; - Button *members_overview_alphabeta_sort_button; + PopupMenu *recent_scripts = nullptr; + PopupMenu *theme_submenu = nullptr; + + Button *help_search = nullptr; + Button *site_search = nullptr; + EditorHelpSearch *help_search_dialog = nullptr; + + ItemList *script_list = nullptr; + HSplitContainer *script_split = nullptr; + ItemList *members_overview = nullptr; + LineEdit *filter_scripts = nullptr; + LineEdit *filter_methods = nullptr; + VBoxContainer *scripts_vbox = nullptr; + VBoxContainer *overview_vbox = nullptr; + HBoxContainer *buttons_hbox = nullptr; + Label *filename = nullptr; + Button *members_overview_alphabeta_sort_button = nullptr; bool members_overview_enabled; - ItemList *help_overview; + ItemList *help_overview = nullptr; bool help_overview_enabled; - VSplitContainer *list_split; - TabContainer *tab_container; - EditorFileDialog *file_dialog; - AcceptDialog *error_dialog; - ConfirmationDialog *erase_tab_confirm; - ScriptCreateDialog *script_create_dialog; - Button *scripts_visible; - FindReplaceBar *find_replace_bar; + VSplitContainer *list_split = nullptr; + TabContainer *tab_container = nullptr; + EditorFileDialog *file_dialog = nullptr; + AcceptDialog *error_dialog = nullptr; + ConfirmationDialog *erase_tab_confirm = nullptr; + ScriptCreateDialog *script_create_dialog = nullptr; + Button *scripts_visible = nullptr; + FindReplaceBar *find_replace_bar = nullptr; String current_theme; - TextureRect *script_icon; - Label *script_name_label; + TextureRect *script_icon = nullptr; + Label *script_name_label = nullptr; - Button *script_back; - Button *script_forward; + Button *script_back = nullptr; + Button *script_forward = nullptr; - FindInFilesDialog *find_in_files_dialog; - FindInFilesPanel *find_in_files; - Button *find_in_files_button; + FindInFilesDialog *find_in_files_dialog = nullptr; + FindInFilesPanel *find_in_files = nullptr; + Button *find_in_files_button = nullptr; enum { SCRIPT_EDITOR_FUNC_MAX = 32, @@ -320,8 +320,8 @@ class ScriptEditor : public PanelContainer { bool _has_script_tab() const; void _prepare_file_menu(); - Tree *disk_changed_list; - ConfirmationDialog *disk_changed; + Tree *disk_changed_list = nullptr; + ConfirmationDialog *disk_changed = nullptr; bool restoring_layout; @@ -361,7 +361,7 @@ class ScriptEditor : public PanelContainer { void _update_selected_editor_menu(); - EditorScriptCodeCompletionCache *completion_cache; + EditorScriptCodeCompletionCache *completion_cache = nullptr; void _editor_stop(); @@ -426,7 +426,7 @@ class ScriptEditor : public PanelContainer { void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from); virtual void input(const Ref<InputEvent> &p_event) override; - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; void _script_list_gui_input(const Ref<InputEvent> &ev); void _make_script_list_context_menu(); @@ -440,6 +440,7 @@ class ScriptEditor : public PanelContainer { void _help_class_open(const String &p_class); void _help_class_goto(const String &p_desc); + bool _help_tab_goto(const String &p_name, const String &p_desc); void _update_history_arrows(); void _save_history(); void _go_to_tab(int p_idx); @@ -528,7 +529,7 @@ public: class ScriptEditorPlugin : public EditorPlugin { GDCLASS(ScriptEditorPlugin, EditorPlugin); - ScriptEditor *script_editor; + ScriptEditor *script_editor = nullptr; public: virtual String get_name() const override { return "Script"; } diff --git a/editor/plugins/shader_editor_plugin.h b/editor/plugins/shader_editor_plugin.h index 600b14362e..067711c75c 100644 --- a/editor/plugins/shader_editor_plugin.h +++ b/editor/plugins/shader_editor_plugin.h @@ -108,19 +108,19 @@ class ShaderEditor : public PanelContainer { HELP_DOCS, }; - MenuButton *edit_menu; - MenuButton *search_menu; - PopupMenu *bookmarks_menu; - MenuButton *help_menu; - PopupMenu *context_menu; + MenuButton *edit_menu = nullptr; + MenuButton *search_menu = nullptr; + PopupMenu *bookmarks_menu = nullptr; + MenuButton *help_menu = nullptr; + PopupMenu *context_menu = nullptr; RichTextLabel *warnings_panel = nullptr; uint64_t idle; - GotoLineDialog *goto_line_dialog; - ConfirmationDialog *erase_tab_confirm; - ConfirmationDialog *disk_changed; + GotoLineDialog *goto_line_dialog = nullptr; + ConfirmationDialog *erase_tab_confirm = nullptr; + ConfirmationDialog *disk_changed = nullptr; - ShaderTextEditor *shader_editor; + ShaderTextEditor *shader_editor = nullptr; void _menu_option(int p_option); mutable Ref<Shader> shader; @@ -161,8 +161,8 @@ class ShaderEditorPlugin : public EditorPlugin { GDCLASS(ShaderEditorPlugin, EditorPlugin); bool _2d; - ShaderEditor *shader_editor; - Button *button; + ShaderEditor *shader_editor = nullptr; + Button *button = nullptr; public: virtual String get_name() const override { return "Shader"; } diff --git a/editor/plugins/shader_file_editor_plugin.h b/editor/plugins/shader_file_editor_plugin.h index 5ee2d01dbf..1ebd644282 100644 --- a/editor/plugins/shader_file_editor_plugin.h +++ b/editor/plugins/shader_file_editor_plugin.h @@ -48,10 +48,10 @@ class ShaderFileEditor : public PanelContainer { Ref<RDShaderFile> shader_file; - HBoxContainer *stage_hb; - ItemList *versions; + HBoxContainer *stage_hb = nullptr; + ItemList *versions = nullptr; Button *stages[RD::SHADER_STAGE_MAX]; - RichTextLabel *error_text; + RichTextLabel *error_text = nullptr; void _update_version(const StringName &p_version_txt, const RenderingDevice::ShaderStage p_stage); void _version_selected(int p_stage); @@ -74,8 +74,8 @@ public: class ShaderFileEditorPlugin : public EditorPlugin { GDCLASS(ShaderFileEditorPlugin, EditorPlugin); - ShaderFileEditor *shader_editor; - Button *button; + ShaderFileEditor *shader_editor = nullptr; + Button *button = nullptr; public: virtual String get_name() const override { return "ShaderFile"; } diff --git a/editor/plugins/skeleton_2d_editor_plugin.h b/editor/plugins/skeleton_2d_editor_plugin.h index 004dac7b05..295725b751 100644 --- a/editor/plugins/skeleton_2d_editor_plugin.h +++ b/editor/plugins/skeleton_2d_editor_plugin.h @@ -43,10 +43,10 @@ class Skeleton2DEditor : public Control { MENU_OPTION_MAKE_REST, }; - Skeleton2D *node; + Skeleton2D *node = nullptr; - MenuButton *options; - AcceptDialog *err_dialog; + MenuButton *options = nullptr; + AcceptDialog *err_dialog = nullptr; void _menu_option(int p_option); @@ -65,7 +65,7 @@ public: class Skeleton2DEditorPlugin : public EditorPlugin { GDCLASS(Skeleton2DEditorPlugin, EditorPlugin); - Skeleton2DEditor *sprite_editor; + Skeleton2DEditor *sprite_editor = nullptr; public: virtual String get_name() const override { return "Skeleton2D"; } diff --git a/editor/plugins/skeleton_3d_editor_plugin.h b/editor/plugins/skeleton_3d_editor_plugin.h index 2dbb552428..911e39a34f 100644 --- a/editor/plugins/skeleton_3d_editor_plugin.h +++ b/editor/plugins/skeleton_3d_editor_plugin.h @@ -60,10 +60,10 @@ class BoneTransformEditor : public VBoxContainer { Rect2 background_rects[5]; - Skeleton3D *skeleton; + Skeleton3D *skeleton = nullptr; // String property; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; bool toggle_enabled = false; bool updating = false; @@ -108,26 +108,26 @@ class Skeleton3DEditor : public VBoxContainer { Transform3D relative_rest; // Relative to skeleton node. }; - EditorInspectorPluginSkeleton *editor_plugin; + EditorInspectorPluginSkeleton *editor_plugin = nullptr; - Skeleton3D *skeleton; + Skeleton3D *skeleton = nullptr; Tree *joint_tree = nullptr; BoneTransformEditor *rest_editor = nullptr; BoneTransformEditor *pose_editor = nullptr; - VSeparator *separator; + VSeparator *separator = nullptr; MenuButton *skeleton_options = nullptr; - Button *edit_mode_button; + Button *edit_mode_button = nullptr; bool edit_mode = false; - HBoxContainer *animation_hb; - Button *key_loc_button; - Button *key_rot_button; - Button *key_scale_button; - Button *key_insert_button; - Button *key_insert_all_button; + HBoxContainer *animation_hb = nullptr; + Button *key_loc_button = nullptr; + Button *key_rot_button = nullptr; + Button *key_scale_button = nullptr; + Button *key_insert_button = nullptr; + Button *key_insert_all_button = nullptr; EditorFileDialog *file_dialog = nullptr; @@ -163,7 +163,7 @@ class Skeleton3DEditor : public VBoxContainer { void set_bone_options_enabled(const bool p_bone_options_enabled); // Handle. - MeshInstance3D *handles_mesh_instance; + MeshInstance3D *handles_mesh_instance = nullptr; Ref<ImmediateMesh> handles_mesh; Ref<ShaderMaterial> handle_material; Ref<Shader> handle_shader; @@ -220,7 +220,7 @@ class EditorInspectorPluginSkeleton : public EditorInspectorPlugin { friend class Skeleton3DEditorPlugin; - Skeleton3DEditor *skel_editor; + Skeleton3DEditor *skel_editor = nullptr; public: virtual bool can_handle(Object *p_object) override; @@ -230,7 +230,7 @@ public: class Skeleton3DEditorPlugin : public EditorPlugin { GDCLASS(Skeleton3DEditorPlugin, EditorPlugin); - EditorInspectorPluginSkeleton *skeleton_plugin; + EditorInspectorPluginSkeleton *skeleton_plugin = nullptr; public: virtual EditorPlugin::AfterGUIInput forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) override; diff --git a/editor/plugins/skeleton_ik_3d_editor_plugin.h b/editor/plugins/skeleton_ik_3d_editor_plugin.h index f71e788232..26aead6d67 100644 --- a/editor/plugins/skeleton_ik_3d_editor_plugin.h +++ b/editor/plugins/skeleton_ik_3d_editor_plugin.h @@ -38,9 +38,9 @@ class SkeletonIK3D; class SkeletonIK3DEditorPlugin : public EditorPlugin { GDCLASS(SkeletonIK3DEditorPlugin, EditorPlugin); - SkeletonIK3D *skeleton_ik; + SkeletonIK3D *skeleton_ik = nullptr; - Button *play_btn; + Button *play_btn = nullptr; void _play(); diff --git a/editor/plugins/sprite_2d_editor_plugin.h b/editor/plugins/sprite_2d_editor_plugin.h index 46953b0937..8e3dc19c7e 100644 --- a/editor/plugins/sprite_2d_editor_plugin.h +++ b/editor/plugins/sprite_2d_editor_plugin.h @@ -47,16 +47,16 @@ class Sprite2DEditor : public Control { Menu selected_menu_item; - Sprite2D *node; + Sprite2D *node = nullptr; - MenuButton *options; + MenuButton *options = nullptr; - ConfirmationDialog *outline_dialog; + ConfirmationDialog *outline_dialog = nullptr; - AcceptDialog *err_dialog; + AcceptDialog *err_dialog = nullptr; - ConfirmationDialog *debug_uv_dialog; - Control *debug_uv; + ConfirmationDialog *debug_uv_dialog = nullptr; + Control *debug_uv = nullptr; Vector<Vector2> uv_lines; Vector<Vector<Vector2>> outline_lines; Vector<Vector<Vector2>> computed_outline_lines; @@ -64,10 +64,10 @@ class Sprite2DEditor : public Control { Vector<Vector2> computed_uv; Vector<int> computed_indices; - SpinBox *simplification; - SpinBox *grow_pixels; - SpinBox *shrink_pixels; - Button *update_preview; + SpinBox *simplification = nullptr; + SpinBox *grow_pixels = nullptr; + SpinBox *shrink_pixels = nullptr; + Button *update_preview = nullptr; void _menu_option(int p_option); @@ -98,7 +98,7 @@ public: class Sprite2DEditorPlugin : public EditorPlugin { GDCLASS(Sprite2DEditorPlugin, EditorPlugin); - Sprite2DEditor *sprite_editor; + Sprite2DEditor *sprite_editor = nullptr; public: virtual String get_name() const override { return "Sprite2D"; } diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp index 87b5b829e0..27160f8c86 100644 --- a/editor/plugins/sprite_frames_editor_plugin.cpp +++ b/editor/plugins/sprite_frames_editor_plugin.cpp @@ -43,6 +43,11 @@ #include "scene/gui/margin_container.h" #include "scene/gui/panel_container.h" +static void _draw_shadowed_line(Control *p_control, const Point2 &p_from, const Size2 &p_size, const Size2 &p_shadow_offset, Color p_color, Color p_shadow_color) { + p_control->draw_line(p_from, p_from + p_size, p_color); + p_control->draw_line(p_from + p_shadow_offset, p_from + p_size + p_shadow_offset, p_shadow_color); +} + void SpriteFramesEditor::gui_input(const Ref<InputEvent> &p_event) { } @@ -58,46 +63,62 @@ void SpriteFramesEditor::_open_sprite_sheet() { } int SpriteFramesEditor::_sheet_preview_position_to_frame_index(const Point2 &p_position) { - if (p_position.x < 0 || p_position.y < 0) { - return -1; - } + const Size2i offset = _get_offset(); + const Size2i frame_size = _get_frame_size(); + const Size2i separation = _get_separation(); + const Size2i block_size = frame_size + separation; + const Point2i position = p_position / sheet_zoom - offset; - Size2i texture_size = split_sheet_preview->get_texture()->get_size(); - int h = split_sheet_h->get_value(); - int v = split_sheet_v->get_value(); - if (h > texture_size.width || v > texture_size.height) { - return -1; + if (position.x % block_size.x > frame_size.x || position.y % block_size.y > frame_size.y) { + return -1; // Gap between frames. } - int x = int(p_position.x / sheet_zoom) / (texture_size.width / h); - int y = int(p_position.y / sheet_zoom) / (texture_size.height / v); - if (x >= h || y >= v) { - return -1; + const Point2i frame = position / block_size; + const Size2i frame_count = _get_frame_count(); + if (frame.x < 0 || frame.y < 0 || frame.x >= frame_count.x || frame.y >= frame_count.y) { + return -1; // Out of bound. } - return h * y + x; + + return frame_count.x * frame.y + frame.x; } void SpriteFramesEditor::_sheet_preview_draw() { - Size2i texture_size = split_sheet_preview->get_texture()->get_size(); - int h = split_sheet_h->get_value(); - int v = split_sheet_v->get_value(); - - real_t width = (texture_size.width / h) * sheet_zoom; - real_t height = (texture_size.height / v) * sheet_zoom; - const float a = 0.3; - - real_t y_end = v * height; - for (int i = 0; i <= h; i++) { - real_t x = i * width; - split_sheet_preview->draw_line(Point2(x, 0), Point2(x, y_end), Color(1, 1, 1, a)); - split_sheet_preview->draw_line(Point2(x + 1, 0), Point2(x + 1, y_end), Color(0, 0, 0, a)); + const Size2i frame_count = _get_frame_count(); + const Size2i separation = _get_separation(); + + const Size2 draw_offset = Size2(_get_offset()) * sheet_zoom; + const Size2 draw_sep = Size2(separation) * sheet_zoom; + const Size2 draw_frame_size = Size2(_get_frame_size()) * sheet_zoom; + const Size2 draw_size = draw_frame_size * frame_count + draw_sep * (frame_count - Size2i(1, 1)); + + const Color line_color = Color(1, 1, 1, 0.3); + const Color shadow_color = Color(0, 0, 0, 0.3); + + // Vertical lines. + _draw_shadowed_line(split_sheet_preview, draw_offset, Vector2(0, draw_size.y), Vector2(1, 0), line_color, shadow_color); + for (int i = 0; i < frame_count.x - 1; i++) { + const Point2 start = draw_offset + Vector2(i * draw_sep.x + (i + 1) * draw_frame_size.x, 0); + if (separation.x == 0) { + _draw_shadowed_line(split_sheet_preview, start, Vector2(0, draw_size.y), Vector2(1, 0), line_color, shadow_color); + } else { + const Size2 size = Size2(draw_sep.x, draw_size.y); + split_sheet_preview->draw_rect(Rect2(start, size), line_color); + } } - real_t x_end = h * width; - for (int i = 0; i <= v; i++) { - real_t y = i * height; - split_sheet_preview->draw_line(Point2(0, y), Point2(x_end, y), Color(1, 1, 1, a)); - split_sheet_preview->draw_line(Point2(0, y + 1), Point2(x_end, y + 1), Color(0, 0, 0, a)); + _draw_shadowed_line(split_sheet_preview, draw_offset + Vector2(draw_size.x, 0), Vector2(0, draw_size.y), Vector2(1, 0), line_color, shadow_color); + + // Horizontal lines. + _draw_shadowed_line(split_sheet_preview, draw_offset, Vector2(draw_size.x, 0), Vector2(0, 1), line_color, shadow_color); + for (int i = 0; i < frame_count.y - 1; i++) { + const Point2 start = draw_offset + Vector2(0, i * draw_sep.y + (i + 1) * draw_frame_size.y); + if (separation.y == 0) { + _draw_shadowed_line(split_sheet_preview, start, Vector2(draw_size.x, 0), Vector2(0, 1), line_color, shadow_color); + } else { + const Size2 size = Size2(draw_size.x, draw_sep.y); + split_sheet_preview->draw_rect(Rect2(start, size), line_color); + } } + _draw_shadowed_line(split_sheet_preview, draw_offset + Vector2(0, draw_size.y), Vector2(draw_size.x, 0), Vector2(0, 1), line_color, shadow_color); if (frames_selected.size() == 0) { split_sheet_dialog->get_ok_button()->set_disabled(true); @@ -105,22 +126,20 @@ void SpriteFramesEditor::_sheet_preview_draw() { return; } - Color accent = get_theme_color(SNAME("accent_color"), SNAME("Editor")); + Color accent = get_theme_color("accent_color", "Editor"); for (Set<int>::Element *E = frames_selected.front(); E; E = E->next()) { - int idx = E->get(); - int xp = idx % h; - int yp = idx / h; - real_t x = xp * width; - real_t y = yp * height; - - split_sheet_preview->draw_rect(Rect2(x + 5, y + 5, width - 10, height - 10), Color(0, 0, 0, 0.35), true); - split_sheet_preview->draw_rect(Rect2(x + 0, y + 0, width - 0, height - 0), Color(0, 0, 0, 1), false); - split_sheet_preview->draw_rect(Rect2(x + 1, y + 1, width - 2, height - 2), Color(0, 0, 0, 1), false); - split_sheet_preview->draw_rect(Rect2(x + 2, y + 2, width - 4, height - 4), accent, false); - split_sheet_preview->draw_rect(Rect2(x + 3, y + 3, width - 6, height - 6), accent, false); - split_sheet_preview->draw_rect(Rect2(x + 4, y + 4, width - 8, height - 8), Color(0, 0, 0, 1), false); - split_sheet_preview->draw_rect(Rect2(x + 5, y + 5, width - 10, height - 10), Color(0, 0, 0, 1), false); + const int idx = E->get(); + const int x = idx % frame_count.x; + const int y = idx / frame_count.x; + const Point2 pos = draw_offset + Point2(x, y) * (draw_frame_size + draw_sep); + split_sheet_preview->draw_rect(Rect2(pos + Size2(5, 5), draw_frame_size - Size2(10, 10)), Color(0, 0, 0, 0.35), true); + split_sheet_preview->draw_rect(Rect2(pos, draw_frame_size), Color(0, 0, 0, 1), false); + split_sheet_preview->draw_rect(Rect2(pos + Size2(1, 1), draw_frame_size - Size2(2, 2)), Color(0, 0, 0, 1), false); + split_sheet_preview->draw_rect(Rect2(pos + Size2(2, 2), draw_frame_size - Size2(4, 4)), accent, false); + split_sheet_preview->draw_rect(Rect2(pos + Size2(3, 3), draw_frame_size - Size2(6, 6)), accent, false); + split_sheet_preview->draw_rect(Rect2(pos + Size2(4, 4), draw_frame_size - Size2(8, 8)), Color(0, 0, 0, 1), false); + split_sheet_preview->draw_rect(Rect2(pos + Size2(5, 5), draw_frame_size - Size2(10, 10)), Color(0, 0, 0, 1), false); } split_sheet_dialog->get_ok_button()->set_disabled(false); @@ -223,10 +242,10 @@ void SpriteFramesEditor::_sheet_scroll_input(const Ref<InputEvent> &p_event) { } void SpriteFramesEditor::_sheet_add_frames() { - Size2i texture_size = split_sheet_preview->get_texture()->get_size(); - int frame_count_x = split_sheet_h->get_value(); - int frame_count_y = split_sheet_v->get_value(); - Size2 frame_size(texture_size.width / frame_count_x, texture_size.height / frame_count_y); + const Size2i frame_count = _get_frame_count(); + const Size2i frame_size = _get_frame_size(); + const Size2i offset = _get_offset(); + const Size2i separation = _get_separation(); undo_redo->create_action(TTR("Add Frame")); @@ -234,12 +253,12 @@ void SpriteFramesEditor::_sheet_add_frames() { for (Set<int>::Element *E = frames_selected.front(); E; E = E->next()) { int idx = E->get(); - Point2 frame_coords(idx % frame_count_x, idx / frame_count_x); + const Point2 frame_coords(idx % frame_count.x, idx / frame_count.x); Ref<AtlasTexture> at; at.instantiate(); at->set_atlas(split_sheet_preview->get_texture()); - at->set_region(Rect2(frame_coords * frame_size, frame_size)); + at->set_region(Rect2(offset + frame_coords * (frame_size + separation), frame_size)); undo_redo->add_do_method(frames, "add_frame", edited_anim, at, -1); undo_redo->add_undo_method(frames, "remove_frame", edited_anim, fc); @@ -293,7 +312,57 @@ void SpriteFramesEditor::_sheet_select_clear_all_frames() { split_sheet_preview->update(); } -void SpriteFramesEditor::_sheet_spin_changed(double) { +void SpriteFramesEditor::_sheet_spin_changed(double p_value, int p_dominant_param) { + if (updating_split_settings) { + return; + } + updating_split_settings = true; + + if (p_dominant_param != PARAM_USE_CURRENT) { + dominant_param = p_dominant_param; + } + + const Size2i texture_size = split_sheet_preview->get_texture()->get_size(); + const Size2i size = texture_size - _get_offset(); + + switch (dominant_param) { + case PARAM_SIZE: { + const Size2i frame_size = _get_frame_size(); + + const Size2i offset_max = texture_size - frame_size; + split_sheet_offset_x->set_max(offset_max.x); + split_sheet_offset_y->set_max(offset_max.y); + + const Size2i sep_max = size - frame_size * 2; + split_sheet_sep_x->set_max(sep_max.x); + split_sheet_sep_y->set_max(sep_max.y); + + const Size2i separation = _get_separation(); + const Size2i count = (size + separation) / (frame_size + separation); + split_sheet_h->set_value(count.x); + split_sheet_v->set_value(count.y); + } break; + + case PARAM_FRAME_COUNT: { + const Size2i count = _get_frame_count(); + + const Size2i offset_max = texture_size - count; + split_sheet_offset_x->set_max(offset_max.x); + split_sheet_offset_y->set_max(offset_max.y); + + const Size2i gap_count = count - Size2i(1, 1); + split_sheet_sep_x->set_max(gap_count.x == 0 ? size.x : (size.x - count.x) / gap_count.x); + split_sheet_sep_y->set_max(gap_count.y == 0 ? size.y : (size.y - count.y) / gap_count.y); + + const Size2i separation = _get_separation(); + const Size2i frame_size = (size - separation * gap_count) / count; + split_sheet_size_x->set_value(frame_size.x); + split_sheet_size_y->set_value(frame_size.y); + } break; + } + + updating_split_settings = false; + frames_selected.clear(); last_frame_selected = -1; split_sheet_preview->update(); @@ -311,10 +380,29 @@ void SpriteFramesEditor::_prepare_sprite_sheet(const String &p_file) { bool new_texture = texture != split_sheet_preview->get_texture(); split_sheet_preview->set_texture(texture); if (new_texture) { - //different texture, reset to 4x4 + // Reset spin max. + const Size2i size = texture->get_size(); + split_sheet_size_x->set_max(size.x); + split_sheet_size_y->set_max(size.y); + split_sheet_sep_x->set_max(size.x); + split_sheet_sep_y->set_max(size.y); + split_sheet_offset_x->set_max(size.x); + split_sheet_offset_y->set_max(size.y); + + // Different texture, reset to 4x4. + dominant_param = PARAM_FRAME_COUNT; + updating_split_settings = true; split_sheet_h->set_value(4); split_sheet_v->set_value(4); - //reset zoom + split_sheet_size_x->set_value(size.x / 4); + split_sheet_size_y->set_value(size.y / 4); + split_sheet_sep_x->set_value(0); + split_sheet_sep_y->set_value(0); + split_sheet_offset_x->set_value(0); + split_sheet_offset_y->set_value(0); + updating_split_settings = false; + + // Reset zoom. _sheet_zoom_reset(); } split_sheet_dialog->popup_centered_ratio(0.65); @@ -392,6 +480,22 @@ void SpriteFramesEditor::_file_load_request(const Vector<String> &p_path, int p_ undo_redo->commit_action(); } +Size2i SpriteFramesEditor::_get_frame_count() const { + return Size2i(split_sheet_h->get_value(), split_sheet_v->get_value()); +} + +Size2i SpriteFramesEditor::_get_frame_size() const { + return Size2i(split_sheet_size_x->get_value(), split_sheet_size_y->get_value()); +} + +Size2i SpriteFramesEditor::_get_offset() const { + return Size2i(split_sheet_offset_x->get_value(), split_sheet_offset_y->get_value()); +} + +Size2i SpriteFramesEditor::_get_separation() const { + return Size2i(split_sheet_sep_x->get_value(), split_sheet_sep_y->get_value()); +} + void SpriteFramesEditor::_load_pressed() { ERR_FAIL_COND(!frames->has_animation(edited_anim)); loading_scene = false; @@ -1210,23 +1314,66 @@ SpriteFramesEditor::SpriteFramesEditor() { HBoxContainer *split_sheet_hb = memnew(HBoxContainer); - Label *ss_label = memnew(Label(TTR("Horizontal:"))); - split_sheet_hb->add_child(ss_label); + split_sheet_hb->add_child(memnew(Label(TTR("Horizontal:")))); split_sheet_h = memnew(SpinBox); split_sheet_h->set_min(1); split_sheet_h->set_max(128); split_sheet_h->set_step(1); split_sheet_hb->add_child(split_sheet_h); - split_sheet_h->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed)); + split_sheet_h->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_FRAME_COUNT)); - ss_label = memnew(Label(TTR("Vertical:"))); - split_sheet_hb->add_child(ss_label); + split_sheet_hb->add_child(memnew(Label(TTR("Vertical:")))); split_sheet_v = memnew(SpinBox); split_sheet_v->set_min(1); split_sheet_v->set_max(128); split_sheet_v->set_step(1); split_sheet_hb->add_child(split_sheet_v); - split_sheet_v->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed)); + split_sheet_v->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_FRAME_COUNT)); + + split_sheet_hb->add_child(memnew(VSeparator)); + split_sheet_hb->add_child(memnew(Label(TTR("Size:")))); + split_sheet_size_x = memnew(SpinBox); + split_sheet_size_x->set_min(1); + split_sheet_size_x->set_step(1); + split_sheet_size_x->set_suffix("px"); + split_sheet_size_x->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_SIZE)); + split_sheet_hb->add_child(split_sheet_size_x); + split_sheet_size_y = memnew(SpinBox); + split_sheet_size_y->set_min(1); + split_sheet_size_y->set_step(1); + split_sheet_size_y->set_suffix("px"); + split_sheet_size_y->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_SIZE)); + split_sheet_hb->add_child(split_sheet_size_y); + + split_sheet_hb->add_child(memnew(VSeparator)); + split_sheet_hb->add_child(memnew(Label(TTR("Separation:")))); + split_sheet_sep_x = memnew(SpinBox); + split_sheet_sep_x->set_min(0); + split_sheet_sep_x->set_step(1); + split_sheet_sep_x->set_suffix("px"); + split_sheet_sep_x->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_USE_CURRENT)); + split_sheet_hb->add_child(split_sheet_sep_x); + split_sheet_sep_y = memnew(SpinBox); + split_sheet_sep_y->set_min(0); + split_sheet_sep_y->set_step(1); + split_sheet_sep_y->set_suffix("px"); + split_sheet_sep_y->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_USE_CURRENT)); + split_sheet_hb->add_child(split_sheet_sep_y); + + split_sheet_hb->add_child(memnew(VSeparator)); + split_sheet_hb->add_child(memnew(Label(TTR("Offset:")))); + split_sheet_offset_x = memnew(SpinBox); + split_sheet_offset_x->set_min(0); + split_sheet_offset_x->set_step(1); + split_sheet_offset_x->set_suffix("px"); + split_sheet_offset_x->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_USE_CURRENT)); + split_sheet_hb->add_child(split_sheet_offset_x); + split_sheet_offset_y = memnew(SpinBox); + split_sheet_offset_y->set_min(0); + split_sheet_offset_y->set_step(1); + split_sheet_offset_y->set_suffix("px"); + split_sheet_offset_y->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_sheet_spin_changed), varray(PARAM_USE_CURRENT)); + split_sheet_hb->add_child(split_sheet_offset_y); split_sheet_hb->add_spacer(); diff --git a/editor/plugins/sprite_frames_editor_plugin.h b/editor/plugins/sprite_frames_editor_plugin.h index 872a88e262..9a00fe5771 100644 --- a/editor/plugins/sprite_frames_editor_plugin.h +++ b/editor/plugins/sprite_frames_editor_plugin.h @@ -48,48 +48,61 @@ class EditorFileDialog; class SpriteFramesEditor : public HSplitContainer { GDCLASS(SpriteFramesEditor, HSplitContainer); - Button *load; - Button *load_sheet; - Button *_delete; - Button *copy; - Button *paste; - Button *empty; - Button *empty2; - Button *move_up; - Button *move_down; - Button *zoom_out; - Button *zoom_reset; - Button *zoom_in; - ItemList *tree; + enum { + PARAM_USE_CURRENT, // Used in callbacks to indicate `dominant_param` should be not updated. + PARAM_FRAME_COUNT, // Keep "Horizontal" & "Vertial" values. + PARAM_SIZE, // Keep "Size" values. + }; + int dominant_param = PARAM_FRAME_COUNT; + + Button *load = nullptr; + Button *load_sheet = nullptr; + Button *_delete = nullptr; + Button *copy = nullptr; + Button *paste = nullptr; + Button *empty = nullptr; + Button *empty2 = nullptr; + Button *move_up = nullptr; + Button *move_down = nullptr; + Button *zoom_out = nullptr; + Button *zoom_reset = nullptr; + Button *zoom_in = nullptr; + ItemList *tree = nullptr; bool loading_scene; int sel; - Button *new_anim; - Button *remove_anim; + Button *new_anim = nullptr; + Button *remove_anim = nullptr; - Tree *animations; - SpinBox *anim_speed; - CheckButton *anim_loop; + Tree *animations = nullptr; + SpinBox *anim_speed = nullptr; + CheckButton *anim_loop = nullptr; - EditorFileDialog *file; + EditorFileDialog *file = nullptr; - AcceptDialog *dialog; + AcceptDialog *dialog = nullptr; - SpriteFrames *frames; + SpriteFrames *frames = nullptr; StringName edited_anim; - ConfirmationDialog *delete_dialog; - - ConfirmationDialog *split_sheet_dialog; - ScrollContainer *split_sheet_scroll; - TextureRect *split_sheet_preview; - SpinBox *split_sheet_h; - SpinBox *split_sheet_v; - Button *split_sheet_zoom_out; - Button *split_sheet_zoom_reset; - Button *split_sheet_zoom_in; - EditorFileDialog *file_split_sheet; + ConfirmationDialog *delete_dialog = nullptr; + + ConfirmationDialog *split_sheet_dialog = nullptr; + ScrollContainer *split_sheet_scroll = nullptr; + TextureRect *split_sheet_preview = nullptr; + SpinBox *split_sheet_h = nullptr; + SpinBox *split_sheet_v = nullptr; + SpinBox *split_sheet_size_x = nullptr; + SpinBox *split_sheet_size_y = nullptr; + SpinBox *split_sheet_sep_x = nullptr; + SpinBox *split_sheet_sep_y = nullptr; + SpinBox *split_sheet_offset_x = nullptr; + SpinBox *split_sheet_offset_y = nullptr; + Button *split_sheet_zoom_out = nullptr; + Button *split_sheet_zoom_reset = nullptr; + Button *split_sheet_zoom_in = nullptr; + EditorFileDialog *file_split_sheet = nullptr; Set<int> frames_selected; Set<int> frames_toggled_by_mouse_hover; int last_frame_selected; @@ -103,6 +116,11 @@ class SpriteFramesEditor : public HSplitContainer { float max_sheet_zoom; float min_sheet_zoom; + Size2i _get_frame_count() const; + Size2i _get_frame_size() const; + Size2i _get_offset() const; + Size2i _get_separation() const; + void _load_pressed(); void _file_load_request(const Vector<String> &p_path, int p_at_pos = -1); void _copy_pressed(); @@ -128,8 +146,9 @@ class SpriteFramesEditor : public HSplitContainer { void _zoom_reset(); bool updating; + bool updating_split_settings = false; // Skip SpinBox/Range callback when setting value by code. - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; Variant get_drag_data_fw(const Point2 &p_point, Control *p_from); bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const; @@ -139,7 +158,7 @@ class SpriteFramesEditor : public HSplitContainer { void _prepare_sprite_sheet(const String &p_file); int _sheet_preview_position_to_frame_index(const Vector2 &p_position); void _sheet_preview_draw(); - void _sheet_spin_changed(double); + void _sheet_spin_changed(double p_value, int p_dominant_param); void _sheet_preview_input(const Ref<InputEvent> &p_event); void _sheet_scroll_input(const Ref<InputEvent> &p_event); void _sheet_add_frames(); @@ -164,8 +183,8 @@ public: class SpriteFramesEditorPlugin : public EditorPlugin { GDCLASS(SpriteFramesEditorPlugin, EditorPlugin); - SpriteFramesEditor *frames_editor; - Button *button; + SpriteFramesEditor *frames_editor = nullptr; + Button *button = nullptr; public: virtual String get_name() const override { return "SpriteFrames"; } diff --git a/editor/plugins/style_box_editor_plugin.h b/editor/plugins/style_box_editor_plugin.h index bdebebbe1c..663440ae31 100644 --- a/editor/plugins/style_box_editor_plugin.h +++ b/editor/plugins/style_box_editor_plugin.h @@ -40,7 +40,7 @@ class StyleBoxPreview : public VBoxContainer { GDCLASS(StyleBoxPreview, VBoxContainer); - Control *preview; + Control *preview = nullptr; Ref<StyleBox> stylebox; void _sb_changed(); diff --git a/editor/plugins/text_control_editor_plugin.h b/editor/plugins/text_control_editor_plugin.h index 1349003a9c..a475f6eba3 100644 --- a/editor/plugins/text_control_editor_plugin.h +++ b/editor/plugins/text_control_editor_plugin.h @@ -100,7 +100,7 @@ public: class TextControlEditorPlugin : public EditorPlugin { GDCLASS(TextControlEditorPlugin, EditorPlugin); - TextControlEditor *text_ctl_editor; + TextControlEditor *text_ctl_editor = nullptr; public: virtual String get_name() const override { return "TextControlFontEditor"; } diff --git a/editor/plugins/texture_3d_editor_plugin.h b/editor/plugins/texture_3d_editor_plugin.h index d418032477..2f7f6f83bb 100644 --- a/editor/plugins/texture_3d_editor_plugin.h +++ b/editor/plugins/texture_3d_editor_plugin.h @@ -39,14 +39,14 @@ class Texture3DEditor : public Control { GDCLASS(Texture3DEditor, Control); - SpinBox *layer; - Label *info; + SpinBox *layer = nullptr; + Label *info = nullptr; Ref<Texture3D> texture; Ref<Shader> shader; Ref<ShaderMaterial> material; - Control *texture_rect; + Control *texture_rect = nullptr; void _make_shaders(); diff --git a/editor/plugins/texture_editor_plugin.cpp b/editor/plugins/texture_editor_plugin.cpp index a7c06ada5c..15f03fd46d 100644 --- a/editor/plugins/texture_editor_plugin.cpp +++ b/editor/plugins/texture_editor_plugin.cpp @@ -70,7 +70,7 @@ void TexturePreview::_update_metadata_label_text() { format = texture->get_class(); } - metadata_label->set_text(itos(texture->get_width()) + "x" + itos(texture->get_height()) + " " + format); + metadata_label->set_text(vformat(String::utf8("%s×%s %s"), itos(texture->get_width()), itos(texture->get_height()), format)); } TexturePreview::TexturePreview(Ref<Texture2D> p_texture, bool p_show_metadata) { diff --git a/editor/plugins/texture_layered_editor_plugin.h b/editor/plugins/texture_layered_editor_plugin.h index 1c59ec4db0..830916e954 100644 --- a/editor/plugins/texture_layered_editor_plugin.h +++ b/editor/plugins/texture_layered_editor_plugin.h @@ -39,8 +39,8 @@ class TextureLayeredEditor : public Control { GDCLASS(TextureLayeredEditor, Control); - SpinBox *layer; - Label *info; + SpinBox *layer = nullptr; + Label *info = nullptr; Ref<TextureLayered> texture; Ref<Shader> shaders[3]; @@ -48,7 +48,7 @@ class TextureLayeredEditor : public Control { float x_rot = 0; float y_rot = 0; - Control *texture_rect; + Control *texture_rect = nullptr; void _make_shaders(); diff --git a/editor/plugins/texture_region_editor_plugin.h b/editor/plugins/texture_region_editor_plugin.h index 041742c28a..1e1cc2b7b2 100644 --- a/editor/plugins/texture_region_editor_plugin.h +++ b/editor/plugins/texture_region_editor_plugin.h @@ -52,23 +52,23 @@ class TextureRegionEditor : public VBoxContainer { }; friend class TextureRegionEditorPlugin; - OptionButton *snap_mode_button; - Button *zoom_in; - Button *zoom_reset; - Button *zoom_out; - HBoxContainer *hb_grid; //For showing/hiding the grid controls when changing the SnapMode - SpinBox *sb_step_y; - SpinBox *sb_step_x; - SpinBox *sb_off_y; - SpinBox *sb_off_x; - SpinBox *sb_sep_y; - SpinBox *sb_sep_x; - Panel *edit_draw; - - VScrollBar *vscroll; - HScrollBar *hscroll; - - UndoRedo *undo_redo; + OptionButton *snap_mode_button = nullptr; + Button *zoom_in = nullptr; + Button *zoom_reset = nullptr; + Button *zoom_out = nullptr; + HBoxContainer *hb_grid = nullptr; //For showing/hiding the grid controls when changing the SnapMode + SpinBox *sb_step_y = nullptr; + SpinBox *sb_step_x = nullptr; + SpinBox *sb_off_y = nullptr; + SpinBox *sb_off_x = nullptr; + SpinBox *sb_sep_y = nullptr; + SpinBox *sb_sep_x = nullptr; + Panel *edit_draw = nullptr; + + VScrollBar *vscroll = nullptr; + HScrollBar *hscroll = nullptr; + + UndoRedo *undo_redo = nullptr; Vector2 draw_ofs; float draw_zoom; @@ -79,9 +79,9 @@ class TextureRegionEditor : public VBoxContainer { Vector2 snap_step; Vector2 snap_separation; - Sprite2D *node_sprite_2d; - Sprite3D *node_sprite_3d; - NinePatchRect *node_ninepatch; + Sprite2D *node_sprite_2d = nullptr; + Sprite3D *node_sprite_3d = nullptr; + NinePatchRect *node_ninepatch = nullptr; Ref<StyleBoxTexture> obj_styleBox; Ref<AtlasTexture> atlas_tex; @@ -146,8 +146,8 @@ class TextureRegionEditorPlugin : public EditorPlugin { GDCLASS(TextureRegionEditorPlugin, EditorPlugin); bool manually_hidden; - Button *texture_region_button; - TextureRegionEditor *region_editor; + Button *texture_region_button = nullptr; + TextureRegionEditor *region_editor = nullptr; protected: static void _bind_methods(); diff --git a/editor/plugins/theme_editor_plugin.h b/editor/plugins/theme_editor_plugin.h index 7c1b0cda3e..4b49fbb186 100644 --- a/editor/plugins/theme_editor_plugin.h +++ b/editor/plugins/theme_editor_plugin.h @@ -75,9 +75,9 @@ class ThemeItemImportTree : public VBoxContainer { Map<ThemeItem, ItemCheckedState> selected_items; - LineEdit *import_items_filter; + LineEdit *import_items_filter = nullptr; - Tree *import_items_tree; + Tree *import_items_tree = nullptr; List<TreeItem *> tree_color_items; List<TreeItem *> tree_constant_items; List<TreeItem *> tree_font_items; @@ -92,57 +92,57 @@ class ThemeItemImportTree : public VBoxContainer { IMPORT_ITEM_DATA = 2, }; - TextureRect *select_colors_icon; - Label *select_colors_label; - Button *select_all_colors_button; - Button *select_full_colors_button; - Button *deselect_all_colors_button; - Label *total_selected_colors_label; - - TextureRect *select_constants_icon; - Label *select_constants_label; - Button *select_all_constants_button; - Button *select_full_constants_button; - Button *deselect_all_constants_button; - Label *total_selected_constants_label; - - TextureRect *select_fonts_icon; - Label *select_fonts_label; - Button *select_all_fonts_button; - Button *select_full_fonts_button; - Button *deselect_all_fonts_button; - Label *total_selected_fonts_label; - - TextureRect *select_font_sizes_icon; - Label *select_font_sizes_label; - Button *select_all_font_sizes_button; - Button *select_full_font_sizes_button; - Button *deselect_all_font_sizes_button; - Label *total_selected_font_sizes_label; - - TextureRect *select_icons_icon; - Label *select_icons_label; - Button *select_all_icons_button; - Button *select_full_icons_button; - Button *deselect_all_icons_button; - Label *total_selected_icons_label; - - TextureRect *select_styleboxes_icon; - Label *select_styleboxes_label; - Button *select_all_styleboxes_button; - Button *select_full_styleboxes_button; - Button *deselect_all_styleboxes_button; - Label *total_selected_styleboxes_label; - - HBoxContainer *select_icons_warning_hb; - TextureRect *select_icons_warning_icon; - Label *select_icons_warning; - - Button *import_collapse_types_button; - Button *import_expand_types_button; - Button *import_select_all_button; - Button *import_select_full_button; - Button *import_deselect_all_button; + TextureRect *select_colors_icon = nullptr; + Label *select_colors_label = nullptr; + Button *select_all_colors_button = nullptr; + Button *select_full_colors_button = nullptr; + Button *deselect_all_colors_button = nullptr; + Label *total_selected_colors_label = nullptr; + + TextureRect *select_constants_icon = nullptr; + Label *select_constants_label = nullptr; + Button *select_all_constants_button = nullptr; + Button *select_full_constants_button = nullptr; + Button *deselect_all_constants_button = nullptr; + Label *total_selected_constants_label = nullptr; + + TextureRect *select_fonts_icon = nullptr; + Label *select_fonts_label = nullptr; + Button *select_all_fonts_button = nullptr; + Button *select_full_fonts_button = nullptr; + Button *deselect_all_fonts_button = nullptr; + Label *total_selected_fonts_label = nullptr; + + TextureRect *select_font_sizes_icon = nullptr; + Label *select_font_sizes_label = nullptr; + Button *select_all_font_sizes_button = nullptr; + Button *select_full_font_sizes_button = nullptr; + Button *deselect_all_font_sizes_button = nullptr; + Label *total_selected_font_sizes_label = nullptr; + + TextureRect *select_icons_icon = nullptr; + Label *select_icons_label = nullptr; + Button *select_all_icons_button = nullptr; + Button *select_full_icons_button = nullptr; + Button *deselect_all_icons_button = nullptr; + Label *total_selected_icons_label = nullptr; + + TextureRect *select_styleboxes_icon = nullptr; + Label *select_styleboxes_label = nullptr; + Button *select_all_styleboxes_button = nullptr; + Button *select_full_styleboxes_button = nullptr; + Button *deselect_all_styleboxes_button = nullptr; + Label *total_selected_styleboxes_label = nullptr; + + HBoxContainer *select_icons_warning_hb = nullptr; + TextureRect *select_icons_warning_icon = nullptr; + Label *select_icons_warning = nullptr; + + Button *import_collapse_types_button = nullptr; + Button *import_expand_types_button = nullptr; + Button *import_select_all_button = nullptr; + Button *import_select_full_button = nullptr; + Button *import_deselect_all_button = nullptr; void _update_items_tree(); void _toggle_type_items(bool p_collapse); @@ -186,31 +186,31 @@ class ThemeTypeEditor; class ThemeItemEditorDialog : public AcceptDialog { GDCLASS(ThemeItemEditorDialog, AcceptDialog); - ThemeTypeEditor *theme_type_editor; + ThemeTypeEditor *theme_type_editor = nullptr; Ref<Theme> edited_theme; - TabContainer *tc; + TabContainer *tc = nullptr; enum TypesTreeAction { TYPES_TREE_REMOVE_ITEM, }; - Tree *edit_type_list; - LineEdit *edit_add_type_value; + Tree *edit_type_list = nullptr; + LineEdit *edit_add_type_value = nullptr; String edited_item_type; - Button *edit_items_add_color; - Button *edit_items_add_constant; - Button *edit_items_add_font; - Button *edit_items_add_font_size; - Button *edit_items_add_icon; - Button *edit_items_add_stylebox; - Button *edit_items_remove_class; - Button *edit_items_remove_custom; - Button *edit_items_remove_all; - Tree *edit_items_tree; - Label *edit_items_message; + Button *edit_items_add_color = nullptr; + Button *edit_items_add_constant = nullptr; + Button *edit_items_add_font = nullptr; + Button *edit_items_add_font_size = nullptr; + Button *edit_items_add_icon = nullptr; + Button *edit_items_add_stylebox = nullptr; + Button *edit_items_remove_class = nullptr; + Button *edit_items_remove_custom = nullptr; + Button *edit_items_remove_all = nullptr; + Tree *edit_items_tree = nullptr; + Label *edit_items_message = nullptr; enum ItemsTreeAction { ITEMS_TREE_RENAME_ITEM, @@ -218,10 +218,10 @@ class ThemeItemEditorDialog : public AcceptDialog { ITEMS_TREE_REMOVE_DATA_TYPE, }; - ConfirmationDialog *edit_theme_item_dialog; - VBoxContainer *edit_theme_item_old_vb; - Label *theme_item_old_name; - LineEdit *theme_item_name; + ConfirmationDialog *edit_theme_item_dialog = nullptr; + VBoxContainer *edit_theme_item_old_vb = nullptr; + Label *theme_item_old_name = nullptr; + LineEdit *theme_item_name = nullptr; enum ItemPopupMode { CREATE_THEME_ITEM, @@ -233,15 +233,15 @@ class ThemeItemEditorDialog : public AcceptDialog { String edit_item_old_name; Theme::DataType edit_item_data_type = Theme::DATA_TYPE_MAX; - ThemeItemImportTree *import_default_theme_items; - ThemeItemImportTree *import_editor_theme_items; - ThemeItemImportTree *import_other_theme_items; + ThemeItemImportTree *import_default_theme_items = nullptr; + ThemeItemImportTree *import_editor_theme_items = nullptr; + ThemeItemImportTree *import_other_theme_items = nullptr; - LineEdit *import_another_theme_value; - Button *import_another_theme_button; - EditorFileDialog *import_another_theme_dialog; + LineEdit *import_another_theme_value = nullptr; + Button *import_another_theme_button = nullptr; + EditorFileDialog *import_another_theme_dialog = nullptr; - ConfirmationDialog *confirm_closing_dialog; + ConfirmationDialog *confirm_closing_dialog = nullptr; void ok_pressed() override; void _close_dialog(); @@ -288,9 +288,9 @@ class ThemeTypeDialog : public ConfirmationDialog { String pre_submitted_value; - LineEdit *add_type_filter; - ItemList *add_type_options; - ConfirmationDialog *add_type_confirmation; + LineEdit *add_type_filter = nullptr; + ItemList *add_type_options = nullptr; + ConfirmationDialog *add_type_confirmation = nullptr; void _dialog_about_to_show(); void ok_pressed() override; @@ -332,22 +332,22 @@ class ThemeTypeEditor : public MarginContainer { LeadingStylebox leading_stylebox; - OptionButton *theme_type_list; - Button *add_type_button; + OptionButton *theme_type_list = nullptr; + Button *add_type_button = nullptr; - CheckButton *show_default_items_button; + CheckButton *show_default_items_button = nullptr; - TabContainer *data_type_tabs; - VBoxContainer *color_items_list; - VBoxContainer *constant_items_list; - VBoxContainer *font_items_list; - VBoxContainer *font_size_items_list; - VBoxContainer *icon_items_list; - VBoxContainer *stylebox_items_list; + TabContainer *data_type_tabs = nullptr; + VBoxContainer *color_items_list = nullptr; + VBoxContainer *constant_items_list = nullptr; + VBoxContainer *font_items_list = nullptr; + VBoxContainer *font_size_items_list = nullptr; + VBoxContainer *icon_items_list = nullptr; + VBoxContainer *stylebox_items_list = nullptr; - LineEdit *type_variation_edit; - Button *type_variation_button; - Label *type_variation_locked; + LineEdit *type_variation_edit = nullptr; + Button *type_variation_button = nullptr; + Label *type_variation_locked = nullptr; enum TypeDialogMode { ADD_THEME_TYPE, @@ -355,10 +355,10 @@ class ThemeTypeEditor : public MarginContainer { }; TypeDialogMode add_type_mode = ADD_THEME_TYPE; - ThemeTypeDialog *add_type_dialog; + ThemeTypeDialog *add_type_dialog = nullptr; Vector<Control *> focusables; - Timer *update_debounce_timer; + Timer *update_debounce_timer = nullptr; VBoxContainer *_create_item_list(Theme::DataType p_data_type); void _update_type_list(); @@ -417,15 +417,15 @@ class ThemeEditor : public VBoxContainer { Ref<Theme> theme; - TabBar *preview_tabs; - PanelContainer *preview_tabs_content; - Button *add_preview_button; - EditorFileDialog *preview_scene_dialog; + TabBar *preview_tabs = nullptr; + PanelContainer *preview_tabs_content = nullptr; + Button *add_preview_button = nullptr; + EditorFileDialog *preview_scene_dialog = nullptr; - ThemeTypeEditor *theme_type_editor; + ThemeTypeEditor *theme_type_editor = nullptr; - Label *theme_name; - ThemeItemEditorDialog *theme_edit_dialog; + Label *theme_name = nullptr; + ThemeItemEditorDialog *theme_edit_dialog = nullptr; void _theme_save_button_cbk(bool p_save_as); void _theme_edit_button_cbk(); @@ -452,8 +452,8 @@ public: class ThemeEditorPlugin : public EditorPlugin { GDCLASS(ThemeEditorPlugin, EditorPlugin); - ThemeEditor *theme_editor; - Button *button; + ThemeEditor *theme_editor = nullptr; + Button *button = nullptr; public: virtual String get_name() const override { return "Theme"; } diff --git a/editor/plugins/theme_editor_preview.h b/editor/plugins/theme_editor_preview.h index 48111df399..d05916afae 100644 --- a/editor/plugins/theme_editor_preview.h +++ b/editor/plugins/theme_editor_preview.h @@ -41,10 +41,10 @@ class ThemeEditorPreview : public VBoxContainer { GDCLASS(ThemeEditorPreview, VBoxContainer); - ScrollContainer *preview_container; - ColorRect *preview_bg; - MarginContainer *preview_overlay; - Control *picker_overlay; + ScrollContainer *preview_container = nullptr; + ColorRect *preview_bg = nullptr; + MarginContainer *preview_overlay = nullptr; + Control *picker_overlay = nullptr; Control *hovered_control = nullptr; struct ThemeCache { @@ -69,9 +69,9 @@ class ThemeEditorPreview : public VBoxContainer { void _reset_picker_overlay(); protected: - HBoxContainer *preview_toolbar; - MarginContainer *preview_content; - Button *picker_button; + HBoxContainer *preview_toolbar = nullptr; + MarginContainer *preview_content = nullptr; + Button *picker_button = nullptr; void add_preview_overlay(Control *p_overlay); @@ -96,7 +96,7 @@ class SceneThemeEditorPreview : public ThemeEditorPreview { Ref<PackedScene> loaded_scene; - Button *reload_scene_button; + Button *reload_scene_button = nullptr; void _reload_scene(); diff --git a/editor/plugins/tiles/atlas_merging_dialog.h b/editor/plugins/tiles/atlas_merging_dialog.h index 6cf555247d..9502d93f6b 100644 --- a/editor/plugins/tiles/atlas_merging_dialog.h +++ b/editor/plugins/tiles/atlas_merging_dialog.h @@ -49,19 +49,19 @@ private: LocalVector<Map<Vector2i, Vector2i>> merged_mapping; Ref<TileSet> tile_set; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; // Settings. int next_line_after_column = 30; // GUI. - ItemList *atlas_merging_atlases_list; - EditorPropertyVector2i *texture_region_size_editor_property; - EditorPropertyInteger *columns_editor_property; - TextureRect *preview; - Label *select_2_atlases_label; - EditorFileDialog *editor_file_dialog; - Button *merge_button; + ItemList *atlas_merging_atlases_list = nullptr; + EditorPropertyVector2i *texture_region_size_editor_property = nullptr; + EditorPropertyInteger *columns_editor_property = nullptr; + TextureRect *preview = nullptr; + Label *select_2_atlases_label = nullptr; + EditorFileDialog *editor_file_dialog = nullptr; + Button *merge_button = nullptr; void _property_changed(const StringName &p_property, const Variant &p_value, const String &p_field, bool p_changing); diff --git a/editor/plugins/tiles/tile_atlas_view.h b/editor/plugins/tiles/tile_atlas_view.h index caf3ef9e4b..6e74858b08 100644 --- a/editor/plugins/tiles/tile_atlas_view.h +++ b/editor/plugins/tiles/tile_atlas_view.h @@ -45,8 +45,8 @@ class TileAtlasView : public Control { GDCLASS(TileAtlasView, Control); private: - TileSet *tile_set; - TileSetAtlasSource *tile_set_atlas_source; + TileSet *tile_set = nullptr; + TileSetAtlasSource *tile_set_atlas_source = nullptr; int source_id = TileSet::INVALID_SOURCE; enum DragType { @@ -55,9 +55,9 @@ private: }; DragType drag_type = DRAG_TYPE_NONE; float previous_zoom = 1.0; - EditorZoomWidget *zoom_widget; - Button *button_center_view; - CenterContainer *center_container; + EditorZoomWidget *zoom_widget = nullptr; + Button *button_center_view = nullptr; + CenterContainer *center_container = nullptr; Vector2 panning; void _update_zoom_and_panning(bool p_zoom_on_mouse_pos = false); void _zoom_widget_changed(); @@ -72,41 +72,41 @@ private: Map<Vector2, Map<int, Rect2i>> alternative_tiles_rect_cache; void _update_alternative_tiles_rect_cache(); - MarginContainer *margin_container; + MarginContainer *margin_container = nullptr; int margin_container_paddings[4] = { 0, 0, 0, 0 }; - HBoxContainer *hbox; - Label *missing_source_label; + HBoxContainer *hbox = nullptr; + Label *missing_source_label = nullptr; // Background - Control *background_left; + Control *background_left = nullptr; void _draw_background_left(); - Control *background_right; + Control *background_right = nullptr; void _draw_background_right(); // Left side. - Control *base_tiles_root_control; + Control *base_tiles_root_control = nullptr; void _base_tiles_root_control_gui_input(const Ref<InputEvent> &p_event); - Control *base_tiles_drawing_root; + Control *base_tiles_drawing_root = nullptr; - Control *base_tiles_draw; + Control *base_tiles_draw = nullptr; void _draw_base_tiles(); - Control *base_tiles_texture_grid; + Control *base_tiles_texture_grid = nullptr; void _draw_base_tiles_texture_grid(); - Control *base_tiles_shape_grid; + Control *base_tiles_shape_grid = nullptr; void _draw_base_tiles_shape_grid(); Size2i _compute_base_tiles_control_size(); // Right side. - Control *alternative_tiles_root_control; + Control *alternative_tiles_root_control = nullptr; void _alternative_tiles_root_control_gui_input(const Ref<InputEvent> &p_event); - Control *alternative_tiles_drawing_root; + Control *alternative_tiles_drawing_root = nullptr; - Control *alternatives_draw; + Control *alternatives_draw = nullptr; void _draw_alternatives(); Size2i _compute_alternative_tiles_control_size(); diff --git a/editor/plugins/tiles/tile_data_editors.h b/editor/plugins/tiles/tile_data_editors.h index 99724760a7..3ac9eacb05 100644 --- a/editor/plugins/tiles/tile_data_editors.h +++ b/editor/plugins/tiles/tile_data_editors.h @@ -93,7 +93,7 @@ private: bool multiple_polygon_mode = false; bool use_undo_redo = true; - UndoRedo *editor_undo_redo; + UndoRedo *editor_undo_redo = nullptr; // UI int hovered_polygon_index = -1; @@ -113,20 +113,20 @@ private: Vector2 drag_last_pos; PackedVector2Array drag_old_polygon; - HBoxContainer *toolbar; + HBoxContainer *toolbar = nullptr; Ref<ButtonGroup> tools_button_group; - Button *button_create; - Button *button_edit; - Button *button_delete; - Button *button_pixel_snap; - MenuButton *button_advanced_menu; + Button *button_create = nullptr; + Button *button_edit = nullptr; + Button *button_delete = nullptr; + Button *button_pixel_snap = nullptr; + MenuButton *button_advanced_menu = nullptr; Vector<Point2> in_creation_polygon; - Panel *panel; - Control *base_control; - EditorZoomWidget *editor_zoom_widget; - Button *button_center_view; + Panel *panel = nullptr; + Control *base_control = nullptr; + EditorZoomWidget *editor_zoom_widget = nullptr; + Button *button_center_view = nullptr; Vector2 panning; Ref<Texture2D> background_texture; @@ -188,12 +188,12 @@ class TileDataDefaultEditor : public TileDataEditor { private: // Toolbar HBoxContainer *toolbar = memnew(HBoxContainer); - Button *picker_button; + Button *picker_button = nullptr; // UI Ref<Texture2D> tile_bool_checked; Ref<Texture2D> tile_bool_unchecked; - Label *label; + Label *label = nullptr; EditorProperty *property_editor = nullptr; @@ -214,7 +214,7 @@ private: protected: DummyObject *dummy_object = memnew(DummyObject); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; StringName type; String property; @@ -268,7 +268,7 @@ private: int occlusion_layer = -1; // UI - GenericTilePolygonEditor *polygon_editor; + GenericTilePolygonEditor *polygon_editor = nullptr; void _polygon_changed(PackedVector2Array p_polygon); @@ -279,7 +279,7 @@ private: virtual void _setup_undo_redo_action(TileSetAtlasSource *p_tile_set_atlas_source, Map<TileMapCell, Variant> p_previous_values, Variant p_new_value) override; protected: - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; virtual void _tile_set_changed() override; @@ -299,7 +299,7 @@ class TileDataCollisionEditor : public TileDataDefaultEditor { int physics_layer = -1; // UI - GenericTilePolygonEditor *polygon_editor; + GenericTilePolygonEditor *polygon_editor = nullptr; DummyObject *dummy_object = memnew(DummyObject); Map<StringName, EditorProperty *> property_editors; @@ -314,7 +314,7 @@ class TileDataCollisionEditor : public TileDataDefaultEditor { virtual void _setup_undo_redo_action(TileSetAtlasSource *p_tile_set_atlas_source, Map<TileMapCell, Variant> p_previous_values, Variant p_new_value) override; protected: - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; virtual void _tile_set_changed() override; @@ -335,7 +335,7 @@ class TileDataTerrainsEditor : public TileDataEditor { private: // Toolbar HBoxContainer *toolbar = memnew(HBoxContainer); - Button *picker_button; + Button *picker_button = nullptr; // Painting state. enum DragType { @@ -352,7 +352,7 @@ private: Variant drag_painted_value; // UI - Label *label; + Label *label = nullptr; DummyObject *dummy_object = memnew(DummyObject); EditorPropertyEnum *terrain_set_property_editor = nullptr; EditorPropertyEnum *terrain_property_editor = nullptr; @@ -366,7 +366,7 @@ protected: void _notification(int p_what); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; public: virtual Control *get_toolbar() override { return toolbar; }; @@ -388,7 +388,7 @@ private: PackedVector2Array navigation_polygon; // UI - GenericTilePolygonEditor *polygon_editor; + GenericTilePolygonEditor *polygon_editor = nullptr; void _polygon_changed(PackedVector2Array p_polygon); @@ -399,7 +399,7 @@ private: virtual void _setup_undo_redo_action(TileSetAtlasSource *p_tile_set_atlas_source, Map<TileMapCell, Variant> p_previous_values, Variant p_new_value) override; protected: - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; virtual void _tile_set_changed() override; diff --git a/editor/plugins/tiles/tile_map_editor.h b/editor/plugins/tiles/tile_map_editor.h index d09061015f..3a0293f48f 100644 --- a/editor/plugins/tiles/tile_map_editor.h +++ b/editor/plugins/tiles/tile_map_editor.h @@ -51,8 +51,8 @@ class UndoRedo; class TileMapEditorPlugin : public Object { public: struct TabData { - Control *toolbar; - Control *panel; + Control *toolbar = nullptr; + Control *panel = nullptr; }; virtual Vector<TabData> get_tabs() const { @@ -69,33 +69,33 @@ class TileMapEditorTilesPlugin : public TileMapEditorPlugin { GDCLASS(TileMapEditorTilesPlugin, TileMapEditorPlugin); private: - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; ObjectID tile_map_id; int tile_map_layer = -1; virtual void edit(ObjectID p_tile_map_id, int p_tile_map_layer) override; ///// Toolbar ///// - HBoxContainer *toolbar; + HBoxContainer *toolbar = nullptr; Ref<ButtonGroup> tool_buttons_group; - Button *select_tool_button; - Button *paint_tool_button; - Button *line_tool_button; - Button *rect_tool_button; - Button *bucket_tool_button; + Button *select_tool_button = nullptr; + Button *paint_tool_button = nullptr; + Button *line_tool_button = nullptr; + Button *rect_tool_button = nullptr; + Button *bucket_tool_button = nullptr; - HBoxContainer *tools_settings; + HBoxContainer *tools_settings = nullptr; - VSeparator *tools_settings_vsep; - Button *picker_button; - Button *erase_button; + VSeparator *tools_settings_vsep = nullptr; + Button *picker_button = nullptr; + Button *erase_button = nullptr; - VSeparator *tools_settings_vsep_2; - CheckBox *bucket_contiguous_checkbox; - CheckBox *random_tile_checkbox; + VSeparator *tools_settings_vsep_2 = nullptr; + CheckBox *bucket_contiguous_checkbox = nullptr; + CheckBox *random_tile_checkbox = nullptr; float scattering = 0.0; - Label *scatter_label; - SpinBox *scatter_spinbox; + Label *scatter_label = nullptr; + SpinBox *scatter_spinbox = nullptr; void _on_random_tile_checkbox_toggled(bool p_pressed); void _on_scattering_spinbox_changed(double p_value); @@ -148,12 +148,12 @@ private: void _tab_changed(); ///// Bottom panel tiles //// - VBoxContainer *tiles_bottom_panel; - Label *missing_source_label; - Label *invalid_source_label; + VBoxContainer *tiles_bottom_panel = nullptr; + Label *missing_source_label = nullptr; + Label *invalid_source_label = nullptr; - ItemList *sources_list; - MenuButton *source_sort_button; + ItemList *sources_list = nullptr; + MenuButton *source_sort_button = nullptr; Ref<Texture2D> missing_atlas_texture_icon; void _update_tile_set_sources_list(); @@ -162,18 +162,18 @@ private: // Atlas sources. TileMapCell hovered_tile; - TileAtlasView *tile_atlas_view; - HSplitContainer *atlas_sources_split_container; + TileAtlasView *tile_atlas_view = nullptr; + HSplitContainer *atlas_sources_split_container = nullptr; bool tile_set_dragging_selection = false; Vector2i tile_set_drag_start_mouse_pos; - Control *tile_atlas_control; + Control *tile_atlas_control = nullptr; void _tile_atlas_control_mouse_exited(); void _tile_atlas_control_gui_input(const Ref<InputEvent> &p_event); void _tile_atlas_control_draw(); - Control *alternative_tiles_control; + Control *alternative_tiles_control = nullptr; void _tile_alternatives_control_draw(); void _tile_alternatives_control_mouse_exited(); void _tile_alternatives_control_gui_input(const Ref<InputEvent> &p_event); @@ -182,7 +182,7 @@ private: void _set_source_sort(int p_sort); // Scenes collection sources. - ItemList *scene_tiles_list; + ItemList *scene_tiles_list = nullptr; void _update_scenes_collection_view(); void _scene_thumbnail_done(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, Variant p_ud); @@ -190,9 +190,9 @@ private: void _scenes_list_nothing_selected(); ///// Bottom panel patterns //// - VBoxContainer *patterns_bottom_panel; - ItemList *patterns_item_list; - Label *patterns_help_label; + VBoxContainer *patterns_bottom_panel = nullptr; + ItemList *patterns_item_list = nullptr; + Label *patterns_help_label = nullptr; void _patterns_item_list_gui_input(const Ref<InputEvent> &p_event); void _pattern_preview_done(Ref<TileMapPattern> p_pattern, Ref<Texture2D> p_texture); bool select_last_pattern = false; @@ -220,32 +220,32 @@ class TileMapEditorTerrainsPlugin : public TileMapEditorPlugin { GDCLASS(TileMapEditorTerrainsPlugin, TileMapEditorPlugin); private: - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; ObjectID tile_map_id; int tile_map_layer = -1; virtual void edit(ObjectID p_tile_map_id, int p_tile_map_layer) override; // Toolbar. - HBoxContainer *toolbar; + HBoxContainer *toolbar = nullptr; Ref<ButtonGroup> tool_buttons_group; - Button *paint_tool_button; - Button *line_tool_button; - Button *rect_tool_button; - Button *bucket_tool_button; + Button *paint_tool_button = nullptr; + Button *line_tool_button = nullptr; + Button *rect_tool_button = nullptr; + Button *bucket_tool_button = nullptr; - HBoxContainer *tools_settings; + HBoxContainer *tools_settings = nullptr; - VSeparator *tools_settings_vsep; - Button *picker_button; - Button *erase_button; + VSeparator *tools_settings_vsep = nullptr; + Button *picker_button = nullptr; + Button *erase_button = nullptr; - VSeparator *tools_settings_vsep_2; - CheckBox *bucket_contiguous_checkbox; + VSeparator *tools_settings_vsep_2 = nullptr; + CheckBox *bucket_contiguous_checkbox = nullptr; void _update_toolbar(); // Main vbox. - VBoxContainer *main_vbox_container; + VBoxContainer *main_vbox_container = nullptr; // TileMap editing. bool has_mouse = false; @@ -278,8 +278,8 @@ private: void _update_selection(); // Bottom panel. - Tree *terrains_tree; - ItemList *terrains_tile_list; + Tree *terrains_tree = nullptr; + ItemList *terrains_tile_list = nullptr; // Cache. LocalVector<LocalVector<Set<TileSet::TerrainsPattern>>> per_terrain_terrains_patterns; @@ -306,7 +306,7 @@ class TileMapEditor : public VBoxContainer { GDCLASS(TileMapEditor, VBoxContainer); private: - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; bool tileset_changed_needs_update = false; ObjectID tile_map_id; int tile_map_layer = -1; @@ -315,24 +315,24 @@ private: Vector<TileMapEditorPlugin *> tile_map_editor_plugins; // Toolbar. - HBoxContainer *tile_map_toolbar; + HBoxContainer *tile_map_toolbar = nullptr; - PopupMenu *layers_selection_popup; - Button *layers_selection_button; - Button *toogle_highlight_selected_layer_button; + PopupMenu *layers_selection_popup = nullptr; + Button *layers_selection_button = nullptr; + Button *toogle_highlight_selected_layer_button = nullptr; void _layers_selection_button_draw(); void _layers_selection_button_pressed(); void _layers_selection_id_pressed(int p_id); - Button *toggle_grid_button; + Button *toggle_grid_button = nullptr; void _on_grid_toggled(bool p_pressed); - MenuButton *advanced_menu_button; + MenuButton *advanced_menu_button = nullptr; void _advanced_menu_button_id_pressed(int p_id); // Bottom panel. - Label *missing_tileset_label; - TabBar *tabs_bar; + Label *missing_tileset_label = nullptr; + TabBar *tabs_bar = nullptr; LocalVector<TileMapEditorPlugin::TabData> tabs_data; LocalVector<TileMapEditorPlugin *> tabs_plugins; void _update_bottom_panel(); diff --git a/editor/plugins/tiles/tile_proxies_manager_dialog.h b/editor/plugins/tiles/tile_proxies_manager_dialog.h index 3f1461391e..00866544be 100644 --- a/editor/plugins/tiles/tile_proxies_manager_dialog.h +++ b/editor/plugins/tiles/tile_proxies_manager_dialog.h @@ -43,24 +43,24 @@ private: int commited_actions_count = 0; Ref<TileSet> tile_set; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; TileMapCell from; TileMapCell to; // GUI - ItemList *source_level_list; - ItemList *coords_level_list; - ItemList *alternative_level_list; + ItemList *source_level_list = nullptr; + ItemList *coords_level_list = nullptr; + ItemList *alternative_level_list = nullptr; - EditorPropertyInteger *source_from_property_editor; - EditorPropertyVector2i *coords_from_property_editor; - EditorPropertyInteger *alternative_from_property_editor; - EditorPropertyInteger *source_to_property_editor; - EditorPropertyVector2i *coords_to_property_editor; - EditorPropertyInteger *alternative_to_property_editor; + EditorPropertyInteger *source_from_property_editor = nullptr; + EditorPropertyVector2i *coords_from_property_editor = nullptr; + EditorPropertyInteger *alternative_from_property_editor = nullptr; + EditorPropertyInteger *source_to_property_editor = nullptr; + EditorPropertyVector2i *coords_to_property_editor = nullptr; + EditorPropertyInteger *alternative_to_property_editor = nullptr; - PopupMenu *popup_menu; + PopupMenu *popup_menu = nullptr; void _right_clicked(int p_item, Vector2 p_local_mouse_pos, Object *p_item_list); void _menu_id_pressed(int p_id); void _delete_selected_bindings(); diff --git a/editor/plugins/tiles/tile_set_atlas_source_editor.h b/editor/plugins/tiles/tile_set_atlas_source_editor.h index 4a90b821f8..b26b7edbfa 100644 --- a/editor/plugins/tiles/tile_set_atlas_source_editor.h +++ b/editor/plugins/tiles/tile_set_atlas_source_editor.h @@ -85,7 +85,7 @@ public: GDCLASS(AtlasTileProxyObject, Object); private: - TileSetAtlasSourceEditor *tiles_set_atlas_source_editor; + TileSetAtlasSourceEditor *tiles_set_atlas_source_editor = nullptr; TileSetAtlasSource *tile_set_atlas_source = nullptr; Set<TileSelection> tiles = Set<TileSelection>(); @@ -114,16 +114,16 @@ private: TileSetAtlasSource *tile_set_atlas_source = nullptr; int tile_set_atlas_source_id = TileSet::INVALID_SOURCE; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; bool tile_set_changed_needs_update = false; // -- Properties painting -- - VBoxContainer *tile_data_painting_editor_container; - Label *tile_data_editors_label; - Button *tile_data_editor_dropdown_button; - Popup *tile_data_editors_popup; - Tree *tile_data_editors_tree; + VBoxContainer *tile_data_painting_editor_container = nullptr; + Label *tile_data_editors_label = nullptr; + Button *tile_data_editor_dropdown_button = nullptr; + Popup *tile_data_editors_popup = nullptr; + Tree *tile_data_editors_tree = nullptr; void _tile_data_editor_dropdown_button_draw(); void _tile_data_editor_dropdown_button_pressed(); @@ -135,21 +135,21 @@ private: void _tile_data_editors_tree_selected(); // -- Inspector -- - AtlasTileProxyObject *tile_proxy_object; - Label *tile_inspector_label; - EditorInspector *tile_inspector; - Label *tile_inspector_no_tile_selected_label; + AtlasTileProxyObject *tile_proxy_object = nullptr; + Label *tile_inspector_label = nullptr; + EditorInspector *tile_inspector = nullptr; + Label *tile_inspector_no_tile_selected_label = nullptr; String selected_property; void _inspector_property_selected(String p_property); - TileSetAtlasSourceProxyObject *atlas_source_proxy_object; - Label *atlas_source_inspector_label; - EditorInspector *atlas_source_inspector; + TileSetAtlasSourceProxyObject *atlas_source_proxy_object = nullptr; + Label *atlas_source_inspector_label = nullptr; + EditorInspector *atlas_source_inspector = nullptr; // -- Atlas view -- - HBoxContainer *toolbox; - Label *tile_atlas_view_missing_source_label; - TileAtlasView *tile_atlas_view; + HBoxContainer *toolbox = nullptr; + Label *tile_atlas_view_missing_source_label = nullptr; + TileAtlasView *tile_atlas_view = nullptr; // Dragging enum DragType { @@ -202,17 +202,17 @@ private: // Tool buttons. Ref<ButtonGroup> tools_button_group; - Button *tool_setup_atlas_source_button; - Button *tool_select_button; - Button *tool_paint_button; - Label *tool_tile_id_label; + Button *tool_setup_atlas_source_button = nullptr; + Button *tool_select_button = nullptr; + Button *tool_paint_button = nullptr; + Label *tool_tile_id_label = nullptr; // Tool settings. - HBoxContainer *tool_settings; - VSeparator *tool_settings_vsep; - HBoxContainer *tool_settings_tile_data_toolbar_container; - Button *tools_settings_erase_button; - MenuButton *tool_advanced_menu_buttom; + HBoxContainer *tool_settings = nullptr; + VSeparator *tool_settings_vsep = nullptr; + HBoxContainer *tool_settings_tile_data_toolbar_container = nullptr; + Button *tools_settings_erase_button = nullptr; + MenuButton *tool_advanced_menu_buttom = nullptr; // Selection. Set<TileSelection> selection; @@ -223,12 +223,12 @@ private: // A control on the tile atlas to draw and handle input events. Vector2i hovered_base_tile_coords = TileSetSource::INVALID_ATLAS_COORDS; - PopupMenu *base_tile_popup_menu; - PopupMenu *empty_base_tile_popup_menu; + PopupMenu *base_tile_popup_menu = nullptr; + PopupMenu *empty_base_tile_popup_menu = nullptr; Ref<Texture2D> resize_handle; Ref<Texture2D> resize_handle_disabled; - Control *tile_atlas_control; - Control *tile_atlas_control_unscaled; + Control *tile_atlas_control = nullptr; + Control *tile_atlas_control_unscaled = nullptr; void _tile_atlas_control_draw(); void _tile_atlas_control_unscaled_draw(); void _tile_atlas_control_mouse_exited(); @@ -238,9 +238,9 @@ private: // A control over the alternative tiles. Vector3i hovered_alternative_tile_coords = Vector3i(TileSetSource::INVALID_ATLAS_COORDS.x, TileSetSource::INVALID_ATLAS_COORDS.y, TileSetSource::INVALID_TILE_ALTERNATIVE); - PopupMenu *alternative_tile_popup_menu; - Control *alternative_tiles_control; - Control *alternative_tiles_control_unscaled; + PopupMenu *alternative_tile_popup_menu = nullptr; + Control *alternative_tiles_control = nullptr; + Control *alternative_tiles_control_unscaled = nullptr; void _tile_alternatives_control_draw(); void _tile_alternatives_control_unscaled_draw(); void _tile_alternatives_control_mouse_exited(); @@ -264,7 +264,7 @@ private: // -- Misc -- void _auto_create_tiles(); void _auto_remove_tiles(); - AcceptDialog *confirm_auto_create_tiles; + AcceptDialog *confirm_auto_create_tiles = nullptr; void _tile_set_changed(); void _tile_proxy_object_changed(String p_what); @@ -293,7 +293,7 @@ class EditorPropertyTilePolygon : public EditorProperty { void _add_focusable_children(Node *p_node); - GenericTilePolygonEditor *generic_tile_polygon_editor; + GenericTilePolygonEditor *generic_tile_polygon_editor = nullptr; void _polygons_changed(); public: diff --git a/editor/plugins/tiles/tile_set_editor.h b/editor/plugins/tiles/tile_set_editor.h index b79b37cf2e..e633de37b0 100644 --- a/editor/plugins/tiles/tile_set_editor.h +++ b/editor/plugins/tiles/tile_set_editor.h @@ -47,18 +47,18 @@ class TileSetEditor : public VBoxContainer { private: Ref<TileSet> tile_set; bool tile_set_changed_needs_update = false; - HSplitContainer *split_container; + HSplitContainer *split_container = nullptr; // TabBar. - HBoxContainer *tile_set_toolbar; - TabBar *tabs_bar; + HBoxContainer *tile_set_toolbar = nullptr; + TabBar *tabs_bar = nullptr; // Tiles. - Label *no_source_selected_label; - TileSetAtlasSourceEditor *tile_set_atlas_source_editor; - TileSetScenesCollectionSourceEditor *tile_set_scenes_collection_source_editor; + Label *no_source_selected_label = nullptr; + TileSetAtlasSourceEditor *tile_set_atlas_source_editor = nullptr; + TileSetScenesCollectionSourceEditor *tile_set_scenes_collection_source_editor = nullptr; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; void _drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from); bool _can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const; @@ -66,11 +66,11 @@ private: void _update_sources_list(int force_selected_id = -1); // Sources management. - Button *sources_delete_button; - MenuButton *sources_add_button; - MenuButton *source_sort_button; - MenuButton *sources_advanced_menu_button; - ItemList *sources_list; + Button *sources_delete_button = nullptr; + MenuButton *sources_add_button = nullptr; + MenuButton *source_sort_button = nullptr; + MenuButton *sources_advanced_menu_button = nullptr; + ItemList *sources_list = nullptr; Ref<Texture2D> missing_texture_texture; void _source_selected(int p_source_index); void _source_delete_pressed(); @@ -78,12 +78,12 @@ private: void _sources_advanced_menu_id_pressed(int p_id_pressed); void _set_source_sort(int p_sort); - AtlasMergingDialog *atlas_merging_dialog; - TileProxiesManagerDialog *tile_proxies_manager_dialog; + AtlasMergingDialog *atlas_merging_dialog = nullptr; + TileProxiesManagerDialog *tile_proxies_manager_dialog = nullptr; // Patterns. - ItemList *patterns_item_list; - Label *patterns_help_label; + ItemList *patterns_item_list = nullptr; + Label *patterns_help_label = nullptr; void _patterns_item_list_gui_input(const Ref<InputEvent> &p_event); void _pattern_preview_done(Ref<TileMapPattern> p_pattern, Ref<Texture2D> p_texture); bool select_last_pattern = false; diff --git a/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h b/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h index 8904e8524a..657bfca032 100644 --- a/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h +++ b/editor/plugins/tiles/tile_set_scenes_collection_source_editor.h @@ -70,7 +70,7 @@ private: GDCLASS(SceneTileProxyObject, Object); private: - TileSetScenesCollectionSourceEditor *tile_set_scenes_collection_source_editor; + TileSetScenesCollectionSourceEditor *tile_set_scenes_collection_source_editor = nullptr; TileSetScenesCollectionSource *tile_set_scenes_collection_source = nullptr; int source_id; @@ -97,23 +97,23 @@ private: TileSetScenesCollectionSource *tile_set_scenes_collection_source = nullptr; int tile_set_source_id = -1; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; bool tile_set_scenes_collection_source_changed_needs_update = false; // Source inspector. - TileSetScenesCollectionProxyObject *scenes_collection_source_proxy_object; - Label *scenes_collection_source_inspector_label; - EditorInspector *scenes_collection_source_inspector; + TileSetScenesCollectionProxyObject *scenes_collection_source_proxy_object = nullptr; + Label *scenes_collection_source_inspector_label = nullptr; + EditorInspector *scenes_collection_source_inspector = nullptr; // Tile inspector. - SceneTileProxyObject *tile_proxy_object; - Label *tile_inspector_label; - EditorInspector *tile_inspector; + SceneTileProxyObject *tile_proxy_object = nullptr; + Label *tile_inspector_label = nullptr; + EditorInspector *tile_inspector = nullptr; - ItemList *scene_tiles_list; - Button *scene_tile_add_button; - Button *scene_tile_delete_button; + ItemList *scene_tiles_list = nullptr; + Button *scene_tile_add_button = nullptr; + Button *scene_tile_delete_button = nullptr; void _tile_set_scenes_collection_source_changed(); void _scenes_collection_source_proxy_object_changed(String p_what); diff --git a/editor/plugins/tiles/tiles_editor_plugin.cpp b/editor/plugins/tiles/tiles_editor_plugin.cpp index 4aabe0e6b7..543304346e 100644 --- a/editor/plugins/tiles/tiles_editor_plugin.cpp +++ b/editor/plugins/tiles/tiles_editor_plugin.cpp @@ -56,7 +56,7 @@ void TilesEditorPlugin::_pattern_preview_done() { } void TilesEditorPlugin::_thread_func(void *ud) { - TilesEditorPlugin *te = (TilesEditorPlugin *)ud; + TilesEditorPlugin *te = static_cast<TilesEditorPlugin *>(ud); te->_thread(); } diff --git a/editor/plugins/tiles/tiles_editor_plugin.h b/editor/plugins/tiles/tiles_editor_plugin.h index eeff4da4e9..a22e782b34 100644 --- a/editor/plugins/tiles/tiles_editor_plugin.h +++ b/editor/plugins/tiles/tiles_editor_plugin.h @@ -57,11 +57,11 @@ private: ObjectID tile_map_id; Ref<TileSet> tile_set; - Button *tilemap_editor_button; - TileMapEditor *tilemap_editor; + Button *tilemap_editor_button = nullptr; + TileMapEditor *tilemap_editor = nullptr; - Button *tileset_editor_button; - TileSetEditor *tileset_editor; + Button *tileset_editor_button = nullptr; + TileSetEditor *tileset_editor = nullptr; void _update_editors(); diff --git a/editor/plugins/version_control_editor_plugin.h b/editor/plugins/version_control_editor_plugin.h index 956c5a334f..39a56de772 100644 --- a/editor/plugins/version_control_editor_plugin.h +++ b/editor/plugins/version_control_editor_plugin.h @@ -57,48 +57,48 @@ private: int staged_files_count; List<StringName> available_addons; - PopupMenu *version_control_actions; - ConfirmationDialog *metadata_dialog; - OptionButton *metadata_selection; - AcceptDialog *set_up_dialog; - VBoxContainer *set_up_vbc; - HBoxContainer *set_up_hbc; - Label *set_up_vcs_label; - OptionButton *set_up_choice; - PanelContainer *set_up_init_settings; - Button *set_up_init_button; - RichTextLabel *set_up_vcs_status; - Button *set_up_ok_button; + PopupMenu *version_control_actions = nullptr; + ConfirmationDialog *metadata_dialog = nullptr; + OptionButton *metadata_selection = nullptr; + AcceptDialog *set_up_dialog = nullptr; + VBoxContainer *set_up_vbc = nullptr; + HBoxContainer *set_up_hbc = nullptr; + Label *set_up_vcs_label = nullptr; + OptionButton *set_up_choice = nullptr; + PanelContainer *set_up_init_settings = nullptr; + Button *set_up_init_button = nullptr; + RichTextLabel *set_up_vcs_status = nullptr; + Button *set_up_ok_button = nullptr; HashMap<ChangeType, String> change_type_to_strings; HashMap<ChangeType, Color> change_type_to_color; - VBoxContainer *version_commit_dock; - VBoxContainer *commit_box_vbc; - HSplitContainer *stage_tools; - Tree *stage_files; - TreeItem *new_files; - TreeItem *modified_files; - TreeItem *renamed_files; - TreeItem *deleted_files; - TreeItem *typechange_files; - Label *staging_area_label; - HSplitContainer *stage_buttons; - Button *stage_all_button; - Button *stage_selected_button; - Button *refresh_button; - TextEdit *commit_message; - Button *commit_button; - Label *commit_status; - - PanelContainer *version_control_dock; - Button *version_control_dock_button; - VBoxContainer *diff_vbc; - HBoxContainer *diff_hbc; - Button *diff_refresh_button; - Label *diff_file_name; - Label *diff_heading; - RichTextLabel *diff; + VBoxContainer *version_commit_dock = nullptr; + VBoxContainer *commit_box_vbc = nullptr; + HSplitContainer *stage_tools = nullptr; + Tree *stage_files = nullptr; + TreeItem *new_files = nullptr; + TreeItem *modified_files = nullptr; + TreeItem *renamed_files = nullptr; + TreeItem *deleted_files = nullptr; + TreeItem *typechange_files = nullptr; + Label *staging_area_label = nullptr; + HSplitContainer *stage_buttons = nullptr; + Button *stage_all_button = nullptr; + Button *stage_selected_button = nullptr; + Button *refresh_button = nullptr; + TextEdit *commit_message = nullptr; + Button *commit_button = nullptr; + Label *commit_status = nullptr; + + PanelContainer *version_control_dock = nullptr; + Button *version_control_dock_button = nullptr; + VBoxContainer *diff_vbc = nullptr; + HBoxContainer *diff_hbc = nullptr; + Button *diff_refresh_button = nullptr; + Label *diff_file_name = nullptr; + Label *diff_heading = nullptr; + RichTextLabel *diff = nullptr; void _populate_available_vcs_names(); void _create_vcs_metadata_files(); diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp index 6b53ce0660..1e7648bc43 100644 --- a/editor/plugins/visual_shader_editor_plugin.cpp +++ b/editor/plugins/visual_shader_editor_plugin.cpp @@ -2061,10 +2061,8 @@ void VisualShaderEditor::_set_node_size(int p_type, int p_node, const Vector2 &p if (!expression_node.is_null() && text_box) { Size2 box_size = size; - if (gn != nullptr) { - if (box_size.x < 150 * EDSCALE || box_size.y < 0) { - box_size.x = gn->get_size().x; - } + if (box_size.x < 150 * EDSCALE || box_size.y < 0) { + box_size.x = gn->get_size().x; } box_size.x -= text_box->get_offset(SIDE_LEFT); box_size.x -= 28 * EDSCALE; diff --git a/editor/plugins/voxel_gi_editor_plugin.h b/editor/plugins/voxel_gi_editor_plugin.h index 67bd1d5105..621e98beef 100644 --- a/editor/plugins/voxel_gi_editor_plugin.h +++ b/editor/plugins/voxel_gi_editor_plugin.h @@ -41,12 +41,12 @@ struct EditorProgress; class VoxelGIEditorPlugin : public EditorPlugin { GDCLASS(VoxelGIEditorPlugin, EditorPlugin); - VoxelGI *voxel_gi; + VoxelGI *voxel_gi = nullptr; - HBoxContainer *bake_hb; - Button *bake; + HBoxContainer *bake_hb = nullptr; + Button *bake = nullptr; - EditorFileDialog *probe_file; + EditorFileDialog *probe_file = nullptr; static EditorProgress *tmp_progress; static void bake_func_begin(int p_steps); diff --git a/editor/pot_generator.cpp b/editor/pot_generator.cpp index f6839bae6b..0835d0212f 100644 --- a/editor/pot_generator.cpp +++ b/editor/pot_generator.cpp @@ -46,8 +46,8 @@ void POTGenerator::_print_all_translation_strings() { print_line("msgid: " + E.key()); print_line("context: " + v_md[i].ctx); print_line("msgid_plural: " + v_md[i].plural); - for (Set<String>::Element *E = v_md[i].locations.front(); E; E = E->next()) { - print_line("location: " + E->get()); + for (Set<String>::Element *F = v_md[i].locations.front(); F; F = F->next()) { + print_line("location: " + F->get()); } } } @@ -93,7 +93,7 @@ void POTGenerator::generate_pot(const String &p_file) { void POTGenerator::_write_to_pot(const String &p_file) { Error err; - FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_file, FileAccess::WRITE, &err); if (err != OK) { ERR_PRINT("Failed to open " + p_file); return; @@ -155,11 +155,9 @@ void POTGenerator::_write_to_pot(const String &p_file) { } } } - - file->close(); } -void POTGenerator::_write_msgid(FileAccess *r_file, const String &p_id, bool p_plural) { +void POTGenerator::_write_msgid(Ref<FileAccess> r_file, const String &p_id, bool p_plural) { // Split \\n and \n. Vector<String> temp = p_id.split("\\n"); Vector<String> msg_lines; diff --git a/editor/pot_generator.h b/editor/pot_generator.h index 2b42c681e5..e7a5f90cee 100644 --- a/editor/pot_generator.h +++ b/editor/pot_generator.h @@ -49,7 +49,7 @@ class POTGenerator { OrderedHashMap<String, Vector<MsgidData>> all_translation_strings; void _write_to_pot(const String &p_file); - void _write_msgid(FileAccess *r_file, const String &p_id, bool p_plural); + void _write_msgid(Ref<FileAccess> r_file, const String &p_id, bool p_plural); void _add_new_msgid(const String &p_msgid, const String &p_context, const String &p_plural, const String &p_location); #ifdef DEBUG_POT diff --git a/editor/progress_dialog.h b/editor/progress_dialog.h index 880e6bc9d4..f395750165 100644 --- a/editor/progress_dialog.h +++ b/editor/progress_dialog.h @@ -74,11 +74,11 @@ class ProgressDialog : public PopupPanel { ProgressBar *progress = nullptr; Label *state = nullptr; }; - HBoxContainer *cancel_hb; - Button *cancel; + HBoxContainer *cancel_hb = nullptr; + Button *cancel = nullptr; Map<String, Task> tasks; - VBoxContainer *main; + VBoxContainer *main = nullptr; uint64_t last_progress_tick; static ProgressDialog *singleton; diff --git a/editor/project_export.h b/editor/project_export.h index 057fd31168..4d1719d6eb 100644 --- a/editor/project_export.h +++ b/editor/project_export.h @@ -58,46 +58,46 @@ class ProjectExportDialog : public ConfirmationDialog { GDCLASS(ProjectExportDialog, ConfirmationDialog); private: - TabContainer *sections; + TabContainer *sections = nullptr; - MenuButton *add_preset; - Button *duplicate_preset; - Button *delete_preset; - ItemList *presets; + MenuButton *add_preset = nullptr; + Button *duplicate_preset = nullptr; + Button *delete_preset = nullptr; + ItemList *presets = nullptr; - LineEdit *name; - EditorPropertyPath *export_path; - EditorInspector *parameters; - CheckButton *runnable; + LineEdit *name = nullptr; + EditorPropertyPath *export_path = nullptr; + EditorInspector *parameters = nullptr; + CheckButton *runnable = nullptr; - Button *button_export; + Button *button_export = nullptr; bool updating = false; - AcceptDialog *error_dialog; - ConfirmationDialog *delete_confirm; + AcceptDialog *error_dialog = nullptr; + ConfirmationDialog *delete_confirm = nullptr; - OptionButton *export_filter; - LineEdit *include_filters; - LineEdit *exclude_filters; - Tree *include_files; + OptionButton *export_filter = nullptr; + LineEdit *include_filters = nullptr; + LineEdit *exclude_filters = nullptr; + Tree *include_files = nullptr; - Label *include_label; - MarginContainer *include_margin; + Label *include_label = nullptr; + MarginContainer *include_margin = nullptr; - Button *export_button; - Button *export_all_button; - AcceptDialog *export_all_dialog; + Button *export_button = nullptr; + Button *export_all_button = nullptr; + AcceptDialog *export_all_dialog = nullptr; - LineEdit *custom_features; - RichTextLabel *custom_feature_display; + LineEdit *custom_features = nullptr; + RichTextLabel *custom_feature_display = nullptr; - OptionButton *script_mode; - LineEdit *script_key; - Label *script_key_error; + OptionButton *script_mode = nullptr; + LineEdit *script_key = nullptr; + Label *script_key_error = nullptr; - Label *export_error; - Label *export_warning; - HBoxContainer *export_templates_error; + Label *export_error = nullptr; + Label *export_warning = nullptr; + HBoxContainer *export_templates_error = nullptr; String default_filename; @@ -127,15 +127,15 @@ private: bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const; void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from); - EditorFileDialog *export_pck_zip; - EditorFileDialog *export_project; - CheckBox *export_debug; - CheckBox *export_pck_zip_debug; + EditorFileDialog *export_pck_zip = nullptr; + EditorFileDialog *export_project = nullptr; + CheckBox *export_debug = nullptr; + CheckBox *export_pck_zip_debug = nullptr; - CheckButton *enc_pck; - CheckButton *enc_directory; - LineEdit *enc_in_filters; - LineEdit *enc_ex_filters; + CheckButton *enc_pck = nullptr; + CheckButton *enc_directory = nullptr; + LineEdit *enc_in_filters = nullptr; + LineEdit *enc_ex_filters = nullptr; void _open_export_template_manager(); diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp index cd95f97286..08b968edb6 100644 --- a/editor/project_manager.cpp +++ b/editor/project_manager.cpp @@ -147,7 +147,7 @@ private: } String _test_path() { - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String valid_path, valid_install_path; if (d->change_dir(project_path->get_text()) == OK) { valid_path = project_path->get_text(); @@ -186,8 +186,7 @@ private: if (mode == MODE_IMPORT || mode == MODE_RENAME) { if (!valid_path.is_empty() && !d->file_exists("project.godot")) { if (valid_path.ends_with(".zip")) { - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); unzFile pkg = unzOpen2(valid_path.utf8().get_data(), &io); if (!pkg) { @@ -202,6 +201,9 @@ private: unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } if (String::utf8(fname).ends_with("project.godot")) { break; @@ -380,7 +382,7 @@ private: return; } - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (d->change_dir(project_path->get_text()) == OK) { if (!d->dir_exists(project_name_no_edges)) { if (d->make_dir(project_name_no_edges) == OK) { @@ -497,8 +499,7 @@ private: zip_path = project_path->get_text(); } - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io); if (!pkg) { @@ -534,6 +535,9 @@ private: unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String path = String::utf8(fname); @@ -543,7 +547,7 @@ private: path = path.substr(0, path.length() - 1); String rel_path = path.substr(zip_root.length()); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); da->make_dir(dir.plus_file(rel_path)); } else { Vector<uint8_t> data; @@ -552,14 +556,15 @@ private: //read unzOpenCurrentFile(pkg); - unzReadCurrentFile(pkg, data.ptrw(), data.size()); + ret = unzReadCurrentFile(pkg, data.ptrw(), data.size()); + if (ret != UNZ_OK) { + break; + } unzCloseCurrentFile(pkg); - FileAccess *f = FileAccess::open(dir.plus_file(rel_path), FileAccess::WRITE); - - if (f) { + Ref<FileAccess> f = FileAccess::open(dir.plus_file(rel_path), FileAccess::WRITE); + if (f.is_valid()) { f->store_buffer(data.ptr(), data.size()); - memdelete(f); } else { failed_files.push_back(rel_path); } @@ -606,7 +611,7 @@ private: void _remove_created_folder() { if (!created_folder_path.is_empty()) { - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); d->remove(created_folder_path); create_dir->set_disabled(false); @@ -710,7 +715,7 @@ public: project_path->set_text(fav_dir); fdialog->set_current_dir(fav_dir); } else { - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); project_path->set_text(d->get_current_dir()); fdialog->set_current_dir(d->get_current_dir()); } @@ -1116,7 +1121,7 @@ struct ProjectListComparator { }; ProjectList::ProjectList() { - _order_option = FilterOption::NAME; + _order_option = FilterOption::EDIT_DATE; _scroll_children = memnew(VBoxContainer); _scroll_children->set_h_size_flags(Control::SIZE_EXPAND_FILL); add_child(_scroll_children); @@ -1903,7 +1908,7 @@ void ProjectManager::_notification(int p_what) { } break; case NOTIFICATION_VISIBILITY_CHANGED: { - set_process_unhandled_key_input(is_visible_in_tree()); + set_process_shortcut_input(is_visible_in_tree()); } break; case NOTIFICATION_WM_CLOSE_REQUEST: { @@ -1962,7 +1967,7 @@ void ProjectManager::_update_project_buttons() { erase_missing_btn->set_disabled(!_project_list->is_any_project_missing()); } -void ProjectManager::unhandled_key_input(const Ref<InputEvent> &p_ev) { +void ProjectManager::shortcut_input(const Ref<InputEvent> &p_ev) { ERR_FAIL_COND(p_ev.is_null()); Ref<InputEventKey> k = p_ev; @@ -2271,7 +2276,7 @@ void ProjectManager::_run_project() { } void ProjectManager::_scan_dir(const String &path, List<String> *r_projects) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error error = da->change_dir(path); ERR_FAIL_COND_MSG(error != OK, "Could not scan directory at: " + path); da->list_dir_begin(); @@ -2393,14 +2398,14 @@ void ProjectManager::_install_project(const String &p_zip_path, const String &p_ npdialog->show_dialog(); } -void ProjectManager::_files_dropped(PackedStringArray p_files, int p_screen) { +void ProjectManager::_files_dropped(PackedStringArray p_files) { if (p_files.size() == 1 && p_files[0].ends_with(".zip")) { const String file = p_files[0].get_file(); _install_project(p_files[0], file.substr(0, file.length() - 4).capitalize()); return; } Set<String> folders_set; - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); for (int i = 0; i < p_files.size(); i++) { String file = p_files[i]; folders_set.insert(da->dir_exists(file) ? file : file.get_base_dir()); @@ -2413,7 +2418,7 @@ void ProjectManager::_files_dropped(PackedStringArray p_files, int p_screen) { bool confirm = true; if (folders.size() == 1) { - DirAccessRef dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (dir->change_dir(folders[0]) == OK) { dir->list_dir_begin(); String file = dir->get_next(); @@ -2601,9 +2606,9 @@ ProjectManager::ProjectManager() { hb->add_child(filter_option); Vector<String> sort_filter_titles; + sort_filter_titles.push_back(TTR("Last Edited")); sort_filter_titles.push_back(TTR("Name")); sort_filter_titles.push_back(TTR("Path")); - sort_filter_titles.push_back(TTR("Last Edited")); for (int i = 0; i < sort_filter_titles.size(); i++) { filter_option->add_item(sort_filter_titles[i]); @@ -2840,7 +2845,7 @@ ProjectManager::ProjectManager() { _load_recent_projects(); - DirAccessRef dir_access = DirAccess::create(DirAccess::AccessType::ACCESS_FILESYSTEM); + Ref<DirAccess> dir_access = DirAccess::create(DirAccess::AccessType::ACCESS_FILESYSTEM); String default_project_path = EditorSettings::get_singleton()->get("filesystem/directories/default_project_path"); if (!dir_access->dir_exists(default_project_path)) { diff --git a/editor/project_manager.h b/editor/project_manager.h index 4f053793fd..a68cc4350c 100644 --- a/editor/project_manager.h +++ b/editor/project_manager.h @@ -42,9 +42,9 @@ class ProjectDialog; class ProjectList; enum FilterOption { + EDIT_DATE, NAME, PATH, - EDIT_DATE, }; class ProjectManager : public Control { @@ -126,8 +126,8 @@ class ProjectManager : public Control { void _install_project(const String &p_zip_path, const String &p_title); void _dim_window(); - virtual void unhandled_key_input(const Ref<InputEvent> &p_ev) override; - void _files_dropped(PackedStringArray p_files, int p_screen); + virtual void shortcut_input(const Ref<InputEvent> &p_ev) override; + void _files_dropped(PackedStringArray p_files); void _version_button_pressed(); void _on_order_option_changed(int p_idx); diff --git a/editor/project_settings_editor.cpp b/editor/project_settings_editor.cpp index 1318287dc8..fa83a58cff 100644 --- a/editor/project_settings_editor.cpp +++ b/editor/project_settings_editor.cpp @@ -49,7 +49,7 @@ void ProjectSettingsEditor::popup_project_settings() { _add_feature_overrides(); general_settings_inspector->update_category_list(); - set_process_unhandled_input(true); + set_process_shortcut_input(true); localization_editor->update_translations(); autoload_settings->update_autoload(); @@ -202,7 +202,7 @@ void ProjectSettingsEditor::_select_type(Variant::Type p_type) { type_box->select(type_box->get_item_index(p_type)); } -void ProjectSettingsEditor::unhandled_input(const Ref<InputEvent> &p_event) { +void ProjectSettingsEditor::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); const Ref<InputEventKey> k = p_event; @@ -351,7 +351,7 @@ void ProjectSettingsEditor::_action_edited(const String &p_name, const Dictionar undo_redo->create_action(TTR("Edit Input Action Event")); } else if (event_count > old_event_count) { undo_redo->create_action(TTR("Add Input Action Event")); - } else if (event_count < old_event_count) { + } else { undo_redo->create_action(TTR("Remove Input Action Event")); } diff --git a/editor/project_settings_editor.h b/editor/project_settings_editor.h index 5dc1ddc0a8..24d61db443 100644 --- a/editor/project_settings_editor.h +++ b/editor/project_settings_editor.h @@ -47,34 +47,34 @@ class ProjectSettingsEditor : public AcceptDialog { GDCLASS(ProjectSettingsEditor, AcceptDialog); static ProjectSettingsEditor *singleton; - ProjectSettings *ps; - Timer *timer; - - TabContainer *tab_container; - SectionedInspector *general_settings_inspector; - ActionMapEditor *action_map_editor; - LocalizationEditor *localization_editor; - EditorAutoloadSettings *autoload_settings; - ShaderGlobalsEditor *shaders_global_variables_editor; - EditorPluginSettings *plugin_settings; - - LineEdit *search_box; - CheckButton *advanced; - - LineEdit *property_box; - OptionButton *feature_box; - OptionButton *type_box; - Button *add_button; - Button *del_button; - - Label *restart_label; - TextureRect *restart_icon; - PanelContainer *restart_container; - Button *restart_close_button; - - ImportDefaultsEditor *import_defaults_editor; - EditorData *data; - UndoRedo *undo_redo; + ProjectSettings *ps = nullptr; + Timer *timer = nullptr; + + TabContainer *tab_container = nullptr; + SectionedInspector *general_settings_inspector = nullptr; + ActionMapEditor *action_map_editor = nullptr; + LocalizationEditor *localization_editor = nullptr; + EditorAutoloadSettings *autoload_settings = nullptr; + ShaderGlobalsEditor *shaders_global_variables_editor = nullptr; + EditorPluginSettings *plugin_settings = nullptr; + + LineEdit *search_box = nullptr; + CheckButton *advanced = nullptr; + + LineEdit *property_box = nullptr; + OptionButton *feature_box = nullptr; + OptionButton *type_box = nullptr; + Button *add_button = nullptr; + Button *del_button = nullptr; + + Label *restart_label = nullptr; + TextureRect *restart_icon = nullptr; + PanelContainer *restart_container = nullptr; + Button *restart_close_button = nullptr; + + ImportDefaultsEditor *import_defaults_editor = nullptr; + EditorData *data = nullptr; + UndoRedo *undo_redo = nullptr; void _advanced_toggled(bool p_button_pressed); void _property_box_changed(const String &p_text); @@ -82,7 +82,7 @@ class ProjectSettingsEditor : public AcceptDialog { void _feature_selected(int p_index); void _select_type(Variant::Type p_type); - virtual void unhandled_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; String _get_setting_name() const; void _setting_edited(const String &p_name); diff --git a/editor/property_editor.h b/editor/property_editor.h index 73306e0bc2..1a4d88f7fa 100644 --- a/editor/property_editor.h +++ b/editor/property_editor.h @@ -95,11 +95,11 @@ class CustomPropertyEditor : public PopupPanel { EASING_OUT_IN }; - PopupMenu *menu; - SceneTreeDialog *scene_tree; - EditorFileDialog *file; - EditorLocaleDialog *locale; - ConfirmationDialog *error; + PopupMenu *menu = nullptr; + SceneTreeDialog *scene_tree = nullptr; + EditorFileDialog *file = nullptr; + EditorLocaleDialog *locale = nullptr; + ConfirmationDialog *error = nullptr; String name; Variant::Type type; Variant v; @@ -107,34 +107,34 @@ class CustomPropertyEditor : public PopupPanel { int hint; String hint_text; HBoxContainer *value_hboxes[MAX_VALUE_EDITORS / 4]; - VBoxContainer *value_vbox; + VBoxContainer *value_vbox = nullptr; LineEdit *value_editor[MAX_VALUE_EDITORS]; int focused_value_editor; Label *value_label[MAX_VALUE_EDITORS]; HScrollBar *scroll[4]; - HBoxContainer *action_hboxes; + HBoxContainer *action_hboxes = nullptr; Button *action_buttons[MAX_ACTION_BUTTONS]; - MenuButton *type_button; + MenuButton *type_button = nullptr; Vector<String> inheritors_array; - TextureRect *texture_preview; - ColorPicker *color_picker; - TextEdit *text_edit; + TextureRect *texture_preview = nullptr; + ColorPicker *color_picker = nullptr; + TextEdit *text_edit = nullptr; bool read_only = false; bool picking_viewport; - GridContainer *checks20gc; + GridContainer *checks20gc = nullptr; CheckBox *checks20[20]; - SpinBox *spinbox; - HSlider *slider; + SpinBox *spinbox = nullptr; + HSlider *slider = nullptr; - Control *easing_draw; - CreateDialog *create_dialog; - PropertySelector *property_select; + Control *easing_draw = nullptr; + CreateDialog *create_dialog = nullptr; + PropertySelector *property_select = nullptr; - Object *owner; + Object *owner = nullptr; bool updating = false; - PropertyValueEvaluator *evaluator; + PropertyValueEvaluator *evaluator = nullptr; void _text_edit_changed(); void _file_selected(String p_file); diff --git a/editor/property_selector.h b/editor/property_selector.h index 7e629a847e..597804da31 100644 --- a/editor/property_selector.h +++ b/editor/property_selector.h @@ -38,8 +38,8 @@ class PropertySelector : public ConfirmationDialog { GDCLASS(PropertySelector, ConfirmationDialog); - LineEdit *search_box; - Tree *search_options; + LineEdit *search_box = nullptr; + Tree *search_options = nullptr; void _text_changed(const String &p_newtext); void _sbox_input(const Ref<InputEvent> &p_ie); @@ -48,14 +48,14 @@ class PropertySelector : public ConfirmationDialog { void _item_selected(); void _hide_requested(); - EditorHelpBit *help_bit; + EditorHelpBit *help_bit = nullptr; bool properties; String selected; Variant::Type type; String base_type; ObjectID script; - Object *instance; + Object *instance = nullptr; bool virtuals_only = false; Vector<Variant::Type> type_filter; diff --git a/editor/quick_open.h b/editor/quick_open.h index f50f09604c..843ef47711 100644 --- a/editor/quick_open.h +++ b/editor/quick_open.h @@ -39,8 +39,8 @@ class EditorQuickOpen : public ConfirmationDialog { GDCLASS(EditorQuickOpen, ConfirmationDialog); - LineEdit *search_box; - Tree *search_options; + LineEdit *search_box = nullptr; + Tree *search_options = nullptr; StringName base_type; bool allow_multi_select = false; diff --git a/editor/rename_dialog.h b/editor/rename_dialog.h index c9747795f0..d05e80fc04 100644 --- a/editor/rename_dialog.h +++ b/editor/rename_dialog.h @@ -62,41 +62,41 @@ class RenameDialog : public ConfirmationDialog { void _update_preview_int(int new_value = 0); static void _error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, bool p_editor_notify, ErrorHandlerType p_type); - SceneTreeEditor *scene_tree_editor; - UndoRedo *undo_redo; + SceneTreeEditor *scene_tree_editor = nullptr; + UndoRedo *undo_redo = nullptr; int global_count; - LineEdit *lne_search; - LineEdit *lne_replace; - LineEdit *lne_prefix; - LineEdit *lne_suffix; + LineEdit *lne_search = nullptr; + LineEdit *lne_replace = nullptr; + LineEdit *lne_prefix = nullptr; + LineEdit *lne_suffix = nullptr; - TabContainer *tabc_features; + TabContainer *tabc_features = nullptr; - CheckBox *cbut_substitute; - CheckButton *cbut_regex; - CheckBox *cbut_process; - CheckBox *chk_per_level_counter; + CheckBox *cbut_substitute = nullptr; + CheckButton *cbut_regex = nullptr; + CheckBox *cbut_process = nullptr; + CheckBox *chk_per_level_counter = nullptr; - Button *but_insert_name; - Button *but_insert_parent; - Button *but_insert_type; - Button *but_insert_scene; - Button *but_insert_root; - Button *but_insert_count; + Button *but_insert_name = nullptr; + Button *but_insert_parent = nullptr; + Button *but_insert_type = nullptr; + Button *but_insert_scene = nullptr; + Button *but_insert_root = nullptr; + Button *but_insert_count = nullptr; - SpinBox *spn_count_start; - SpinBox *spn_count_step; - SpinBox *spn_count_padding; + SpinBox *spn_count_start = nullptr; + SpinBox *spn_count_step = nullptr; + SpinBox *spn_count_padding = nullptr; - OptionButton *opt_style; - OptionButton *opt_case; + OptionButton *opt_style = nullptr; + OptionButton *opt_case = nullptr; - Label *lbl_preview_title; - Label *lbl_preview; + Label *lbl_preview_title = nullptr; + Label *lbl_preview = nullptr; List<Pair<NodePath, String>> to_rename; - Node *preview_node; + Node *preview_node = nullptr; bool lock_preview_update; ErrorHandlerList eh; bool has_errors; diff --git a/editor/reparent_dialog.h b/editor/reparent_dialog.h index 981829a871..121a86e9f0 100644 --- a/editor/reparent_dialog.h +++ b/editor/reparent_dialog.h @@ -41,8 +41,8 @@ class ReparentDialog : public ConfirmationDialog { GDCLASS(ReparentDialog, ConfirmationDialog); - SceneTreeEditor *tree; - CheckBox *keep_transform; + SceneTreeEditor *tree = nullptr; + CheckBox *keep_transform = nullptr; void _reparent(); void _cancel(); diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp index 551a0ff9c8..03f65cdf52 100644 --- a/editor/scene_tree_dock.cpp +++ b/editor/scene_tree_dock.cpp @@ -79,7 +79,7 @@ void SceneTreeDock::input(const Ref<InputEvent> &p_event) { } } -void SceneTreeDock::unhandled_key_input(const Ref<InputEvent> &p_event) { +void SceneTreeDock::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (get_viewport()->gui_get_focus_owner() && get_viewport()->gui_get_focus_owner()->is_text_field()) { @@ -2012,7 +2012,7 @@ void SceneTreeDock::_delete_confirm(bool p_cut) { bool entire_scene = false; - for (Node *E : remove_list) { + for (const Node *E : remove_list) { if (E == edited_scene) { entire_scene = true; } @@ -3149,9 +3149,8 @@ void SceneTreeDock::_update_create_root_dialog() { favorite_nodes->get_child(i)->queue_delete(); } - FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("favorites.Node"), FileAccess::READ); - - if (f) { + Ref<FileAccess> f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("favorites.Node"), FileAccess::READ); + if (f.is_valid()) { while (!f->eof_reached()) { String l = f->get_line().strip_edges(); @@ -3168,8 +3167,6 @@ void SceneTreeDock::_update_create_root_dialog() { button->connect("pressed", callable_mp(this, &SceneTreeDock::_favorite_root_selected), make_binds(l)); } } - - memdelete(f); } if (!favorite_nodes->is_visible_in_tree()) { @@ -3476,7 +3473,7 @@ SceneTreeDock::SceneTreeDock(Node *p_scene_root, EditorSelection *p_editor_selec add_child(quick_open); quick_open->connect("quick_open", callable_mp(this, &SceneTreeDock::_quick_open)); - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); delete_dialog = memnew(ConfirmationDialog); add_child(delete_dialog); diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h index 938f83725d..599fb01203 100644 --- a/editor/scene_tree_dock.h +++ b/editor/scene_tree_dock.h @@ -109,29 +109,29 @@ class SceneTreeDock : public VBoxContainer { bool reset_create_dialog = false; int current_option; - CreateDialog *create_dialog; + CreateDialog *create_dialog = nullptr; #ifdef MODULE_REGEX_ENABLED - RenameDialog *rename_dialog; + RenameDialog *rename_dialog = nullptr; #endif // MODULE_REGEX_ENABLED - Button *button_add; - Button *button_instance; - Button *button_create_script; - Button *button_detach_script; - MenuButton *button_tree_menu; + Button *button_add = nullptr; + Button *button_instance = nullptr; + Button *button_create_script = nullptr; + Button *button_detach_script = nullptr; + MenuButton *button_tree_menu = nullptr; - Button *button_2d; - Button *button_3d; - Button *button_ui; - Button *button_custom; - Button *button_clipboard; + Button *button_2d = nullptr; + Button *button_3d = nullptr; + Button *button_ui = nullptr; + Button *button_custom = nullptr; + Button *button_clipboard = nullptr; - HBoxContainer *button_hb; + HBoxContainer *button_hb = nullptr; Button *edit_local, *edit_remote; - SceneTreeEditor *scene_tree; - Control *remote_tree; + SceneTreeEditor *scene_tree = nullptr; + Control *remote_tree = nullptr; - HBoxContainer *tool_hbc; + HBoxContainer *tool_hbc = nullptr; void _tool_selected(int p_tool, bool p_confirm_override = false); void _property_selected(int p_idx); void _node_collapsed(Object *p_obj); @@ -140,40 +140,40 @@ class SceneTreeDock : public VBoxContainer { String resource_drop_path; void _perform_property_drop(Node *p_node, String p_property, RES p_res); - EditorData *editor_data; - EditorSelection *editor_selection; + EditorData *editor_data = nullptr; + EditorSelection *editor_selection = nullptr; List<Node *> node_clipboard; String clipboard_source_scene; HashMap<String, Map<RES, RES>> clipboard_resource_remap; - ScriptCreateDialog *script_create_dialog; - ShaderCreateDialog *shader_create_dialog; - AcceptDialog *accept; - ConfirmationDialog *delete_dialog; - ConfirmationDialog *editable_instance_remove_dialog; - ConfirmationDialog *placeholder_editable_instance_remove_dialog; + ScriptCreateDialog *script_create_dialog = nullptr; + ShaderCreateDialog *shader_create_dialog = nullptr; + AcceptDialog *accept = nullptr; + ConfirmationDialog *delete_dialog = nullptr; + ConfirmationDialog *editable_instance_remove_dialog = nullptr; + ConfirmationDialog *placeholder_editable_instance_remove_dialog = nullptr; - ReparentDialog *reparent_dialog; - EditorQuickOpen *quick_open; - EditorFileDialog *new_scene_from_dialog; + ReparentDialog *reparent_dialog = nullptr; + EditorQuickOpen *quick_open = nullptr; + EditorFileDialog *new_scene_from_dialog = nullptr; - LineEdit *filter; - TextureRect *filter_icon; + LineEdit *filter = nullptr; + TextureRect *filter_icon = nullptr; - PopupMenu *menu; - PopupMenu *menu_subresources; - PopupMenu *menu_properties; - ConfirmationDialog *clear_inherit_confirm; + PopupMenu *menu = nullptr; + PopupMenu *menu_subresources = nullptr; + PopupMenu *menu_properties = nullptr; + ConfirmationDialog *clear_inherit_confirm = nullptr; bool first_enter = true; void _create(); void _do_create(Node *p_parent); - Node *scene_root; - Node *edited_scene; + Node *scene_root = nullptr; + Node *edited_scene = nullptr; - VBoxContainer *create_root_dialog; + VBoxContainer *create_root_dialog = nullptr; String selected_favorite_root; Ref<ShaderMaterial> selected_shader_material; @@ -220,7 +220,7 @@ class SceneTreeDock : public VBoxContainer { void _nodes_drag_begin(); virtual void input(const Ref<InputEvent> &p_event) override; - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; void _import_subscene(); diff --git a/editor/scene_tree_editor.h b/editor/scene_tree_editor.h index 2466b8576a..547a5b57ca 100644 --- a/editor/scene_tree_editor.h +++ b/editor/scene_tree_editor.h @@ -41,7 +41,7 @@ class SceneTreeEditor : public Control { GDCLASS(SceneTreeEditor, Control); - EditorSelection *editor_selection; + EditorSelection *editor_selection = nullptr; enum SceneTreeEditorButton { BUTTON_SUBSCENE = 0, @@ -55,14 +55,14 @@ class SceneTreeEditor : public Control { BUTTON_PIN = 8, }; - Tree *tree; - Node *selected; + Tree *tree = nullptr; + Node *selected = nullptr; ObjectID instance_node; String filter; - AcceptDialog *error; - AcceptDialog *warning; + AcceptDialog *error = nullptr; + AcceptDialog *warning = nullptr; bool auto_expand_selected = true; bool connect_to_script_mode = false; @@ -96,7 +96,7 @@ class SceneTreeEditor : public Control { bool show_enabled_subscene = false; void _renamed(); - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; Set<Node *> marked; bool marked_selectable = false; @@ -125,7 +125,7 @@ class SceneTreeEditor : public Control { void _warning_changed(Node *p_for_node); - Timer *update_timer; + Timer *update_timer = nullptr; List<StringName> *script_types; bool _is_script_type(const StringName &p_type) const; @@ -166,10 +166,10 @@ public: class SceneTreeDialog : public ConfirmationDialog { GDCLASS(SceneTreeDialog, ConfirmationDialog); - SceneTreeEditor *tree; + SceneTreeEditor *tree = nullptr; //Button *select; //Button *cancel; - LineEdit *filter; + LineEdit *filter = nullptr; void _select(); void _cancel(); diff --git a/editor/script_create_dialog.cpp b/editor/script_create_dialog.cpp index 72f77c859b..7d063e13f9 100644 --- a/editor/script_create_dialog.cpp +++ b/editor/script_create_dialog.cpp @@ -246,7 +246,7 @@ String ScriptCreateDialog::_validate_path(const String &p_path, bool p_file_must } { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->change_dir(p.get_base_dir()) != OK) { return TTR("Base path is invalid."); } @@ -254,7 +254,7 @@ String ScriptCreateDialog::_validate_path(const String &p_path, bool p_file_must { // Check if file exists. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (da->dir_exists(p)) { return TTR("A directory with the same name exists."); } else if (p_file_must_exist && !da->file_exists(p)) { @@ -547,7 +547,7 @@ void ScriptCreateDialog::_path_changed(const String &p_path) { } // Check if file exists. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); String p = ProjectSettings::get_singleton()->localize_path(p_path.strip_edges()); if (da->file_exists(p)) { is_new_script_created = false; @@ -824,8 +824,8 @@ Vector<ScriptLanguage::ScriptTemplate> ScriptCreateDialog::_get_user_templates(c String dir_path = p_dir.plus_file(p_object); - DirAccessRef d = DirAccess::open(dir_path); - if (d) { + Ref<DirAccess> d = DirAccess::open(dir_path); + if (d.is_valid()) { d->list_dir_begin(); String file = d->get_next(); while (file != String()) { @@ -858,7 +858,7 @@ ScriptLanguage::ScriptTemplate ScriptCreateDialog::_parse_template(const ScriptL // Parse file for meta-information and script content Error err; - FileAccess *file = FileAccess::open(p_path.plus_file(p_filename), FileAccess::READ, &err); + Ref<FileAccess> file = FileAccess::open(p_path.plus_file(p_filename), FileAccess::READ, &err); if (!err) { while (!file->eof_reached()) { String line = file->get_line(); @@ -890,8 +890,6 @@ ScriptLanguage::ScriptTemplate ScriptCreateDialog::_parse_template(const ScriptL script_template.content += line.replace("\t", "_TS_") + "\n"; } } - file->close(); - memdelete(file); } script_template.content = script_template.content.lstrip("\n"); diff --git a/editor/script_create_dialog.h b/editor/script_create_dialog.h index e9f634e2c0..c7d8cfc38a 100644 --- a/editor/script_create_dialog.h +++ b/editor/script_create_dialog.h @@ -45,27 +45,27 @@ class EditorFileDialog; class ScriptCreateDialog : public ConfirmationDialog { GDCLASS(ScriptCreateDialog, ConfirmationDialog); - LineEdit *class_name; - Label *error_label; - Label *path_error_label; - Label *builtin_warning_label; - Label *script_name_warning_label; - Label *template_info_label; - PanelContainer *status_panel; - LineEdit *parent_name; - Button *parent_browse_button; - Button *parent_search_button; - OptionButton *language_menu; - OptionButton *template_menu; - LineEdit *file_path; - LineEdit *internal_name; - Button *path_button; - EditorFileDialog *file_browse; - CheckBox *internal; - CheckBox *use_templates; - VBoxContainer *path_vb; - AcceptDialog *alert; - CreateDialog *select_class; + LineEdit *class_name = nullptr; + Label *error_label = nullptr; + Label *path_error_label = nullptr; + Label *builtin_warning_label = nullptr; + Label *script_name_warning_label = nullptr; + Label *template_info_label = nullptr; + PanelContainer *status_panel = nullptr; + LineEdit *parent_name = nullptr; + Button *parent_browse_button = nullptr; + Button *parent_search_button = nullptr; + OptionButton *language_menu = nullptr; + OptionButton *template_menu = nullptr; + LineEdit *file_path = nullptr; + LineEdit *internal_name = nullptr; + Button *path_button = nullptr; + EditorFileDialog *file_browse = nullptr; + CheckBox *internal = nullptr; + CheckBox *use_templates = nullptr; + VBoxContainer *path_vb = nullptr; + AcceptDialog *alert = nullptr; + CreateDialog *select_class = nullptr; bool is_browsing_parent = false; String template_inactive_message; String initial_bp; @@ -89,7 +89,7 @@ class ScriptCreateDialog : public ConfirmationDialog { Control *name_controls[2]; Vector<ScriptLanguage::ScriptTemplate> template_list; - ScriptLanguage *language; + ScriptLanguage *language = nullptr; String base_type; diff --git a/editor/shader_create_dialog.cpp b/editor/shader_create_dialog.cpp index dbc78e846c..f07ec161c2 100644 --- a/editor/shader_create_dialog.cpp +++ b/editor/shader_create_dialog.cpp @@ -313,7 +313,7 @@ void ShaderCreateDialog::_path_changed(const String &p_path) { return; } - DirAccessRef f = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES); String p = ProjectSettings::get_singleton()->localize_path(p_path.strip_edges()); if (f->file_exists(p)) { is_new_shader_created = false; @@ -371,12 +371,12 @@ String ShaderCreateDialog::_validate_path(const String &p_path) { return TTR("Path is not local."); } - DirAccessRef d = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (d->change_dir(p.get_base_dir()) != OK) { return TTR("Invalid base path."); } - DirAccessRef f = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES); if (f->dir_exists(p)) { return TTR("A directory with the same name exists."); } diff --git a/editor/shader_globals_editor.h b/editor/shader_globals_editor.h index 3b337e07de..d29052eaee 100644 --- a/editor/shader_globals_editor.h +++ b/editor/shader_globals_editor.h @@ -43,12 +43,12 @@ class ShaderGlobalsEditorInterface; class ShaderGlobalsEditor : public VBoxContainer { GDCLASS(ShaderGlobalsEditor, VBoxContainer) - ShaderGlobalsEditorInterface *interface; - EditorInspector *inspector; + ShaderGlobalsEditorInterface *interface = nullptr; + EditorInspector *inspector = nullptr; - LineEdit *variable_name; - OptionButton *variable_type; - Button *variable_add; + LineEdit *variable_name = nullptr; + OptionButton *variable_type = nullptr; + Button *variable_add = nullptr; void _variable_added(); void _variable_deleted(const String &p_variable); diff --git a/main/main.cpp b/main/main.cpp index b730f65286..f20ec94fa5 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -606,8 +606,6 @@ Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_ph I = I->next(); } - I = args.front(); - String display_driver = ""; String audio_driver = ""; String project_path = "."; @@ -2114,8 +2112,8 @@ bool Main::start() { } { - DirAccessRef da = DirAccess::open(doc_tool_path); - ERR_FAIL_COND_V_MSG(!da, false, "Argument supplied to --doctool must be a valid directory path."); + Ref<DirAccess> da = DirAccess::open(doc_tool_path); + ERR_FAIL_COND_V_MSG(da.is_null(), false, "Argument supplied to --doctool must be a valid directory path."); } #ifndef MODULE_MONO_ENABLED @@ -2151,7 +2149,7 @@ bool Main::start() { checked_paths.insert(path); // Create the module documentation directory if it doesn't exist - DirAccessRef da = DirAccess::create_for_path(path); + Ref<DirAccess> da = DirAccess::create_for_path(path); err = da->make_dir_recursive(path); ERR_FAIL_COND_V_MSG(err != OK, false, "Error: Can't create directory: " + path + ": " + itos(err)); @@ -2163,7 +2161,7 @@ bool Main::start() { String index_path = doc_tool_path.plus_file("doc/classes"); // Create the main documentation directory if it doesn't exist - DirAccessRef da = DirAccess::create_for_path(index_path); + Ref<DirAccess> da = DirAccess::create_for_path(index_path); err = da->make_dir_recursive(index_path); ERR_FAIL_COND_V_MSG(err != OK, false, "Error: Can't create index directory: " + index_path + ": " + itos(err)); @@ -2336,7 +2334,7 @@ bool Main::start() { } else if (script_res.is_valid()) { StringName ibt = script_res->get_instance_base_type(); bool valid_type = ClassDB::is_parent_class(ibt, "Node"); - ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path); + ERR_CONTINUE_MSG(!valid_type, "Script does not inherit from Node: " + info.path); Object *obj = ClassDB::instantiate(ibt); @@ -2503,11 +2501,11 @@ bool Main::start() { int sep = local_game_path.rfind("/"); if (sep == -1) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); local_game_path = da->get_current_dir().plus_file(local_game_path); } else { - DirAccessRef da = DirAccess::open(local_game_path.substr(0, sep)); - if (da) { + Ref<DirAccess> da = DirAccess::open(local_game_path.substr(0, sep)); + if (da.is_valid()) { local_game_path = da->get_current_dir().plus_file( local_game_path.substr(sep + 1, local_game_path.length())); } diff --git a/modules/basis_universal/register_types.cpp b/modules/basis_universal/register_types.cpp index 4c2ebe603f..18554177d9 100644 --- a/modules/basis_universal/register_types.cpp +++ b/modules/basis_universal/register_types.cpp @@ -244,7 +244,7 @@ static Ref<Image> basis_universal_unpacker_ptr(const uint8_t *p_data, int p_size bool ret = tr.transcode_image_level(ptr, size, 0, i, dst + ofs, level.m_total_blocks - i, format); if (!ret) { - printf("failed! on level %i\n", i); + printf("failed! on level %u\n", i); break; }; diff --git a/modules/bmp/image_loader_bmp.cpp b/modules/bmp/image_loader_bmp.cpp index ad2c7d6a3e..8813c3827a 100644 --- a/modules/bmp/image_loader_bmp.cpp +++ b/modules/bmp/image_loader_bmp.cpp @@ -200,8 +200,7 @@ Error ImageLoaderBMP::convert_to_image(Ref<Image> p_image, return err; } -Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, - bool p_force_linear, float p_scale) { +Error ImageLoaderBMP::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale) { bmp_header_s bmp_header; Error err = ERR_INVALID_DATA; @@ -241,7 +240,6 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, case BI_CMYKRLE8: case BI_CMYKRLE4: { // Stop parsing. - f->close(); ERR_FAIL_V_MSG(ERR_UNAVAILABLE, vformat("Compressed BMP files are not supported: %s", f->get_path())); } break; @@ -283,7 +281,6 @@ Error ImageLoaderBMP::load_image(Ref<Image> p_image, FileAccess *f, err = convert_to_image(p_image, bmp_buffer_r, bmp_color_table_r, color_table_size, bmp_header); } - f->close(); } } return err; @@ -294,12 +291,14 @@ void ImageLoaderBMP::get_recognized_extensions(List<String> *p_extensions) const } static Ref<Image> _bmp_mem_loader_func(const uint8_t *p_bmp, int p_size) { - FileAccessMemory memfile; - Error open_memfile_error = memfile.open_custom(p_bmp, p_size); + Ref<FileAccessMemory> memfile; + memfile.instantiate(); + Error open_memfile_error = memfile->open_custom(p_bmp, p_size); ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for BMP image buffer."); + Ref<Image> img; img.instantiate(); - Error load_error = ImageLoaderBMP().load_image(img, &memfile, false, 1.0f); + Error load_error = ImageLoaderBMP().load_image(img, memfile, false, 1.0f); ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load BMP image."); return img; } diff --git a/modules/bmp/image_loader_bmp.h b/modules/bmp/image_loader_bmp.h index 9c9a16a9f5..63dee0a969 100644 --- a/modules/bmp/image_loader_bmp.h +++ b/modules/bmp/image_loader_bmp.h @@ -83,8 +83,7 @@ protected: const bmp_header_s &p_header); public: - virtual Error load_image(Ref<Image> p_image, FileAccess *f, - bool p_force_linear, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderBMP(); }; diff --git a/modules/csg/csg_shape.h b/modules/csg/csg_shape.h index 4721d0c11c..b5d5f97cf3 100644 --- a/modules/csg/csg_shape.h +++ b/modules/csg/csg_shape.h @@ -368,7 +368,7 @@ private: PathRotation path_rotation; bool path_local; - Path3D *path; + Path3D *path = nullptr; bool smooth_faces; bool path_continuous_u; diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp index 7bfe849106..58e5e31f46 100644 --- a/modules/dds/texture_loader_dds.cpp +++ b/modules/dds/texture_loader_dds.cpp @@ -100,12 +100,12 @@ RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, } Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); + if (f.is_null()) { return RES(); } - FileAccessRef fref(f); + Ref<FileAccess> fref(f); if (r_error) { *r_error = ERR_FILE_CORRUPT; } diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 3a0e320e9b..59254fc3ad 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -92,6 +92,21 @@ Object *GDScriptNativeClass::instantiate() { return ClassDB::instantiate(name); } +Variant GDScriptNativeClass::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { + if (p_method == SNAME("new")) { + // Constructor. + return Object::callp(p_method, p_args, p_argcount, r_error); + } + MethodBind *method = ClassDB::get_method(name, p_method); + if (method) { + // Native static method. + return method->call(nullptr, p_args, p_argcount, r_error); + } + + r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; + return Variant(); +} + GDScriptFunction *GDScript::_super_constructor(GDScript *p_script) { if (p_script->initializer) { return p_script->initializer; @@ -1015,7 +1030,7 @@ Error GDScript::load_byte_code(const String &p_path) { Error GDScript::load_source_code(const String &p_path) { Vector<uint8_t> sourcef; Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { ERR_FAIL_COND_V(err, err); } @@ -1024,8 +1039,6 @@ Error GDScript::load_source_code(const String &p_path) { sourcef.resize(len + 1); uint8_t *w = sourcef.ptrw(); uint64_t r = f->get_buffer(w, len); - f->close(); - memdelete(f); ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); w[len] = 0; @@ -2084,7 +2097,7 @@ bool GDScriptLanguage::handles_global_class_type(const String &p_type) const { String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_base_type, String *r_icon_path) const { Vector<uint8_t> sourcef; Error err; - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { return String(); } @@ -2118,8 +2131,8 @@ String GDScriptLanguage::get_global_class_name(const String &p_path, String *r_b } else { Vector<StringName> extend_classes = subclass->extends; - FileAccessRef subfile = FileAccess::open(subclass->extends_path, FileAccess::READ); - if (!subfile) { + Ref<FileAccess> subfile = FileAccess::open(subclass->extends_path, FileAccess::READ); + if (subfile.is_null()) { break; } String subsource = subfile->get_as_utf8_string(); @@ -2316,8 +2329,8 @@ String ResourceFormatLoaderGDScript::get_resource_type(const String &p_path) con } void ResourceFormatLoaderGDScript::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { - FileAccessRef file = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_MSG(!file, "Cannot open file '" + p_path + "'."); + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_MSG(file.is_null(), "Cannot open file '" + p_path + "'."); String source = file->get_as_utf8_string(); if (source.is_empty()) { @@ -2340,18 +2353,17 @@ Error ResourceFormatSaverGDScript::save(const String &p_path, const RES &p_resou String source = sqscr->get_source_code(); - Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); + { + Error err; + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V_MSG(err, err, "Cannot save GDScript file '" + p_path + "'."); + ERR_FAIL_COND_V_MSG(err, err, "Cannot save GDScript file '" + p_path + "'."); - file->store_string(source); - if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { - memdelete(file); - return ERR_CANT_CREATE; + file->store_string(source); + if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { + return ERR_CANT_CREATE; + } } - file->close(); - memdelete(file); if (ScriptServer::is_reload_scripts_on_save_enabled()) { GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false); diff --git a/modules/gdscript/gdscript.h b/modules/gdscript/gdscript.h index f7fa967883..79171cac73 100644 --- a/modules/gdscript/gdscript.h +++ b/modules/gdscript/gdscript.h @@ -52,6 +52,7 @@ public: _FORCE_INLINE_ const StringName &get_name() const { return name; } Variant _new(); Object *instantiate(); + virtual Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override; GDScriptNativeClass(const StringName &p_name); }; @@ -265,7 +266,7 @@ class GDScriptInstance : public ScriptInstance { friend struct GDScriptUtilityFunctionsDefinitions; ObjectID owner_id; - Object *owner; + Object *owner = nullptr; Ref<GDScript> script; #ifdef DEBUG_ENABLED Map<StringName, int> member_indices_cache; //used only for hot script reloading @@ -311,17 +312,17 @@ class GDScriptLanguage : public ScriptLanguage { static GDScriptLanguage *singleton; - Variant *_global_array; + Variant *_global_array = nullptr; Vector<Variant> global_array; Map<StringName, int> globals; Map<StringName, Variant> named_globals; struct CallLevel { - Variant *stack; - GDScriptFunction *function; - GDScriptInstance *instance; - int *ip; - int *line; + Variant *stack = nullptr; + GDScriptFunction *function = nullptr; + GDScriptInstance *instance = nullptr; + int *ip = nullptr; + int *line = nullptr; }; int _debug_parse_err_line; @@ -329,7 +330,7 @@ class GDScriptLanguage : public ScriptLanguage { String _debug_error; int _debug_call_stack_pos; int _debug_max_call_stack; - CallLevel *_call_stack; + CallLevel *_call_stack = nullptr; void _add_global(const StringName &p_name, const Variant &p_value); diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 00931961b7..01118a6b4f 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -2508,8 +2508,9 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a call_type = return_type; } else { - // Check if the name exists as something else. bool found = false; + + // Check if the name exists as something else. if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) { GDScriptParser::IdentifierNode *callee_id; if (callee_type == GDScriptParser::Node::IDENTIFIER) { @@ -2539,6 +2540,8 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) { String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string(); push_error(vformat(R"*(Function "%s()" not found in base %s.)*", p_call->function_name, base_name), p_call->is_super ? p_call : p_call->callee); + } else if (!found && (!p_call->is_super && base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::NATIVE && base_type.is_meta_type)) { + push_error(vformat(R"*(Static function "%s()" not found in base "%s".)*", p_call->function_name, base_type.native_type.operator String()), p_call); } } @@ -3773,6 +3776,7 @@ bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GD r_return_type = type_from_property(p_info.return_val); r_default_arg_count = p_info.default_arguments.size(); r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0; + r_static = (p_info.flags & METHOD_FLAG_STATIC) != 0; for (const PropertyInfo &E : p_info.arguments) { r_par_types.push_back(type_from_property(E)); diff --git a/modules/gdscript/gdscript_byte_codegen.cpp b/modules/gdscript/gdscript_byte_codegen.cpp index 82aa14795e..000d36d2e6 100644 --- a/modules/gdscript/gdscript_byte_codegen.cpp +++ b/modules/gdscript/gdscript_byte_codegen.cpp @@ -1080,6 +1080,24 @@ void GDScriptByteCodeGenerator::write_call_builtin_type_static(const Address &p_ append(Variant::get_validated_builtin_method(p_type, p_method)); } +void GDScriptByteCodeGenerator::write_call_native_static(const Address &p_target, const StringName &p_class, const StringName &p_method, const Vector<Address> &p_arguments) { + bool is_validated = false; + + MethodBind *method = ClassDB::get_method(p_class, p_method); + + if (!is_validated) { + // Perform regular call. + append(GDScriptFunction::OPCODE_CALL_NATIVE_STATIC, p_arguments.size() + 1); + for (int i = 0; i < p_arguments.size(); i++) { + append(p_arguments[i]); + } + append(p_target); + append(method); + append(p_arguments.size()); + return; + } +} + void GDScriptByteCodeGenerator::write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) { append(p_target.mode == Address::NIL ? GDScriptFunction::OPCODE_CALL_METHOD_BIND : GDScriptFunction::OPCODE_CALL_METHOD_BIND_RET, 2 + p_arguments.size()); for (int i = 0; i < p_arguments.size(); i++) { diff --git a/modules/gdscript/gdscript_byte_codegen.h b/modules/gdscript/gdscript_byte_codegen.h index db15dc55ef..222ae13390 100644 --- a/modules/gdscript/gdscript_byte_codegen.h +++ b/modules/gdscript/gdscript_byte_codegen.h @@ -464,6 +464,7 @@ public: virtual void write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) override; virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) override; virtual void write_call_builtin_type_static(const Address &p_target, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) override; + virtual void write_call_native_static(const Address &p_target, const StringName &p_class, const StringName &p_method, const Vector<Address> &p_arguments) override; virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override; virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override; virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override; diff --git a/modules/gdscript/gdscript_cache.cpp b/modules/gdscript/gdscript_cache.cpp index 6ada7d36f5..8c198345c2 100644 --- a/modules/gdscript/gdscript_cache.cpp +++ b/modules/gdscript/gdscript_cache.cpp @@ -145,7 +145,7 @@ Ref<GDScriptParserRef> GDScriptCache::get_parser(const String &p_path, GDScriptP String GDScriptCache::get_source_code(const String &p_path) { Vector<uint8_t> source_file; Error err; - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); if (err) { ERR_FAIL_COND_V(err, ""); } @@ -153,7 +153,6 @@ String GDScriptCache::get_source_code(const String &p_path) { uint64_t len = f->get_length(); source_file.resize(len + 1); uint64_t r = f->get_buffer(source_file.ptrw(), len); - f->close(); ERR_FAIL_COND_V(r != len, ""); source_file.write[len] = 0; diff --git a/modules/gdscript/gdscript_codegen.h b/modules/gdscript/gdscript_codegen.h index 4542dd94ae..3d42ce06c0 100644 --- a/modules/gdscript/gdscript_codegen.h +++ b/modules/gdscript/gdscript_codegen.h @@ -125,6 +125,7 @@ public: virtual void write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) = 0; virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_builtin_type_static(const Address &p_target, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) = 0; + virtual void write_call_native_static(const Address &p_target, const StringName &p_class, const StringName &p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) = 0; virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) = 0; diff --git a/modules/gdscript/gdscript_compiler.cpp b/modules/gdscript/gdscript_compiler.cpp index 8190eecbc7..0138147fcc 100644 --- a/modules/gdscript/gdscript_compiler.cpp +++ b/modules/gdscript/gdscript_compiler.cpp @@ -35,6 +35,7 @@ #include "gdscript_cache.h" #include "gdscript_utility_functions.h" +#include "core/config/engine.h" #include "core/config/project_settings.h" bool GDScriptCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) { @@ -575,6 +576,10 @@ GDScriptCodeGenerator::Address GDScriptCompiler::_parse_expression(CodeGen &code // May be static built-in method call. if (!call->is_super && subscript->base->type == GDScriptParser::Node::IDENTIFIER && GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name) < Variant::VARIANT_MAX) { gen->write_call_builtin_type_static(result, GDScriptParser::get_builtin_type(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name), subscript->attribute->name, arguments); + } else if (!call->is_super && subscript->base->type == GDScriptParser::Node::IDENTIFIER && call->function_name != SNAME("new") && + ClassDB::class_exists(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name) && !Engine::get_singleton()->has_singleton(static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name)) { + // It's a static native method call. + gen->write_call_native_static(result, static_cast<GDScriptParser::IdentifierNode *>(subscript->base)->name, subscript->attribute->name, arguments); } else { GDScriptCodeGenerator::Address base = _parse_expression(codegen, r_error, subscript->base); if (r_error) { diff --git a/modules/gdscript/gdscript_disassembler.cpp b/modules/gdscript/gdscript_disassembler.cpp index cc0be94a9e..e5fbbfa0c1 100644 --- a/modules/gdscript/gdscript_disassembler.cpp +++ b/modules/gdscript/gdscript_disassembler.cpp @@ -564,6 +564,28 @@ void GDScriptFunction::disassemble(const Vector<String> &p_code_lines) const { incr += 5 + argc; } break; + case OPCODE_CALL_NATIVE_STATIC: { + MethodBind *method = _methods_ptr[_code_ptr[ip + 1 + instr_var_args]]; + int argc = _code_ptr[ip + 2 + instr_var_args]; + + text += "call native method static "; + text += DADDR(1 + argc); + text += " = "; + text += method->get_instance_class(); + text += "."; + text += method->get_name(); + text += "("; + + for (int i = 0; i < argc; i++) { + if (i > 0) { + text += ", "; + } + text += DADDR(1 + i); + } + text += ")"; + + incr += 4 + argc; + } break; case OPCODE_CALL_PTRCALL_NO_RETURN: { text += "call-ptrcall (no return) "; diff --git a/modules/gdscript/gdscript_editor.cpp b/modules/gdscript/gdscript_editor.cpp index 7f0ffb4586..718df7a0a6 100644 --- a/modules/gdscript/gdscript_editor.cpp +++ b/modules/gdscript/gdscript_editor.cpp @@ -777,7 +777,22 @@ static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_a } } +static void _find_built_in_variants(Map<String, ScriptLanguage::CodeCompletionOption> &r_result, bool exclude_nil = false) { + for (int i = 0; i < Variant::VARIANT_MAX; i++) { + if (!exclude_nil && Variant::Type(i) == Variant::Type::NIL) { + ScriptLanguage::CodeCompletionOption option("null", ScriptLanguage::CODE_COMPLETION_KIND_CLASS); + r_result.insert(option.display, option); + } else { + ScriptLanguage::CodeCompletionOption option(Variant::get_type_name(Variant::Type(i)), ScriptLanguage::CODE_COMPLETION_KIND_CLASS); + r_result.insert(option.display, option); + } + } +} + static void _list_available_types(bool p_inherit_only, GDScriptParser::CompletionContext &p_context, Map<String, ScriptLanguage::CodeCompletionOption> &r_result) { + // Built-in Variant Types + _find_built_in_variants(r_result, true); + List<StringName> native_types; ClassDB::get_class_list(&native_types); for (const StringName &E : native_types) { @@ -957,7 +972,7 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base bool _static = base_type.is_meta_type; if (_static && base_type.kind != GDScriptParser::DataType::BUILTIN) { - ScriptLanguage::CodeCompletionOption option("new", ScriptLanguage::CODE_COMPLETION_KIND_FUNCTION); + ScriptLanguage::CodeCompletionOption option("new", ScriptLanguage::CODE_COMPLETION_KIND_FUNCTION, ScriptLanguage::LOCATION_LOCAL); option.insert_text += "("; r_result.insert(option.display, option); } @@ -1058,22 +1073,25 @@ static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base } } - if (!_static || Engine::get_singleton()->has_singleton(type)) { - List<MethodInfo> methods; - ClassDB::get_method_list(type, &methods, false, true); - for (const MethodInfo &E : methods) { - if (E.name.begins_with("_")) { - continue; - } - int location = p_recursion_depth + _get_method_location(type, E.name); - ScriptLanguage::CodeCompletionOption option(E.name, ScriptLanguage::CODE_COMPLETION_KIND_FUNCTION, location); - if (E.arguments.size()) { - option.insert_text += "("; - } else { - option.insert_text += "()"; - } - r_result.insert(option.display, option); + bool only_static = _static && !Engine::get_singleton()->has_singleton(type); + + List<MethodInfo> methods; + ClassDB::get_method_list(type, &methods, false, true); + for (const MethodInfo &E : methods) { + if (only_static && (E.flags & METHOD_FLAG_STATIC) == 0) { + continue; + } + if (E.name.begins_with("_")) { + continue; + } + int location = p_recursion_depth + _get_method_location(type, E.name); + ScriptLanguage::CodeCompletionOption option(E.name, ScriptLanguage::CODE_COMPLETION_KIND_FUNCTION, location); + if (E.arguments.size()) { + option.insert_text += "("; + } else { + option.insert_text += "()"; } + r_result.insert(option.display, option); } return; } break; @@ -1150,17 +1168,7 @@ static void _find_identifiers(GDScriptParser::CompletionContext &p_context, bool return; } - static const char *_type_names[Variant::VARIANT_MAX] = { - "null", "bool", "int", "float", "String", "StringName", "Vector2", "Vector2i", "Rect2", "Rect2i", "Vector3", "Vector3i", "Transform2D", "Plane", "Quaternion", "AABB", "Basis", "Transform3D", - "Color", "NodePath", "RID", "Signal", "Callable", "Object", "Dictionary", "Array", "PackedByteArray", "PackedInt32Array", "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray", - "PackedVector2Array", "PackedVector3Array", "PackedColorArray" - }; - static_assert((sizeof(_type_names) / sizeof(*_type_names)) == Variant::VARIANT_MAX, "Completion for builtin types is incomplete"); - - for (int i = 0; i < Variant::VARIANT_MAX; i++) { - ScriptLanguage::CodeCompletionOption option(_type_names[i], ScriptLanguage::CODE_COMPLETION_KIND_CLASS); - r_result.insert(option.display, option); - } + _find_built_in_variants(r_result); static const char *_keywords[] = { "false", "PI", "TAU", "INF", "NAN", "self", "true", "breakpoint", "tool", "super", diff --git a/modules/gdscript/gdscript_function.h b/modules/gdscript/gdscript_function.h index 3ee664c76d..a7ad2b65fd 100644 --- a/modules/gdscript/gdscript_function.h +++ b/modules/gdscript/gdscript_function.h @@ -259,6 +259,7 @@ public: OPCODE_CALL_METHOD_BIND, OPCODE_CALL_METHOD_BIND_RET, OPCODE_CALL_BUILTIN_STATIC, + OPCODE_CALL_NATIVE_STATIC, // ptrcall have one instruction per return type. OPCODE_CALL_PTRCALL_NO_RETURN, OPCODE_CALL_PTRCALL_BOOL, diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index 0da1896936..487b7d0449 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -312,7 +312,7 @@ public: bool is_constant = false; Variant reduced_value; - virtual bool is_expression() const { return true; } + virtual bool is_expression() const override { return true; } virtual ~ExpressionNode() {} protected: diff --git a/modules/gdscript/gdscript_utility_functions.cpp b/modules/gdscript/gdscript_utility_functions.cpp index 16b2dac343..89d94d8635 100644 --- a/modules/gdscript/gdscript_utility_functions.cpp +++ b/modules/gdscript/gdscript_utility_functions.cpp @@ -432,21 +432,21 @@ struct GDScriptUtilityFunctionsDefinitions { } static inline void print_debug(Variant *r_ret, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) { - String str; + String s; for (int i = 0; i < p_arg_count; i++) { - str += p_args[i]->operator String(); + s += p_args[i]->operator String(); } if (Thread::get_caller_id() == Thread::get_main_id()) { ScriptLanguage *script = GDScriptLanguage::get_singleton(); if (script->debug_get_stack_level_count() > 0) { - str += "\n At: " + script->debug_get_stack_level_source(0) + ":" + itos(script->debug_get_stack_level_line(0)) + ":" + script->debug_get_stack_level_function(0) + "()"; + s += "\n At: " + script->debug_get_stack_level_source(0) + ":" + itos(script->debug_get_stack_level_line(0)) + ":" + script->debug_get_stack_level_function(0) + "()"; } } else { - str += "\n At: Cannot retrieve debug info outside the main thread. Thread ID: " + itos(Thread::get_caller_id()); + s += "\n At: Cannot retrieve debug info outside the main thread. Thread ID: " + itos(Thread::get_caller_id()); } - print_line(str); + print_line(s); *r_ret = Variant(); } diff --git a/modules/gdscript/gdscript_vm.cpp b/modules/gdscript/gdscript_vm.cpp index 41c59c7703..152f548f4e 100644 --- a/modules/gdscript/gdscript_vm.cpp +++ b/modules/gdscript/gdscript_vm.cpp @@ -93,9 +93,13 @@ static String _get_var_type(const Variant *p_var) { basestr = "null instance"; } } else { - basestr = bobj->get_class(); - if (bobj->get_script_instance()) { - basestr += " (" + _get_script_name(bobj->get_script_instance()->get_script()) + ")"; + if (bobj->is_class_ptr(GDScriptNativeClass::get_class_ptr_static())) { + basestr = Object::cast_to<GDScriptNativeClass>(bobj)->get_name(); + } else { + basestr = bobj->get_class(); + if (bobj->get_script_instance()) { + basestr += " (" + _get_script_name(bobj->get_script_instance()->get_script()) + ")"; + } } } @@ -263,6 +267,7 @@ void (*type_init_function_table[])(Variant *) = { &&OPCODE_CALL_METHOD_BIND, \ &&OPCODE_CALL_METHOD_BIND_RET, \ &&OPCODE_CALL_BUILTIN_STATIC, \ + &&OPCODE_CALL_NATIVE_STATIC, \ &&OPCODE_CALL_PTRCALL_NO_RETURN, \ &&OPCODE_CALL_PTRCALL_BOOL, \ &&OPCODE_CALL_PTRCALL_INT, \ @@ -1710,6 +1715,47 @@ Variant GDScriptFunction::call(GDScriptInstance *p_instance, const Variant **p_a } DISPATCH_OPCODE; + OPCODE(OPCODE_CALL_NATIVE_STATIC) { + CHECK_SPACE(3 + instr_arg_count); + + ip += instr_arg_count; + + GD_ERR_BREAK(_code_ptr[ip + 1] < 0 || _code_ptr[ip + 1] >= _methods_count); + MethodBind *method = _methods_ptr[_code_ptr[ip + 1]]; + + int argc = _code_ptr[ip + 2]; + GD_ERR_BREAK(argc < 0); + + GET_INSTRUCTION_ARG(ret, argc); + + const Variant **argptrs = const_cast<const Variant **>(instruction_args); + +#ifdef DEBUG_ENABLED + uint64_t call_time = 0; + + if (GDScriptLanguage::get_singleton()->profiling) { + call_time = OS::get_singleton()->get_ticks_usec(); + } +#endif + + Callable::CallError err; + *ret = method->call(nullptr, argptrs, argc, err); + +#ifdef DEBUG_ENABLED + if (GDScriptLanguage::get_singleton()->profiling) { + function_call_time += OS::get_singleton()->get_ticks_usec() - call_time; + } + + if (err.error != Callable::CallError::CALL_OK) { + err_text = _get_call_error(err, "static function '" + method->get_name().operator String() + "' in type '" + method->get_instance_class().operator String() + "'", argptrs); + OPCODE_BREAK; + } +#endif + + ip += 3; + } + DISPATCH_OPCODE; + #ifdef DEBUG_ENABLED #define OPCODE_CALL_PTR(m_type) \ OPCODE(OPCODE_CALL_PTRCALL_##m_type) { \ diff --git a/modules/gdscript/language_server/gdscript_extend_parser.cpp b/modules/gdscript/language_server/gdscript_extend_parser.cpp index 17886181d5..4c4e810370 100644 --- a/modules/gdscript/language_server/gdscript_extend_parser.cpp +++ b/modules/gdscript/language_server/gdscript_extend_parser.cpp @@ -108,7 +108,7 @@ void ExtendGDScriptParser::update_document_links(const String &p_code) { document_links.clear(); GDScriptTokenizer tokenizer; - FileAccessRef fs = FileAccess::create(FileAccess::ACCESS_RESOURCES); + Ref<FileAccess> fs = FileAccess::create(FileAccess::ACCESS_RESOURCES); tokenizer.set_source_code(p_code); while (true) { GDScriptTokenizer::Token token = tokenizer.scan(); diff --git a/modules/gdscript/language_server/gdscript_text_document.cpp b/modules/gdscript/language_server/gdscript_text_document.cpp index d5ef8fed74..c42bd58aeb 100644 --- a/modules/gdscript/language_server/gdscript_text_document.cpp +++ b/modules/gdscript/language_server/gdscript_text_document.cpp @@ -424,10 +424,6 @@ GDScriptTextDocument::GDScriptTextDocument() { file_checker = FileAccess::create(FileAccess::ACCESS_RESOURCES); } -GDScriptTextDocument::~GDScriptTextDocument() { - memdelete(file_checker); -} - void GDScriptTextDocument::sync_script_content(const String &p_path, const String &p_content) { String path = GDScriptLanguageProtocol::get_singleton()->get_workspace()->get_file_path(p_path); GDScriptLanguageProtocol::get_singleton()->get_workspace()->parse_script(path, p_content); diff --git a/modules/gdscript/language_server/gdscript_text_document.h b/modules/gdscript/language_server/gdscript_text_document.h index eb7b2c0240..9732765f34 100644 --- a/modules/gdscript/language_server/gdscript_text_document.h +++ b/modules/gdscript/language_server/gdscript_text_document.h @@ -40,7 +40,7 @@ class GDScriptTextDocument : public RefCounted { protected: static void _bind_methods(); - FileAccess *file_checker; + Ref<FileAccess> file_checker; void didOpen(const Variant &p_param); void didClose(const Variant &p_param); @@ -75,7 +75,6 @@ public: void initialize(); GDScriptTextDocument(); - virtual ~GDScriptTextDocument(); }; #endif diff --git a/modules/gdscript/language_server/gdscript_workspace.cpp b/modules/gdscript/language_server/gdscript_workspace.cpp index 1bf0b40842..229c322f26 100644 --- a/modules/gdscript/language_server/gdscript_workspace.cpp +++ b/modules/gdscript/language_server/gdscript_workspace.cpp @@ -221,7 +221,7 @@ void GDScriptWorkspace::reload_all_workspace_scripts() { void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) { Error err; - DirAccessRef dir = DirAccess::open(p_root_dir, &err); + Ref<DirAccess> dir = DirAccess::open(p_root_dir, &err); if (OK == err) { dir->list_dir_begin(); String file_name = dir->get_next(); diff --git a/modules/gdscript/tests/gdscript_test_runner.cpp b/modules/gdscript/tests/gdscript_test_runner.cpp index e8ddf90836..e78517a708 100644 --- a/modules/gdscript/tests/gdscript_test_runner.cpp +++ b/modules/gdscript/tests/gdscript_test_runner.cpp @@ -80,7 +80,7 @@ void init_autoloads() { } else if (script.is_valid()) { StringName ibt = script->get_instance_base_type(); bool valid_type = ClassDB::is_parent_class(ibt, "Node"); - ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path); + ERR_CONTINUE_MSG(!valid_type, "Script does not inherit from Node: " + info.path); Object *obj = ClassDB::instantiate(ibt); @@ -229,7 +229,7 @@ bool GDScriptTestRunner::generate_outputs() { bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) { Error err = OK; - DirAccessRef dir(DirAccess::open(p_dir, &err)); + Ref<DirAccess> dir(DirAccess::open(p_dir, &err)); if (err != OK) { return false; @@ -254,7 +254,7 @@ bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) { #ifndef DEBUG_ENABLED // On release builds, skip tests marked as debug only. Error open_err = OK; - FileAccessRef script_file(FileAccess::open(current_dir.plus_file(next), FileAccess::READ, &open_err)); + Ref<FileAccess> script_file(FileAccess::open(current_dir.plus_file(next), FileAccess::READ, &open_err)); if (open_err != OK) { ERR_PRINT(vformat(R"(Couldn't open test file "%s".)", next)); next = dir->get_next(); @@ -286,7 +286,7 @@ bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) { bool GDScriptTestRunner::make_tests() { Error err = OK; - DirAccessRef dir(DirAccess::open(source_dir, &err)); + Ref<DirAccess> dir(DirAccess::open(source_dir, &err)); ERR_FAIL_COND_V_MSG(err != OK, false, "Could not open specified test directory."); @@ -611,7 +611,7 @@ bool GDScriptTest::generate_output() { } Error err = OK; - FileAccessRef out_file = FileAccess::open(output_file, FileAccess::WRITE, &err); + Ref<FileAccess> out_file = FileAccess::open(output_file, FileAccess::WRITE, &err); if (err != OK) { return false; } @@ -620,7 +620,6 @@ bool GDScriptTest::generate_output() { output += "\n"; // Make sure to insert newline for CI static checks. out_file->store_string(output); - out_file->close(); return true; } diff --git a/modules/gdscript/tests/gdscript_test_runner.h b/modules/gdscript/tests/gdscript_test_runner.h index 1a950c6898..d6c6419e21 100644 --- a/modules/gdscript/tests/gdscript_test_runner.h +++ b/modules/gdscript/tests/gdscript_test_runner.h @@ -63,8 +63,8 @@ public: private: struct ErrorHandlerData { - TestResult *result; - GDScriptTest *self; + TestResult *result = nullptr; + GDScriptTest *self = nullptr; ErrorHandlerData(TestResult *p_result, GDScriptTest *p_this) { result = p_result; self = p_this; diff --git a/modules/gdscript/tests/test_gdscript.cpp b/modules/gdscript/tests/test_gdscript.cpp index 4255030b4e..d8f60d5e9b 100644 --- a/modules/gdscript/tests/test_gdscript.cpp +++ b/modules/gdscript/tests/test_gdscript.cpp @@ -204,8 +204,8 @@ void test(TestType p_type) { return; } - FileAccessRef fa = FileAccess::open(test, FileAccess::READ); - ERR_FAIL_COND_MSG(!fa, "Could not open file: " + test); + Ref<FileAccess> fa = FileAccess::open(test, FileAccess::READ); + ERR_FAIL_COND_MSG(fa.is_null(), "Could not open file: " + test); // Initialize the language for the test routine. init_language(fa->get_path_absolute().get_base_dir()); diff --git a/modules/gltf/editor/editor_scene_importer_blend.cpp b/modules/gltf/editor/editor_scene_importer_blend.cpp index cdb22b7d19..173d5131cf 100644 --- a/modules/gltf/editor/editor_scene_importer_blend.cpp +++ b/modules/gltf/editor/editor_scene_importer_blend.cpp @@ -62,10 +62,11 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ List<String> *r_missing_deps, Error *r_err) { // Get global paths for source and sink. - const String source_global = ProjectSettings::get_singleton()->globalize_path(p_path); + // Escape paths to be valid Python strings to embed in the script. + const String source_global = ProjectSettings::get_singleton()->globalize_path(p_path).c_escape(); const String sink = ProjectSettings::get_singleton()->get_imported_files_path().plus_file( vformat("%s-%s.gltf", p_path.get_file().get_basename(), p_path.md5_text())); - const String sink_global = ProjectSettings::get_singleton()->globalize_path(sink); + const String sink_global = ProjectSettings::get_singleton()->globalize_path(sink).c_escape(); // Handle configuration options. @@ -237,13 +238,12 @@ Node *EditorSceneFormatImporterBlend::import_scene(const String &p_path, uint32_ return gltf->generate_scene(state, p_bake_fps); } -Ref<Animation> EditorSceneFormatImporterBlend::import_animation(const String &p_path, uint32_t p_flags, - const Map<StringName, Variant> &p_options, int p_bake_fps) { - return Ref<Animation>(); -} - -Variant EditorSceneFormatImporterBlend::get_option_visibility(const String &p_path, const String &p_option, +Variant EditorSceneFormatImporterBlend::get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) { + if (p_path.get_extension().to_lower() != "blend") { + return true; + } + if (p_option.begins_with("animation/")) { if (p_option != "animation/import" && !bool(p_options["animation/import"])) { return false; @@ -253,6 +253,9 @@ Variant EditorSceneFormatImporterBlend::get_option_visibility(const String &p_pa } void EditorSceneFormatImporterBlend::get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options) { + if (p_path.get_extension().to_lower() != "blend") { + return; + } #define ADD_OPTION_BOOL(PATH, VALUE) \ r_options->push_back(ResourceImporter::ImportOption(PropertyInfo(Variant::BOOL, SNAME(PATH)), VALUE)); #define ADD_OPTION_ENUM(PATH, ENUM_HINT, VALUE) \ diff --git a/modules/gltf/editor/editor_scene_importer_blend.h b/modules/gltf/editor/editor_scene_importer_blend.h index 9a1b5f5803..0925333a28 100644 --- a/modules/gltf/editor/editor_scene_importer_blend.h +++ b/modules/gltf/editor/editor_scene_importer_blend.h @@ -68,11 +68,9 @@ public: virtual Node *import_scene(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr) override; - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, - const Map<StringName, Variant> &p_options, int p_bake_fps) override; virtual void get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options) override; - virtual Variant get_option_visibility(const String &p_path, const String &p_option, + virtual Variant get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) override; }; diff --git a/modules/gltf/editor/editor_scene_importer_fbx.cpp b/modules/gltf/editor/editor_scene_importer_fbx.cpp index 7cfd85c73a..893d2efcec 100644 --- a/modules/gltf/editor/editor_scene_importer_fbx.cpp +++ b/modules/gltf/editor/editor_scene_importer_fbx.cpp @@ -53,10 +53,13 @@ Node *EditorSceneFormatImporterFBX::import_scene(const String &p_path, uint32_t List<String> *r_missing_deps, Error *r_err) { // Get global paths for source and sink. - const String source_global = ProjectSettings::get_singleton()->globalize_path(p_path); + // Don't use `c_escape()` as it can generate broken paths. These paths will be + // enclosed in double quotes by OS::execute(), so we only need to escape those. + // `c_escape_multiline()` seems to do this (escapes `\` and `"` only). + const String source_global = ProjectSettings::get_singleton()->globalize_path(p_path).c_escape_multiline(); const String sink = ProjectSettings::get_singleton()->get_imported_files_path().plus_file( vformat("%s-%s.glb", p_path.get_file().get_basename(), p_path.md5_text())); - const String sink_global = ProjectSettings::get_singleton()->globalize_path(sink); + const String sink_global = ProjectSettings::get_singleton()->globalize_path(sink).c_escape_multiline(); // Run fbx2gltf. @@ -65,9 +68,9 @@ Node *EditorSceneFormatImporterFBX::import_scene(const String &p_path, uint32_t List<String> args; args.push_back("--pbr-metallic-roughness"); args.push_back("--input"); - args.push_back(vformat("\"%s\"", source_global)); + args.push_back(source_global); args.push_back("--output"); - args.push_back(vformat("\"%s\"", sink_global)); + args.push_back(sink_global); args.push_back("--binary"); String standard_out; @@ -102,12 +105,7 @@ Node *EditorSceneFormatImporterFBX::import_scene(const String &p_path, uint32_t return gltf->generate_scene(state, p_bake_fps); } -Ref<Animation> EditorSceneFormatImporterFBX::import_animation(const String &p_path, - uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) { - return Ref<Animation>(); -} - -Variant EditorSceneFormatImporterFBX::get_option_visibility(const String &p_path, +Variant EditorSceneFormatImporterFBX::get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) { return true; } diff --git a/modules/gltf/editor/editor_scene_importer_fbx.h b/modules/gltf/editor/editor_scene_importer_fbx.h index bb69cfaa30..84de7fd1cc 100644 --- a/modules/gltf/editor/editor_scene_importer_fbx.h +++ b/modules/gltf/editor/editor_scene_importer_fbx.h @@ -47,11 +47,9 @@ public: virtual Node *import_scene(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr) override; - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, - const Map<StringName, Variant> &p_options, int p_bake_fps) override; virtual void get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options) override; - virtual Variant get_option_visibility(const String &p_path, const String &p_option, + virtual Variant get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const Map<StringName, Variant> &p_options) override; }; diff --git a/modules/gltf/editor/editor_scene_importer_gltf.cpp b/modules/gltf/editor/editor_scene_importer_gltf.cpp index 1d6a82e58a..5e7811ad2b 100644 --- a/modules/gltf/editor/editor_scene_importer_gltf.cpp +++ b/modules/gltf/editor/editor_scene_importer_gltf.cpp @@ -64,9 +64,4 @@ Node *EditorSceneFormatImporterGLTF::import_scene(const String &p_path, uint32_t return doc->generate_scene(state, p_bake_fps); } -Ref<Animation> EditorSceneFormatImporterGLTF::import_animation(const String &p_path, - uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps) { - return Ref<Animation>(); -} - #endif // TOOLS_ENABLED diff --git a/modules/gltf/editor/editor_scene_importer_gltf.h b/modules/gltf/editor/editor_scene_importer_gltf.h index 1f62ca9537..b714ada124 100644 --- a/modules/gltf/editor/editor_scene_importer_gltf.h +++ b/modules/gltf/editor/editor_scene_importer_gltf.h @@ -47,8 +47,6 @@ public: virtual Node *import_scene(const String &p_path, uint32_t p_flags, const Map<StringName, Variant> &p_options, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = nullptr) override; - virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags, - const Map<StringName, Variant> &p_options, int p_bake_fps) override; }; #endif // TOOLS_ENABLED diff --git a/modules/gltf/gltf_document.cpp b/modules/gltf/gltf_document.cpp index ee756c6d2e..784733aba2 100644 --- a/modules/gltf/gltf_document.cpp +++ b/modules/gltf/gltf_document.cpp @@ -256,8 +256,8 @@ Error GLTFDocument::_serialize_scenes(Ref<GLTFState> state) { Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> state) { Error err; - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); + if (f.is_null()) { return err; } @@ -278,7 +278,7 @@ Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> state) { return OK; } -Error GLTFDocument::_parse_glb(FileAccess *f, Ref<GLTFState> state) { +Error GLTFDocument::_parse_glb(Ref<FileAccess> f, Ref<GLTFState> state) { ERR_FAIL_NULL_V(f, ERR_INVALID_PARAMETER); ERR_FAIL_NULL_V(state, ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(f->get_position() != 0, ERR_FILE_CANT_READ); @@ -696,8 +696,8 @@ Error GLTFDocument::_encode_buffer_glb(Ref<GLTFState> state, const String &p_pat String filename = p_path.get_basename().get_file() + itos(i) + ".bin"; String path = p_path.get_base_dir() + "/" + filename; Error err; - FileAccessRef f = FileAccess::open(path, FileAccess::WRITE, &err); - if (!f) { + Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE, &err); + if (f.is_null()) { return err; } if (buffer_data.size() == 0) { @@ -705,7 +705,6 @@ Error GLTFDocument::_encode_buffer_glb(Ref<GLTFState> state, const String &p_pat } f->create(FileAccess::ACCESS_RESOURCES); f->store_buffer(buffer_data.ptr(), buffer_data.size()); - f->close(); gltf_buffer["uri"] = filename; gltf_buffer["byteLength"] = buffer_data.size(); buffers.push_back(gltf_buffer); @@ -729,8 +728,8 @@ Error GLTFDocument::_encode_buffer_bins(Ref<GLTFState> state, const String &p_pa String filename = p_path.get_basename().get_file() + itos(i) + ".bin"; String path = p_path.get_base_dir() + "/" + filename; Error err; - FileAccessRef f = FileAccess::open(path, FileAccess::WRITE, &err); - if (!f) { + Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE, &err); + if (f.is_null()) { return err; } if (buffer_data.size() == 0) { @@ -738,7 +737,6 @@ Error GLTFDocument::_encode_buffer_bins(Ref<GLTFState> state, const String &p_pa } f->create(FileAccess::ACCESS_RESOURCES); f->store_buffer(buffer_data.ptr(), buffer_data.size()); - f->close(); gltf_buffer["uri"] = filename; gltf_buffer["byteLength"] = buffer_data.size(); buffers.push_back(gltf_buffer); @@ -3021,7 +3019,7 @@ Error GLTFDocument::_serialize_images(Ref<GLTFState> state, const String &p_path String texture_dir = "textures"; String path = p_path.get_base_dir(); String new_texture_dir = path + "/" + texture_dir; - DirAccessRef da = DirAccess::open(path); + Ref<DirAccess> da = DirAccess::open(path); if (!da->dir_exists(new_texture_dir)) { da->make_dir(new_texture_dir); } @@ -3274,7 +3272,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { Dictionary mr; { Array arr; - const Color c = material->get_albedo().to_linear(); + const Color c = material->get_albedo().srgb_to_linear(); arr.push_back(c.r); arr.push_back(c.g); arr.push_back(c.b); @@ -3475,7 +3473,7 @@ Error GLTFDocument::_serialize_materials(Ref<GLTFState> state) { } if (material->get_feature(BaseMaterial3D::FEATURE_EMISSION)) { - const Color c = material->get_emission().to_srgb(); + const Color c = material->get_emission().linear_to_srgb(); Array arr; arr.push_back(c.r); arr.push_back(c.g); @@ -3557,7 +3555,7 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { if (sgm.has("diffuseFactor")) { const Array &arr = sgm["diffuseFactor"]; ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR); - const Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb(); + const Color c = Color(arr[0], arr[1], arr[2], arr[3]).linear_to_srgb(); spec_gloss->diffuse_factor = c; material->set_albedo(spec_gloss->diffuse_factor); } @@ -3588,7 +3586,7 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { if (mr.has("baseColorFactor")) { const Array &arr = mr["baseColorFactor"]; ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR); - const Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb(); + const Color c = Color(arr[0], arr[1], arr[2], arr[3]).linear_to_srgb(); material->set_albedo(c); } @@ -3655,7 +3653,7 @@ Error GLTFDocument::_parse_materials(Ref<GLTFState> state) { if (d.has("emissiveFactor")) { const Array &arr = d["emissiveFactor"]; ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR); - const Color c = Color(arr[0], arr[1], arr[2]).to_srgb(); + const Color c = Color(arr[0], arr[1], arr[2]).linear_to_srgb(); material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true); material->set_emission(c); @@ -3739,11 +3737,11 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re } for (int32_t y = 0; y < r_spec_gloss->spec_gloss_img->get_height(); y++) { for (int32_t x = 0; x < r_spec_gloss->spec_gloss_img->get_width(); x++) { - const Color specular_pixel = r_spec_gloss->spec_gloss_img->get_pixel(x, y).to_linear(); + const Color specular_pixel = r_spec_gloss->spec_gloss_img->get_pixel(x, y).srgb_to_linear(); Color specular = Color(specular_pixel.r, specular_pixel.g, specular_pixel.b); specular *= r_spec_gloss->specular_factor; Color diffuse = Color(1.0f, 1.0f, 1.0f); - diffuse *= r_spec_gloss->diffuse_img->get_pixel(x, y).to_linear(); + diffuse *= r_spec_gloss->diffuse_img->get_pixel(x, y).srgb_to_linear(); float metallic = 0.0f; Color base_color; spec_gloss_to_metal_base_color(specular, diffuse, base_color, metallic); @@ -3760,7 +3758,7 @@ void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Re mr.g = 1.0f - mr.g; rm_img->set_pixel(x, y, mr); if (r_spec_gloss->diffuse_img.is_valid()) { - r_spec_gloss->diffuse_img->set_pixel(x, y, base_color.to_srgb()); + r_spec_gloss->diffuse_img->set_pixel(x, y, base_color.linear_to_srgb()); } } } @@ -4628,7 +4626,7 @@ Error GLTFDocument::_parse_lights(Ref<GLTFState> state) { if (d.has("color")) { const Array &arr = d["color"]; ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR); - const Color c = Color(arr[0], arr[1], arr[2]).to_srgb(); + const Color c = Color(arr[0], arr[1], arr[2]).linear_to_srgb(); light->color = c; } if (d.has("intensity")) { @@ -6097,7 +6095,14 @@ void GLTFDocument::_import_animation(Ref<GLTFState> state, AnimationPlayer *ap, animation->set_length(length); - ap->add_animation(name, animation); + Ref<AnimationLibrary> library; + if (!ap->has_animation_library("")) { + library.instantiate(); + ap->add_animation_library("", library); + } else { + library = ap->get_animation_library(""); + } + library->add_animation(name, animation); } void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> state) { @@ -6588,9 +6593,9 @@ void GLTFDocument::_convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, } } -Error GLTFDocument::_parse(Ref<GLTFState> state, String p_path, FileAccess *f, int p_bake_fps) { +Error GLTFDocument::_parse(Ref<GLTFState> state, String p_path, Ref<FileAccess> f, int p_bake_fps) { Error err; - if (!f) { + if (f.is_null()) { return FAILED; } f->seek(0); @@ -6614,7 +6619,6 @@ Error GLTFDocument::_parse(Ref<GLTFState> state, String p_path, FileAccess *f, i ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR); state->json = json.get_data(); } - f->close(); if (!state->json.has("asset")) { return ERR_PARSE_ERROR; @@ -6703,8 +6707,8 @@ Error GLTFDocument::_serialize_file(Ref<GLTFState> state, const String p_path) { if (p_path.to_lower().ends_with("glb")) { err = _encode_buffer_glb(state, p_path); ERR_FAIL_COND_V(err != OK, err); - FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V(!f, FAILED); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err); + ERR_FAIL_COND_V(f.is_null(), FAILED); String json = Variant(state->json).to_json_string(); @@ -6741,18 +6745,15 @@ Error GLTFDocument::_serialize_file(Ref<GLTFState> state, const String p_path) { for (uint32_t pad_i = binary_data_length; pad_i < binary_chunk_length; pad_i++) { f->store_8(0); } - - f->close(); } else { err = _encode_buffer_bins(state, p_path); ERR_FAIL_COND_V(err != OK, err); - FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V(!f, FAILED); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err); + ERR_FAIL_COND_V(f.is_null(), FAILED); f->create(FileAccess::ACCESS_RESOURCES); String json = Variant(state->json).to_json_string(); f->store_string(json); - f->close(); } return err; } @@ -6927,9 +6928,10 @@ Error GLTFDocument::append_from_buffer(PackedByteArray p_bytes, String p_base_pa ERR_FAIL_COND_V(state.is_null(), FAILED); // TODO Add missing texture and missing .bin file paths to r_missing_deps 2021-09-10 fire Error err = FAILED; - state->use_named_skin_binds = - p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS; - FileAccessMemory *file_access = memnew(FileAccessMemory); + state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS; + + Ref<FileAccessMemory> file_access; + file_access.instantiate(); file_access->open_custom(p_bytes.ptr(), p_bytes.size()); err = _parse(state, p_base_path.get_base_dir(), file_access, p_bake_fps); ERR_FAIL_COND_V(err != OK, FAILED); @@ -7032,7 +7034,7 @@ Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> r_state, uint r_state->filename = p_path.get_file().get_basename(); r_state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS; Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN); ERR_FAIL_NULL_V(f, ERR_FILE_CANT_OPEN); String base_path = p_base_path; diff --git a/modules/gltf/gltf_document.h b/modules/gltf/gltf_document.h index 0b7664a616..19bc507a8d 100644 --- a/modules/gltf/gltf_document.h +++ b/modules/gltf/gltf_document.h @@ -196,7 +196,7 @@ private: Ref<Texture2D> _get_texture(Ref<GLTFState> state, const GLTFTextureIndex p_texture); Error _parse_json(const String &p_path, Ref<GLTFState> state); - Error _parse_glb(FileAccess *f, Ref<GLTFState> state); + Error _parse_glb(Ref<FileAccess> f, Ref<GLTFState> state); void _compute_node_heights(Ref<GLTFState> state); Error _parse_buffers(Ref<GLTFState> state, const String &p_base_path); Error _parse_buffer_views(Ref<GLTFState> state); @@ -457,7 +457,7 @@ public: void _convert_animation(Ref<GLTFState> state, AnimationPlayer *ap, String p_animation_track_name); Error _serialize(Ref<GLTFState> state, const String &p_path); - Error _parse(Ref<GLTFState> state, String p_path, FileAccess *f, int p_bake_fps); + Error _parse(Ref<GLTFState> state, String p_path, Ref<FileAccess> f, int p_bake_fps); }; #endif // GLTF_DOCUMENT_H diff --git a/modules/gltf/register_types.cpp b/modules/gltf/register_types.cpp index 4166f92502..b656788a10 100644 --- a/modules/gltf/register_types.cpp +++ b/modules/gltf/register_types.cpp @@ -60,7 +60,7 @@ static void _editor_init() { Ref<EditorSceneFormatImporterGLTF> import_gltf; import_gltf.instantiate(); - ResourceImporterScene::get_singleton()->add_importer(import_gltf); + ResourceImporterScene::add_importer(import_gltf); // Blend to glTF importer. @@ -72,7 +72,7 @@ static void _editor_init() { if (blend_enabled) { Ref<EditorSceneFormatImporterBlend> importer; importer.instantiate(); - ResourceImporterScene::get_singleton()->add_importer(importer); + ResourceImporterScene::add_importer(importer); Ref<EditorFileSystemImportFormatSupportQueryBlend> blend_import_query; blend_import_query.instantiate(); @@ -87,7 +87,7 @@ static void _editor_init() { EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "filesystem/import/fbx/fbx2gltf_path", PROPERTY_HINT_GLOBAL_FILE)); if (fbx_enabled) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (fbx2gltf_path.is_empty()) { WARN_PRINT("FBX file import is enabled, but no FBX2glTF path is configured. FBX files will not be imported."); } else if (!da->file_exists(fbx2gltf_path)) { @@ -95,7 +95,7 @@ static void _editor_init() { } else { Ref<EditorSceneFormatImporterFBX> importer; importer.instantiate(); - ResourceImporterScene::get_singleton()->add_importer(importer); + ResourceImporterScene::add_importer(importer); } } } diff --git a/modules/gridmap/editor/grid_map_editor_plugin.h b/modules/gridmap/editor/grid_map_editor_plugin.h index adb0da6e2c..3b29397502 100644 --- a/modules/gridmap/editor/grid_map_editor_plugin.h +++ b/modules/gridmap/editor/grid_map_editor_plugin.h @@ -62,21 +62,21 @@ class GridMapEditor : public VBoxContainer { DISPLAY_LIST }; - UndoRedo *undo_redo; + UndoRedo *undo_redo = nullptr; InputAction input_action = INPUT_NONE; - Panel *panel; - MenuButton *options; - SpinBox *floor; + Panel *panel = nullptr; + MenuButton *options = nullptr; + SpinBox *floor = nullptr; double accumulated_floor_delta = 0.0; - Button *mode_thumbnail; - Button *mode_list; - LineEdit *search_box; - HSlider *size_slider; - HBoxContainer *spatial_editor_hb; - ConfirmationDialog *settings_dialog; - VBoxContainer *settings_vbc; - SpinBox *settings_pick_distance; - Label *spin_box_label; + Button *mode_thumbnail = nullptr; + Button *mode_list = nullptr; + LineEdit *search_box = nullptr; + HSlider *size_slider = nullptr; + HBoxContainer *spatial_editor_hb = nullptr; + ConfirmationDialog *settings_dialog = nullptr; + VBoxContainer *settings_vbc = nullptr; + SpinBox *settings_pick_distance = nullptr; + Label *spin_box_label = nullptr; struct SetItem { Vector3i position; @@ -89,7 +89,7 @@ class GridMapEditor : public VBoxContainer { List<SetItem> set_items; GridMap *node = nullptr; - MeshLibrary *last_mesh_library; + MeshLibrary *last_mesh_library = nullptr; Transform3D grid_xform; Transform3D edit_grid_xform; @@ -173,15 +173,15 @@ class GridMapEditor : public VBoxContainer { }; - Node3DEditorPlugin *spatial_editor; + Node3DEditorPlugin *spatial_editor = nullptr; struct AreaDisplay { RID mesh; RID instance; }; - ItemList *mesh_library_palette; - Label *info_message; + ItemList *mesh_library_palette = nullptr; + Label *info_message = nullptr; void update_grid(); // Change which and where the grid is displayed void _draw_grids(const Vector3 &cell_size); @@ -234,7 +234,7 @@ public: class GridMapEditorPlugin : public EditorPlugin { GDCLASS(GridMapEditorPlugin, EditorPlugin); - GridMapEditor *grid_map_editor; + GridMapEditor *grid_map_editor = nullptr; protected: void _notification(int p_what); diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp index 996bbfadd1..eca689e87a 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, FileAccess *f, bool p_force_linear, float p_scale) { +Error ImageLoaderHDR::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, 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 + "."); @@ -132,7 +132,7 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force ptr[2] * exp / 255.0); if (p_force_linear) { - c = c.to_linear(); + c = c.srgb_to_linear(); } *(uint32_t *)ptr = c.to_rgbe9995(); diff --git a/modules/hdr/image_loader_hdr.h b/modules/hdr/image_loader_hdr.h index 0213fdbcb2..f2d53cc206 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, FileAccess *f, bool p_force_linear, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderHDR(); }; diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp index e8c66ab9da..51358876a4 100644 --- a/modules/jpg/image_loader_jpegd.cpp +++ b/modules/jpg/image_loader_jpegd.cpp @@ -103,7 +103,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, FileAccess *f, bool p_force_linear, float p_scale) { +Error ImageLoaderJPG::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, 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); @@ -113,8 +113,6 @@ Error ImageLoaderJPG::load_image(Ref<Image> p_image, FileAccess *f, bool p_force f->get_buffer(&w[0], src_image_len); - f->close(); - Error err = jpeg_load_image_from_buffer(p_image.ptr(), w, src_image_len); return err; diff --git a/modules/jpg/image_loader_jpegd.h b/modules/jpg/image_loader_jpegd.h index 8e64f6fba7..de9700faec 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, FileAccess *f, bool p_force_linear, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderJPG(); }; diff --git a/modules/mbedtls/crypto_mbedtls.cpp b/modules/mbedtls/crypto_mbedtls.cpp index ea6b6d8233..e62581ab40 100644 --- a/modules/mbedtls/crypto_mbedtls.cpp +++ b/modules/mbedtls/crypto_mbedtls.cpp @@ -55,14 +55,13 @@ Error CryptoKeyMbedTLS::load(String p_path, bool p_public_only) { ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Key is in use"); PackedByteArray out; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot open CryptoKeyMbedTLS file '" + p_path + "'."); uint64_t flen = f->get_length(); out.resize(flen + 1); f->get_buffer(out.ptrw(), flen); out.write[flen] = 0; // string terminator - memdelete(f); int ret = 0; if (p_public_only) { @@ -79,8 +78,8 @@ Error CryptoKeyMbedTLS::load(String p_path, bool p_public_only) { } Error CryptoKeyMbedTLS::save(String p_path, bool p_public_only) { - FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot save CryptoKeyMbedTLS file '" + p_path + "'."); unsigned char w[16000]; memset(w, 0, sizeof(w)); @@ -92,14 +91,12 @@ Error CryptoKeyMbedTLS::save(String p_path, bool p_public_only) { ret = mbedtls_pk_write_key_pem(&pkey, w, sizeof(w)); } if (ret != 0) { - memdelete(f); mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize anything we might have written. ERR_FAIL_V_MSG(FAILED, "Error writing key '" + itos(ret) + "'."); } size_t len = strlen((char *)w); f->store_buffer(w, len); - memdelete(f); mbedtls_platform_zeroize(w, sizeof(w)); // Zeroize temporary buffer. return OK; } @@ -143,14 +140,13 @@ Error X509CertificateMbedTLS::load(String p_path) { ERR_FAIL_COND_V_MSG(locks, ERR_ALREADY_IN_USE, "Certificate is in use"); PackedByteArray out; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot open X509CertificateMbedTLS file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot open X509CertificateMbedTLS file '" + p_path + "'."); uint64_t flen = f->get_length(); out.resize(flen + 1); f->get_buffer(out.ptrw(), flen); out.write[flen] = 0; // string terminator - memdelete(f); int ret = mbedtls_x509_crt_parse(&cert, out.ptr(), out.size()); ERR_FAIL_COND_V_MSG(ret, FAILED, "Error parsing some certificates: " + itos(ret)); @@ -167,8 +163,8 @@ Error X509CertificateMbedTLS::load_from_memory(const uint8_t *p_buffer, int p_le } Error X509CertificateMbedTLS::save(String p_path) { - FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!f, ERR_INVALID_PARAMETER, "Cannot save X509CertificateMbedTLS file '" + p_path + "'."); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_INVALID_PARAMETER, "Cannot save X509CertificateMbedTLS file '" + p_path + "'."); mbedtls_x509_crt *crt = &cert; while (crt) { @@ -176,14 +172,12 @@ Error X509CertificateMbedTLS::save(String p_path) { size_t wrote = 0; int ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT, cert.raw.p, cert.raw.len, w, sizeof(w), &wrote); if (ret != 0 || wrote == 0) { - memdelete(f); ERR_FAIL_V_MSG(FAILED, "Error writing certificate '" + itos(ret) + "'."); } f->store_buffer(w, wrote - 1); // don't write the string terminator crt = crt->next; } - memdelete(f); return OK; } diff --git a/modules/mbedtls/packet_peer_mbed_dtls.cpp b/modules/mbedtls/packet_peer_mbed_dtls.cpp index 2a5eaa0109..ddc2e945a7 100644 --- a/modules/mbedtls/packet_peer_mbed_dtls.cpp +++ b/modules/mbedtls/packet_peer_mbed_dtls.cpp @@ -35,11 +35,11 @@ #include "core/io/stream_peer_ssl.h" int PacketPeerMbedDTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) { - if (buf == nullptr || len <= 0) { + if (buf == nullptr || len == 0) { return 0; } - PacketPeerMbedDTLS *sp = (PacketPeerMbedDTLS *)ctx; + PacketPeerMbedDTLS *sp = static_cast<PacketPeerMbedDTLS *>(ctx); ERR_FAIL_COND_V(sp == nullptr, 0); @@ -53,11 +53,11 @@ int PacketPeerMbedDTLS::bio_send(void *ctx, const unsigned char *buf, size_t len } int PacketPeerMbedDTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { - if (buf == nullptr || len <= 0) { + if (buf == nullptr || len == 0) { return 0; } - PacketPeerMbedDTLS *sp = (PacketPeerMbedDTLS *)ctx; + PacketPeerMbedDTLS *sp = static_cast<PacketPeerMbedDTLS *>(ctx); ERR_FAIL_COND_V(sp == nullptr, 0); diff --git a/modules/mbedtls/stream_peer_mbedtls.cpp b/modules/mbedtls/stream_peer_mbedtls.cpp index 05a57607cd..1818048877 100644 --- a/modules/mbedtls/stream_peer_mbedtls.cpp +++ b/modules/mbedtls/stream_peer_mbedtls.cpp @@ -34,11 +34,11 @@ #include "core/io/stream_peer_tcp.h" int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) { - if (buf == nullptr || len <= 0) { + if (buf == nullptr || len == 0) { return 0; } - StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; + StreamPeerMbedTLS *sp = static_cast<StreamPeerMbedTLS *>(ctx); ERR_FAIL_COND_V(sp == nullptr, 0); @@ -54,11 +54,11 @@ int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) } int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) { - if (buf == nullptr || len <= 0) { + if (buf == nullptr || len == 0) { return 0; } - StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx; + StreamPeerMbedTLS *sp = static_cast<StreamPeerMbedTLS *>(ctx); ERR_FAIL_COND_V(sp == nullptr, 0); diff --git a/modules/minimp3/resource_importer_mp3.cpp b/modules/minimp3/resource_importer_mp3.cpp index 0e0da806bf..6cd710e792 100644 --- a/modules/minimp3/resource_importer_mp3.cpp +++ b/modules/minimp3/resource_importer_mp3.cpp @@ -75,9 +75,8 @@ Error ResourceImporterMP3::import(const String &p_source_file, const String &p_s bool loop = p_options["loop"]; float loop_offset = p_options["loop_offset"]; - FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ); - - ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); + Ref<FileAccess> f = FileAccess::open(p_source_file, FileAccess::READ); + ERR_FAIL_COND_V(f.is_null(), ERR_CANT_OPEN); uint64_t len = f->get_length(); @@ -87,8 +86,6 @@ Error ResourceImporterMP3::import(const String &p_source_file, const String &p_s f->get_buffer(w, len); - memdelete(f); - Ref<AudioStreamMP3> mp3_stream; mp3_stream.instantiate(); diff --git a/modules/mono/class_db_api_json.cpp b/modules/mono/class_db_api_json.cpp index 5884a24454..9253f105bb 100644 --- a/modules/mono/class_db_api_json.cpp +++ b/modules/mono/class_db_api_json.cpp @@ -238,11 +238,10 @@ void class_db_api_to_json(const String &p_output_file, ClassDB::APIType p_api) { } } - FileAccessRef f = FileAccess::open(p_output_file, FileAccess::WRITE); - ERR_FAIL_COND_MSG(!f, "Cannot open file '" + p_output_file + "'."); + Ref<FileAccess> f = FileAccess::open(p_output_file, FileAccess::WRITE); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file '" + p_output_file + "'."); JSON json; f->store_string(json.stringify(classes_dict, "\t")); - f->close(); print_line(String() + "ClassDB API JSON written to: " + ProjectSettings::get_singleton()->globalize_path(p_output_file)); } diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 8acd119880..02aebb3805 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -3641,20 +3641,18 @@ Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_r } #endif - Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); - ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'."); + { + Error err; + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); + ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'."); - file->store_string(source); + file->store_string(source); - if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { - memdelete(file); - return ERR_CANT_CREATE; + if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { + return ERR_CANT_CREATE; + } } - file->close(); - memdelete(file); - #ifdef TOOLS_ENABLED if (ScriptServer::is_reload_scripts_on_save_enabled()) { CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false); diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index d8f5b814e4..2a93c15282 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -1035,8 +1035,8 @@ void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) { Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) { ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V(!da, ERR_CANT_CREATE); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE); if (!DirAccess::exists(p_proj_dir)) { Error err = da->make_dir_recursive(p_proj_dir); @@ -1170,8 +1170,8 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) { Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) { ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V(!da, ERR_CANT_CREATE); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE); if (!DirAccess::exists(p_proj_dir)) { Error err = da->make_dir_recursive(p_proj_dir); @@ -1280,8 +1280,8 @@ Error BindingsGenerator::generate_cs_api(const String &p_output_dir) { String output_dir = path::abspath(path::realpath(p_output_dir)); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V(!da, ERR_CANT_CREATE); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE); if (!DirAccess::exists(output_dir)) { Error err = da->make_dir_recursive(output_dir); @@ -2255,12 +2255,10 @@ uint32_t BindingsGenerator::get_version() { } Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) { - FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE); - - ERR_FAIL_COND_V_MSG(!file, ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'."); + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(file.is_null(), ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'."); file->store_string(p_content.as_string()); - file->close(); return OK; } diff --git a/modules/mono/editor/code_completion.cpp b/modules/mono/editor/code_completion.cpp index 3a41b3f6f5..79015686c3 100644 --- a/modules/mono/editor/code_completion.cpp +++ b/modules/mono/editor/code_completion.cpp @@ -144,7 +144,7 @@ PackedStringArray get_code_completion(CompletionKind p_kind, const String &p_scr } } break; case CompletionKind::SCENE_PATHS: { - DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES); List<String> directories; directories.push_back(dir_access->get_current_dir()); diff --git a/modules/mono/glue/arguments_vector.h b/modules/mono/glue/arguments_vector.h index 7c991d87a4..4405809887 100644 --- a/modules/mono/glue/arguments_vector.h +++ b/modules/mono/glue/arguments_vector.h @@ -37,7 +37,7 @@ template <typename T, int POOL_SIZE = 5> struct ArgumentsVector { private: T pool[POOL_SIZE]; - T *_ptr; + T *_ptr = nullptr; int size; ArgumentsVector() = delete; diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index 7c2cb2e260..cb2b60fcce 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -76,7 +76,7 @@ String _get_mono_user_dir() { exe_dir = exe_dir.plus_file("../../..").simplify_path(); } - DirAccessRef d = DirAccess::create_for_path(exe_dir); + Ref<DirAccess> d = DirAccess::create_for_path(exe_dir); if (d->file_exists("._sc_") || d->file_exists("_sc_")) { // contain yourself diff --git a/modules/mono/managed_callable.h b/modules/mono/managed_callable.h index ea7231f43b..d50a8a7b08 100644 --- a/modules/mono/managed_callable.h +++ b/modules/mono/managed_callable.h @@ -43,7 +43,7 @@ class ManagedCallable : public CallableCustom { friend class CSharpLanguage; MonoGCHandleData delegate_handle; - GDMonoMethod *delegate_invoke; + GDMonoMethod *delegate_invoke = nullptr; #ifdef GD_MONO_HOT_RELOAD SelfList<ManagedCallable> self_instance = this; diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index 424b74906f..e98ce8f6c1 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -643,7 +643,7 @@ bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const // Create destination directory if needed if (!DirAccess::exists(dst_dir)) { - DirAccessRef da = DirAccess::create_for_path(dst_dir); + Ref<DirAccess> da = DirAccess::create_for_path(dst_dir); Error err = da->make_dir_recursive(dst_dir); if (err != OK) { @@ -652,7 +652,7 @@ bool GDMono::copy_prebuilt_api_assembly(ApiAssemblyInfo::Type p_api_type, const } } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); String xml_file = assembly_name + ".xml"; if (da->copy(src_dir.plus_file(xml_file), dst_dir.plus_file(xml_file)) != OK) { diff --git a/modules/mono/mono_gd/gd_mono.h b/modules/mono/mono_gd/gd_mono.h index aab0b31c37..51fd0f8483 100644 --- a/modules/mono/mono_gd/gd_mono.h +++ b/modules/mono/mono_gd/gd_mono.h @@ -94,16 +94,16 @@ private: UnhandledExceptionPolicy unhandled_exception_policy; - MonoDomain *root_domain; - MonoDomain *scripts_domain; + MonoDomain *root_domain = nullptr; + MonoDomain *scripts_domain = nullptr; HashMap<int32_t, HashMap<String, GDMonoAssembly *>> assemblies; - GDMonoAssembly *corlib_assembly; - GDMonoAssembly *project_assembly; + GDMonoAssembly *corlib_assembly = nullptr; + GDMonoAssembly *project_assembly = nullptr; #ifdef TOOLS_ENABLED - GDMonoAssembly *tools_assembly; - GDMonoAssembly *tools_project_editor_assembly; + GDMonoAssembly *tools_assembly = nullptr; + GDMonoAssembly *tools_project_editor_assembly = nullptr; #endif LoadedApiAssembly core_api_assembly; @@ -150,7 +150,7 @@ private: void _init_godot_api_hashes(); void _init_exception_policy(); - GDMonoLog *gdmono_log; + GDMonoLog *gdmono_log = nullptr; #if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED) MonoRegInfo mono_reg_info; @@ -250,7 +250,7 @@ public: namespace gdmono { class ScopeDomain { - MonoDomain *prev_domain; + MonoDomain *prev_domain = nullptr; public: ScopeDomain(MonoDomain *p_domain) { @@ -270,7 +270,7 @@ public: }; class ScopeExitDomainUnload { - MonoDomain *domain; + MonoDomain *domain = nullptr; public: ScopeExitDomainUnload(MonoDomain *p_domain) : diff --git a/modules/mono/mono_gd/gd_mono_assembly.h b/modules/mono/mono_gd/gd_mono_assembly.h index b25d773be7..a96357b082 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.h +++ b/modules/mono/mono_gd/gd_mono_assembly.h @@ -68,8 +68,8 @@ class GDMonoAssembly { }; String name; - MonoImage *image; - MonoAssembly *assembly; + MonoImage *image = nullptr; + MonoAssembly *assembly = nullptr; bool attrs_fetched = false; MonoCustomAttrInfo *attributes = nullptr; diff --git a/modules/mono/mono_gd/gd_mono_cache.h b/modules/mono/mono_gd/gd_mono_cache.h index 49f47b0a15..4000342c94 100644 --- a/modules/mono/mono_gd/gd_mono_cache.h +++ b/modules/mono/mono_gd/gd_mono_cache.h @@ -41,91 +41,91 @@ struct CachedData { // corlib classes // Let's use the no-namespace format for these too - GDMonoClass *class_MonoObject; // object - GDMonoClass *class_bool; // bool - GDMonoClass *class_int8_t; // sbyte - GDMonoClass *class_int16_t; // short - GDMonoClass *class_int32_t; // int - GDMonoClass *class_int64_t; // long - GDMonoClass *class_uint8_t; // byte - GDMonoClass *class_uint16_t; // ushort - GDMonoClass *class_uint32_t; // uint - GDMonoClass *class_uint64_t; // ulong - GDMonoClass *class_float; // float - GDMonoClass *class_double; // double - GDMonoClass *class_String; // string - GDMonoClass *class_IntPtr; // System.IntPtr - - GDMonoClass *class_System_Collections_IEnumerable; - GDMonoClass *class_System_Collections_ICollection; - GDMonoClass *class_System_Collections_IDictionary; + GDMonoClass *class_MonoObject = nullptr; // object + GDMonoClass *class_bool = nullptr; // bool + GDMonoClass *class_int8_t = nullptr; // sbyte + GDMonoClass *class_int16_t = nullptr; // short + GDMonoClass *class_int32_t = nullptr; // int + GDMonoClass *class_int64_t = nullptr; // long + GDMonoClass *class_uint8_t = nullptr; // byte + GDMonoClass *class_uint16_t = nullptr; // ushort + GDMonoClass *class_uint32_t = nullptr; // uint + GDMonoClass *class_uint64_t = nullptr; // ulong + GDMonoClass *class_float = nullptr; // float + GDMonoClass *class_double = nullptr; // double + GDMonoClass *class_String = nullptr; // string + GDMonoClass *class_IntPtr = nullptr; // System.IntPtr + + GDMonoClass *class_System_Collections_IEnumerable = nullptr; + GDMonoClass *class_System_Collections_ICollection = nullptr; + GDMonoClass *class_System_Collections_IDictionary = nullptr; #ifdef DEBUG_ENABLED - GDMonoClass *class_System_Diagnostics_StackTrace; + GDMonoClass *class_System_Diagnostics_StackTrace = nullptr; GDMonoMethodThunkR<MonoArray *, MonoObject *> methodthunk_System_Diagnostics_StackTrace_GetFrames; - GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_bool; - GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_Exception_bool; + GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_bool = nullptr; + GDMonoMethod *method_System_Diagnostics_StackTrace_ctor_Exception_bool = nullptr; #endif - GDMonoClass *class_KeyNotFoundException; + GDMonoClass *class_KeyNotFoundException = nullptr; - MonoClass *rawclass_Dictionary; + MonoClass *rawclass_Dictionary = nullptr; // ----------------------------------------------- - GDMonoClass *class_Vector2; - GDMonoClass *class_Vector2i; - GDMonoClass *class_Rect2; - GDMonoClass *class_Rect2i; - GDMonoClass *class_Transform2D; - GDMonoClass *class_Vector3; - GDMonoClass *class_Vector3i; - GDMonoClass *class_Basis; - GDMonoClass *class_Quaternion; - GDMonoClass *class_Transform3D; - GDMonoClass *class_AABB; - GDMonoClass *class_Color; - GDMonoClass *class_Plane; - GDMonoClass *class_StringName; - GDMonoClass *class_NodePath; - GDMonoClass *class_RID; - GDMonoClass *class_GodotObject; - GDMonoClass *class_GodotResource; - GDMonoClass *class_Node; - GDMonoClass *class_Control; - GDMonoClass *class_Node3D; - GDMonoClass *class_WeakRef; - GDMonoClass *class_Callable; - GDMonoClass *class_SignalInfo; - GDMonoClass *class_Array; - GDMonoClass *class_Dictionary; - GDMonoClass *class_MarshalUtils; - GDMonoClass *class_ISerializationListener; + GDMonoClass *class_Vector2 = nullptr; + GDMonoClass *class_Vector2i = nullptr; + GDMonoClass *class_Rect2 = nullptr; + GDMonoClass *class_Rect2i = nullptr; + GDMonoClass *class_Transform2D = nullptr; + GDMonoClass *class_Vector3 = nullptr; + GDMonoClass *class_Vector3i = nullptr; + GDMonoClass *class_Basis = nullptr; + GDMonoClass *class_Quaternion = nullptr; + GDMonoClass *class_Transform3D = nullptr; + GDMonoClass *class_AABB = nullptr; + GDMonoClass *class_Color = nullptr; + GDMonoClass *class_Plane = nullptr; + GDMonoClass *class_StringName = nullptr; + GDMonoClass *class_NodePath = nullptr; + GDMonoClass *class_RID = nullptr; + GDMonoClass *class_GodotObject = nullptr; + GDMonoClass *class_GodotResource = nullptr; + GDMonoClass *class_Node = nullptr; + GDMonoClass *class_Control = nullptr; + GDMonoClass *class_Node3D = nullptr; + GDMonoClass *class_WeakRef = nullptr; + GDMonoClass *class_Callable = nullptr; + GDMonoClass *class_SignalInfo = nullptr; + GDMonoClass *class_Array = nullptr; + GDMonoClass *class_Dictionary = nullptr; + GDMonoClass *class_MarshalUtils = nullptr; + GDMonoClass *class_ISerializationListener = nullptr; #ifdef DEBUG_ENABLED - GDMonoClass *class_DebuggingUtils; + GDMonoClass *class_DebuggingUtils = nullptr; GDMonoMethodThunk<MonoObject *, MonoString **, int *, MonoString **> methodthunk_DebuggingUtils_GetStackFrameInfo; #endif - GDMonoClass *class_ExportAttribute; - GDMonoField *field_ExportAttribute_hint; - GDMonoField *field_ExportAttribute_hintString; - GDMonoClass *class_SignalAttribute; - GDMonoClass *class_ToolAttribute; - GDMonoClass *class_AnyPeerAttribute; - GDMonoClass *class_AuthorityAttribute; - GDMonoClass *class_GodotMethodAttribute; - GDMonoField *field_GodotMethodAttribute_methodName; - GDMonoClass *class_ScriptPathAttribute; - GDMonoField *field_ScriptPathAttribute_path; - GDMonoClass *class_AssemblyHasScriptsAttribute; - GDMonoField *field_AssemblyHasScriptsAttribute_requiresLookup; - GDMonoField *field_AssemblyHasScriptsAttribute_scriptTypes; - - GDMonoField *field_GodotObject_ptr; - GDMonoField *field_StringName_ptr; - GDMonoField *field_NodePath_ptr; - GDMonoField *field_Image_ptr; - GDMonoField *field_RID_ptr; + GDMonoClass *class_ExportAttribute = nullptr; + GDMonoField *field_ExportAttribute_hint = nullptr; + GDMonoField *field_ExportAttribute_hintString = nullptr; + GDMonoClass *class_SignalAttribute = nullptr; + GDMonoClass *class_ToolAttribute = nullptr; + GDMonoClass *class_AnyPeerAttribute = nullptr; + GDMonoClass *class_AuthorityAttribute = nullptr; + GDMonoClass *class_GodotMethodAttribute = nullptr; + GDMonoField *field_GodotMethodAttribute_methodName = nullptr; + GDMonoClass *class_ScriptPathAttribute = nullptr; + GDMonoField *field_ScriptPathAttribute_path = nullptr; + GDMonoClass *class_AssemblyHasScriptsAttribute = nullptr; + GDMonoField *field_AssemblyHasScriptsAttribute_requiresLookup = nullptr; + GDMonoField *field_AssemblyHasScriptsAttribute_scriptTypes = nullptr; + + GDMonoField *field_GodotObject_ptr = nullptr; + GDMonoField *field_StringName_ptr = nullptr; + GDMonoField *field_NodePath_ptr = nullptr; + GDMonoField *field_Image_ptr = nullptr; + GDMonoField *field_RID_ptr = nullptr; GDMonoMethodThunk<MonoObject *> methodthunk_GodotObject_Dispose; GDMonoMethodThunkR<Array *, MonoObject *> methodthunk_Array_GetPtr; diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h index bfb5797d4b..b32d561f61 100644 --- a/modules/mono/mono_gd/gd_mono_class.h +++ b/modules/mono/mono_gd/gd_mono_class.h @@ -70,11 +70,11 @@ class GDMonoClass { StringName namespace_name; StringName class_name; - MonoClass *mono_class; - GDMonoAssembly *assembly; + MonoClass *mono_class = nullptr; + GDMonoAssembly *assembly = nullptr; bool attrs_fetched; - MonoCustomAttrInfo *attributes; + MonoCustomAttrInfo *attributes = nullptr; // This contains both the original method names and remapped method names from the native Godot identifiers to the C# functions. // Most method-related functions refer to this and it's possible this is unintuitive for outside users; this may be a prime location for refactoring or renaming. diff --git a/modules/mono/mono_gd/gd_mono_field.h b/modules/mono/mono_gd/gd_mono_field.h index abcdef378c..87ef245f3f 100644 --- a/modules/mono/mono_gd/gd_mono_field.h +++ b/modules/mono/mono_gd/gd_mono_field.h @@ -36,14 +36,14 @@ #include "i_mono_class_member.h" class GDMonoField : public IMonoClassMember { - GDMonoClass *owner; - MonoClassField *mono_field; + GDMonoClass *owner = nullptr; + MonoClassField *mono_field = nullptr; StringName name; ManagedType type; bool attrs_fetched; - MonoCustomAttrInfo *attributes; + MonoCustomAttrInfo *attributes = nullptr; public: virtual GDMonoClass *get_enclosing_class() const final { return owner; } diff --git a/modules/mono/mono_gd/gd_mono_log.cpp b/modules/mono/mono_gd/gd_mono_log.cpp index 01a6521876..6ea3c5539e 100644 --- a/modules/mono/mono_gd/gd_mono_log.cpp +++ b/modules/mono/mono_gd/gd_mono_log.cpp @@ -77,23 +77,20 @@ static String make_text(const char *log_domain, const char *log_level, const cha } void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level, const char *message, mono_bool fatal, void *) { - FileAccess *f = GDMonoLog::get_singleton()->log_file; - if (GDMonoLog::get_singleton()->log_level_id >= get_log_level_id(log_level)) { String text = make_text(log_domain, log_level, message); text += "\n"; - f->seek_end(); - f->store_string(text); + GDMonoLog::get_singleton()->log_file->seek_end(); + GDMonoLog::get_singleton()->log_file->store_string(text); } if (fatal) { String text = make_text(log_domain, log_level, message); ERR_PRINT("Mono: FATAL ERROR '" + text + "', ABORTING! Logfile: '" + GDMonoLog::get_singleton()->log_file_path + "'."); // Make sure to flush before aborting - f->flush(); - f->close(); - memdelete(f); + GDMonoLog::get_singleton()->log_file->flush(); + GDMonoLog::get_singleton()->log_file.unref(); abort(); } @@ -101,8 +98,8 @@ void GDMonoLog::mono_log_callback(const char *log_domain, const char *log_level, bool GDMonoLog::_try_create_logs_dir(const String &p_logs_dir) { if (!DirAccess::exists(p_logs_dir)) { - DirAccessRef diraccess = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V(!diraccess, false); + Ref<DirAccess> diraccess = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V(diraccess.is_null(), false); Error logs_mkdir_err = diraccess->make_dir_recursive(p_logs_dir); ERR_FAIL_COND_V_MSG(logs_mkdir_err != OK, false, "Failed to create mono logs directory."); } @@ -113,8 +110,8 @@ bool GDMonoLog::_try_create_logs_dir(const String &p_logs_dir) { void GDMonoLog::_delete_old_log_files(const String &p_logs_dir) { static const uint64_t MAX_SECS = 5 * 86400; // 5 days - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND(!da); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND(da.is_null()); Error err = da->change_dir(p_logs_dir); ERR_FAIL_COND_MSG(err != OK, "Cannot change directory to '" + p_logs_dir + "'."); @@ -170,7 +167,7 @@ void GDMonoLog::initialize() { log_file_path = logs_dir.plus_file(log_file_name); log_file = FileAccess::open(log_file_path, FileAccess::WRITE); - if (!log_file) { + if (log_file.is_null()) { ERR_PRINT("Mono: Cannot create log file at: " + log_file_path); } } @@ -178,7 +175,7 @@ void GDMonoLog::initialize() { mono_trace_set_level_string(log_level.get_data()); log_level_id = get_log_level_id(log_level.get_data()); - if (log_file) { + if (log_file.is_valid()) { OS::get_singleton()->print("Mono: Log file is: '%s'\n", log_file_path.utf8().get_data()); mono_trace_set_log_handler(mono_log_callback, this); } else { @@ -192,11 +189,6 @@ GDMonoLog::GDMonoLog() { GDMonoLog::~GDMonoLog() { singleton = nullptr; - - if (log_file) { - log_file->close(); - memdelete(log_file); - } } #else diff --git a/modules/mono/mono_gd/gd_mono_log.h b/modules/mono/mono_gd/gd_mono_log.h index 9aa67a09e2..9fc35f8e31 100644 --- a/modules/mono/mono_gd/gd_mono_log.h +++ b/modules/mono/mono_gd/gd_mono_log.h @@ -48,7 +48,7 @@ class GDMonoLog { #ifdef GD_MONO_LOG_ENABLED int log_level_id = -1; - FileAccess *log_file = nullptr; + Ref<FileAccess> log_file; String log_file_path; bool _try_create_logs_dir(const String &p_logs_dir); diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h index 20d4743e5c..eb33c6119e 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ b/modules/mono/mono_gd/gd_mono_marshal.h @@ -196,14 +196,14 @@ PackedVector3Array mono_array_to_PackedVector3Array(MonoArray *p_array); #pragma pack(push, 1) struct M_Callable { - MonoObject *target; - MonoObject *method_string_name; - MonoDelegate *delegate; + MonoObject *target = nullptr; + MonoObject *method_string_name = nullptr; + MonoDelegate *delegate = nullptr; }; struct M_SignalInfo { - MonoObject *owner; - MonoObject *name_string_name; + MonoObject *owner = nullptr; + MonoObject *name_string_name = nullptr; }; #pragma pack(pop) diff --git a/modules/mono/mono_gd/gd_mono_method.h b/modules/mono/mono_gd/gd_mono_method.h index 6e87a60ee2..be11ef5bfe 100644 --- a/modules/mono/mono_gd/gd_mono_method.h +++ b/modules/mono/mono_gd/gd_mono_method.h @@ -54,7 +54,7 @@ class GDMonoMethod : public IMonoClassMember { friend class GDMonoClass; - MonoMethod *mono_method; + MonoMethod *mono_method = nullptr; public: virtual GDMonoClass *get_enclosing_class() const final; diff --git a/modules/mono/mono_gd/gd_mono_property.h b/modules/mono/mono_gd/gd_mono_property.h index 003bcf05e1..6fc681aeb5 100644 --- a/modules/mono/mono_gd/gd_mono_property.h +++ b/modules/mono/mono_gd/gd_mono_property.h @@ -36,14 +36,14 @@ #include "i_mono_class_member.h" class GDMonoProperty : public IMonoClassMember { - GDMonoClass *owner; - MonoProperty *mono_property; + GDMonoClass *owner = nullptr; + MonoProperty *mono_property = nullptr; StringName name; ManagedType type; bool attrs_fetched; - MonoCustomAttrInfo *attributes; + MonoCustomAttrInfo *attributes = nullptr; unsigned int param_buffer_size; diff --git a/modules/mono/mono_gd/gd_mono_wasm_m2n.h b/modules/mono/mono_gd/gd_mono_wasm_m2n.h index 68299aa984..83e2750e5a 100644 --- a/modules/mono/mono_gd/gd_mono_wasm_m2n.h +++ b/modules/mono/mono_gd/gd_mono_wasm_m2n.h @@ -47,11 +47,11 @@ struct Mono_InterpMethodArguments { size_t ilen; void **iargs; size_t flen; - double *fargs; + double *fargs = nullptr; void **retval; size_t is_float_ret; //#ifdef TARGET_WASM - void *sig; + void *sig = nullptr; //#endif }; } // extern "C" diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h index 1a62f36625..532aa3e327 100644 --- a/modules/mono/signal_awaiter_utils.h +++ b/modules/mono/signal_awaiter_utils.h @@ -68,7 +68,7 @@ public: }; class EventSignalCallable : public CallableCustom { - Object *owner; + Object *owner = nullptr; const CSharpScript::EventSignal *event_signal; public: diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp index dd29299330..e6975611d2 100644 --- a/modules/mono/utils/string_utils.cpp +++ b/modules/mono/utils/string_utils.cpp @@ -167,15 +167,13 @@ String escape_csharp_keyword(const String &p_name) { Error read_all_file_utf8(const String &p_path, String &r_content) { Vector<uint8_t> sourcef; Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot open file '" + p_path + "'."); uint64_t len = f->get_length(); sourcef.resize(len + 1); uint8_t *w = sourcef.ptrw(); uint64_t r = f->get_buffer(w, len); - f->close(); - memdelete(f); ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); w[len] = 0; diff --git a/modules/navigation/editor/navigation_mesh_editor_plugin.h b/modules/navigation/editor/navigation_mesh_editor_plugin.h index 3c3e804fd2..bc9e4185b7 100644 --- a/modules/navigation/editor/navigation_mesh_editor_plugin.h +++ b/modules/navigation/editor/navigation_mesh_editor_plugin.h @@ -42,14 +42,14 @@ class NavigationMeshEditor : public Control { GDCLASS(NavigationMeshEditor, Control); - AcceptDialog *err_dialog; + AcceptDialog *err_dialog = nullptr; - HBoxContainer *bake_hbox; - Button *button_bake; - Button *button_reset; - Label *bake_info; + HBoxContainer *bake_hbox = nullptr; + Button *button_bake = nullptr; + Button *button_reset = nullptr; + Label *bake_info = nullptr; - NavigationRegion3D *node; + NavigationRegion3D *node = nullptr; void _bake_pressed(); void _clear_pressed(); @@ -68,7 +68,7 @@ public: class NavigationMeshEditorPlugin : public EditorPlugin { GDCLASS(NavigationMeshEditorPlugin, EditorPlugin); - NavigationMeshEditor *navigation_mesh_editor; + NavigationMeshEditor *navigation_mesh_editor = nullptr; public: virtual String get_name() const override { return "NavigationMesh"; } diff --git a/modules/navigation/godot_navigation_server.cpp b/modules/navigation/godot_navigation_server.cpp index f3da85063a..ca4fc4f628 100644 --- a/modules/navigation/godot_navigation_server.cpp +++ b/modules/navigation/godot_navigation_server.cpp @@ -109,9 +109,7 @@ } \ void GodotNavigationServer::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3) -GodotNavigationServer::GodotNavigationServer() : - NavigationServer3D() { -} +GodotNavigationServer::GodotNavigationServer() {} GodotNavigationServer::~GodotNavigationServer() { flush_queries(); diff --git a/modules/navigation/godot_navigation_server.h b/modules/navigation/godot_navigation_server.h index c555a358db..7ad5e2d501 100644 --- a/modules/navigation/godot_navigation_server.h +++ b/modules/navigation/godot_navigation_server.h @@ -45,16 +45,16 @@ #define MERGE_INTERNAL(A, B) A##B #define MERGE(A, B) MERGE_INTERNAL(A, B) -#define COMMAND_1(F_NAME, T_0, D_0) \ - virtual void F_NAME(T_0 D_0) const; \ +#define COMMAND_1(F_NAME, T_0, D_0) \ + virtual void F_NAME(T_0 D_0) const override; \ void MERGE(_cmd_, F_NAME)(T_0 D_0) -#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \ - virtual void F_NAME(T_0 D_0, T_1 D_1) const; \ +#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \ + virtual void F_NAME(T_0 D_0, T_1 D_1) const override; \ void MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1) -#define COMMAND_4_DEF(F_NAME, T_0, D_0, T_1, D_1, T_2, D_2, T_3, D_3, D_3_DEF) \ - virtual void F_NAME(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3 = D_3_DEF) const; \ +#define COMMAND_4_DEF(F_NAME, T_0, D_0, T_1, D_1, T_2, D_2, T_3, D_3, D_3_DEF) \ + virtual void F_NAME(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3 = D_3_DEF) const override; \ void MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1, T_2 D_2, T_3 D_3) class GodotNavigationServer; @@ -85,38 +85,38 @@ public: void add_command(SetCommand *command) const; - virtual RID map_create() const; + virtual RID map_create() const override; COMMAND_2(map_set_active, RID, p_map, bool, p_active); - virtual bool map_is_active(RID p_map) const; + virtual bool map_is_active(RID p_map) const override; COMMAND_2(map_set_up, RID, p_map, Vector3, p_up); - virtual Vector3 map_get_up(RID p_map) const; + virtual Vector3 map_get_up(RID p_map) const override; COMMAND_2(map_set_cell_size, RID, p_map, real_t, p_cell_size); - virtual real_t map_get_cell_size(RID p_map) const; + virtual real_t map_get_cell_size(RID p_map) const override; COMMAND_2(map_set_edge_connection_margin, RID, p_map, real_t, p_connection_margin); - virtual real_t map_get_edge_connection_margin(RID p_map) const; + virtual real_t map_get_edge_connection_margin(RID p_map) const override; - virtual Vector<Vector3> map_get_path(RID p_map, Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_layers = 1) const; + virtual Vector<Vector3> map_get_path(RID p_map, Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_layers = 1) const override; - virtual Vector3 map_get_closest_point_to_segment(RID p_map, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision = false) const; - virtual Vector3 map_get_closest_point(RID p_map, const Vector3 &p_point) const; - virtual Vector3 map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const; - virtual RID map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const; + virtual Vector3 map_get_closest_point_to_segment(RID p_map, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision = false) const override; + virtual Vector3 map_get_closest_point(RID p_map, const Vector3 &p_point) const override; + virtual Vector3 map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const override; + virtual RID map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const override; - virtual RID region_create() const; + virtual RID region_create() const override; COMMAND_2(region_set_map, RID, p_region, RID, p_map); COMMAND_2(region_set_layers, RID, p_region, uint32_t, p_layers); - virtual uint32_t region_get_layers(RID p_region) const; + virtual uint32_t region_get_layers(RID p_region) const override; COMMAND_2(region_set_transform, RID, p_region, Transform3D, p_transform); COMMAND_2(region_set_navmesh, RID, p_region, Ref<NavigationMesh>, p_nav_mesh); - virtual void region_bake_navmesh(Ref<NavigationMesh> r_mesh, Node *p_node) const; - virtual int region_get_connections_count(RID p_region) const; - virtual Vector3 region_get_connection_pathway_start(RID p_region, int p_connection_id) const; - virtual Vector3 region_get_connection_pathway_end(RID p_region, int p_connection_id) const; + virtual void region_bake_navmesh(Ref<NavigationMesh> r_mesh, Node *p_node) const override; + virtual int region_get_connections_count(RID p_region) const override; + virtual Vector3 region_get_connection_pathway_start(RID p_region, int p_connection_id) const override; + virtual Vector3 region_get_connection_pathway_end(RID p_region, int p_connection_id) const override; - virtual RID agent_create() const; + virtual RID agent_create() const override; COMMAND_2(agent_set_map, RID, p_agent, RID, p_map); COMMAND_2(agent_set_neighbor_dist, RID, p_agent, real_t, p_dist); COMMAND_2(agent_set_max_neighbors, RID, p_agent, int, p_count); @@ -127,15 +127,15 @@ public: COMMAND_2(agent_set_target_velocity, RID, p_agent, Vector3, p_velocity); COMMAND_2(agent_set_position, RID, p_agent, Vector3, p_position); COMMAND_2(agent_set_ignore_y, RID, p_agent, bool, p_ignore); - virtual bool agent_is_map_changed(RID p_agent) const; + virtual bool agent_is_map_changed(RID p_agent) const override; COMMAND_4_DEF(agent_set_callback, RID, p_agent, Object *, p_receiver, StringName, p_method, Variant, p_udata, Variant()); COMMAND_1(free, RID, p_object); - virtual void set_active(bool p_active) const; + virtual void set_active(bool p_active) const override; void flush_queries(); - virtual void process(real_t p_delta_time); + virtual void process(real_t p_delta_time) override; }; #undef COMMAND_1 diff --git a/modules/navigation/nav_map.cpp b/modules/navigation/nav_map.cpp index 1151df6390..70d50999f9 100644 --- a/modules/navigation/nav_map.cpp +++ b/modules/navigation/nav_map.cpp @@ -351,11 +351,15 @@ Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p // Add mid points int np_id = least_cost_id; - while (np_id != -1) { - path.push_back(navigation_polys[np_id].entry); + while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) { + int prev = navigation_polys[np_id].back_navigation_edge; + int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->points.size(); + Vector3 point = (navigation_polys[np_id].poly->points[prev].pos + navigation_polys[np_id].poly->points[prev_n].pos) * 0.5; + path.push_back(point); np_id = navigation_polys[np_id].back_navigation_poly_id; } + path.push_back(begin_point); path.reverse(); } diff --git a/modules/navigation/nav_utils.h b/modules/navigation/nav_utils.h index 0c02885b10..5b6c695ca4 100644 --- a/modules/navigation/nav_utils.h +++ b/modules/navigation/nav_utils.h @@ -89,7 +89,7 @@ struct Edge { }; struct Polygon { - NavRegion *owner; + NavRegion *owner = nullptr; /// The points of this `Polygon` std::vector<Point> points; diff --git a/modules/navigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp index 61c3cefc7a..9e2daf3a99 100644 --- a/modules/navigation/navigation_mesh_generator.cpp +++ b/modules/navigation/navigation_mesh_generator.cpp @@ -124,6 +124,28 @@ void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform } } +void NavigationMeshGenerator::_add_mesh_array(const Array &p_array, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) { + Vector<Vector3> mesh_vertices = p_array[Mesh::ARRAY_VERTEX]; + const Vector3 *vr = mesh_vertices.ptr(); + + Vector<int> mesh_indices = p_array[Mesh::ARRAY_INDEX]; + const int *ir = mesh_indices.ptr(); + + const int face_count = mesh_indices.size() / 3; + const int current_vertex_count = p_vertices.size() / 3; + + for (int j = 0; j < mesh_vertices.size(); j++) { + _add_vertex(p_xform.xform(vr[j]), p_vertices); + } + + for (int j = 0; j < face_count; j++) { + // CCW + p_indices.push_back(current_vertex_count + (ir[j * 3 + 0])); + p_indices.push_back(current_vertex_count + (ir[j * 3 + 2])); + p_indices.push_back(current_vertex_count + (ir[j * 3 + 1])); + } +} + void NavigationMeshGenerator::_add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) { int face_count = p_faces.size() / 3; int current_vertex_count = p_vertices.size() / 3; @@ -187,43 +209,38 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans Transform3D transform = p_navmesh_transform * static_body->get_global_transform() * col_shape->get_transform(); - Ref<Mesh> mesh; Ref<Shape3D> s = col_shape->get_shape(); BoxShape3D *box = Object::cast_to<BoxShape3D>(*s); if (box) { - Ref<BoxMesh> box_mesh; - box_mesh.instantiate(); - box_mesh->set_size(box->get_size()); - mesh = box_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + BoxMesh::create_mesh_array(arr, box->get_size()); + _add_mesh_array(arr, transform, p_vertices, p_indices); } CapsuleShape3D *capsule = Object::cast_to<CapsuleShape3D>(*s); if (capsule) { - Ref<CapsuleMesh> capsule_mesh; - capsule_mesh.instantiate(); - capsule_mesh->set_radius(capsule->get_radius()); - capsule_mesh->set_height(capsule->get_height()); - mesh = capsule_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + CapsuleMesh::create_mesh_array(arr, capsule->get_radius(), capsule->get_height()); + _add_mesh_array(arr, transform, p_vertices, p_indices); } CylinderShape3D *cylinder = Object::cast_to<CylinderShape3D>(*s); if (cylinder) { - Ref<CylinderMesh> cylinder_mesh; - cylinder_mesh.instantiate(); - cylinder_mesh->set_height(cylinder->get_height()); - cylinder_mesh->set_bottom_radius(cylinder->get_radius()); - cylinder_mesh->set_top_radius(cylinder->get_radius()); - mesh = cylinder_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + CylinderMesh::create_mesh_array(arr, cylinder->get_radius(), cylinder->get_radius(), cylinder->get_height()); + _add_mesh_array(arr, transform, p_vertices, p_indices); } SphereShape3D *sphere = Object::cast_to<SphereShape3D>(*s); if (sphere) { - Ref<SphereMesh> sphere_mesh; - sphere_mesh.instantiate(); - sphere_mesh->set_radius(sphere->get_radius()); - sphere_mesh->set_height(sphere->get_radius() * 2.0); - mesh = sphere_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + SphereMesh::create_mesh_array(arr, sphere->get_radius(), sphere->get_radius() * 2.0); + _add_mesh_array(arr, transform, p_vertices, p_indices); } ConcavePolygonShape3D *concave_polygon = Object::cast_to<ConcavePolygonShape3D>(*s); @@ -254,10 +271,6 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans _add_faces(faces, transform, p_vertices, p_indices); } } - - if (mesh.is_valid()) { - _add_mesh(mesh, transform, p_vertices, p_indices); - } } } } @@ -284,44 +297,39 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans RID shape = shapes[i + 1]; PhysicsServer3D::ShapeType type = PhysicsServer3D::get_singleton()->shape_get_type(shape); Variant data = PhysicsServer3D::get_singleton()->shape_get_data(shape); - Ref<Mesh> mesh; switch (type) { case PhysicsServer3D::SHAPE_SPHERE: { real_t radius = data; - Ref<SphereMesh> sphere_mesh; - sphere_mesh.instantiate(); - sphere_mesh->set_radius(radius); - sphere_mesh->set_height(radius * 2.0); - mesh = sphere_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + SphereMesh::create_mesh_array(arr, radius, radius * 2.0); + _add_mesh_array(arr, shapes[i], p_vertices, p_indices); } break; case PhysicsServer3D::SHAPE_BOX: { Vector3 extents = data; - Ref<BoxMesh> box_mesh; - box_mesh.instantiate(); - box_mesh->set_size(2.0 * extents); - mesh = box_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + BoxMesh::create_mesh_array(arr, extents * 2.0); + _add_mesh_array(arr, shapes[i], p_vertices, p_indices); } break; case PhysicsServer3D::SHAPE_CAPSULE: { Dictionary dict = data; real_t radius = dict["radius"]; real_t height = dict["height"]; - Ref<CapsuleMesh> capsule_mesh; - capsule_mesh.instantiate(); - capsule_mesh->set_radius(radius); - capsule_mesh->set_height(height); - mesh = capsule_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + CapsuleMesh::create_mesh_array(arr, radius, height); + _add_mesh_array(arr, shapes[i], p_vertices, p_indices); } break; case PhysicsServer3D::SHAPE_CYLINDER: { Dictionary dict = data; real_t radius = dict["radius"]; real_t height = dict["height"]; - Ref<CylinderMesh> cylinder_mesh; - cylinder_mesh.instantiate(); - cylinder_mesh->set_height(height); - cylinder_mesh->set_bottom_radius(radius); - cylinder_mesh->set_top_radius(radius); - mesh = cylinder_mesh; + Array arr; + arr.resize(RS::ARRAY_MAX); + CylinderMesh::create_mesh_array(arr, radius, radius, height); + _add_mesh_array(arr, shapes[i], p_vertices, p_indices); } break; case PhysicsServer3D::SHAPE_CONVEX_POLYGON: { PackedVector3Array vertices = data; @@ -354,10 +362,6 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans WARN_PRINT("Unsupported collision shape type."); } break; } - - if (mesh.is_valid()) { - _add_mesh(mesh, shapes[i], p_vertices, p_indices); - } } } } diff --git a/modules/navigation/navigation_mesh_generator.h b/modules/navigation/navigation_mesh_generator.h index 21f7a4941b..8cc1531b53 100644 --- a/modules/navigation/navigation_mesh_generator.h +++ b/modules/navigation/navigation_mesh_generator.h @@ -51,6 +51,7 @@ protected: static void _add_vertex(const Vector3 &p_vec3, Vector<float> &p_vertices); static void _add_mesh(const Ref<Mesh> &p_mesh, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices); + static void _add_mesh_array(const Array &p_array, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices); static void _add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices); static void _parse_geometry(const Transform3D &p_navmesh_transform, Node *p_node, Vector<float> &p_vertices, Vector<int> &p_indices, NavigationMesh::ParsedGeometryType p_generate_from, uint32_t p_collision_mask, bool p_recurse_children); diff --git a/modules/noise/noise.h b/modules/noise/noise.h index c05bc057da..853c24b485 100644 --- a/modules/noise/noise.h +++ b/modules/noise/noise.h @@ -39,7 +39,7 @@ class Noise : public Resource { // Helper struct for get_seamless_image(). See comments in .cpp for usage. template <typename T> struct img_buff { - T *img; + T *img = nullptr; int width; // Array dimensions & default modulo for image. int height; int offset_x; // Offset index location on image (wrapped by specified modulo). @@ -101,6 +101,7 @@ class Noise : public Resource { on Source it's translated to corner of Q1/s3 unless the ALT_XY modulo moves it to Q4 */ + ERR_FAIL_COND_V(p_blend_skirt < 0, Ref<Image>()); int skirt_width = MAX(1, p_width * p_blend_skirt); int skirt_height = MAX(1, p_height * p_blend_skirt); diff --git a/modules/noise/noise_texture.cpp b/modules/noise/noise_texture.cpp index 3721043a09..276335797a 100644 --- a/modules/noise/noise_texture.cpp +++ b/modules/noise/noise_texture.cpp @@ -119,7 +119,7 @@ void NoiseTexture::_thread_done(const Ref<Image> &p_image) { } void NoiseTexture::_thread_function(void *p_ud) { - NoiseTexture *tex = (NoiseTexture *)p_ud; + NoiseTexture *tex = static_cast<NoiseTexture *>(p_ud); tex->call_deferred(SNAME("_thread_done"), tex->_generate_texture()); } diff --git a/modules/openxr/SCsub b/modules/openxr/SCsub index d5df33b261..ff320236a7 100644 --- a/modules/openxr/SCsub +++ b/modules/openxr/SCsub @@ -88,4 +88,3 @@ if env["tools"]: # Needed to force rebuilding the module files when the thirdparty library is updated. env.Depends(module_obj, thirdparty_obj) - diff --git a/modules/openxr/action_map/openxr_action_map.cpp b/modules/openxr/action_map/openxr_action_map.cpp index 1ea1346f61..2ba33419d7 100644 --- a/modules/openxr/action_map/openxr_action_map.cpp +++ b/modules/openxr/action_map/openxr_action_map.cpp @@ -226,27 +226,6 @@ void OpenXRActionMap::create_default_action_sets() { profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); add_interaction_profile(profile); - // Create our HP MR controller profile - profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/hp/mixed_reality_controller"); - profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); - profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); - profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); - // hpmr controllers have no select button we can use - profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); - // hpmr controllers only register click, not touch, on our a/b/x/y buttons - profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand - profile->add_new_binding(by_button, "/user/hand/left/input/y/click,/user/hand/right/input/b/click"); // y on left hand, b on right hand - profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); - profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); - profile->add_new_binding(grip, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); - profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); - // primary on our hpmr controller is our thumbstick - profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); - profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); - // No secondary on our hpmr controller - profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); - add_interaction_profile(profile); - // Create our Meta touch controller profile profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/oculus/touch_controller"); profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); @@ -297,6 +276,116 @@ void OpenXRActionMap::create_default_action_sets() { profile->add_new_binding(secondary_touch, "/user/hand/left/input/trackpad/touch,/user/hand/right/input/trackpad/touch"); profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); add_interaction_profile(profile); + + // Note, the following profiles are all part of extensions. + // We include these regardless of whether the extension is active. + // We want our action map to be as complete as possible so our game is as portable as possible. + // It is very possible these will in due time become core. + + // Create our HP MR controller profile + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/hp/mixed_reality_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + // hpmr controllers have no select button we can use + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); + // hpmr controllers only register click, not touch, on our a/b/x/y buttons + profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand + profile->add_new_binding(by_button, "/user/hand/left/input/y/click,/user/hand/right/input/b/click"); // y on left hand, b on right hand + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/value,/user/hand/right/input/squeeze/value"); + // primary on our hpmr controller is our thumbstick + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + // No secondary on our hpmr controller + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our Samsung Odyssey controller profile, + // Note that this controller is only identified specifically on WMR, on SteamVR this is identified as a normal WMR controller. + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/samsung/odyssey_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + // Odyssey controllers have no select button we can use + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click,/user/hand/right/input/menu/click"); + // Odyssey controller has no a/b/x/y buttons + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + // primary on our Odyssey controller is our thumbstick, no touch + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + // secondary on our Odyssey controller is our trackpad + profile->add_new_binding(secondary, "/user/hand/left/input/trackpad,/user/hand/right/input/trackpad"); + profile->add_new_binding(secondary_click, "/user/hand/left/input/trackpad/click,/user/hand/right/input/trackpad/click"); + profile->add_new_binding(secondary_touch, "/user/hand/left/input/trackpad/touch,/user/hand/right/input/trackpad/touch"); + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our Vive Cosmos controller + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_cosmos_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click"); + profile->add_new_binding(select_button, "/user/hand/left/input/system/click"); // we'll map system to select + profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand + profile->add_new_binding(by_button, "/user/hand/left/input/y/click,/user/hand/right/input/b/click"); // y on left hand, b on right hand + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/click,/user/hand/right/input/trigger/click"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + // primary on our Cosmos controller is our thumbstick + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + profile->add_new_binding(primary_touch, "/user/hand/left/input/thumbstick/touch,/user/hand/right/input/thumbstick/touch"); + // No secondary on our cosmos controller + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our Vive Focus 3 controller + // Note, Vive Focus 3 currently is not yet supported as a stand alone device + // however HTC currently has a beta OpenXR runtime in testing we may support in the near future + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/htc/vive_focus3_controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(menu_button, "/user/hand/left/input/menu/click"); + profile->add_new_binding(select_button, "/user/hand/left/input/system/click"); // we'll map system to select + profile->add_new_binding(ax_button, "/user/hand/left/input/x/click,/user/hand/right/input/a/click"); // x on left hand, a on right hand + profile->add_new_binding(by_button, "/user/hand/left/input/y/click,/user/hand/right/input/b/click"); // y on left hand, b on right hand + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/click,/user/hand/right/input/trigger/click"); + profile->add_new_binding(trigger_touch, "/user/hand/left/input/trigger/touch,/user/hand/right/input/trigger/touch"); + profile->add_new_binding(grip, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + profile->add_new_binding(grip_click, "/user/hand/left/input/squeeze/click,/user/hand/right/input/squeeze/click"); + // primary on our Focus 3 controller is our thumbstick + profile->add_new_binding(primary, "/user/hand/left/input/thumbstick,/user/hand/right/input/thumbstick"); + profile->add_new_binding(primary_click, "/user/hand/left/input/thumbstick/click,/user/hand/right/input/thumbstick/click"); + profile->add_new_binding(primary_touch, "/user/hand/left/input/thumbstick/touch,/user/hand/right/input/thumbstick/touch"); + // We only have a thumb rest + profile->add_new_binding(secondary_touch, "/user/hand/left/input/thumbrest/touch,/user/hand/right/input/thumbrest/touch"); + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); + + // Create our Huawei controller + profile = OpenXRInteractionProfile::new_profile("/interaction_profiles/huawei/controller"); + profile->add_new_binding(default_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(aim_pose, "/user/hand/left/input/aim/pose,/user/hand/right/input/aim/pose"); + profile->add_new_binding(grip_pose, "/user/hand/left/input/grip/pose,/user/hand/right/input/grip/pose"); + profile->add_new_binding(menu_button, "/user/hand/left/input/home/click,/user/hand/right/input/home/click"); + profile->add_new_binding(trigger, "/user/hand/left/input/trigger/value,/user/hand/right/input/trigger/value"); + profile->add_new_binding(trigger_click, "/user/hand/left/input/trigger/click,/user/hand/right/input/trigger/click"); + // primary on our Huawei controller is our trackpad + profile->add_new_binding(primary, "/user/hand/left/input/trackpad,/user/hand/right/input/trackpad"); + profile->add_new_binding(primary_click, "/user/hand/left/input/trackpad/click,/user/hand/right/input/trackpad/click"); + profile->add_new_binding(primary_touch, "/user/hand/left/input/trackpad/touch,/user/hand/right/input/trackpad/touch"); + profile->add_new_binding(haptic, "/user/hand/left/output/haptic,/user/hand/right/output/haptic"); + add_interaction_profile(profile); } void OpenXRActionMap::create_editor_action_sets() { diff --git a/modules/openxr/action_map/openxr_defs.cpp b/modules/openxr/action_map/openxr_defs.cpp index 3358b03276..e10326449c 100644 --- a/modules/openxr/action_map/openxr_defs.cpp +++ b/modules/openxr/action_map/openxr_defs.cpp @@ -234,6 +234,150 @@ OpenXRDefs::IOPath OpenXRDefs::index_io_paths[] = { { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, }; +// Samsung odyssey controller +OpenXRDefs::IOPath OpenXRDefs::odyssey_io_paths[] = { + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + + { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Squeeze click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/squeeze/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Squeeze click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/squeeze/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Thumbstick", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Thumbstick click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Thumbstick", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Thumbstick click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Trackpad", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trackpad", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Trackpad click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trackpad/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trackpad touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trackpad/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trackpad", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trackpad", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Trackpad click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trackpad/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trackpad touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trackpad/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, +}; + +// Vive Cosmos controller +OpenXRDefs::IOPath OpenXRDefs::vive_cosmos_paths[] = { + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + + { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "System click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/system/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "X click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/x/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Y click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/y/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "A click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/a/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "B click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/b/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Shoulder click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/right/input/shoulder/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Shoulder click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/shoulder/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Squeeze click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/squeeze/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Squeeze click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/squeeze/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Thumbstick", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Thumbstick click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Thumbstick touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Thumbstick", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Thumbstick click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Thumbstick touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, +}; + +// Vive Focus 3 controller +OpenXRDefs::IOPath OpenXRDefs::vive_focus3_paths[] = { + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + + { "Menu click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/menu/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "System click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/system/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "X click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/x/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Y click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/y/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "A click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/a/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "B click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/b/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trigger touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trigger touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/touch ", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Squeeze click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/squeeze/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Squeeze touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/squeeze/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Squeeze click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/squeeze/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Squeeze touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/squeeze/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Thumbstick", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Thumbstick click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Thumbstick touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/thumbstick/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Thumbstick", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Thumbstick click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Thumbstick touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbstick/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Thumbrest touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/thumbrest/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, +}; + +// Huawei controller +OpenXRDefs::IOPath OpenXRDefs::huawei_controller_paths[] = { + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Grip pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/grip/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + { "Aim pose", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/aim/pose", OpenXRAction::OPENXR_ACTION_POSE }, + + { "Home click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/home/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Home click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/home/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Back click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/back/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Back click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/back/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Volume up click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/volume_up/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Volume up click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/volume_up/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Volume down click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/volume_down/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Volume down click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/volume_down/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trigger", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/value", OpenXRAction::OPENXR_ACTION_FLOAT }, + { "Trigger click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trigger/click", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Trackpad", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trackpad", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Trackpad click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trackpad/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trackpad touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/input/trackpad/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trackpad", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trackpad", OpenXRAction::OPENXR_ACTION_VECTOR2 }, + { "Trackpad click", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trackpad/click", OpenXRAction::OPENXR_ACTION_BOOL }, + { "Trackpad touch", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/input/trackpad/touch", OpenXRAction::OPENXR_ACTION_BOOL }, + + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_LEFT_HAND], "/user/hand/left/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, + { "Haptic output", &OpenXRDefs::available_top_level_paths[OpenXRDefs::OPENXR_RIGHT_HAND], "/user/hand/right/output/haptic", OpenXRAction::OPENXR_ACTION_HAPTIC }, +}; + OpenXRDefs::InteractionProfile OpenXRDefs::available_interaction_profiles[] = { { "Simple controller", // display_name @@ -271,6 +415,30 @@ OpenXRDefs::InteractionProfile OpenXRDefs::available_interaction_profiles[] = { index_io_paths, // io_paths sizeof(index_io_paths) / sizeof(OpenXRDefs::IOPath) // io_path_count }, + { + "Samsung Odyssey controller", // display_name + "/interaction_profiles/samsung/odyssey_controller", // openxr_path + odyssey_io_paths, // io_paths + sizeof(odyssey_io_paths) / sizeof(OpenXRDefs::IOPath) // io_path_count + }, + { + "Vive Cosmos controller", // display_name + "/interaction_profiles/htc/vive_cosmos_controller", // openxr_path + vive_cosmos_paths, // io_paths + sizeof(vive_cosmos_paths) / sizeof(OpenXRDefs::IOPath) // io_path_count + }, + { + "Vive Focus 3 controller", // display_name + "/interaction_profiles/htc/vive_focus3_controller", // openxr_path + vive_focus3_paths, // io_paths + sizeof(vive_focus3_paths) / sizeof(OpenXRDefs::IOPath) // io_path_count + }, + { + "Huawei controller", // display_name + "/interaction_profiles/huawei/controller", // openxr_path + huawei_controller_paths, // io_paths + sizeof(huawei_controller_paths) / sizeof(OpenXRDefs::IOPath) // io_path_count + }, }; int OpenXRDefs::available_interaction_profile_count = sizeof(OpenXRDefs::available_interaction_profiles) / sizeof(OpenXRDefs::InteractionProfile); diff --git a/modules/openxr/action_map/openxr_defs.h b/modules/openxr/action_map/openxr_defs.h index aa3b2a8f8a..dbda4757f1 100644 --- a/modules/openxr/action_map/openxr_defs.h +++ b/modules/openxr/action_map/openxr_defs.h @@ -85,6 +85,10 @@ private: static IOPath hpmr_io_paths[]; static IOPath touch_io_paths[]; static IOPath index_io_paths[]; + static IOPath odyssey_io_paths[]; + static IOPath vive_cosmos_paths[]; + static IOPath vive_focus3_paths[]; + static IOPath huawei_controller_paths[]; static InteractionProfile available_interaction_profiles[]; static int available_interaction_profile_count; diff --git a/modules/openxr/editor/openxr_editor_plugin.h b/modules/openxr/editor/openxr_editor_plugin.h index 9d04bc4e45..af8ee7d54c 100644 --- a/modules/openxr/editor/openxr_editor_plugin.h +++ b/modules/openxr/editor/openxr_editor_plugin.h @@ -37,7 +37,7 @@ class OpenXREditorPlugin : public EditorPlugin { GDCLASS(OpenXREditorPlugin, EditorPlugin); - OpenXRActionMapEditor *action_map_editor; + OpenXRActionMapEditor *action_map_editor = nullptr; public: virtual String get_name() const override { return "OpenXRPlugin"; } diff --git a/modules/openxr/editor/openxr_interaction_profile_editor.cpp b/modules/openxr/editor/openxr_interaction_profile_editor.cpp index 669cc694f2..24ac5494dd 100644 --- a/modules/openxr/editor/openxr_interaction_profile_editor.cpp +++ b/modules/openxr/editor/openxr_interaction_profile_editor.cpp @@ -209,6 +209,8 @@ void OpenXRInteractionProfileEditor::_add_io_path(VBoxContainer *p_container, co } void OpenXRInteractionProfileEditor::_update_interaction_profile() { + ERR_FAIL_NULL(profile_def); + // out with the old... while (main_hb->get_child_count() > 0) { memdelete(main_hb->get_child(0)); diff --git a/modules/openxr/extensions/openxr_extension_wrapper.h b/modules/openxr/extensions/openxr_extension_wrapper.h index 5242ee6063..f3064041b8 100644 --- a/modules/openxr/extensions/openxr_extension_wrapper.h +++ b/modules/openxr/extensions/openxr_extension_wrapper.h @@ -40,10 +40,11 @@ #include <openxr/openxr.h> class OpenXRAPI; +class OpenXRActionMap; class OpenXRExtensionWrapper { protected: - OpenXRAPI *openxr_api; + OpenXRAPI *openxr_api = nullptr; // Store extension we require. // If bool pointer is a nullptr this means this extension is mandatory and initialisation will fail if it is not available diff --git a/modules/openxr/openxr_api.cpp b/modules/openxr/openxr_api.cpp index e92f4c2cff..ae3617938e 100644 --- a/modules/openxr/openxr_api.cpp +++ b/modules/openxr/openxr_api.cpp @@ -172,11 +172,18 @@ bool OpenXRAPI::load_supported_extensions() { bool OpenXRAPI::is_extension_supported(const char *p_extension) const { for (uint32_t i = 0; i < num_supported_extensions; i++) { - if (strcmp(supported_extensions[i].extensionName, p_extension)) { + if (strcmp(supported_extensions[i].extensionName, p_extension) == 0) { +#ifdef DEBUG + print_line("OpenXR: requested extension", p_extension, "is supported"); +#endif return true; } } +#ifdef DEBUG + print_line("OpenXR: requested extension", p_extension, "is not supported"); +#endif + return false; } @@ -207,6 +214,14 @@ bool OpenXRAPI::create_instance() { } } + // Add optional extensions for controllers that may be supported. + // Overkill to create extension classes for this. + requested_extensions[XR_EXT_HP_MIXED_REALITY_CONTROLLER_EXTENSION_NAME] = &ext_hp_mixed_reality_available; + requested_extensions[XR_EXT_SAMSUNG_ODYSSEY_CONTROLLER_EXTENSION_NAME] = &ext_samsung_odyssey_available; + requested_extensions[XR_HTC_VIVE_COSMOS_CONTROLLER_INTERACTION_EXTENSION_NAME] = &ext_vive_cosmos_available; + requested_extensions[XR_HTC_VIVE_FOCUS3_CONTROLLER_INTERACTION_EXTENSION_NAME] = &ext_vive_focus3_available; + requested_extensions[XR_HUAWEI_CONTROLLER_INTERACTION_EXTENSION_NAME] = &ext_huawei_controller_available; + // Check which extensions are supported enabled_extensions.clear(); for (auto &requested_extension : requested_extensions) { @@ -408,7 +423,7 @@ bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType for (uint32_t i = 0; i < view_count; i++) { view_configuration_views[i].type = XR_TYPE_VIEW_CONFIGURATION_VIEW; - view_configuration_views[i].next = NULL; + view_configuration_views[i].next = nullptr; } result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views); @@ -680,10 +695,10 @@ bool OpenXRAPI::create_main_swapchain() { for (uint32_t i = 0; i < view_count; i++) { views[i].type = XR_TYPE_VIEW; - views[i].next = NULL; + views[i].next = nullptr; projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW; - projection_views[i].next = NULL; + projection_views[i].next = nullptr; projection_views[i].subImage.swapchain = swapchain; projection_views[i].subImage.imageArrayIndex = i; projection_views[i].subImage.imageRect.offset.x = 0; @@ -1147,7 +1162,7 @@ bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) { } // we don't have valid view info - if (views == NULL || !view_pose_valid) { + if (views == nullptr || !view_pose_valid) { return false; } @@ -1167,7 +1182,7 @@ bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z } // we don't have valid view info - if (views == NULL || !view_pose_valid) { + if (views == nullptr || !view_pose_valid) { return false; } diff --git a/modules/openxr/openxr_api.h b/modules/openxr/openxr_api.h index d641767a9b..7baf581a05 100644 --- a/modules/openxr/openxr_api.h +++ b/modules/openxr/openxr_api.h @@ -75,6 +75,12 @@ private: Vector<OpenXRExtensionWrapper *> registered_extension_wrappers; Vector<const char *> enabled_extensions; + bool ext_hp_mixed_reality_available = false; + bool ext_samsung_odyssey_available = false; + bool ext_vive_cosmos_available = false; + bool ext_vive_focus3_available = false; + bool ext_huawei_controller_available = false; + // composition layer providers Vector<OpenXRCompositionLayerProvider *> composition_layer_providers; diff --git a/modules/raycast/raycast_occlusion_cull.h b/modules/raycast/raycast_occlusion_cull.h index a22e52dd17..8453c5341d 100644 --- a/modules/raycast/raycast_occlusion_cull.h +++ b/modules/raycast/raycast_occlusion_cull.h @@ -115,7 +115,7 @@ private: struct Scenario { struct RaycastThreadData { - CameraRayTile *rays; + CameraRayTile *rays = nullptr; const uint32_t *masks; }; @@ -124,7 +124,7 @@ private: uint32_t vertex_count; Transform3D xform; const Vector3 *read; - Vector3 *write; + Vector3 *write = nullptr; }; Thread *commit_thread = nullptr; diff --git a/modules/regex/regex.h b/modules/regex/regex.h index a745c50a58..e7221f4070 100644 --- a/modules/regex/regex.h +++ b/modules/regex/regex.h @@ -71,7 +71,7 @@ public: class RegEx : public RefCounted { GDCLASS(RegEx, RefCounted); - void *general_ctx; + void *general_ctx = nullptr; void *code = nullptr; String pattern; diff --git a/modules/svg/image_loader_svg.cpp b/modules/svg/image_loader_svg.cpp index 79ef2de929..7fe2e589b1 100644 --- a/modules/svg/image_loader_svg.cpp +++ b/modules/svg/image_loader_svg.cpp @@ -136,7 +136,7 @@ void ImageLoaderSVG::get_recognized_extensions(List<String> *p_extensions) const p_extensions->push_back("svg"); } -Error ImageLoaderSVG::load_image(Ref<Image> p_image, FileAccess *p_fileaccess, bool p_force_linear, float p_scale) { +Error ImageLoaderSVG::load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) { String svg = p_fileaccess->get_as_utf8_string(); create_image_from_string(p_image, svg, p_scale, false, false); ERR_FAIL_COND_V(p_image->is_empty(), FAILED); diff --git a/modules/svg/image_loader_svg.h b/modules/svg/image_loader_svg.h index d0bd71d92d..94c17fda43 100644 --- a/modules/svg/image_loader_svg.h +++ b/modules/svg/image_loader_svg.h @@ -42,7 +42,7 @@ public: void set_replace_colors(Dictionary p_replace_colors) { replace_colors = p_replace_colors; } void create_image_from_string(Ref<Image> p_image, String p_string, float p_scale, bool p_upsample, bool p_convert_color); - virtual Error load_image(Ref<Image> p_image, FileAccess *p_fileaccess, bool p_force_linear, float p_scale) override; + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> p_fileaccess, bool p_force_linear, float p_scale) override; virtual void get_recognized_extensions(List<String> *p_extensions) const override; }; diff --git a/modules/text_server_adv/script_iterator.cpp b/modules/text_server_adv/script_iterator.cpp index 06e934c67d..3331254b20 100644 --- a/modules/text_server_adv/script_iterator.cpp +++ b/modules/text_server_adv/script_iterator.cpp @@ -51,7 +51,7 @@ ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length } int paren_size = PAREN_STACK_DEPTH; - ParenStackEntry *paren_stack = (ParenStackEntry *)memalloc(paren_size * sizeof(ParenStackEntry)); + ParenStackEntry *paren_stack = static_cast<ParenStackEntry *>(memalloc(paren_size * sizeof(ParenStackEntry))); int script_start; int script_end = p_start; @@ -77,7 +77,7 @@ ScriptIterator::ScriptIterator(const String &p_string, int p_start, int p_length if (unlikely(paren_sp >= paren_size)) { // If the stack is full, allocate more space to handle deeply nested parentheses. This is unlikely to happen with any real text. paren_size += PAREN_STACK_DEPTH; - paren_stack = (ParenStackEntry *)memrealloc(paren_stack, paren_size * sizeof(ParenStackEntry)); + paren_stack = static_cast<ParenStackEntry *>(memrealloc(paren_stack, paren_size * sizeof(ParenStackEntry))); } paren_stack[paren_sp].pair_index = ch; paren_stack[paren_sp].script_code = script_code; diff --git a/modules/text_server_adv/text_server_adv.cpp b/modules/text_server_adv/text_server_adv.cpp index e02ddbb3f4..4cd5dada4d 100644 --- a/modules/text_server_adv/text_server_adv.cpp +++ b/modules/text_server_adv/text_server_adv.cpp @@ -89,12 +89,12 @@ TextServerAdvanced::bmp_font_t *TextServerAdvanced::_bmp_font_create(TextServerA } void TextServerAdvanced::_bmp_font_destroy(void *p_data) { - bmp_font_t *bm_font = reinterpret_cast<bmp_font_t *>(p_data); + bmp_font_t *bm_font = static_cast<bmp_font_t *>(p_data); memdelete(bm_font); } hb_bool_t TextServerAdvanced::_bmp_get_nominal_glyph(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_unicode, hb_codepoint_t *r_glyph, void *p_user_data) { - const bmp_font_t *bm_font = reinterpret_cast<const bmp_font_t *>(p_font_data); + const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data); if (!bm_font->face) { return false; @@ -114,7 +114,7 @@ hb_bool_t TextServerAdvanced::_bmp_get_nominal_glyph(hb_font_t *p_font, void *p_ } hb_position_t TextServerAdvanced::_bmp_get_glyph_h_advance(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, void *p_user_data) { - const bmp_font_t *bm_font = reinterpret_cast<const bmp_font_t *>(p_font_data); + const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data); if (!bm_font->face) { return 0; @@ -128,7 +128,7 @@ hb_position_t TextServerAdvanced::_bmp_get_glyph_h_advance(hb_font_t *p_font, vo } hb_position_t TextServerAdvanced::_bmp_get_glyph_v_advance(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, void *p_user_data) { - const bmp_font_t *bm_font = reinterpret_cast<const bmp_font_t *>(p_font_data); + const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data); if (!bm_font->face) { return 0; @@ -142,7 +142,7 @@ hb_position_t TextServerAdvanced::_bmp_get_glyph_v_advance(hb_font_t *p_font, vo } hb_position_t TextServerAdvanced::_bmp_get_glyph_h_kerning(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_left_glyph, hb_codepoint_t p_right_glyph, void *p_user_data) { - const bmp_font_t *bm_font = reinterpret_cast<const bmp_font_t *>(p_font_data); + const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data); if (!bm_font->face) { return 0; @@ -156,7 +156,7 @@ hb_position_t TextServerAdvanced::_bmp_get_glyph_h_kerning(hb_font_t *p_font, vo } hb_bool_t TextServerAdvanced::_bmp_get_glyph_v_origin(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, hb_position_t *r_x, hb_position_t *r_y, void *p_user_data) { - const bmp_font_t *bm_font = reinterpret_cast<const bmp_font_t *>(p_font_data); + const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data); if (!bm_font->face) { return false; @@ -173,7 +173,7 @@ hb_bool_t TextServerAdvanced::_bmp_get_glyph_v_origin(hb_font_t *p_font, void *p } hb_bool_t TextServerAdvanced::_bmp_get_glyph_extents(hb_font_t *p_font, void *p_font_data, hb_codepoint_t p_glyph, hb_glyph_extents_t *r_extents, void *p_user_data) { - const bmp_font_t *bm_font = reinterpret_cast<const bmp_font_t *>(p_font_data); + const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data); if (!bm_font->face) { return false; @@ -192,7 +192,7 @@ hb_bool_t TextServerAdvanced::_bmp_get_glyph_extents(hb_font_t *p_font, void *p_ } hb_bool_t TextServerAdvanced::_bmp_get_font_h_extents(hb_font_t *p_font, void *p_font_data, hb_font_extents_t *r_metrics, void *p_user_data) { - const bmp_font_t *bm_font = reinterpret_cast<const bmp_font_t *>(p_font_data); + const bmp_font_t *bm_font = static_cast<const bmp_font_t *>(p_font_data); if (!bm_font->face) { return false; @@ -410,7 +410,6 @@ bool TextServerAdvanced::load_support_data(const String &p_filename) { } uint64_t len = f->get_length(); PackedByteArray icu_data = f->get_buffer(len); - f->close(); UErrorCode err = U_ZERO_ERROR; udata_setCommonData(icu_data.ptr(), &err); @@ -461,9 +460,8 @@ bool TextServerAdvanced::save_support_data(const String &p_filename) const { icu_data.resize(U_ICUDATA_SIZE); memcpy(icu_data.ptrw(), U_ICUDATA_ENTRY_POINT, U_ICUDATA_SIZE); f->store_buffer(icu_data); - f->close(); - return true; + return true; #else return false; #endif @@ -768,12 +766,6 @@ _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_ for (int i = 0; i < p_data->textures.size(); i++) { const FontTexture &ct = p_data->textures[i]; - if (RenderingServer::get_singleton() != nullptr) { - if (ct.texture->get_format() != p_image_format) { - continue; - } - } - if (mw > ct.texture_w || mh > ct.texture_h) { // Too big for this texture. continue; } @@ -815,12 +807,6 @@ _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_ ret.y = 0; int texsize = MAX(p_data->size.x * p_data->oversampling * 8, 256); - if (mw > texsize) { - texsize = mw; // Special case, adapt to it? - } - if (mh > texsize) { - texsize = mh; // Special case, adapt to it? - } #ifdef GDEXTENSION texsize = Math::next_power_of_2(texsize); @@ -832,6 +818,20 @@ _FORCE_INLINE_ TextServerAdvanced::FontTexturePosition TextServerAdvanced::find_ } else { texsize = MIN(texsize, 1024); } + if (mw > texsize) { // Special case, adapt to it? +#ifdef GDEXTENSION + texsize = Math::next_power_of_2(mw); +#else + texsize = next_power_of_2(mw); +#endif + } + if (mh > texsize) { // Special case, adapt to it? +#ifdef GDEXTENSION + texsize = Math::next_power_of_2(mh); +#else + texsize = next_power_of_2(mh); +#endif + } FontTexture tex; tex.texture_w = texsize; @@ -908,7 +908,7 @@ static msdfgen::Point2 ft_point2(const FT_Vector &vector) { } static int ft_move_to(const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); if (!(context->contour && context->contour->edges.empty())) { context->contour = &context->shape->addContour(); } @@ -917,7 +917,7 @@ static int ft_move_to(const FT_Vector *to, void *user) { } static int ft_line_to(const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); msdfgen::Point2 endpoint = ft_point2(*to); if (endpoint != context->position) { context->contour->addEdge(new msdfgen::LinearSegment(context->position, endpoint)); @@ -927,21 +927,21 @@ static int ft_line_to(const FT_Vector *to, void *user) { } static int ft_conic_to(const FT_Vector *control, const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); context->contour->addEdge(new msdfgen::QuadraticSegment(context->position, ft_point2(*control), ft_point2(*to))); context->position = ft_point2(*to); return 0; } static int ft_cubic_to(const FT_Vector *control1, const FT_Vector *control2, const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); context->contour->addEdge(new msdfgen::CubicSegment(context->position, ft_point2(*control1), ft_point2(*control2), ft_point2(*to))); context->position = ft_point2(*to); return 0; } void TextServerAdvanced::_generateMTSDF_threaded(uint32_t y, void *p_td) const { - MSDFThreadData *td = (MSDFThreadData *)p_td; + MSDFThreadData *td = static_cast<MSDFThreadData *>(p_td); msdfgen::ShapeDistanceFinder<msdfgen::OverlappingContourCombiner<msdfgen::MultiAndTrueDistanceSelector>> distanceFinder(*td->shape); int row = td->shape->inverseYAxis ? td->output->height() - y - 1 : y; @@ -997,8 +997,8 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf( int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 1024, FontGlyph()); - ERR_FAIL_COND_V(mh > 1024, FontGlyph()); + ERR_FAIL_COND_V(mw > 4096, FontGlyph()); + ERR_FAIL_COND_V(mh > 4096, FontGlyph()); FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); @@ -1039,20 +1039,7 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_msdf( } } - // Blit to image and texture. - { - if (RenderingServer::get_singleton() != nullptr) { - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, Image::FORMAT_RGBA8, tex.imgdata); - if (tex.texture.is_null()) { - tex.texture.instantiate(); - tex.texture->create_from_image(img); - } else { - tex.texture->update(img); - } - } - } + tex.dirty = true; // Update height array. int32_t *offw = tex.offsets.ptrw(); @@ -1078,8 +1065,8 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitma int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 1024, FontGlyph()); - ERR_FAIL_COND_V(mh > 1024, FontGlyph()); + ERR_FAIL_COND_V(mw > 4096, FontGlyph()); + ERR_FAIL_COND_V(mh > 4096, FontGlyph()); int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2; Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8; @@ -1124,21 +1111,7 @@ _FORCE_INLINE_ TextServerAdvanced::FontGlyph TextServerAdvanced::rasterize_bitma } } - // Blit to image and texture. - { - if (RenderingServer::get_singleton() != nullptr) { - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, require_format, tex.imgdata); - - if (tex.texture.is_null()) { - tex.texture.instantiate(); - tex.texture->create_from_image(img); - } else { - tex.texture->update(img); - } - } - } + tex.dirty = true; // Update height array. int32_t *offw = tex.offsets.ptrw(); @@ -1885,9 +1858,7 @@ void TextServerAdvanced::font_set_fixed_size(const RID &p_font_rid, int64_t p_fi ERR_FAIL_COND(!fd); MutexLock lock(fd->mutex); - if (fd->fixed_size != p_fixed_size) { - fd->fixed_size = p_fixed_size; - } + fd->fixed_size = p_fixed_size; } int64_t TextServerAdvanced::font_get_fixed_size(const RID &p_font_rid) const { @@ -1941,9 +1912,7 @@ void TextServerAdvanced::font_set_subpixel_positioning(const RID &p_font_rid, Te ERR_FAIL_COND(!fd); MutexLock lock(fd->mutex); - if (fd->subpixel_positioning != p_subpixel) { - fd->subpixel_positioning = p_subpixel; - } + fd->subpixel_positioning = p_subpixel; } TextServer::SubpixelPositioning TextServerAdvanced::font_get_subpixel_positioning(const RID &p_font_rid) const { @@ -2306,11 +2275,12 @@ void TextServerAdvanced::font_set_texture_image(const RID &p_font_rid, const Vec Ref<Image> img; img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, tex.format, tex.imgdata); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); tex.texture = Ref<ImageTexture>(); tex.texture.instantiate(); tex.texture->create_from_image(img); + tex.dirty = false; } Ref<Image> TextServerAdvanced::font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { @@ -2325,7 +2295,7 @@ Ref<Image> TextServerAdvanced::font_get_texture_image(const RID &p_font_rid, con const FontTexture &tex = fd->cache[size]->textures[p_texture_index]; Ref<Image> img; img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, tex.format, tex.imgdata); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); return img; } @@ -2598,10 +2568,10 @@ Dictionary TextServerAdvanced::font_get_glyph_contours(const RID &p_font_rid, in ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Dictionary()); +#ifdef MODULE_FREETYPE_ENABLED PackedVector3Array points; PackedInt32Array contours; - bool orientation; -#ifdef MODULE_FREETYPE_ENABLED + int32_t index = p_index & 0xffffff; // Remove subpixel shifts. int error = FT_Load_Glyph(fd->cache[size]->face, index, FT_LOAD_NO_BITMAP | (fd->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)); @@ -2618,16 +2588,16 @@ Dictionary TextServerAdvanced::font_get_glyph_contours(const RID &p_font_rid, in for (short i = 0; i < fd->cache[size]->face->glyph->outline.n_contours; i++) { contours.push_back(fd->cache[size]->face->glyph->outline.contours[i]); } - orientation = (FT_Outline_Get_Orientation(&fd->cache[size]->face->glyph->outline) == FT_ORIENTATION_FILL_RIGHT); -#else - return Dictionary(); -#endif + bool orientation = (FT_Outline_Get_Orientation(&fd->cache[size]->face->glyph->outline) == FT_ORIENTATION_FILL_RIGHT); Dictionary out; out["points"] = points; out["contours"] = contours; out["orientation"] = orientation; return out; +#else + return Dictionary(); +#endif } Array TextServerAdvanced::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const { @@ -2890,6 +2860,19 @@ void TextServerAdvanced::font_draw_glyph(const RID &p_font_rid, const RID &p_can } #endif if (RenderingServer::get_singleton() != nullptr) { + if (fd->cache[size]->textures[gl.texture_idx].dirty) { + FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img; + img.instantiate(); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + if (tex.texture.is_null()) { + tex.texture.instantiate(); + tex.texture->create_from_image(img); + } else { + tex.texture->update(img); + } + tex.dirty = false; + } RID texture = fd->cache[size]->textures[gl.texture_idx].texture->get_rid(); if (fd->msdf) { Point2 cpos = p_pos; @@ -2953,6 +2936,19 @@ void TextServerAdvanced::font_draw_glyph_outline(const RID &p_font_rid, const RI } #endif if (RenderingServer::get_singleton() != nullptr) { + if (fd->cache[size]->textures[gl.texture_idx].dirty) { + FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img; + img.instantiate(); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + if (tex.texture.is_null()) { + tex.texture.instantiate(); + tex.texture->create_from_image(img); + } else { + tex.texture->update(img); + } + tex.dirty = false; + } RID texture = fd->cache[size]->textures[gl.texture_idx].texture->get_rid(); if (fd->msdf) { Point2 cpos = p_pos; @@ -3876,9 +3872,9 @@ double TextServerAdvanced::shaped_text_fit_to_width(const RID &p_shaped, double } } } - double adv_remain = 0; if ((space_count > 0) && ((p_jst_flags & JUSTIFICATION_WORD_BOUND) == JUSTIFICATION_WORD_BOUND)) { double delta_width_per_space = (p_width - justification_width) / space_count; + double adv_remain = 0; for (int i = start_pos; i <= end_pos; i++) { Glyph &gl = sd->glyphs.write[i]; if (gl.count > 0) { @@ -4638,6 +4634,8 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star } RID f = p_fonts[p_fb_index]; + FontDataAdvanced *fd = font_owner.get_or_null(f); + Vector2i fss = _get_size(fd, fs); hb_font_t *hb_font = _font_get_hb_handle(f, fs); double scale = font_get_scale(f, fs); double sp_sp = font_get_spacing(f, fs, SPACING_SPACE); @@ -4719,6 +4717,7 @@ void TextServerAdvanced::_shape_run(ShapedTextDataAdvanced *p_sd, int64_t p_star gl.index = glyph_info[i].codepoint; if (gl.index != 0) { + _ensure_glyph(fd, fss, gl.index); if (p_sd->orientation == ORIENTATION_HORIZONTAL) { if (subpos) { gl.advance = glyph_pos[i].x_advance / (64.0 / scale) + ea; diff --git a/modules/text_server_adv/text_server_adv.h b/modules/text_server_adv/text_server_adv.h index bb3968ee3f..8afba6adca 100644 --- a/modules/text_server_adv/text_server_adv.h +++ b/modules/text_server_adv/text_server_adv.h @@ -159,6 +159,7 @@ class TextServerAdvanced : public TextServerExtension { int texture_h = 0; PackedInt32Array offsets; Ref<ImageTexture> texture; + bool dirty = true; }; struct FontTexturePosition { diff --git a/modules/text_server_fb/text_server_fb.cpp b/modules/text_server_fb/text_server_fb.cpp index 6c2e5a6084..47c6a73b24 100644 --- a/modules/text_server_fb/text_server_fb.cpp +++ b/modules/text_server_fb/text_server_fb.cpp @@ -209,12 +209,6 @@ _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_ for (int i = 0; i < p_data->textures.size(); i++) { const FontTexture &ct = p_data->textures[i]; - if (RenderingServer::get_singleton() != nullptr) { - if (ct.texture->get_format() != p_image_format) { - continue; - } - } - if (mw > ct.texture_w || mh > ct.texture_h) { // Too big for this texture. continue; } @@ -256,12 +250,6 @@ _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_ ret.y = 0; int texsize = MAX(p_data->size.x * p_data->oversampling * 8, 256); - if (mw > texsize) { - texsize = mw; // Special case, adapt to it? - } - if (mh > texsize) { - texsize = mh; // Special case, adapt to it? - } #ifdef GDEXTENSION texsize = Math::next_power_of_2(texsize); @@ -274,6 +262,20 @@ _FORCE_INLINE_ TextServerFallback::FontTexturePosition TextServerFallback::find_ } else { texsize = MIN(texsize, 1024); } + if (mw > texsize) { // Special case, adapt to it? +#ifdef GDEXTENSION + texsize = Math::next_power_of_2(mw); +#else + texsize = next_power_of_2(mw); +#endif + } + if (mh > texsize) { // Special case, adapt to it? +#ifdef GDEXTENSION + texsize = Math::next_power_of_2(mh); +#else + texsize = next_power_of_2(mh); +#endif + } FontTexture tex; tex.texture_w = texsize; @@ -350,7 +352,7 @@ static msdfgen::Point2 ft_point2(const FT_Vector &vector) { } static int ft_move_to(const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); if (!(context->contour && context->contour->edges.empty())) { context->contour = &context->shape->addContour(); } @@ -359,7 +361,7 @@ static int ft_move_to(const FT_Vector *to, void *user) { } static int ft_line_to(const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); msdfgen::Point2 endpoint = ft_point2(*to); if (endpoint != context->position) { context->contour->addEdge(new msdfgen::LinearSegment(context->position, endpoint)); @@ -369,21 +371,21 @@ static int ft_line_to(const FT_Vector *to, void *user) { } static int ft_conic_to(const FT_Vector *control, const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); context->contour->addEdge(new msdfgen::QuadraticSegment(context->position, ft_point2(*control), ft_point2(*to))); context->position = ft_point2(*to); return 0; } static int ft_cubic_to(const FT_Vector *control1, const FT_Vector *control2, const FT_Vector *to, void *user) { - MSContext *context = reinterpret_cast<MSContext *>(user); + MSContext *context = static_cast<MSContext *>(user); context->contour->addEdge(new msdfgen::CubicSegment(context->position, ft_point2(*control1), ft_point2(*control2), ft_point2(*to))); context->position = ft_point2(*to); return 0; } void TextServerFallback::_generateMTSDF_threaded(uint32_t y, void *p_td) const { - MSDFThreadData *td = (MSDFThreadData *)p_td; + MSDFThreadData *td = static_cast<MSDFThreadData *>(p_td); msdfgen::ShapeDistanceFinder<msdfgen::OverlappingContourCombiner<msdfgen::MultiAndTrueDistanceSelector>> distanceFinder(*td->shape); int row = td->shape->inverseYAxis ? td->output->height() - y - 1 : y; @@ -439,8 +441,8 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_msdf( int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 1024, FontGlyph()); - ERR_FAIL_COND_V(mh > 1024, FontGlyph()); + ERR_FAIL_COND_V(mw > 4096, FontGlyph()); + ERR_FAIL_COND_V(mh > 4096, FontGlyph()); FontTexturePosition tex_pos = find_texture_pos_for_glyph(p_data, 4, Image::FORMAT_RGBA8, mw, mh, true); ERR_FAIL_COND_V(tex_pos.index < 0, FontGlyph()); @@ -481,20 +483,7 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_msdf( } } - // Blit to image and texture. - { - if (RenderingServer::get_singleton() != nullptr) { - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, Image::FORMAT_RGBA8, tex.imgdata); - if (tex.texture.is_null()) { - tex.texture.instantiate(); - tex.texture->create_from_image(img); - } else { - tex.texture->update(img); - } - } - } + tex.dirty = true; // Update height array. int32_t *offw = tex.offsets.ptrw(); @@ -520,8 +509,8 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_bitma int mw = w + p_rect_margin * 2; int mh = h + p_rect_margin * 2; - ERR_FAIL_COND_V(mw > 1024, FontGlyph()); - ERR_FAIL_COND_V(mh > 1024, FontGlyph()); + ERR_FAIL_COND_V(mw > 4096, FontGlyph()); + ERR_FAIL_COND_V(mh > 4096, FontGlyph()); int color_size = bitmap.pixel_mode == FT_PIXEL_MODE_BGRA ? 4 : 2; Image::Format require_format = color_size == 4 ? Image::FORMAT_RGBA8 : Image::FORMAT_LA8; @@ -566,21 +555,7 @@ _FORCE_INLINE_ TextServerFallback::FontGlyph TextServerFallback::rasterize_bitma } } - // Blit to image and texture. - { - if (RenderingServer::get_singleton() != nullptr) { - Ref<Image> img; - img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, require_format, tex.imgdata); - - if (tex.texture.is_null()) { - tex.texture.instantiate(); - tex.texture->create_from_image(img); - } else { - tex.texture->update(img); - } - } - } + tex.dirty = true; // Update height array. int32_t *offw = tex.offsets.ptrw(); @@ -1046,9 +1021,7 @@ void TextServerFallback::font_set_fixed_size(const RID &p_font_rid, int64_t p_fi ERR_FAIL_COND(!fd); MutexLock lock(fd->mutex); - if (fd->fixed_size != p_fixed_size) { - fd->fixed_size = p_fixed_size; - } + fd->fixed_size = p_fixed_size; } int64_t TextServerFallback::font_get_fixed_size(const RID &p_font_rid) const { @@ -1102,9 +1075,7 @@ void TextServerFallback::font_set_subpixel_positioning(const RID &p_font_rid, Te ERR_FAIL_COND(!fd); MutexLock lock(fd->mutex); - if (fd->subpixel_positioning != p_subpixel) { - fd->subpixel_positioning = p_subpixel; - } + fd->subpixel_positioning = p_subpixel; } TextServer::SubpixelPositioning TextServerFallback::font_get_subpixel_positioning(const RID &p_font_rid) const { @@ -1467,11 +1438,12 @@ void TextServerFallback::font_set_texture_image(const RID &p_font_rid, const Vec Ref<Image> img; img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, tex.format, tex.imgdata); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); tex.texture = Ref<ImageTexture>(); tex.texture.instantiate(); tex.texture->create_from_image(img); + tex.dirty = false; } Ref<Image> TextServerFallback::font_get_texture_image(const RID &p_font_rid, const Vector2i &p_size, int64_t p_texture_index) const { @@ -1486,7 +1458,7 @@ Ref<Image> TextServerFallback::font_get_texture_image(const RID &p_font_rid, con const FontTexture &tex = fd->cache[size]->textures[p_texture_index]; Ref<Image> img; img.instantiate(); - img->create_from_data(tex.texture_w, tex.texture_h, 0, tex.format, tex.imgdata); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); return img; } @@ -1745,10 +1717,10 @@ Dictionary TextServerFallback::font_get_glyph_contours(const RID &p_font_rid, in ERR_FAIL_COND_V(!_ensure_cache_for_size(fd, size), Dictionary()); +#ifdef MODULE_FREETYPE_ENABLED PackedVector3Array points; PackedInt32Array contours; - bool orientation; -#ifdef MODULE_FREETYPE_ENABLED + int32_t index = p_index & 0xffffff; // Remove subpixel shifts. int error = FT_Load_Glyph(fd->cache[size]->face, FT_Get_Char_Index(fd->cache[size]->face, index), FT_LOAD_NO_BITMAP | (fd->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0)); @@ -1765,16 +1737,16 @@ Dictionary TextServerFallback::font_get_glyph_contours(const RID &p_font_rid, in for (short i = 0; i < fd->cache[size]->face->glyph->outline.n_contours; i++) { contours.push_back(fd->cache[size]->face->glyph->outline.contours[i]); } - orientation = (FT_Outline_Get_Orientation(&fd->cache[size]->face->glyph->outline) == FT_ORIENTATION_FILL_RIGHT); -#else - return Dictionary(); -#endif + bool orientation = (FT_Outline_Get_Orientation(&fd->cache[size]->face->glyph->outline) == FT_ORIENTATION_FILL_RIGHT); Dictionary out; out["points"] = points; out["contours"] = contours; out["orientation"] = orientation; return out; +#else + return Dictionary(); +#endif } Array TextServerFallback::font_get_kerning_list(const RID &p_font_rid, int64_t p_size) const { @@ -2019,6 +1991,19 @@ void TextServerFallback::font_draw_glyph(const RID &p_font_rid, const RID &p_can } #endif if (RenderingServer::get_singleton() != nullptr) { + if (fd->cache[size]->textures[gl.texture_idx].dirty) { + FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img; + img.instantiate(); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + if (tex.texture.is_null()) { + tex.texture.instantiate(); + tex.texture->create_from_image(img); + } else { + tex.texture->update(img); + } + tex.dirty = false; + } RID texture = fd->cache[size]->textures[gl.texture_idx].texture->get_rid(); if (fd->msdf) { Point2 cpos = p_pos; @@ -2082,6 +2067,19 @@ void TextServerFallback::font_draw_glyph_outline(const RID &p_font_rid, const RI } #endif if (RenderingServer::get_singleton() != nullptr) { + if (fd->cache[size]->textures[gl.texture_idx].dirty) { + FontTexture &tex = fd->cache[size]->textures.write[gl.texture_idx]; + Ref<Image> img; + img.instantiate(); + img->create_from_data(tex.texture_w, tex.texture_h, false, tex.format, tex.imgdata); + if (tex.texture.is_null()) { + tex.texture.instantiate(); + tex.texture->create_from_image(img); + } else { + tex.texture->update(img); + } + tex.dirty = false; + } RID texture = fd->cache[size]->textures[gl.texture_idx].texture->get_rid(); if (fd->msdf) { Point2 cpos = p_pos; diff --git a/modules/text_server_fb/text_server_fb.h b/modules/text_server_fb/text_server_fb.h index 3944c371b7..ea77659b5d 100644 --- a/modules/text_server_fb/text_server_fb.h +++ b/modules/text_server_fb/text_server_fb.h @@ -127,6 +127,7 @@ class TextServerFallback : public TextServerExtension { int texture_h = 0; PackedInt32Array offsets; Ref<ImageTexture> texture; + bool dirty = true; }; struct FontTexturePosition { @@ -343,8 +344,12 @@ public: virtual bool has(const RID &p_rid) override; virtual bool load_support_data(const String &p_filename) override; - virtual String get_support_data_filename() const override { return ""; }; - virtual String get_support_data_info() const override { return "Not supported"; }; + virtual String get_support_data_filename() const override { + return ""; + }; + virtual String get_support_data_info() const override { + return "Not supported"; + }; virtual bool save_support_data(const String &p_filename) const override; virtual bool is_locale_right_to_left(const String &p_locale) const override; diff --git a/modules/tga/image_loader_tga.cpp b/modules/tga/image_loader_tga.cpp index 5060c1ab35..08ad1ef9f8 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, FileAccess *f, bool p_force_linear, float p_scale) { +Error ImageLoaderTGA::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, 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); @@ -330,7 +330,6 @@ Error ImageLoaderTGA::load_image(Ref<Image> p_image, FileAccess *f, bool p_force } } - f->close(); return err; } @@ -339,12 +338,14 @@ void ImageLoaderTGA::get_recognized_extensions(List<String> *p_extensions) const } static Ref<Image> _tga_mem_loader_func(const uint8_t *p_tga, int p_size) { - FileAccessMemory memfile; - Error open_memfile_error = memfile.open_custom(p_tga, p_size); + Ref<FileAccessMemory> memfile; + memfile.instantiate(); + Error open_memfile_error = memfile->open_custom(p_tga, p_size); ERR_FAIL_COND_V_MSG(open_memfile_error, Ref<Image>(), "Could not create memfile for TGA image buffer."); + Ref<Image> img; img.instantiate(); - Error load_error = ImageLoaderTGA().load_image(img, &memfile, false, 1.0f); + Error load_error = ImageLoaderTGA().load_image(img, memfile, false, 1.0f); ERR_FAIL_COND_V_MSG(load_error, Ref<Image>(), "Failed to load TGA image."); return img; } diff --git a/modules/tga/image_loader_tga.h b/modules/tga/image_loader_tga.h index 282a2a1662..9b7cbbac77 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, FileAccess *f, bool p_force_linear, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderTGA(); }; diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp index 0a4ad96d97..3f5140cc8c 100644 --- a/modules/theora/video_stream_theora.cpp +++ b/modules/theora/video_stream_theora.cpp @@ -114,7 +114,7 @@ void VideoStreamPlaybackTheora::video_write() { } void VideoStreamPlaybackTheora::clear() { - if (!file) { + if (file.is_null()) { return; } @@ -152,10 +152,7 @@ void VideoStreamPlaybackTheora::clear() { theora_eos = false; vorbis_eos = false; - if (file) { - memdelete(file); - } - file = nullptr; + file.unref(); playing = false; }; @@ -165,11 +162,8 @@ void VideoStreamPlaybackTheora::set_file(const String &p_file) { th_setup_info *ts = nullptr; file_name = p_file; - if (file) { - memdelete(file); - } file = FileAccess::open(p_file, FileAccess::READ); - ERR_FAIL_COND_MSG(!file, "Cannot open file '" + p_file + "'."); + ERR_FAIL_COND_MSG(file.is_null(), "Cannot open file '" + p_file + "'."); #ifdef THEORA_USE_THREAD_STREAMING thread_exit = false; @@ -375,7 +369,7 @@ Ref<Texture2D> VideoStreamPlaybackTheora::get_texture() const { } void VideoStreamPlaybackTheora::update(float p_delta) { - if (!file) { + if (file.is_null()) { return; } @@ -506,9 +500,9 @@ void VideoStreamPlaybackTheora::update(float p_delta) { } #ifdef THEORA_USE_THREAD_STREAMING - if (file && thread_eof && no_theora && theora_eos && ring_buffer.data_left() == 0) { + if (file.is_valid() && thread_eof && no_theora && theora_eos && ring_buffer.data_left() == 0) { #else - if (file && /*!videobuf_ready && */ no_theora && theora_eos) { + if (file.is_valid() && /*!videobuf_ready && */ no_theora && theora_eos) { #endif //printf("video done, stopping\n"); stop(); @@ -627,7 +621,7 @@ int VideoStreamPlaybackTheora::get_mix_rate() const { #ifdef THEORA_USE_THREAD_STREAMING void VideoStreamPlaybackTheora::_streaming_thread(void *ud) { - VideoStreamPlaybackTheora *vs = (VideoStreamPlaybackTheora *)ud; + VideoStreamPlaybackTheora *vs = static_cast<VideoStreamPlaybackTheora *>(ud); while (!vs->thread_exit) { //just fill back the buffer @@ -664,10 +658,6 @@ VideoStreamPlaybackTheora::~VideoStreamPlaybackTheora() { memdelete(thread_sem); #endif clear(); - - if (file) { - memdelete(file); - } }; void VideoStreamTheora::_bind_methods() { @@ -680,8 +670,8 @@ void VideoStreamTheora::_bind_methods() { //////////// RES ResourceFormatLoaderTheora::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { if (r_error) { *r_error = ERR_CANT_OPEN; } @@ -697,8 +687,6 @@ RES ResourceFormatLoaderTheora::load(const String &p_path, const String &p_origi *r_error = OK; } - f->close(); - memdelete(f); return ogv_stream; } diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h index 3bc96908a2..6fa7313fad 100644 --- a/modules/theora/video_stream_theora.h +++ b/modules/theora/video_stream_theora.h @@ -56,7 +56,7 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { Image::Format format = Image::Format::FORMAT_L8; Vector<uint8_t> frame_data; int frames_pending = 0; - FileAccess *file = nullptr; + Ref<FileAccess> file; String file_name; int audio_frames_wrote = 0; Point2i size; @@ -112,7 +112,7 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback { RingBuffer<uint8_t> ring_buffer; Vector<uint8_t> read_buffer; bool thread_eof = false; - Semaphore *thread_sem; + Semaphore *thread_sem = nullptr; Thread thread; SafeFlag thread_exit; diff --git a/modules/tinyexr/image_loader_tinyexr.cpp b/modules/tinyexr/image_loader_tinyexr.cpp index 688707a42d..864df765ee 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, FileAccess *f, bool p_force_linear, float p_scale) { +Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, 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); @@ -47,8 +47,6 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f f->get_buffer(&w[0], src_image_len); - f->close(); - // Re-implementation of tinyexr's LoadEXRFromMemory using Godot types to store the Image data // and Godot's error codes. // When debugging after updating the thirdparty library, check that we're still in sync with @@ -232,7 +230,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f } if (p_force_linear) { - color = color.to_linear(); + color = color.srgb_to_linear(); } *row_w++ = Math::make_half_float(color.r); @@ -263,7 +261,7 @@ Error ImageLoaderTinyEXR::load_image(Ref<Image> p_image, FileAccess *f, bool p_f } if (p_force_linear) { - color = color.to_linear(); + color = color.srgb_to_linear(); } *row_w++ = color.r; diff --git a/modules/tinyexr/image_loader_tinyexr.h b/modules/tinyexr/image_loader_tinyexr.h index aba5fdb959..c147861c26 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, FileAccess *f, bool p_force_linear, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderTinyEXR(); }; diff --git a/modules/tinyexr/image_saver_tinyexr.cpp b/modules/tinyexr/image_saver_tinyexr.cpp index 3750994663..5fa6ace827 100644 --- a/modules/tinyexr/image_saver_tinyexr.cpp +++ b/modules/tinyexr/image_saver_tinyexr.cpp @@ -275,8 +275,8 @@ Error save_exr(const String &p_path, const Ref<Image> &p_img, bool p_grayscale) print_error(String("Saving EXR failed. Error: {0}").format(varray(err))); return ERR_FILE_CANT_WRITE; } else { - FileAccessRef ref = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V(!ref, ERR_FILE_CANT_WRITE); + Ref<FileAccess> ref = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V(ref.is_null(), ERR_FILE_CANT_WRITE); ref->store_buffer(mem, bytes); free(mem); } diff --git a/modules/visual_script/editor/visual_script_editor.cpp b/modules/visual_script/editor/visual_script_editor.cpp index a2e59c9cdf..495303d6c4 100644 --- a/modules/visual_script/editor/visual_script_editor.cpp +++ b/modules/visual_script/editor/visual_script_editor.cpp @@ -2727,7 +2727,7 @@ void VisualScriptEditor::_center_on_node(int p_id) { if (gn) { gn->set_selected(true); - Vector2 new_scroll = gn->get_position_offset() - graph->get_size() * 0.5 + gn->get_size() * 0.5; + Vector2 new_scroll = gn->get_position_offset() * graph->get_zoom() - graph->get_size() * 0.5 + gn->get_size() * 0.5; graph->set_scroll_ofs(new_scroll); script->set_scroll(new_scroll / EDSCALE); script->set_edited(true); diff --git a/modules/visual_script/editor/visual_script_property_selector.h b/modules/visual_script/editor/visual_script_property_selector.h index 6b5112f1af..faf39a14e4 100644 --- a/modules/visual_script/editor/visual_script_property_selector.h +++ b/modules/visual_script/editor/visual_script_property_selector.h @@ -62,23 +62,23 @@ class VisualScriptPropertySelector : public ConfirmationDialog { SCOPE_ALL = SCOPE_BASE | SCOPE_INHERITERS | SCOPE_UNRELATED }; - LineEdit *search_box; + LineEdit *search_box = nullptr; - Button *case_sensitive_button; - Button *hierarchy_button; + Button *case_sensitive_button = nullptr; + Button *hierarchy_button = nullptr; - Button *search_visual_script_nodes; - Button *search_classes; - Button *search_operators; + Button *search_visual_script_nodes = nullptr; + Button *search_classes = nullptr; + Button *search_operators = nullptr; - Button *search_methods; - Button *search_signals; - Button *search_constants; - Button *search_properties; - Button *search_theme_items; + Button *search_methods = nullptr; + Button *search_signals = nullptr; + Button *search_constants = nullptr; + Button *search_properties = nullptr; + Button *search_theme_items = nullptr; - OptionButton *scope_combo; - Tree *results_tree; + OptionButton *scope_combo = nullptr; + Tree *results_tree = nullptr; class SearchRunner; Ref<SearchRunner> search_runner; @@ -94,7 +94,7 @@ class VisualScriptPropertySelector : public ConfirmationDialog { void _item_selected(); void _hide_requested(); - EditorHelpBit *help_bit; + EditorHelpBit *help_bit = nullptr; bool properties = false; bool visual_script_generic = false; @@ -104,9 +104,9 @@ class VisualScriptPropertySelector : public ConfirmationDialog { String base_type; String base_script; ObjectID script; - Object *instance; + Object *instance = nullptr; bool virtuals_only = false; - VBoxContainer *vbox; + VBoxContainer *vbox = nullptr; protected: void _notification(int p_what); @@ -159,9 +159,9 @@ class VisualScriptPropertySelector::SearchRunner : public RefCounted { } }; - VisualScriptPropertySelector *selector_ui; - Control *ui_service; - Tree *results_tree; + VisualScriptPropertySelector *selector_ui = nullptr; + Control *ui_service = nullptr; + Tree *results_tree = nullptr; String term; int search_flags; int scope_flags; diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h index d72bdf9128..6b27af15f6 100644 --- a/modules/visual_script/visual_script.h +++ b/modules/visual_script/visual_script.h @@ -495,7 +495,7 @@ class VisualScriptLanguage : public ScriptLanguage { String _debug_error; int _debug_call_stack_pos = 0; int _debug_max_call_stack; - CallLevel *_call_stack; + CallLevel *_call_stack = nullptr; public: StringName notification = "_notification"; diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp index f6bc855a50..7e2df23618 100644 --- a/modules/visual_script/visual_script_builtin_funcs.cpp +++ b/modules/visual_script/visual_script_builtin_funcs.cpp @@ -1185,11 +1185,11 @@ public: VisualScriptBuiltinFunc::BuiltinFunc func; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { VisualScriptBuiltinFunc::exec_func(func, p_inputs, p_outputs[0], r_error, r_error_str); return 0; } diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp index fef159bf87..bd36a9ceec 100644 --- a/modules/visual_script/visual_script_expression.cpp +++ b/modules/visual_script/visual_script_expression.cpp @@ -1302,7 +1302,7 @@ public: VisualScriptInstance *instance; VisualScriptExpression *expression; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } //execute by parsing the tree directly virtual bool _execute(const Variant **p_inputs, VisualScriptExpression::ENode *p_node, Variant &r_ret, String &r_error_str, Callable::CallError &ce) { switch (p_node->type) { @@ -1512,7 +1512,7 @@ public: return false; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!expression->root || expression->error_set) { r_error_str = expression->error_str; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; diff --git a/modules/visual_script/visual_script_flow_control.cpp b/modules/visual_script/visual_script_flow_control.cpp index d28744a09f..7946d96b29 100644 --- a/modules/visual_script/visual_script_flow_control.cpp +++ b/modules/visual_script/visual_script_flow_control.cpp @@ -123,11 +123,11 @@ public: VisualScriptInstance *instance; bool with_value; - virtual int get_working_memory_size() const { return 1; } + virtual int get_working_memory_size() const override { return 1; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (with_value) { *p_working_mem = *p_inputs[0]; return STEP_EXIT_FUNCTION_BIT; @@ -216,11 +216,11 @@ public: VisualScriptCondition *node; VisualScriptInstance *instance; - //virtual int get_working_memory_size() const { return 1; } + //virtual int get_working_memory_size() const override { return 1; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (p_start_mode == START_MODE_CONTINUE_SEQUENCE) { return 2; } else if (p_inputs[0]->operator bool()) { @@ -296,11 +296,11 @@ public: VisualScriptWhile *node; VisualScriptInstance *instance; - //virtual int get_working_memory_size() const { return 1; } + //virtual int get_working_memory_size() const override { return 1; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool keep_going = p_inputs[0]->operator bool(); if (keep_going) { @@ -379,11 +379,11 @@ public: VisualScriptIterator *node; VisualScriptInstance *instance; - virtual int get_working_memory_size() const { return 2; } + virtual int get_working_memory_size() const override { return 2; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (p_start_mode == START_MODE_BEGIN_SEQUENCE) { p_working_mem[0] = *p_inputs[0]; bool valid; @@ -512,11 +512,11 @@ public: VisualScriptInstance *instance; int steps; - virtual int get_working_memory_size() const { return 1; } + virtual int get_working_memory_size() const override { return 1; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (p_start_mode == START_MODE_BEGIN_SEQUENCE) { p_working_mem[0] = 0; } @@ -599,11 +599,11 @@ public: VisualScriptInstance *instance; int case_count; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (p_start_mode == START_MODE_CONTINUE_SEQUENCE) { return case_count; //exit } @@ -778,11 +778,11 @@ public: StringName base_type; String script; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Object *obj = *p_inputs[0]; *p_outputs[0] = Variant(); diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp index 2c9d23e457..5cc9236a9a 100644 --- a/modules/visual_script/visual_script_func_nodes.cpp +++ b/modules/visual_script/visual_script_func_nodes.cpp @@ -730,7 +730,7 @@ public: VisualScriptFunctionCall *node; VisualScriptInstance *instance; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } @@ -765,7 +765,7 @@ public: return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (call_mode) { case VisualScriptFunctionCall::CALL_MODE_SELF: { Object *object = instance->get_owner_ptr(); @@ -1468,7 +1468,7 @@ public: StringName index; bool needs_get; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } @@ -1529,7 +1529,7 @@ public: } } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (call_mode) { case VisualScriptPropertySet::CALL_MODE_SELF: { Object *object = instance->get_owner_ptr(); @@ -2155,7 +2155,7 @@ public: VisualScriptPropertyGet *node; VisualScriptInstance *instance; - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (call_mode) { case VisualScriptPropertyGet::CALL_MODE_SELF: { Object *object = instance->get_owner_ptr(); @@ -2367,11 +2367,11 @@ public: int argcount; StringName name; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Object *obj = instance->get_owner_ptr(); obj->emit_signalp(name, p_inputs, argcount); diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp index b65b9f090a..6e10b72013 100644 --- a/modules/visual_script/visual_script_nodes.cpp +++ b/modules/visual_script/visual_script_nodes.cpp @@ -274,9 +274,9 @@ public: VisualScriptFunction *node; VisualScriptInstance *instance; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { int ac = node->get_argument_count(); for (int i = 0; i < ac; i++) { @@ -777,9 +777,9 @@ String VisualScriptComposeArray::get_text() const { class VisualScriptComposeArrayNode : public VisualScriptNodeInstance { public: int input_count = 0; - virtual int get_working_memory_size() const { return 0; } + virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (input_count > 0) { Array arr; for (int i = 0; i < input_count; i++) { @@ -1100,9 +1100,9 @@ public: bool unary; Variant::Operator op; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool valid; if (unary) { Variant::evaluate(op, *p_inputs[0], Variant(), *p_outputs[0], valid); @@ -1220,9 +1220,9 @@ void VisualScriptSelect::_bind_methods() { class VisualScriptNodeInstanceSelect : public VisualScriptNodeInstance { public: - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool cond = *p_inputs[0]; if (cond) { *p_outputs[0] = *p_inputs[1]; @@ -1332,7 +1332,7 @@ public: VisualScriptInstance *instance; StringName variable; - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!instance->get_variable(variable, p_outputs[0])) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("VariableGet not found in script: ") + "'" + String(variable) + "'"; @@ -1442,9 +1442,9 @@ public: VisualScriptInstance *instance; StringName variable; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!instance->set_variable(variable, *p_inputs[0])) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR("VariableSet not found in script: ") + "'" + String(variable) + "'"; @@ -1561,9 +1561,9 @@ void VisualScriptConstant::_bind_methods() { class VisualScriptNodeInstanceConstant : public VisualScriptNodeInstance { public: Variant constant; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = constant; return 0; } @@ -1654,9 +1654,9 @@ void VisualScriptPreload::_bind_methods() { class VisualScriptNodeInstancePreload : public VisualScriptNodeInstance { public: Ref<Resource> preload; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = preload; return 0; } @@ -1713,9 +1713,9 @@ String VisualScriptIndexGet::get_caption() const { class VisualScriptNodeInstanceIndexGet : public VisualScriptNodeInstance { public: - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool valid; *p_outputs[0] = p_inputs[0]->get(*p_inputs[1], &valid); @@ -1780,9 +1780,9 @@ String VisualScriptIndexSet::get_caption() const { class VisualScriptNodeInstanceIndexSet : public VisualScriptNodeInstance { public: - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool valid; ((Variant *)p_inputs[0])->set(*p_inputs[1], *p_inputs[2], &valid); @@ -1852,9 +1852,9 @@ int VisualScriptGlobalConstant::get_global_constant() { class VisualScriptNodeInstanceGlobalConstant : public VisualScriptNodeInstance { public: int index; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = CoreConstants::get_global_constant_value(index); return 0; } @@ -1965,9 +1965,9 @@ class VisualScriptNodeInstanceClassConstant : public VisualScriptNodeInstance { public: int value; bool valid; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!valid) { r_error_str = "Invalid constant name, pick a valid class constant."; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; @@ -2099,9 +2099,9 @@ class VisualScriptNodeInstanceBasicTypeConstant : public VisualScriptNodeInstanc public: Variant value; bool valid; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!valid) { r_error_str = "Invalid constant name, pick a valid basic type constant."; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; @@ -2228,9 +2228,9 @@ VisualScriptMathConstant::MathConstant VisualScriptMathConstant::get_math_consta class VisualScriptNodeInstanceMathConstant : public VisualScriptNodeInstance { public: float value; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = value; return 0; } @@ -2322,9 +2322,9 @@ class VisualScriptNodeInstanceEngineSingleton : public VisualScriptNodeInstance public: Object *singleton; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = singleton; return 0; } @@ -2433,9 +2433,9 @@ public: VisualScriptInstance *instance; NodePath path; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Node *node = Object::cast_to<Node>(instance->get_owner_ptr()); if (!node) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; @@ -2613,9 +2613,9 @@ public: VisualScriptSceneTree *node; VisualScriptInstance *instance; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Node *node = Object::cast_to<Node>(instance->get_owner_ptr()); if (!node) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; @@ -2709,9 +2709,9 @@ class VisualScriptNodeInstanceResourcePath : public VisualScriptNodeInstance { public: String path; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = path; return 0; } @@ -2781,9 +2781,9 @@ class VisualScriptNodeInstanceSelf : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = instance->get_owner_ptr(); return 0; } @@ -2971,8 +2971,8 @@ public: int out_count; int work_mem_size; - virtual int get_working_memory_size() const { return work_mem_size; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int get_working_memory_size() const override { return work_mem_size; } + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (GDVIRTUAL_IS_OVERRIDDEN_PTR(node, _step)) { Array in_values; Array out_values; @@ -3166,9 +3166,9 @@ public: int input_args; bool valid; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!valid) { r_error_str = "Node requires a script with a _subcall(<args>) method to work."; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; @@ -3283,9 +3283,9 @@ class VisualScriptNodeInstanceComment : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { return 0; } }; @@ -3384,9 +3384,9 @@ public: Variant::Type type; int argcount; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Callable::CallError ce; Variant::construct(type, *p_outputs[0], p_inputs, argcount, ce); if (ce.error != Callable::CallError::CALL_OK) { @@ -3500,8 +3500,8 @@ public: VisualScriptInstance *instance; StringName name; - virtual int get_working_memory_size() const { return 1; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int get_working_memory_size() const override { return 1; } + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = *p_working_mem; return 0; } @@ -3607,8 +3607,8 @@ public: VisualScriptInstance *instance; StringName name; - virtual int get_working_memory_size() const { return 1; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int get_working_memory_size() const override { return 1; } + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_working_mem = *p_inputs[0]; *p_outputs[0] = *p_working_mem; return 0; @@ -3732,7 +3732,7 @@ public: StringName action; VisualScriptInputAction::Mode mode; - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (mode) { case VisualScriptInputAction::MODE_PRESSED: { *p_outputs[0] = Input::get_singleton()->is_action_pressed(action); @@ -3909,9 +3909,9 @@ public: VisualScriptInstance *instance; Vector<StringName> outputs; - //virtual int get_working_memory_size() const { return 0; } + //virtual int get_working_memory_size() const override { return 0; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Variant in = *p_inputs[0]; for (int i = 0; i < outputs.size(); i++) { diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp index dcd8815394..e6e7f79d1f 100644 --- a/modules/visual_script/visual_script_yield_nodes.cpp +++ b/modules/visual_script/visual_script_yield_nodes.cpp @@ -95,11 +95,11 @@ public: VisualScriptYield::YieldMode mode; double wait_time; - virtual int get_working_memory_size() const { return 1; } //yield needs at least 1 + virtual int get_working_memory_size() const override { return 1; } //yield needs at least 1 //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return false; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (p_start_mode == START_MODE_RESUME_YIELD) { return 0; //resuming yield } else { @@ -506,11 +506,11 @@ public: VisualScriptYieldSignal *node; VisualScriptInstance *instance; - virtual int get_working_memory_size() const { return 1; } + virtual int get_working_memory_size() const override { return 1; } //virtual bool is_output_port_unsequenced(int p_idx) const { return false; } //virtual bool get_output_port_unsequenced(int p_idx,Variant* r_value,Variant* p_working_mem,String &r_error) const { return true; } - virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) { + virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (p_start_mode == START_MODE_RESUME_YIELD) { return 0; //resuming yield } else { diff --git a/modules/vorbis/resource_importer_ogg_vorbis.cpp b/modules/vorbis/resource_importer_ogg_vorbis.cpp index d12e65a96a..03e145216a 100644 --- a/modules/vorbis/resource_importer_ogg_vorbis.cpp +++ b/modules/vorbis/resource_importer_ogg_vorbis.cpp @@ -78,9 +78,8 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin bool loop = p_options["loop"]; float loop_offset = p_options["loop_offset"]; - FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ); - - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, "Cannot open file '" + p_source_file + "'."); + Ref<FileAccess> f = FileAccess::open(p_source_file, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, "Cannot open file '" + p_source_file + "'."); uint64_t len = f->get_length(); @@ -90,8 +89,6 @@ Error ResourceImporterOGGVorbis::import(const String &p_source_file, const Strin f->get_buffer(w, len); - memdelete(f); - Ref<AudioStreamOGGVorbis> ogg_vorbis_stream; ogg_vorbis_stream.instantiate(); diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp index 902e182d83..0e41f6c973 100644 --- a/modules/webp/image_loader_webp.cpp +++ b/modules/webp/image_loader_webp.cpp @@ -211,7 +211,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, FileAccess *f, bool p_force_linear, float p_scale) { +Error ImageLoaderWEBP::load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, 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); @@ -221,8 +221,6 @@ Error ImageLoaderWEBP::load_image(Ref<Image> p_image, FileAccess *f, bool p_forc f->get_buffer(&w[0], src_image_len); - f->close(); - Error err = webp_load_image_from_buffer(p_image.ptr(), w, src_image_len); return err; diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h index 327582ca55..1acd1459a0 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, FileAccess *f, bool p_force_linear, float p_scale); + virtual Error load_image(Ref<Image> p_image, Ref<FileAccess> f, bool p_force_linear, float p_scale); virtual void get_recognized_extensions(List<String> *p_extensions) const; ImageLoaderWEBP(); }; diff --git a/modules/webrtc/webrtc_peer_connection_js.h b/modules/webrtc/webrtc_peer_connection_js.h index 3d0b365355..8fa5ea7779 100644 --- a/modules/webrtc/webrtc_peer_connection_js.h +++ b/modules/webrtc/webrtc_peer_connection_js.h @@ -63,16 +63,16 @@ private: static void _on_error(void *p_obj); public: - virtual ConnectionState get_connection_state() const; + virtual ConnectionState get_connection_state() const override; - virtual Error initialize(Dictionary configuration = Dictionary()); - virtual Ref<WebRTCDataChannel> create_data_channel(String p_channel_name, Dictionary p_channel_config = Dictionary()); - virtual Error create_offer(); - virtual Error set_remote_description(String type, String sdp); - virtual Error set_local_description(String type, String sdp); - virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName); - virtual Error poll(); - virtual void close(); + virtual Error initialize(Dictionary configuration = Dictionary()) override; + virtual Ref<WebRTCDataChannel> create_data_channel(String p_channel_name, Dictionary p_channel_config = Dictionary()) override; + virtual Error create_offer() override; + virtual Error set_remote_description(String type, String sdp) override; + virtual Error set_local_description(String type, String sdp) override; + virtual Error add_ice_candidate(String sdpMidName, int sdpMlineIndexName, String sdpName) override; + virtual Error poll() override; + virtual void close() override; WebRTCPeerConnectionJS(); ~WebRTCPeerConnectionJS(); diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml index ef3279aac4..46b0274de3 100644 --- a/modules/websocket/doc_classes/WebSocketServer.xml +++ b/modules/websocket/doc_classes/WebSocketServer.xml @@ -60,6 +60,13 @@ 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(id)[/code] to communicate with the peer with given [code]id[/code] (e.g. [code]get_peer(id).get_available_packet_count[/code]). </description> </method> + <method name="set_extra_headers"> + <return type="void" /> + <argument index="0" name="headers" type="PackedStringArray" default="PackedStringArray()" /> + <description> + Sets additional headers to be sent to clients during the HTTP handshake. + </description> + </method> <method name="stop"> <return type="void" /> <description> diff --git a/modules/websocket/emws_client.h b/modules/websocket/emws_client.h index 61ea0002ea..ca327a56fa 100644 --- a/modules/websocket/emws_client.h +++ b/modules/websocket/emws_client.h @@ -53,15 +53,15 @@ private: static void _esws_on_close(void *obj, int code, const char *reason, int was_clean); public: - Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); - 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>()); - Ref<WebSocketPeer> get_peer(int p_peer_id) const; - void disconnect_from_host(int p_code = 1000, String p_reason = ""); - IPAddress get_connected_host() const; - uint16_t get_connected_port() const; - virtual ConnectionStatus get_connection_status() const; - int get_max_packet_size() const; - virtual void poll(); + 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; + 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; + uint16_t get_connected_port() const override; + virtual ConnectionStatus get_connection_status() const override; + int get_max_packet_size() const override; + virtual void poll() override; EMWSClient(); ~EMWSClient(); }; diff --git a/modules/websocket/emws_peer.h b/modules/websocket/emws_peer.h index df63d2d801..6bb4552c37 100644 --- a/modules/websocket/emws_peer.h +++ b/modules/websocket/emws_peer.h @@ -68,21 +68,21 @@ private: public: Error read_msg(const uint8_t *p_data, uint32_t p_size, bool p_is_string); void set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size); - virtual int get_available_packet_count() const; - virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); - virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); - virtual int get_max_packet_size() const { return _packet_buffer.size(); }; - virtual int get_current_outbound_buffered_amount() const; + virtual int get_available_packet_count() const override; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; + virtual int get_max_packet_size() const override { return _packet_buffer.size(); }; + virtual int get_current_outbound_buffered_amount() const override; - virtual void close(int p_code = 1000, String p_reason = ""); - virtual bool is_connected_to_host() const; - virtual IPAddress get_connected_host() const; - virtual uint16_t get_connected_port() const; + virtual void close(int p_code = 1000, String p_reason = "") override; + virtual bool is_connected_to_host() const override; + virtual IPAddress get_connected_host() const override; + virtual uint16_t get_connected_port() const override; - virtual WriteMode get_write_mode() const; - virtual void set_write_mode(WriteMode p_mode); - virtual bool was_string_packet() const; - virtual void set_no_delay(bool p_enabled); + virtual WriteMode get_write_mode() const override; + virtual void set_write_mode(WriteMode p_mode) override; + virtual bool was_string_packet() const override; + virtual void set_no_delay(bool p_enabled) override; EMWSPeer(); ~EMWSPeer(); diff --git a/modules/websocket/emws_server.cpp b/modules/websocket/emws_server.cpp index 53b4a0207d..2033098cad 100644 --- a/modules/websocket/emws_server.cpp +++ b/modules/websocket/emws_server.cpp @@ -33,6 +33,9 @@ #include "emws_server.h" #include "core/os/os.h" +void EMWSServer::set_extra_headers(const Vector<String> &p_headers) { +} + Error EMWSServer::listen(int p_port, Vector<String> p_protocols, bool gd_mp_api) { return FAILED; } diff --git a/modules/websocket/emws_server.h b/modules/websocket/emws_server.h index f310c17c9d..ae31d9dbb0 100644 --- a/modules/websocket/emws_server.h +++ b/modules/websocket/emws_server.h @@ -41,17 +41,18 @@ class EMWSServer : public WebSocketServer { GDCIIMPL(EMWSServer, WebSocketServer); public: - Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); - Error listen(int p_port, Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false); - void stop(); - bool is_listening() const; - bool has_peer(int p_id) const; - Ref<WebSocketPeer> get_peer(int p_id) const; - IPAddress get_peer_address(int p_peer_id) const; - int get_peer_port(int p_peer_id) const; - void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = ""); - int get_max_packet_size() const; - virtual void poll(); + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override; + void set_extra_headers(const Vector<String> &p_headers) override; + Error listen(int p_port, Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) override; + void stop() override; + bool is_listening() const override; + bool has_peer(int p_id) const override; + Ref<WebSocketPeer> get_peer(int p_id) const override; + IPAddress get_peer_address(int p_peer_id) const override; + int get_peer_port(int p_peer_id) const override; + void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "") override; + int get_max_packet_size() const override; + virtual void poll() override; virtual Vector<String> get_protocols() const; EMWSServer(); diff --git a/modules/websocket/remote_debugger_peer_websocket.h b/modules/websocket/remote_debugger_peer_websocket.h index 84f9506625..3227065ded 100644 --- a/modules/websocket/remote_debugger_peer_websocket.h +++ b/modules/websocket/remote_debugger_peer_websocket.h @@ -51,14 +51,14 @@ public: static RemoteDebuggerPeer *create(const String &p_uri); Error connect_to_host(const String &p_uri); - bool is_peer_connected(); - int get_max_message_size() const; - bool has_message(); - Error put_message(const Array &p_arr); - Array get_message(); - void close(); - void poll(); - bool can_block() const; + bool is_peer_connected() override; + int get_max_message_size() const override; + bool has_message() override; + Error put_message(const Array &p_arr) override; + Array get_message() override; + void close() override; + void poll() override; + bool can_block() const override; RemoteDebuggerPeerWebSocket(Ref<WebSocketPeer> p_peer = Ref<WebSocketPeer>()); }; diff --git a/modules/websocket/websocket_server.cpp b/modules/websocket/websocket_server.cpp index b3f0140b80..b7851b02c4 100644 --- a/modules/websocket/websocket_server.cpp +++ b/modules/websocket/websocket_server.cpp @@ -42,6 +42,7 @@ WebSocketServer::~WebSocketServer() { void WebSocketServer::_bind_methods() { ClassDB::bind_method(D_METHOD("is_listening"), &WebSocketServer::is_listening); + ClassDB::bind_method(D_METHOD("set_extra_headers", "headers"), &WebSocketServer::set_extra_headers, DEFVAL(Vector<String>())); ClassDB::bind_method(D_METHOD("listen", "port", "protocols", "gd_mp_api"), &WebSocketServer::listen, DEFVAL(Vector<String>()), DEFVAL(false)); ClassDB::bind_method(D_METHOD("stop"), &WebSocketServer::stop); ClassDB::bind_method(D_METHOD("has_peer", "id"), &WebSocketServer::has_peer); diff --git a/modules/websocket/websocket_server.h b/modules/websocket/websocket_server.h index f6f3b80045..7bd80851f5 100644 --- a/modules/websocket/websocket_server.h +++ b/modules/websocket/websocket_server.h @@ -51,6 +51,7 @@ protected: uint32_t handshake_timeout = 3000; public: + virtual void set_extra_headers(const Vector<String> &p_headers) = 0; virtual Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) = 0; virtual void stop() = 0; virtual bool is_listening() const = 0; diff --git a/modules/websocket/wsl_client.h b/modules/websocket/wsl_client.h index d846e6be00..22b3a4f373 100644 --- a/modules/websocket/wsl_client.h +++ b/modules/websocket/wsl_client.h @@ -73,15 +73,15 @@ private: bool _verify_headers(String &r_protocol); public: - Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); - 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>()); - int get_max_packet_size() const; - Ref<WebSocketPeer> get_peer(int p_peer_id) const; - void disconnect_from_host(int p_code = 1000, String p_reason = ""); - IPAddress get_connected_host() const; - uint16_t get_connected_port() const; - virtual ConnectionStatus get_connection_status() const; - virtual void poll(); + 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; + 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; + IPAddress get_connected_host() const override; + uint16_t get_connected_port() const override; + virtual ConnectionStatus get_connection_status() const override; + virtual void poll() override; WSLClient(); ~WSLClient(); diff --git a/modules/websocket/wsl_peer.cpp b/modules/websocket/wsl_peer.cpp index d277eedace..15df4d039c 100644 --- a/modules/websocket/wsl_peer.cpp +++ b/modules/websocket/wsl_peer.cpp @@ -146,17 +146,17 @@ void wsl_msg_recv_callback(wslay_event_context_ptr ctx, const struct wslay_event if (!peer_data->valid || peer_data->closing) { return; } - WSLPeer *peer = (WSLPeer *)peer_data->peer; + WSLPeer *peer = static_cast<WSLPeer *>(peer_data->peer); if (peer->parse_message(arg) != OK) { return; } if (peer_data->is_server) { - WSLServer *helper = (WSLServer *)peer_data->obj; + WSLServer *helper = static_cast<WSLServer *>(peer_data->obj); helper->_on_peer_packet(peer_data->id); } else { - WSLClient *helper = (WSLClient *)peer_data->obj; + WSLClient *helper = static_cast<WSLClient *>(peer_data->obj); helper->_on_peer_packet(); } } @@ -184,10 +184,10 @@ Error WSLPeer::parse_message(const wslay_event_on_msg_recv_arg *arg) { } if (!wslay_event_get_close_sent(_data->ctx)) { if (_data->is_server) { - WSLServer *helper = (WSLServer *)_data->obj; + WSLServer *helper = static_cast<WSLServer *>(_data->obj); helper->_on_close_request(_data->id, close_code, close_reason); } else { - WSLClient *helper = (WSLClient *)_data->obj; + WSLClient *helper = static_cast<WSLClient *>(_data->obj); helper->_on_close_request(close_code, close_reason); } } diff --git a/modules/websocket/wsl_peer.h b/modules/websocket/wsl_peer.h index 555559c6e1..abeecdd537 100644 --- a/modules/websocket/wsl_peer.h +++ b/modules/websocket/wsl_peer.h @@ -85,22 +85,22 @@ public: String close_reason; void poll(); // Used by client and server. - virtual int get_available_packet_count() const; - virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size); - virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size); - virtual int get_max_packet_size() const { return _packet_buffer.size(); }; - virtual int get_current_outbound_buffered_amount() const; + virtual int get_available_packet_count() const override; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; + virtual int get_max_packet_size() const override { return _packet_buffer.size(); }; + virtual int get_current_outbound_buffered_amount() const override; virtual void close_now(); - virtual void close(int p_code = 1000, String p_reason = ""); - virtual bool is_connected_to_host() const; - virtual IPAddress get_connected_host() const; - virtual uint16_t get_connected_port() const; - - virtual WriteMode get_write_mode() const; - virtual void set_write_mode(WriteMode p_mode); - virtual bool was_string_packet() const; - virtual void set_no_delay(bool p_enabled); + virtual void close(int p_code = 1000, String p_reason = "") override; + virtual bool is_connected_to_host() const override; + virtual IPAddress get_connected_host() const override; + virtual uint16_t get_connected_port() const override; + + virtual WriteMode get_write_mode() const override; + virtual void set_write_mode(WriteMode p_mode) override; + virtual bool was_string_packet() const override; + virtual void set_no_delay(bool p_enabled) override; void make_context(PeerData *p_data, unsigned int p_in_buf_size, unsigned int p_in_pkt_size, unsigned int p_out_buf_size, unsigned int p_out_pkt_size); Error parse_message(const wslay_event_on_msg_recv_arg *arg); diff --git a/modules/websocket/wsl_server.cpp b/modules/websocket/wsl_server.cpp index eadd7ef7ac..b58b2e4724 100644 --- a/modules/websocket/wsl_server.cpp +++ b/modules/websocket/wsl_server.cpp @@ -96,7 +96,7 @@ bool WSLServer::PendingPeer::_parse_request(const Vector<String> p_protocols, St return true; } -Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name) { +Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name, const Vector<String> &p_extra_headers) { if (OS::get_singleton()->get_ticks_msec() - time > p_timeout) { print_verbose(vformat("WebSocket handshake timed out after %.3f seconds.", p_timeout * 0.001)); return ERR_TIMEOUT; @@ -141,6 +141,9 @@ Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uin if (!protocol.is_empty()) { s += "Sec-WebSocket-Protocol: " + protocol + "\r\n"; } + for (int i = 0; i < p_extra_headers.size(); i++) { + s += p_extra_headers[i] + "\r\n"; + } s += "\r\n"; response = s.utf8(); has_request = true; @@ -167,6 +170,10 @@ Error WSLServer::PendingPeer::do_handshake(const Vector<String> p_protocols, uin return OK; } +void WSLServer::set_extra_headers(const Vector<String> &p_headers) { + _extra_headers = p_headers; +} + Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp_api) { ERR_FAIL_COND_V(is_listening(), ERR_ALREADY_IN_USE); @@ -183,7 +190,7 @@ Error WSLServer::listen(int p_port, const Vector<String> p_protocols, bool gd_mp void WSLServer::poll() { List<int> remove_ids; for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - Ref<WSLPeer> peer = (WSLPeer *)E.value.ptr(); + Ref<WSLPeer> peer = const_cast<WSLPeer *>(static_cast<const WSLPeer *>(E.value.ptr())); peer->poll(); if (!peer->is_connected_to_host()) { _on_disconnect(E.key, peer->close_code != -1); @@ -199,7 +206,7 @@ void WSLServer::poll() { for (const Ref<PendingPeer> &E : _pending) { String resource_name; Ref<PendingPeer> ppeer = E; - Error err = ppeer->do_handshake(_protocols, handshake_timeout, resource_name); + Error err = ppeer->do_handshake(_protocols, handshake_timeout, resource_name, _extra_headers); if (err == ERR_BUSY) { continue; } else if (err != OK) { @@ -266,7 +273,7 @@ int WSLServer::get_max_packet_size() const { void WSLServer::stop() { _server->stop(); for (const KeyValue<int, Ref<WebSocketPeer>> &E : _peer_map) { - Ref<WSLPeer> peer = (WSLPeer *)E.value.ptr(); + Ref<WSLPeer> peer = const_cast<WSLPeer *>(static_cast<const WSLPeer *>(E.value.ptr())); peer->close_now(); } _pending.clear(); diff --git a/modules/websocket/wsl_server.h b/modules/websocket/wsl_server.h index 221cae4793..a920e9c665 100644 --- a/modules/websocket/wsl_server.h +++ b/modules/websocket/wsl_server.h @@ -62,7 +62,7 @@ private: CharString response; int response_sent = 0; - Error do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name); + Error do_handshake(const Vector<String> p_protocols, uint64_t p_timeout, String &r_resource_name, const Vector<String> &p_extra_headers); }; int _in_buf_size = DEF_BUF_SHIFT; @@ -73,19 +73,21 @@ private: List<Ref<PendingPeer>> _pending; Ref<TCPServer> _server; Vector<String> _protocols; + Vector<String> _extra_headers; public: - Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets); - Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false); - void stop(); - bool is_listening() const; - int get_max_packet_size() const; - bool has_peer(int p_id) const; - Ref<WebSocketPeer> get_peer(int p_id) const; - IPAddress get_peer_address(int p_peer_id) const; - int get_peer_port(int p_peer_id) const; - void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = ""); - virtual void poll(); + Error set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) override; + void set_extra_headers(const Vector<String> &p_headers) override; + Error listen(int p_port, const Vector<String> p_protocols = Vector<String>(), bool gd_mp_api = false) override; + void stop() override; + bool is_listening() const override; + int get_max_packet_size() const override; + bool has_peer(int p_id) const override; + Ref<WebSocketPeer> get_peer(int p_id) const override; + IPAddress get_peer_address(int p_peer_id) const override; + int get_peer_port(int p_peer_id) const override; + void disconnect_peer(int p_peer_id, int p_code = 1000, String p_reason = "") override; + virtual void poll() override; WSLServer(); ~WSLServer(); diff --git a/platform/android/audio_driver_opensl.cpp b/platform/android/audio_driver_opensl.cpp index 8495d2cc18..dcaa586e3b 100644 --- a/platform/android/audio_driver_opensl.cpp +++ b/platform/android/audio_driver_opensl.cpp @@ -75,7 +75,7 @@ void AudioDriverOpenSL::_buffer_callback( void AudioDriverOpenSL::_buffer_callbacks( SLAndroidSimpleBufferQueueItf queueItf, void *pContext) { - AudioDriverOpenSL *ad = (AudioDriverOpenSL *)pContext; + AudioDriverOpenSL *ad = static_cast<AudioDriverOpenSL *>(pContext); ad->_buffer_callback(queueItf); } @@ -208,7 +208,7 @@ void AudioDriverOpenSL::_record_buffer_callback(SLAndroidSimpleBufferQueueItf qu } void AudioDriverOpenSL::_record_buffer_callbacks(SLAndroidSimpleBufferQueueItf queueItf, void *pContext) { - AudioDriverOpenSL *ad = (AudioDriverOpenSL *)pContext; + AudioDriverOpenSL *ad = static_cast<AudioDriverOpenSL *>(pContext); ad->_record_buffer_callback(queueItf); } diff --git a/platform/android/dir_access_jandroid.cpp b/platform/android/dir_access_jandroid.cpp index 7fb4f54fca..e2b1c757d6 100644 --- a/platform/android/dir_access_jandroid.cpp +++ b/platform/android/dir_access_jandroid.cpp @@ -42,7 +42,7 @@ jmethodID DirAccessJAndroid::_dir_next = nullptr; jmethodID DirAccessJAndroid::_dir_close = nullptr; jmethodID DirAccessJAndroid::_dir_is_dir = nullptr; -DirAccess *DirAccessJAndroid::create_fs() { +Ref<DirAccess> DirAccessJAndroid::create_fs() { return memnew(DirAccessJAndroid); } @@ -143,7 +143,7 @@ Error DirAccessJAndroid::change_dir(String p_dir) { return OK; } -String DirAccessJAndroid::get_current_dir(bool p_include_drive) { +String DirAccessJAndroid::get_current_dir(bool p_include_drive) const { return "res://" + current_dir; } @@ -155,9 +155,9 @@ bool DirAccessJAndroid::file_exists(String p_file) { sd = current_dir.plus_file(p_file); } - FileAccessAndroid *f = memnew(FileAccessAndroid); + Ref<FileAccessAndroid> f; + f.instantiate(); bool exists = f->file_exists(sd); - memdelete(f); return exists; } diff --git a/platform/android/dir_access_jandroid.h b/platform/android/dir_access_jandroid.h index 4f4a984b12..3d3c9f9223 100644 --- a/platform/android/dir_access_jandroid.h +++ b/platform/android/dir_access_jandroid.h @@ -51,7 +51,7 @@ class DirAccessJAndroid : public DirAccess { String current_dir; String current; - static DirAccess *create_fs(); + static Ref<DirAccess> create_fs(); public: virtual Error list_dir_begin(); ///< This starts dir listing @@ -64,7 +64,7 @@ public: virtual String get_drive(int p_drive); virtual Error change_dir(String p_dir); ///< can be relative or absolute, return false on success - virtual String get_current_dir(bool p_include_drive = true); ///< return current dir location + virtual String get_current_dir(bool p_include_drive = true) const; ///< return current dir location virtual bool file_exists(String p_file); virtual bool dir_exists(String p_dir); diff --git a/platform/android/display_server_android.cpp b/platform/android/display_server_android.cpp index a7a8801bdc..e7de287fc6 100644 --- a/platform/android/display_server_android.cpp +++ b/platform/android/display_server_android.cpp @@ -42,7 +42,7 @@ #endif DisplayServerAndroid *DisplayServerAndroid::get_singleton() { - return (DisplayServerAndroid *)DisplayServer::get_singleton(); + return static_cast<DisplayServerAndroid *>(DisplayServer::get_singleton()); } bool DisplayServerAndroid::has_feature(Feature p_feature) const { @@ -161,6 +161,13 @@ int DisplayServerAndroid::screen_get_dpi(int p_screen) const { return godot_io_java->get_screen_dpi(); } +float DisplayServerAndroid::screen_get_scale(int p_screen) const { + GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); + ERR_FAIL_COND_V(!godot_io_java, 1.0f); + + return godot_io_java->get_scaled_density(); +} + float DisplayServerAndroid::screen_get_refresh_rate(int p_screen) const { GodotIOJavaWrapper *godot_io_java = OS_Android::get_singleton()->get_godot_io_java(); if (!godot_io_java) { @@ -270,7 +277,7 @@ int64_t DisplayServerAndroid::window_get_native_handle(HandleType p_handle_type, return 0; // Not supported. } case WINDOW_HANDLE: { - return (int64_t)((OS_Android *)OS::get_singleton())->get_godot_java()->get_activity(); + return reinterpret_cast<int64_t>(static_cast<OS_Android *>(OS::get_singleton())->get_godot_java()->get_activity()); } case WINDOW_VIEW: { return 0; // Not supported. diff --git a/platform/android/display_server_android.h b/platform/android/display_server_android.h index 23077a6529..1d268bbcfd 100644 --- a/platform/android/display_server_android.h +++ b/platform/android/display_server_android.h @@ -106,6 +106,7 @@ public: virtual Size2i screen_get_size(int p_screen = SCREEN_OF_MAIN_WINDOW) const override; virtual Rect2i screen_get_usable_rect(int p_screen = SCREEN_OF_MAIN_WINDOW) const override; virtual int screen_get_dpi(int p_screen = SCREEN_OF_MAIN_WINDOW) const override; + virtual float screen_get_scale(int p_screen = SCREEN_OF_MAIN_WINDOW) const override; virtual float screen_get_refresh_rate(int p_screen = SCREEN_OF_MAIN_WINDOW) const override; virtual bool screen_is_touchscreen(int p_screen = SCREEN_OF_MAIN_WINDOW) const override; diff --git a/platform/android/export/export_plugin.cpp b/platform/android/export/export_plugin.cpp index 69ae8ed74c..8cfa3a67b9 100644 --- a/platform/android/export/export_plugin.cpp +++ b/platform/android/export/export_plugin.cpp @@ -249,7 +249,7 @@ static const int DEFAULT_TARGET_SDK_VERSION = 30; // Should match the value in ' const String SDK_VERSION_RANGE = vformat("%s,%s,1", DEFAULT_MIN_SDK_VERSION, DEFAULT_TARGET_SDK_VERSION); void EditorExportPlatformAndroid::_check_for_changes_poll_thread(void *ud) { - EditorExportPlatformAndroid *ea = (EditorExportPlatformAndroid *)ud; + EditorExportPlatformAndroid *ea = static_cast<EditorExportPlatformAndroid *>(ud); while (!ea->quit_request.is_set()) { // Check for plugins updates @@ -596,8 +596,8 @@ Vector<String> EditorExportPlatformAndroid::get_abis() { /// List the gdap files in the directory specified by the p_path parameter. Vector<String> EditorExportPlatformAndroid::list_gdap_files(const String &p_path) { Vector<String> dir_files; - DirAccessRef da = DirAccess::open(p_path); - if (da) { + Ref<DirAccess> da = DirAccess::open(p_path); + if (da.is_valid()) { da->list_dir_begin(); while (true) { String file = da->get_next(); @@ -685,7 +685,7 @@ Error EditorExportPlatformAndroid::save_apk_so(void *p_userdata, const SharedObj ERR_PRINT(err); return FAILED; } - APKExportData *ed = (APKExportData *)p_userdata; + APKExportData *ed = static_cast<APKExportData *>(p_userdata); Vector<String> abis = get_abis(); bool exported = false; for (int i = 0; i < p_so.tags.size(); ++i) { @@ -710,7 +710,7 @@ Error EditorExportPlatformAndroid::save_apk_so(void *p_userdata, const SharedObj } Error EditorExportPlatformAndroid::save_apk_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key) { - APKExportData *ed = (APKExportData *)p_userdata; + APKExportData *ed = static_cast<APKExportData *>(p_userdata); String dst_path = p_path.replace_first("res://", "assets/"); store_in_apk(ed, dst_path, p_data, _should_compress_asset(p_path, p_data) ? Z_DEFLATED : 0); @@ -725,7 +725,7 @@ Error EditorExportPlatformAndroid::copy_gradle_so(void *p_userdata, const Shared ERR_FAIL_COND_V_MSG(!p_so.path.get_file().begins_with("lib"), FAILED, "Android .so file names must start with \"lib\", but got: " + p_so.path); Vector<String> abis = get_abis(); - CustomExportData *export_data = (CustomExportData *)p_userdata; + CustomExportData *export_data = static_cast<CustomExportData *>(p_userdata); bool exported = false; for (int i = 0; i < p_so.tags.size(); ++i) { int abi_index = abis.find(p_so.tags[i]); @@ -863,7 +863,7 @@ void EditorExportPlatformAndroid::_fix_manifest(const Ref<EditorExportPreset> &p bool classify_as_game = p_preset->get("package/classify_as_game"); bool retain_data_on_uninstall = p_preset->get("package/retain_data_on_uninstall"); bool exclude_from_recents = p_preset->get("package/exclude_from_recents"); - bool is_resizeable = p_preset->get("screen/is_resizeable"); + bool is_resizeable = bool(GLOBAL_GET("display/window/size/resizable")); Vector<String> perms; // Write permissions into the perms variable. @@ -1738,7 +1738,6 @@ void EditorExportPlatformAndroid::get_export_options(List<ExportOption> *r_optio r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_normal"), true)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_large"), true)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/support_xlarge"), true)); - r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "screen/is_resizeable"), false)); r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "user_data_backup/allow"), false)); @@ -2009,7 +2008,7 @@ String EditorExportPlatformAndroid::get_apksigner_path() { Error errn; String build_tools_dir = sdk_path.plus_file("build-tools"); - DirAccessRef da = DirAccess::open(build_tools_dir, &errn); + Ref<DirAccess> da = DirAccess::open(build_tools_dir, &errn); if (errn != OK) { print_error("Unable to open Android 'build-tools' directory."); return apksigner_path; @@ -2126,7 +2125,7 @@ bool EditorExportPlatformAndroid::can_export(const Ref<EditorExportPreset> &p_pr } else { Error errn; // Check for the platform-tools directory. - DirAccessRef da = DirAccess::open(sdk_path.plus_file("platform-tools"), &errn); + Ref<DirAccess> da = DirAccess::open(sdk_path.plus_file("platform-tools"), &errn); if (errn != OK) { err += TTR("Invalid Android SDK path in Editor Settings."); err += TTR("Missing 'platform-tools' directory!"); @@ -2144,7 +2143,7 @@ bool EditorExportPlatformAndroid::can_export(const Ref<EditorExportPreset> &p_pr } // Check for the build-tools directory. - DirAccessRef build_tools_da = DirAccess::open(sdk_path.plus_file("build-tools"), &errn); + Ref<DirAccess> build_tools_da = DirAccess::open(sdk_path.plus_file("build-tools"), &errn); if (errn != OK) { err += TTR("Invalid Android SDK path in Editor Settings."); err += TTR("Missing 'build-tools' directory!"); @@ -2423,12 +2422,12 @@ Error EditorExportPlatformAndroid::sign_apk(const Ref<EditorExportPreset> &p_pre } void EditorExportPlatformAndroid::_clear_assets_directory() { - DirAccessRef da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da_res = DirAccess::create(DirAccess::ACCESS_RESOURCES); // Clear the APK assets directory if (da_res->dir_exists(APK_ASSETS_DIRECTORY)) { print_verbose("Clearing APK assets directory.."); - DirAccessRef da_assets = DirAccess::open(APK_ASSETS_DIRECTORY); + Ref<DirAccess> da_assets = DirAccess::open(APK_ASSETS_DIRECTORY); da_assets->erase_contents_recursive(); da_res->remove(APK_ASSETS_DIRECTORY); } @@ -2436,7 +2435,7 @@ void EditorExportPlatformAndroid::_clear_assets_directory() { // Clear the AAB assets directory if (da_res->dir_exists(AAB_ASSETS_DIRECTORY)) { print_verbose("Clearing AAB assets directory.."); - DirAccessRef da_assets = DirAccess::open(AAB_ASSETS_DIRECTORY); + Ref<DirAccess> da_assets = DirAccess::open(AAB_ASSETS_DIRECTORY); da_assets->erase_contents_recursive(); da_res->remove(AAB_ASSETS_DIRECTORY); } @@ -2456,7 +2455,7 @@ void EditorExportPlatformAndroid::_remove_copied_libs() { ERR_FAIL_COND_MSG(error, "Error parsing \"" + libs_json + "\" on line " + itos(json.get_error_line()) + ": " + json.get_error_message()); Vector<String> libs = json.get_data(); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); for (int i = 0; i < libs.size(); i++) { print_verbose("Removing previously installed library " + libs[i]); da->remove(libs[i]); @@ -2545,14 +2544,13 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP //test that installed build version is alright { print_verbose("Checking build version.."); - FileAccessRef f = FileAccess::open("res://android/.build_version", FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open("res://android/.build_version", FileAccess::READ); + if (f.is_null()) { EditorNode::get_singleton()->show_warning(TTR("Trying to build from a custom built template, but no version info for it exists. Please reinstall from the 'Project' menu.")); return ERR_UNCONFIGURED; } String version = f->get_line().strip_edges(); print_verbose("- build version: " + version); - f->close(); if (version != VERSION_FULL_CONFIG) { EditorNode::get_singleton()->show_warning(vformat(TTR("Android build version mismatch:\n Template installed: %s\n Godot Version: %s\nPlease reinstall Android build template from 'Project' menu."), version, VERSION_FULL_CONFIG)); return ERR_UNCONFIGURED; @@ -2588,10 +2586,9 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP return err; } if (user_data.libs.size() > 0) { - FileAccessRef fa = FileAccess::open(GDNATIVE_LIBS_PATH, FileAccess::WRITE); + Ref<FileAccess> fa = FileAccess::open(GDNATIVE_LIBS_PATH, FileAccess::WRITE); JSON json; fa->store_string(json.stringify(user_data.libs, "\t")); - fa->close(); } } else { print_verbose("Saving apk expansion file.."); @@ -2771,8 +2768,7 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP return ERR_FILE_BAD_PATH; } - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); if (ep.step(TTR("Creating APK..."), 0)) { return ERR_SKIP; @@ -2786,9 +2782,7 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP int ret = unzGoToFirstFile(pkg); - zlib_filefunc_def io2 = io; - FileAccess *dst_f = nullptr; - io2.opaque = &dst_f; + zlib_filefunc_def io2 = zipio_create_io(); String tmp_unaligned_path = EditorPaths::get_singleton()->get_cache_dir().plus_file("tmpexport-unaligned." + uitos(OS::get_singleton()->get_unix_time()) + ".apk"); @@ -2813,6 +2807,9 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } bool skip = false; @@ -2981,9 +2978,7 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP ret = unzGoToFirstFile(tmp_unaligned); - io2 = io; - dst_f = nullptr; - io2.opaque = &dst_f; + io2 = zipio_create_io(); zipFile final_apk = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io2); // Take files from the unaligned APK and write them out to the aligned one @@ -2997,6 +2992,9 @@ Error EditorExportPlatformAndroid::export_project_helper(const Ref<EditorExportP char fname[16384]; char extra[16384]; ret = unzGetCurrentFileInfo(tmp_unaligned, &info, fname, 16384, extra, 16384 - ZIP_ALIGNMENT, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String file = String::utf8(fname); diff --git a/platform/android/export/gradle_export_util.cpp b/platform/android/export/gradle_export_util.cpp index c4cf82de6c..173bb8bcb7 100644 --- a/platform/android/export/gradle_export_util.cpp +++ b/platform/android/export/gradle_export_util.cpp @@ -75,8 +75,8 @@ String _get_android_orientation_label(DisplayServer::ScreenOrientation screen_or // Utility method used to create a directory. Error create_directory(const String &p_dir) { if (!DirAccess::exists(p_dir)) { - DirAccessRef filesystem_da = DirAccess::create(DirAccess::ACCESS_RESOURCES); - ERR_FAIL_COND_V_MSG(!filesystem_da, ERR_CANT_CREATE, "Cannot create directory '" + p_dir + "'."); + Ref<DirAccess> filesystem_da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + ERR_FAIL_COND_V_MSG(filesystem_da.is_null(), ERR_CANT_CREATE, "Cannot create directory '" + p_dir + "'."); Error err = filesystem_da->make_dir_recursive(p_dir); ERR_FAIL_COND_V_MSG(err, ERR_CANT_CREATE, "Cannot create directory '" + p_dir + "'."); } @@ -91,10 +91,9 @@ Error store_file_at_path(const String &p_path, const Vector<uint8_t> &p_data) { if (err != OK) { return err; } - FileAccess *fa = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!fa, ERR_CANT_CREATE, "Cannot create file '" + p_path + "'."); + Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'."); fa->store_buffer(p_data.ptr(), p_data.size()); - memdelete(fa); return OK; } @@ -109,10 +108,9 @@ Error store_string_at_path(const String &p_path, const String &p_data) { } return err; } - FileAccess *fa = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!fa, ERR_CANT_CREATE, "Cannot create file '" + p_path + "'."); + Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(fa.is_null(), ERR_CANT_CREATE, "Cannot create file '" + p_path + "'."); fa->store_string(p_data); - memdelete(fa); return OK; } @@ -122,7 +120,7 @@ Error store_string_at_path(const String &p_path, const String &p_data) { // It's functionality mirrors that of the method save_apk_file. // This method will be called ONLY when custom build is enabled. Error rename_and_store_file_in_gradle_project(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key) { - CustomExportData *export_data = (CustomExportData *)p_userdata; + CustomExportData *export_data = static_cast<CustomExportData *>(p_userdata); String dst_path = p_path.replace_first("res://", export_data->assets_directory + "/"); print_verbose("Saving project files from " + p_path + " into " + dst_path); Error err = store_file_at_path(dst_path, p_data); @@ -152,8 +150,8 @@ Error _create_project_name_strings_files(const Ref<EditorExportPreset> &p_preset store_string_at_path("res://android/build/res/values/godot_project_name_string.xml", processed_default_xml_string); // Searches the Gradle project res/ directory to find all supported locales - DirAccessRef da = DirAccess::open("res://android/build/res"); - if (!da) { + Ref<DirAccess> da = DirAccess::open("res://android/build/res"); + if (da.is_null()) { if (OS::get_singleton()->is_stdout_verbose()) { print_error("Unable to open Android resources directory."); } @@ -259,7 +257,7 @@ String _get_activity_tag(const Ref<EditorExportPreset> &p_preset) { "android:resizeableActivity=\"%s\">\n", bool_to_string(p_preset->get("package/exclude_from_recents")), orientation, - bool_to_string(p_preset->get("screen/is_resizeable"))); + bool_to_string(bool(GLOBAL_GET("display/window/size/resizable")))); if (uses_xr) { manifest_activity_text += " <meta-data tools:node=\"replace\" android:name=\"com.oculus.vr.focusaware\" android:value=\"true\" />\n"; } else { diff --git a/platform/android/file_access_android.cpp b/platform/android/file_access_android.cpp index c84a919b6b..d7ba31e3c9 100644 --- a/platform/android/file_access_android.cpp +++ b/platform/android/file_access_android.cpp @@ -34,11 +34,13 @@ AAssetManager *FileAccessAndroid::asset_manager = nullptr; -FileAccess *FileAccessAndroid::create_android() { +Ref<FileAccess> FileAccessAndroid::create_android() { return memnew(FileAccessAndroid); } Error FileAccessAndroid::_open(const String &p_path, int p_mode_flags) { + _close(); + String path = fix_path(p_path).simplify_path(); if (path.begins_with("/")) { path = path.substr(1, path.length()); @@ -58,7 +60,7 @@ Error FileAccessAndroid::_open(const String &p_path, int p_mode_flags) { return OK; } -void FileAccessAndroid::close() { +void FileAccessAndroid::_close() { if (!a) { return; } @@ -162,5 +164,5 @@ bool FileAccessAndroid::file_exists(const String &p_path) { } FileAccessAndroid::~FileAccessAndroid() { - close(); + _close(); } diff --git a/platform/android/file_access_android.h b/platform/android/file_access_android.h index fb612cd008..33b692da20 100644 --- a/platform/android/file_access_android.h +++ b/platform/android/file_access_android.h @@ -38,17 +38,18 @@ //#include <android_native_app_glue.h> class FileAccessAndroid : public FileAccess { - static FileAccess *create_android(); + static Ref<FileAccess> create_android(); mutable AAsset *a = nullptr; mutable uint64_t len = 0; mutable uint64_t pos = 0; mutable bool eof = false; + void _close(); + public: static AAssetManager *asset_manager; virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file - virtual void close(); ///< close a file virtual bool is_open() const; ///< true when file is open virtual void seek(uint64_t p_position); ///< seek to a given position diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotEditor.java b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotEditor.java index b3a340cc64..8a6bf88267 100644 --- a/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotEditor.java +++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotEditor.java @@ -107,4 +107,18 @@ public class GodotEditor extends FullScreenGodotApp { Intent newInstance = new Intent(this, targetClass).putExtra(COMMAND_LINE_PARAMS, args); startActivity(newInstance); } + + @Override + public void setRequestedOrientation(int requestedOrientation) { + if (!overrideOrientationRequest()) { + super.setRequestedOrientation(requestedOrientation); + } + } + + /** + * The Godot Android Editor sets its own orientation via its AndroidManifest + */ + protected boolean overrideOrientationRequest() { + return true; + } } diff --git a/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotGame.java b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotGame.java index 5a0be391cf..12766775a8 100644 --- a/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotGame.java +++ b/platform/android/java/editor/src/main/java/org/godotengine/editor/GodotGame.java @@ -34,4 +34,7 @@ package org.godotengine.editor; * Drives the 'run project' window of the Godot Editor. */ public class GodotGame extends GodotEditor { + protected boolean overrideOrientationRequest() { + return false; + } } diff --git a/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java index b151e7eec1..e8e292df5d 100644 --- a/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java +++ b/platform/android/java/lib/src/org/godotengine/godot/GodotIO.java @@ -222,10 +222,14 @@ public class GodotIO { } public int getScreenDPI() { - DisplayMetrics metrics = activity.getApplicationContext().getResources().getDisplayMetrics(); + DisplayMetrics metrics = activity.getResources().getDisplayMetrics(); return (int)(metrics.density * 160f); } + public float getScaledDensity() { + return activity.getResources().getDisplayMetrics().scaledDensity; + } + public double getScreenRefreshRate(double fallback) { Display display = activity.getWindowManager().getDefaultDisplay(); if (display != null) { diff --git a/platform/android/java_godot_io_wrapper.cpp b/platform/android/java_godot_io_wrapper.cpp index a5698f4efc..5b21e696c3 100644 --- a/platform/android/java_godot_io_wrapper.cpp +++ b/platform/android/java_godot_io_wrapper.cpp @@ -54,6 +54,7 @@ GodotIOJavaWrapper::GodotIOJavaWrapper(JNIEnv *p_env, jobject p_godot_io_instanc _get_locale = p_env->GetMethodID(cls, "getLocale", "()Ljava/lang/String;"); _get_model = p_env->GetMethodID(cls, "getModel", "()Ljava/lang/String;"); _get_screen_DPI = p_env->GetMethodID(cls, "getScreenDPI", "()I"); + _get_scaled_density = p_env->GetMethodID(cls, "getScaledDensity", "()F"); _get_screen_refresh_rate = p_env->GetMethodID(cls, "getScreenRefreshRate", "(D)D"); _screen_get_usable_rect = p_env->GetMethodID(cls, "screenGetUsableRect", "()[I"), _get_unique_id = p_env->GetMethodID(cls, "getUniqueID", "()Ljava/lang/String;"); @@ -138,6 +139,16 @@ int GodotIOJavaWrapper::get_screen_dpi() { } } +float GodotIOJavaWrapper::get_scaled_density() { + if (_get_scaled_density) { + JNIEnv *env = get_jni_env(); + ERR_FAIL_COND_V(env == nullptr, 1.0f); + return env->CallFloatMethod(godot_io_instance, _get_scaled_density); + } else { + return 1.0f; + } +} + float GodotIOJavaWrapper::get_screen_refresh_rate(float fallback) { if (_get_screen_refresh_rate) { JNIEnv *env = get_jni_env(); @@ -198,14 +209,11 @@ void GodotIOJavaWrapper::hide_vk() { } void GodotIOJavaWrapper::set_screen_orientation(int p_orient) { - // The Godot Android Editor sets its own orientation via its AndroidManifest -#ifndef TOOLS_ENABLED if (_set_screen_orientation) { JNIEnv *env = get_jni_env(); ERR_FAIL_COND(env == nullptr); env->CallVoidMethod(godot_io_instance, _set_screen_orientation, p_orient); } -#endif } int GodotIOJavaWrapper::get_screen_orientation() { diff --git a/platform/android/java_godot_io_wrapper.h b/platform/android/java_godot_io_wrapper.h index 38a2b710a9..08e3092afd 100644 --- a/platform/android/java_godot_io_wrapper.h +++ b/platform/android/java_godot_io_wrapper.h @@ -51,6 +51,7 @@ private: jmethodID _get_locale = 0; jmethodID _get_model = 0; jmethodID _get_screen_DPI = 0; + jmethodID _get_scaled_density = 0; jmethodID _get_screen_refresh_rate = 0; jmethodID _screen_get_usable_rect = 0; jmethodID _get_unique_id = 0; @@ -72,6 +73,7 @@ public: String get_locale(); String get_model(); int get_screen_dpi(); + float get_scaled_density(); float get_screen_refresh_rate(float fallback); void screen_get_usable_rect(int (&p_rect_xywh)[4]); String get_unique_id(); diff --git a/platform/android/os_android.h b/platform/android/os_android.h index 48239b3f84..a40e17dc2c 100644 --- a/platform/android/os_android.h +++ b/platform/android/os_android.h @@ -52,7 +52,7 @@ private: #endif #if defined(VULKAN_ENABLED) - ANativeWindow *native_window; + ANativeWindow *native_window = nullptr; #endif mutable String data_dir_cache; @@ -60,10 +60,10 @@ private: AudioDriverOpenSL audio_driver_android; - MainLoop *main_loop; + MainLoop *main_loop = nullptr; - GodotJavaWrapper *godot_java; - GodotIOJavaWrapper *godot_io_java; + GodotJavaWrapper *godot_java = nullptr; + GodotIOJavaWrapper *godot_io_java = nullptr; public: static const char *ANDROID_EXEC_PATH; diff --git a/platform/iphone/export/export_plugin.cpp b/platform/iphone/export/export_plugin.cpp index ac5886e620..57bee59523 100644 --- a/platform/iphone/export/export_plugin.cpp +++ b/platform/iphone/export/export_plugin.cpp @@ -530,8 +530,8 @@ Error EditorExportPlatformIOS::_export_icons(const Ref<EditorExportPreset> &p_pr String json_description = "{\"images\":["; String sizes; - DirAccessRef da = DirAccess::open(p_iconset_dir); - ERR_FAIL_COND_V_MSG(!da, ERR_CANT_OPEN, "Cannot open directory '" + p_iconset_dir + "'."); + Ref<DirAccess> da = DirAccess::open(p_iconset_dir); + ERR_FAIL_COND_V_MSG(da.is_null(), ERR_CANT_OPEN, "Cannot open directory '" + p_iconset_dir + "'."); for (uint64_t i = 0; i < (sizeof(icon_infos) / sizeof(icon_infos[0])); ++i) { IconInfo info = icon_infos[i]; @@ -588,17 +588,15 @@ Error EditorExportPlatformIOS::_export_icons(const Ref<EditorExportPreset> &p_pr } json_description += "]}"; - FileAccess *json_file = FileAccess::open(p_iconset_dir + "Contents.json", FileAccess::WRITE); - ERR_FAIL_COND_V(!json_file, ERR_CANT_CREATE); + Ref<FileAccess> json_file = FileAccess::open(p_iconset_dir + "Contents.json", FileAccess::WRITE); + ERR_FAIL_COND_V(json_file.is_null(), ERR_CANT_CREATE); CharString json_utf8 = json_description.utf8(); json_file->store_buffer((const uint8_t *)json_utf8.get_data(), json_utf8.length()); - memdelete(json_file); - FileAccess *sizes_file = FileAccess::open(p_iconset_dir + "sizes", FileAccess::WRITE); - ERR_FAIL_COND_V(!sizes_file, ERR_CANT_CREATE); + Ref<FileAccess> sizes_file = FileAccess::open(p_iconset_dir + "sizes", FileAccess::WRITE); + ERR_FAIL_COND_V(sizes_file.is_null(), ERR_CANT_CREATE); CharString sizes_utf8 = sizes.utf8(); sizes_file->store_buffer((const uint8_t *)sizes_utf8.get_data(), sizes_utf8.length()); - memdelete(sizes_file); return OK; } @@ -672,8 +670,8 @@ Error EditorExportPlatformIOS::_export_loading_screen_file(const Ref<EditorExpor } Error EditorExportPlatformIOS::_export_loading_screen_images(const Ref<EditorExportPreset> &p_preset, const String &p_dest_dir) { - DirAccessRef da = DirAccess::open(p_dest_dir); - ERR_FAIL_COND_V_MSG(!da, ERR_CANT_OPEN, "Cannot open directory '" + p_dest_dir + "'."); + Ref<DirAccess> da = DirAccess::open(p_dest_dir); + ERR_FAIL_COND_V_MSG(da.is_null(), ERR_CANT_OPEN, "Cannot open directory '" + p_dest_dir + "'."); for (uint64_t i = 0; i < sizeof(loading_screen_infos) / sizeof(loading_screen_infos[0]); ++i) { LoadingScreenInfo info = loading_screen_infos[i]; @@ -761,7 +759,7 @@ Error EditorExportPlatformIOS::_export_loading_screen_images(const Ref<EditorExp return OK; } -Error EditorExportPlatformIOS::_walk_dir_recursive(DirAccess *p_da, FileHandler p_handler, void *p_userdata) { +Error EditorExportPlatformIOS::_walk_dir_recursive(Ref<DirAccess> &p_da, FileHandler p_handler, void *p_userdata) { Vector<String> dirs; String current_dir = p_da->get_current_dir(); p_da->list_dir_begin(); @@ -807,7 +805,7 @@ struct CodesignData { Error EditorExportPlatformIOS::_codesign(String p_file, void *p_userdata) { if (p_file.ends_with(".dylib")) { - CodesignData *data = (CodesignData *)p_userdata; + CodesignData *data = static_cast<CodesignData *>(p_userdata); print_line(String("Signing ") + p_file); String sign_id; @@ -964,8 +962,8 @@ void EditorExportPlatformIOS::_add_assets_to_project(const Ref<EditorExportPrese Error EditorExportPlatformIOS::_copy_asset(const String &p_out_dir, const String &p_asset, const String *p_custom_file_name, bool p_is_framework, bool p_should_embed, Vector<IOSExportAsset> &r_exported_assets) { String binary_name = p_out_dir.get_file().get_basename(); - DirAccessRef da = DirAccess::create_for_path(p_asset); - if (!da) { + Ref<DirAccess> da = DirAccess::create_for_path(p_asset); + if (da.is_null()) { ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Can't create directory: " + p_asset + "."); } bool file_exists = da->file_exists(p_asset); @@ -1030,8 +1028,8 @@ Error EditorExportPlatformIOS::_copy_asset(const String &p_out_dir, const String destination = p_out_dir.plus_file(asset_path); } - DirAccessRef filesystem_da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V_MSG(!filesystem_da, ERR_CANT_CREATE, "Cannot create DirAccess for path '" + p_out_dir + "'."); + Ref<DirAccess> filesystem_da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V_MSG(filesystem_da.is_null(), ERR_CANT_CREATE, "Cannot create DirAccess for path '" + p_out_dir + "'."); if (!filesystem_da->dir_exists(destination_dir)) { Error make_dir_err = filesystem_da->make_dir_recursive(destination_dir); @@ -1097,11 +1095,9 @@ Error EditorExportPlatformIOS::_copy_asset(const String &p_out_dir, const String String info_plist = info_plist_format.replace("$name", file_name); - FileAccess *f = FileAccess::open(destination_dir.plus_file("Info.plist"), FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(destination_dir.plus_file("Info.plist"), FileAccess::WRITE); + if (f.is_valid()) { f->store_string(info_plist); - f->close(); - memdelete(f); } } } @@ -1411,8 +1407,8 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p } { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - if (da) { + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (da.is_valid()) { String current_dir = da->get_current_dir(); // remove leftovers from last export so they don't interfere @@ -1488,12 +1484,11 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p Vector<IOSExportAsset> assets; - DirAccessRef tmp_app_path = DirAccess::create_for_path(dest_dir); - ERR_FAIL_COND_V(!tmp_app_path, ERR_CANT_CREATE); + Ref<DirAccess> tmp_app_path = DirAccess::create_for_path(dest_dir); + ERR_FAIL_COND_V(tmp_app_path.is_null(), ERR_CANT_CREATE); print_line("Unzipping..."); - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); unzFile src_pkg_zip = unzOpen2(src_pkg_name.utf8().get_data(), &io); if (!src_pkg_zip) { EditorNode::add_io_error("Could not open export template (not a zip file?):\n" + src_pkg_name); @@ -1515,6 +1510,9 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String file = String::utf8(fname); @@ -1572,15 +1570,15 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p } /* write the file */ - FileAccess *f = FileAccess::open(file, FileAccess::WRITE); - if (!f) { - ERR_PRINT("Can't write '" + file + "'."); - unzClose(src_pkg_zip); - return ERR_CANT_CREATE; - }; - f->store_buffer(data.ptr(), data.size()); - f->close(); - memdelete(f); + { + Ref<FileAccess> f = FileAccess::open(file, FileAccess::WRITE); + if (f.is_null()) { + ERR_PRINT("Can't write '" + file + "'."); + unzClose(src_pkg_zip); + return ERR_CANT_CREATE; + }; + f->store_buffer(data.ptr(), data.size()); + } #if defined(OSX_ENABLED) || defined(X11_ENABLED) if (is_execute) { @@ -1611,7 +1609,7 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p { String fname = dest_dir + binary_name + "/en.lproj"; tmp_app_path->make_dir_recursive(fname); - FileAccessRef f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); f->store_line("/* Localized versions of Info.plist keys */"); f->store_line(""); f->store_line("CFBundleDisplayName = \"" + ProjectSettings::get_singleton()->get("application/config/name").operator String() + "\";"); @@ -1626,7 +1624,7 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p String lang = tr->get_locale(); String fname = dest_dir + binary_name + "/" + lang + ".lproj"; tmp_app_path->make_dir_recursive(fname); - FileAccessRef f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); f->store_line("/* Localized versions of Info.plist keys */"); f->store_line(""); if (appnames.has(lang)) { @@ -1680,9 +1678,8 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p String launch_image_path = dest_dir + binary_name + "/Images.xcassets/LaunchImage.launchimage/"; String splash_image_path = dest_dir + binary_name + "/Images.xcassets/SplashImage.imageset/"; - DirAccessRef launch_screen_da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - - if (!launch_screen_da) { + Ref<DirAccess> launch_screen_da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (launch_screen_da.is_null()) { return ERR_CANT_CREATE; } @@ -1719,25 +1716,24 @@ Error EditorExportPlatformIOS::export_project(const Ref<EditorExportPreset> &p_p _export_additional_assets(dest_dir + binary_name, libraries, assets); _add_assets_to_project(p_preset, project_file_data, assets); String project_file_name = dest_dir + binary_name + ".xcodeproj/project.pbxproj"; - FileAccess *f = FileAccess::open(project_file_name, FileAccess::WRITE); - if (!f) { - ERR_PRINT("Can't write '" + project_file_name + "'."); - return ERR_CANT_CREATE; - }; - f->store_buffer(project_file_data.ptr(), project_file_data.size()); - f->close(); - memdelete(f); + { + Ref<FileAccess> f = FileAccess::open(project_file_name, FileAccess::WRITE); + if (f.is_null()) { + ERR_PRINT("Can't write '" + project_file_name + "'."); + return ERR_CANT_CREATE; + }; + f->store_buffer(project_file_data.ptr(), project_file_data.size()); + } #ifdef OSX_ENABLED { if (ep.step("Code-signing dylibs", 2)) { return ERR_SKIP; } - DirAccess *dylibs_dir = DirAccess::open(dest_dir + binary_name + "/dylibs"); - ERR_FAIL_COND_V(!dylibs_dir, ERR_CANT_OPEN); + Ref<DirAccess> dylibs_dir = DirAccess::open(dest_dir + binary_name + "/dylibs"); + ERR_FAIL_COND_V(dylibs_dir.is_null(), ERR_CANT_OPEN); CodesignData codesign_data(p_preset, p_debug); err = _walk_dir_recursive(dylibs_dir, _codesign, &codesign_data); - memdelete(dylibs_dir); ERR_FAIL_COND_V(err, err); } diff --git a/platform/iphone/export/export_plugin.h b/platform/iphone/export/export_plugin.h index c01983e39f..3831f3bff2 100644 --- a/platform/iphone/export/export_plugin.h +++ b/platform/iphone/export/export_plugin.h @@ -65,7 +65,7 @@ class EditorExportPlatformIOS : public EditorExportPlatform { Vector<PluginConfigIOS> plugins; typedef Error (*FileHandler)(String p_file, void *p_userdata); - static Error _walk_dir_recursive(DirAccess *p_da, FileHandler p_handler, void *p_userdata); + static Error _walk_dir_recursive(Ref<DirAccess> &p_da, FileHandler p_handler, void *p_userdata); static Error _codesign(String p_file, void *p_userdata); void _blend_and_rotate(Ref<Image> &p_dst, Ref<Image> &p_src, bool p_rot); @@ -141,7 +141,7 @@ class EditorExportPlatformIOS : public EditorExportPlatform { } static void _check_for_changes_poll_thread(void *ud) { - EditorExportPlatformIOS *ea = (EditorExportPlatformIOS *)ud; + EditorExportPlatformIOS *ea = static_cast<EditorExportPlatformIOS *>(ud); while (!ea->quit_request.is_set()) { // Nothing to do if we already know the plugins have changed. @@ -215,8 +215,8 @@ public: /// List the gdip files in the directory specified by the p_path parameter. static Vector<String> list_plugin_config_files(const String &p_path, bool p_check_directories) { Vector<String> dir_files; - DirAccessRef da = DirAccess::open(p_path); - if (da) { + Ref<DirAccess> da = DirAccess::open(p_path); + if (da.is_valid()) { da->list_dir_begin(); while (true) { String file = da->get_next(); diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h index 3281ff0cdb..6a61f3a910 100644 --- a/platform/iphone/os_iphone.h +++ b/platform/iphone/os_iphone.h @@ -52,11 +52,11 @@ private: AudioDriverCoreAudio audio_driver; - iOS *ios; + iOS *ios = nullptr; - JoypadIPhone *joypad_iphone; + JoypadIPhone *joypad_iphone = nullptr; - MainLoop *main_loop; + MainLoop *main_loop = nullptr; virtual void initialize_core() override; virtual void initialize() override; diff --git a/platform/iphone/os_iphone.mm b/platform/iphone/os_iphone.mm index 1d990b5625..ea1bc0ef64 100644 --- a/platform/iphone/os_iphone.mm +++ b/platform/iphone/os_iphone.mm @@ -259,7 +259,7 @@ Error OSIPhone::shell_open(String p_uri) { } void OSIPhone::set_user_data_dir(String p_dir) { - DirAccessRef da = DirAccess::open(p_dir); + Ref<DirAccess> da = DirAccess::open(p_dir); user_data_dir = da->get_current_dir(); printf("setting data dir to %s from %s\n", user_data_dir.utf8().get_data(), p_dir.utf8().get_data()); } diff --git a/platform/javascript/api/javascript_tools_editor_plugin.cpp b/platform/javascript/api/javascript_tools_editor_plugin.cpp index 0442a1eaeb..31ce71127d 100644 --- a/platform/javascript/api/javascript_tools_editor_plugin.cpp +++ b/platform/javascript/api/javascript_tools_editor_plugin.cpp @@ -64,8 +64,7 @@ void JavaScriptToolsEditorPlugin::_download_zip(Variant p_v) { } String resource_path = ProjectSettings::get_singleton()->get_resource_path(); - FileAccess *src_f; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); // Name the downloaded ZIP file to contain the project name and download date for easier organization. // Replace characters not allowed (or risky) in Windows file names with safe characters. @@ -82,22 +81,22 @@ void JavaScriptToolsEditorPlugin::_download_zip(Variant p_v) { const String base_path = resource_path.substr(0, resource_path.rfind("/")) + "/"; _zip_recursive(resource_path, base_path, zip); zipClose(zip, nullptr); - FileAccess *f = FileAccess::open(output_path, FileAccess::READ); - ERR_FAIL_COND_MSG(!f, "Unable to create ZIP file."); - Vector<uint8_t> buf; - buf.resize(f->get_length()); - f->get_buffer(buf.ptrw(), buf.size()); - godot_js_os_download_buffer(buf.ptr(), buf.size(), output_name.utf8().get_data(), "application/zip"); + { + Ref<FileAccess> f = FileAccess::open(output_path, FileAccess::READ); + ERR_FAIL_COND_MSG(f.is_null(), "Unable to create ZIP file."); + Vector<uint8_t> buf; + buf.resize(f->get_length()); + f->get_buffer(buf.ptrw(), buf.size()); + godot_js_os_download_buffer(buf.ptr(), buf.size(), output_name.utf8().get_data(), "application/zip"); + } - f->close(); - memdelete(f); // Remove the temporary file since it was sent to the user's native filesystem as a download. DirAccess::remove_file_or_error(output_path); } void JavaScriptToolsEditorPlugin::_zip_file(String p_path, String p_base_path, zipFile p_zip) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { WARN_PRINT("Unable to open file for zipping: " + p_path); return; } @@ -105,8 +104,6 @@ void JavaScriptToolsEditorPlugin::_zip_file(String p_path, String p_base_path, z uint64_t len = f->get_length(); data.resize(len); f->get_buffer(data.ptrw(), len); - f->close(); - memdelete(f); String path = p_path.replace_first(p_base_path, ""); zipOpenNewFileInZip(p_zip, @@ -124,7 +121,7 @@ void JavaScriptToolsEditorPlugin::_zip_file(String p_path, String p_base_path, z } void JavaScriptToolsEditorPlugin::_zip_recursive(String p_path, String p_base_path, zipFile p_zip) { - DirAccessRef dir = DirAccess::open(p_path); + Ref<DirAccess> dir = DirAccess::open(p_path); if (!dir) { WARN_PRINT("Unable to open directory for zipping: " + p_path); return; diff --git a/platform/javascript/export/export_plugin.cpp b/platform/javascript/export/export_plugin.cpp index 84694461cf..66d93d7c49 100644 --- a/platform/javascript/export/export_plugin.cpp +++ b/platform/javascript/export/export_plugin.cpp @@ -33,8 +33,7 @@ #include "core/config/project_settings.h" Error EditorExportPlatformJavaScript::_extract_template(const String &p_template, const String &p_dir, const String &p_name, bool pwa) { - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); unzFile pkg = unzOpen2(p_template.utf8().get_data(), &io); if (!pkg) { @@ -70,14 +69,13 @@ Error EditorExportPlatformJavaScript::_extract_template(const String &p_template //write String dst = p_dir.plus_file(file.replace("godot", p_name)); - FileAccess *f = FileAccess::open(dst, FileAccess::WRITE); - if (!f) { + Ref<FileAccess> f = FileAccess::open(dst, FileAccess::WRITE); + if (f.is_null()) { EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + dst); unzClose(pkg); return ERR_FILE_CANT_WRITE; } f->store_buffer(data.ptr(), data.size()); - memdelete(f); } while (unzGoToNextFile(pkg) == UNZ_OK); unzClose(pkg); @@ -85,13 +83,12 @@ Error EditorExportPlatformJavaScript::_extract_template(const String &p_template } Error EditorExportPlatformJavaScript::_write_or_error(const uint8_t *p_content, int p_size, String p_path) { - FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); + if (f.is_null()) { EditorNode::get_singleton()->show_warning(TTR("Could not write file:") + "\n" + p_path); return ERR_FILE_CANT_WRITE; } f->store_buffer(p_content, p_size); - memdelete(f); return OK; } @@ -233,15 +230,13 @@ Error EditorExportPlatformJavaScript::_build_pwa(const Ref<EditorExportPreset> & const String sw_path = dir.plus_file(name + ".service.worker.js"); Vector<uint8_t> sw; { - FileAccess *f = FileAccess::open(sw_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(sw_path, FileAccess::READ); + if (f.is_null()) { EditorNode::get_singleton()->show_warning(TTR("Could not read file:") + "\n" + sw_path); return ERR_FILE_CANT_READ; } sw.resize(f->get_length()); f->get_buffer(sw.ptrw(), sw.size()); - memdelete(f); - f = nullptr; } _replace_strings(replaces, sw); Error err = _write_or_error(sw.ptr(), sw.size(), dir.plus_file(name + ".service.worker.js")); @@ -252,7 +247,7 @@ Error EditorExportPlatformJavaScript::_build_pwa(const Ref<EditorExportPreset> & // Custom offline page const String offline_page = p_preset->get("progressive_web_app/offline_page"); if (!offline_page.is_empty()) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); const String offline_dest = dir.plus_file(name + ".offline.html"); err = da->copy(ProjectSettings::get_singleton()->globalize_path(offline_page), offline_dest); if (err != OK) { @@ -456,7 +451,7 @@ Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPrese } { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); for (int i = 0; i < shared_objects.size(); i++) { String dst = base_dir.plus_file(shared_objects[i].path.get_file()); error = da->copy(shared_objects[i].path, dst); @@ -475,32 +470,25 @@ Error EditorExportPlatformJavaScript::export_project(const Ref<EditorExportPrese // Parse generated file sizes (pck and wasm, to help show a meaningful loading bar). Dictionary file_sizes; - FileAccess *f = nullptr; - f = FileAccess::open(pck_path, FileAccess::READ); - if (f) { + Ref<FileAccess> f = FileAccess::open(pck_path, FileAccess::READ); + if (f.is_valid()) { file_sizes[pck_path.get_file()] = (uint64_t)f->get_length(); - memdelete(f); - f = nullptr; } f = FileAccess::open(base_path + ".wasm", FileAccess::READ); - if (f) { + if (f.is_valid()) { file_sizes[base_name + ".wasm"] = (uint64_t)f->get_length(); - memdelete(f); - f = nullptr; } // Read the HTML shell file (custom or from template). const String html_path = custom_html.is_empty() ? base_path + ".html" : custom_html; Vector<uint8_t> html; f = FileAccess::open(html_path, FileAccess::READ); - if (!f) { + if (f.is_null()) { EditorNode::get_singleton()->show_warning(TTR("Could not read HTML shell:") + "\n" + html_path); return ERR_FILE_CANT_READ; } html.resize(f->get_length()); f->get_buffer(html.ptrw(), html.size()); - memdelete(f); - f = nullptr; // Generate HTML file with replaced strings. _fix_html(html, p_preset, base_name, p_debug, p_flags, shared_objects, file_sizes); @@ -586,7 +574,7 @@ Error EditorExportPlatformJavaScript::run(const Ref<EditorExportPreset> &p_prese } const String dest = EditorPaths::get_singleton()->get_cache_dir().plus_file("web"); - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (!da->dir_exists(dest)) { Error err = da->make_dir_recursive(dest); if (err != OK) { @@ -651,7 +639,7 @@ Ref<Texture2D> EditorExportPlatformJavaScript::get_run_icon() const { } void EditorExportPlatformJavaScript::_server_thread_poll(void *data) { - EditorExportPlatformJavaScript *ej = (EditorExportPlatformJavaScript *)data; + EditorExportPlatformJavaScript *ej = static_cast<EditorExportPlatformJavaScript *>(data); while (!ej->server_quit) { OS::get_singleton()->delay_usec(6900); { diff --git a/platform/javascript/export/export_server.h b/platform/javascript/export/export_server.h index 1b908ad9b0..f77ac3d1ad 100644 --- a/platform/javascript/export/export_server.h +++ b/platform/javascript/export/export_server.h @@ -153,8 +153,8 @@ public: } const String ctype = mimes[req_ext]; - FileAccess *f = FileAccess::open(filepath, FileAccess::READ); - ERR_FAIL_COND(!f); + Ref<FileAccess> f = FileAccess::open(filepath, FileAccess::READ); + ERR_FAIL_COND(f.is_null()); String s = "HTTP/1.1 200 OK\r\n"; s += "Connection: Close\r\n"; s += "Content-Type: " + ctype + "\r\n"; @@ -166,7 +166,6 @@ public: CharString cs = s.utf8(); Error err = peer->put_data((const uint8_t *)cs.get_data(), cs.size() - 1); if (err != OK) { - memdelete(f); ERR_FAIL(); } @@ -178,11 +177,9 @@ public: } err = peer->put_data(bytes, read); if (err != OK) { - memdelete(f); ERR_FAIL(); } } - memdelete(f); } void poll() { diff --git a/platform/linuxbsd/detect.py b/platform/linuxbsd/detect.py index f3a6004356..39f9b99108 100644 --- a/platform/linuxbsd/detect.py +++ b/platform/linuxbsd/detect.py @@ -115,7 +115,7 @@ def configure(env): ## Architecture - is64 = sys.maxsize > 2 ** 32 + is64 = sys.maxsize > 2**32 if env["bits"] == "default": env["bits"] = "64" if is64 else "32" diff --git a/platform/linuxbsd/display_server_x11.cpp b/platform/linuxbsd/display_server_x11.cpp index 8fa8c64efe..7da30ac363 100644 --- a/platform/linuxbsd/display_server_x11.cpp +++ b/platform/linuxbsd/display_server_x11.cpp @@ -3052,7 +3052,7 @@ void DisplayServerX11::_window_changed(XEvent *event) { } void DisplayServerX11::_dispatch_input_events(const Ref<InputEvent> &p_event) { - ((DisplayServerX11 *)(get_singleton()))->_dispatch_input_event(p_event); + static_cast<DisplayServerX11 *>(get_singleton())->_dispatch_input_event(p_event); } void DisplayServerX11::_dispatch_input_event(const Ref<InputEvent> &p_event) { @@ -3062,7 +3062,7 @@ void DisplayServerX11::_dispatch_input_event(const Ref<InputEvent> &p_event) { Callable::CallError ce; { - List<WindowID>::Element *E = popup_list.front(); + List<WindowID>::Element *E = popup_list.back(); if (E && Object::cast_to<InputEventKey>(*p_event)) { // Redirect keyboard input to active popup. if (windows.has(E->get())) { @@ -3106,7 +3106,7 @@ void DisplayServerX11::_send_window_event(const WindowData &wd, WindowEvent p_ev } void DisplayServerX11::_poll_events_thread(void *ud) { - DisplayServerX11 *display_server = (DisplayServerX11 *)ud; + DisplayServerX11 *display_server = static_cast<DisplayServerX11 *>(ud); display_server->_poll_events(); } @@ -3208,20 +3208,24 @@ Rect2i DisplayServerX11::window_get_popup_safe_rect(WindowID p_window) const { } void DisplayServerX11::popup_open(WindowID p_window) { + _THREAD_SAFE_METHOD_ + WindowData &wd = windows[p_window]; if (wd.is_popup) { - // Close all popups, up to current popup parent, or every popup if new window is not transient. + // Find current popup parent, or root popup if new window is not transient. + List<WindowID>::Element *C = nullptr; List<WindowID>::Element *E = popup_list.back(); while (E) { if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) { - _send_window_event(windows[E->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST); - List<WindowID>::Element *F = E->prev(); - popup_list.erase(E); - E = F; + C = E; + E = E->prev(); } else { break; } } + if (C) { + _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST); + } time_since_popup = OS::get_singleton()->get_ticks_msec(); popup_list.push_back(p_window); @@ -3229,16 +3233,22 @@ void DisplayServerX11::popup_open(WindowID p_window) { } void DisplayServerX11::popup_close(WindowID p_window) { + _THREAD_SAFE_METHOD_ + List<WindowID>::Element *E = popup_list.find(p_window); while (E) { - _send_window_event(windows[E->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST); List<WindowID>::Element *F = E->next(); + WindowID win_id = E->get(); popup_list.erase(E); + + _send_window_event(windows[win_id], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST); E = F; } } void DisplayServerX11::mouse_process_popups() { + _THREAD_SAFE_METHOD_ + if (popup_list.is_empty()) { return; } @@ -3259,7 +3269,9 @@ void DisplayServerX11::mouse_process_popups() { Vector2i pos = Vector2i(root_attrs.x + root_x, root_attrs.y + root_y); if ((pos != last_mouse_monitor_pos) || (mask != last_mouse_monitor_mask)) { if (((mask & Button1Mask) || (mask & Button2Mask) || (mask & Button3Mask) || (mask & Button4Mask) || (mask & Button5Mask))) { + List<WindowID>::Element *C = nullptr; List<WindowID>::Element *E = popup_list.back(); + // Find top popup to close. while (E) { // Popup window area. Rect2i win_rect = Rect2i(window_get_position(E->get()), window_get_size(E->get())); @@ -3270,12 +3282,13 @@ void DisplayServerX11::mouse_process_popups() { } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) { break; } else { - _send_window_event(windows[E->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST); - List<WindowID>::Element *F = E->prev(); - popup_list.erase(E); - E = F; + C = E; + E = E->prev(); } } + if (C) { + _send_window_event(windows[C->get()], DisplayServerX11::WINDOW_EVENT_CLOSE_REQUEST); + } } } last_mouse_monitor_mask = mask; diff --git a/platform/linuxbsd/display_server_x11.h b/platform/linuxbsd/display_server_x11.h index 0f44aa4b11..cd673d94d9 100644 --- a/platform/linuxbsd/display_server_x11.h +++ b/platform/linuxbsd/display_server_x11.h @@ -108,7 +108,7 @@ class DisplayServerX11 : public DisplayServer { #endif #if defined(DBUS_ENABLED) - FreeDesktopScreenSaver *screensaver; + FreeDesktopScreenSaver *screensaver = nullptr; bool keep_screen_on = false; #endif @@ -168,7 +168,7 @@ class DisplayServerX11 : public DisplayServer { String internal_clipboard_primary; Window xdnd_source_window; ::Display *x11_display; - char *xmbstring; + char *xmbstring = nullptr; int xmblen; unsigned long last_timestamp; ::Time last_keyrelease_time; @@ -249,7 +249,7 @@ class DisplayServerX11 : public DisplayServer { typedef void (*xrr_free_monitors_t)(xrr_monitor_info *monitors); xrr_get_monitors_t xrr_get_monitors; xrr_free_monitors_t xrr_free_monitors; - void *xrandr_handle; + void *xrandr_handle = nullptr; Bool xrandr_ext_ok; struct Property { diff --git a/platform/linuxbsd/export/export_plugin.cpp b/platform/linuxbsd/export/export_plugin.cpp index 24906fa3fb..9f7fab6ee8 100644 --- a/platform/linuxbsd/export/export_plugin.cpp +++ b/platform/linuxbsd/export/export_plugin.cpp @@ -34,8 +34,8 @@ #include "editor/editor_node.h" Error EditorExportPlatformLinuxBSD::_export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path) { - FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V(!f, ERR_CANT_CREATE); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE); f->store_line("#!/bin/sh"); f->store_line("echo -ne '\\033c\\033]0;" + p_app_name + "\\a'"); @@ -101,8 +101,8 @@ List<String> EditorExportPlatformLinuxBSD::get_binary_extensions(const Ref<Edito Error EditorExportPlatformLinuxBSD::fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size) const { // Patch the header of the "pck" section in the ELF file so that it corresponds to the embedded data - FileAccess *f = FileAccess::open(p_path, FileAccess::READ_WRITE); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ_WRITE); + if (f.is_null()) { return ERR_CANT_OPEN; } @@ -110,7 +110,6 @@ Error EditorExportPlatformLinuxBSD::fixup_embedded_pck(const String &p_path, int { uint32_t magic = f->get_32(); if (magic != 0x464c457f) { // 0x7F + "ELF" - f->close(); return ERR_FILE_CORRUPT; } } @@ -120,7 +119,6 @@ Error EditorExportPlatformLinuxBSD::fixup_embedded_pck(const String &p_path, int int bits = f->get_8() * 32; if (bits == 32 && p_embedded_size >= 0x100000000) { - f->close(); ERR_FAIL_V_MSG(ERR_INVALID_DATA, "32-bit executables cannot have embedded data >= 4 GiB."); } @@ -165,7 +163,6 @@ Error EditorExportPlatformLinuxBSD::fixup_embedded_pck(const String &p_path, int f->seek(string_data_pos); strings = (uint8_t *)memalloc(string_data_size); if (!strings) { - f->close(); return ERR_OUT_OF_MEMORY; } f->get_buffer(strings, string_data_size); @@ -198,7 +195,6 @@ Error EditorExportPlatformLinuxBSD::fixup_embedded_pck(const String &p_path, int } memfree(strings); - f->close(); return found ? OK : ERR_FILE_CORRUPT; } diff --git a/platform/linuxbsd/gl_manager_x11.h b/platform/linuxbsd/gl_manager_x11.h index 0bb0a446ab..fb2c74a2b6 100644 --- a/platform/linuxbsd/gl_manager_x11.h +++ b/platform/linuxbsd/gl_manager_x11.h @@ -52,21 +52,20 @@ public: private: // any data specific to the window struct GLWindow { - GLWindow() { in_use = false; } - bool in_use; + bool in_use = false; // the external ID .. should match the GL window number .. unused I think - DisplayServer::WindowID window_id; - int width; - int height; + DisplayServer::WindowID window_id = DisplayServer::INVALID_WINDOW_ID; + int width = 0; + int height = 0; ::Window x11_window; - int gldisplay_id; + int gldisplay_id = 0; }; struct GLDisplay { GLDisplay() { context = nullptr; } ~GLDisplay(); - GLManager_X11_Private *context; + GLManager_X11_Private *context = nullptr; ::Display *x11_display; XVisualInfo x_vi; XSetWindowAttributes x_swa; @@ -82,7 +81,7 @@ private: LocalVector<GLWindow> _windows; LocalVector<GLDisplay> _displays; - GLWindow *_current_window; + GLWindow *_current_window = nullptr; void _internal_set_current_window(GLWindow *p_win); diff --git a/platform/linuxbsd/joypad_linux.cpp b/platform/linuxbsd/joypad_linux.cpp index 65d53b266f..22a9518a25 100644 --- a/platform/linuxbsd/joypad_linux.cpp +++ b/platform/linuxbsd/joypad_linux.cpp @@ -95,7 +95,7 @@ JoypadLinux::~JoypadLinux() { void JoypadLinux::joy_thread_func(void *p_user) { if (p_user) { - JoypadLinux *joy = (JoypadLinux *)p_user; + JoypadLinux *joy = static_cast<JoypadLinux *>(p_user); joy->run_joypad_thread(); } } diff --git a/platform/linuxbsd/os_linuxbsd.cpp b/platform/linuxbsd/os_linuxbsd.cpp index 86874687ad..bf142f8804 100644 --- a/platform/linuxbsd/os_linuxbsd.cpp +++ b/platform/linuxbsd/os_linuxbsd.cpp @@ -131,20 +131,19 @@ void OS_LinuxBSD::initialize_joypads() { String OS_LinuxBSD::get_unique_id() const { static String machine_id; if (machine_id.is_empty()) { - if (FileAccess *f = FileAccess::open("/etc/machine-id", FileAccess::READ)) { + Ref<FileAccess> f = FileAccess::open("/etc/machine-id", FileAccess::READ); + if (f.is_valid()) { while (machine_id.is_empty() && !f->eof_reached()) { machine_id = f->get_line().strip_edges(); } - f->close(); - memdelete(f); } } return machine_id; } String OS_LinuxBSD::get_processor_name() const { - FileAccessRef f = FileAccess::open("/proc/cpuinfo", FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, "", String("Couldn't open `/proc/cpuinfo` to get the CPU model name. Returning an empty string.")); + Ref<FileAccess> f = FileAccess::open("/proc/cpuinfo", FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), "", String("Couldn't open `/proc/cpuinfo` to get the CPU model name. Returning an empty string.")); while (!f->eof_reached()) { const String line = f->get_line(); @@ -465,7 +464,7 @@ Error OS_LinuxBSD::move_to_trash(const String &p_path) { // Create needed directories for decided trash can location. { - DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); Error err = dir_access->make_dir_recursive(trash_path); // Issue an error if trash can is not created properly. @@ -512,13 +511,14 @@ Error OS_LinuxBSD::move_to_trash(const String &p_path) { String trash_info = "[Trash Info]\nPath=" + path.uri_encode() + "\nDeletionDate=" + timestamp + "\n"; { Error err; - FileAccessRef file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err); - ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\""); - file->store_string(trash_info); - file->close(); + { + Ref<FileAccess> file = FileAccess::open(trash_path + "/info/" + file_name + ".trashinfo", FileAccess::WRITE, &err); + ERR_FAIL_COND_V_MSG(err != OK, err, "Can't create trashinfo file: \"" + trash_path + "/info/" + file_name + ".trashinfo\""); + file->store_string(trash_info); + } // Rename our resource before moving it to the trash can. - DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); err = dir_access->rename(path, renamed_path); ERR_FAIL_COND_V_MSG(err != OK, err, "Can't rename file \"" + path + "\" to \"" + renamed_path + "\""); } @@ -535,7 +535,7 @@ Error OS_LinuxBSD::move_to_trash(const String &p_path) { // Issue an error if "mv" failed to move the given resource to the trash can. if (err != OK || retval != 0) { ERR_PRINT("move_to_trash: Could not move the resource \"" + path + "\" to the trash can \"" + trash_path + "/files\""); - DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); err = dir_access->rename(renamed_path, path); ERR_FAIL_COND_V_MSG(err != OK, err, "Could not rename \"" + renamed_path + "\" back to its original name: \"" + path + "\""); return FAILED; diff --git a/platform/linuxbsd/os_linuxbsd.h b/platform/linuxbsd/os_linuxbsd.h index d3857e85f8..7b912ddee3 100644 --- a/platform/linuxbsd/os_linuxbsd.h +++ b/platform/linuxbsd/os_linuxbsd.h @@ -63,7 +63,7 @@ class OS_LinuxBSD : public OS_Unix { CrashHandler crash_handler; - MainLoop *main_loop; + MainLoop *main_loop = nullptr; protected: virtual void initialize() override; diff --git a/platform/osx/display_server_osx.mm b/platform/osx/display_server_osx.mm index 6cdadcae39..d209c90d87 100644 --- a/platform/osx/display_server_osx.mm +++ b/platform/osx/display_server_osx.mm @@ -326,7 +326,7 @@ void DisplayServerOSX::_dispatch_input_event(const Ref<InputEvent> &p_event) { Callable::CallError ce; { - List<WindowID>::Element *E = popup_list.front(); + List<WindowID>::Element *E = popup_list.back(); if (E && Object::cast_to<InputEventKey>(*p_event)) { // Redirect keyboard input to active popup. if (windows.has(E->get())) { @@ -2892,14 +2892,13 @@ void DisplayServerOSX::swap_buffers() { void DisplayServerOSX::set_native_icon(const String &p_filename) { _THREAD_SAFE_METHOD_ - FileAccess *f = FileAccess::open(p_filename, FileAccess::READ); - ERR_FAIL_COND(!f); + Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::READ); + ERR_FAIL_COND(f.is_null()); Vector<uint8_t> data; uint64_t len = f->get_length(); data.resize(len); f->get_buffer((uint8_t *)&data.write[0], len); - memdelete(f); NSData *icon_data = [[NSData alloc] initWithBytes:&data.write[0] length:len]; ERR_FAIL_COND_MSG(!icon_data, "Error reading icon data."); @@ -3000,21 +2999,25 @@ Rect2i DisplayServerOSX::window_get_popup_safe_rect(WindowID p_window) const { } void DisplayServerOSX::popup_open(WindowID p_window) { + _THREAD_SAFE_METHOD_ + WindowData &wd = windows[p_window]; if (wd.is_popup) { bool was_empty = popup_list.is_empty(); - // Close all popups, up to current popup parent, or every popup if new window is not transient. + // Find current popup parent, or root popup if new window is not transient. + List<WindowID>::Element *C = nullptr; List<WindowID>::Element *E = popup_list.back(); while (E) { if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) { - send_window_event(windows[E->get()], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST); - List<WindowID>::Element *F = E->prev(); - popup_list.erase(E); - E = F; + C = E; + E = E->prev(); } else { break; } } + if (C) { + send_window_event(windows[C->get()], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST); + } if (was_empty && popup_list.is_empty()) { // Inform OS that popup was opened, to close other native popups. @@ -3026,12 +3029,16 @@ void DisplayServerOSX::popup_open(WindowID p_window) { } void DisplayServerOSX::popup_close(WindowID p_window) { + _THREAD_SAFE_METHOD_ + bool was_empty = popup_list.is_empty(); List<WindowID>::Element *E = popup_list.find(p_window); while (E) { - send_window_event(windows[E->get()], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST); List<WindowID>::Element *F = E->next(); + WindowID win_id = E->get(); popup_list.erase(E); + + send_window_event(windows[win_id], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST); E = F; } if (!was_empty && popup_list.is_empty()) { @@ -3047,11 +3054,8 @@ void DisplayServerOSX::mouse_process_popups(bool p_close) { if (p_close) { // Close all popups. List<WindowID>::Element *E = popup_list.front(); - while (E) { + if (E) { send_window_event(windows[E->get()], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST); - List<WindowID>::Element *F = E->next(); - popup_list.erase(E); - E = F; } if (!was_empty) { // Inform OS that all popups are closed. @@ -3064,7 +3068,9 @@ void DisplayServerOSX::mouse_process_popups(bool p_close) { } Point2i pos = mouse_get_position(); + List<WindowID>::Element *C = nullptr; List<WindowID>::Element *E = popup_list.back(); + // Find top popup to close. while (E) { // Popup window area. Rect2i win_rect = Rect2i(window_get_position(E->get()), window_get_size(E->get())); @@ -3075,12 +3081,13 @@ void DisplayServerOSX::mouse_process_popups(bool p_close) { } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) { break; } else { - send_window_event(windows[E->get()], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST); - List<WindowID>::Element *F = E->prev(); - popup_list.erase(E); - E = F; + C = E; + E = E->prev(); } } + if (C) { + send_window_event(windows[C->get()], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST); + } if (!was_empty && popup_list.is_empty()) { // Inform OS that all popups are closed. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"]; diff --git a/platform/osx/export/codesign.cpp b/platform/osx/export/codesign.cpp index b609a21c44..fd044c00cc 100644 --- a/platform/osx/export/codesign.cpp +++ b/platform/osx/export/codesign.cpp @@ -49,8 +49,8 @@ /*************************************************************************/ String CodeSignCodeResources::hash_sha1_base64(const String &p_path) { - FileAccessRef fa = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!fa, String(), vformat("CodeSign/CodeResources: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(fa.is_null(), String(), vformat("CodeSign/CodeResources: Can't open file: \"%s\".", p_path)); CryptoCore::SHA1Context ctx; ctx.start(); @@ -68,14 +68,13 @@ String CodeSignCodeResources::hash_sha1_base64(const String &p_path) { unsigned char hash[0x14]; ctx.finish(hash); - fa->close(); return CryptoCore::b64_encode_str(hash, 0x14); } String CodeSignCodeResources::hash_sha256_base64(const String &p_path) { - FileAccessRef fa = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!fa, String(), vformat("CodeSign/CodeResources: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(fa.is_null(), String(), vformat("CodeSign/CodeResources: Can't open file: \"%s\".", p_path)); CryptoCore::SHA256Context ctx; ctx.start(); @@ -93,7 +92,6 @@ String CodeSignCodeResources::hash_sha256_base64(const String &p_path) { unsigned char hash[0x20]; ctx.finish(hash); - fa->close(); return CryptoCore::b64_encode_str(hash, 0x20); } @@ -211,16 +209,14 @@ bool CodeSignCodeResources::add_nested_file(const String &p_root, const String & } \ } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V(!da, false); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V(da.is_null(), false); Vector<String> files_to_add; if (LipO::is_lipo(p_exepath)) { String tmp_path_name = EditorPaths::get_singleton()->get_cache_dir().plus_file("_lipo"); Error err = da->make_dir_recursive(tmp_path_name); - if (err != OK) { - ERR_FAIL_V_MSG(false, vformat("CodeSign/CodeResources: Failed to create \"%s\" subfolder.", tmp_path_name)); - } + ERR_FAIL_COND_V_MSG(err != OK, false, vformat("CodeSign/CodeResources: Failed to create \"%s\" subfolder.", tmp_path_name)); LipO lip; if (lip.open_file(p_exepath)) { for (int i = 0; i < lip.get_arch_count(); i++) { @@ -287,8 +283,8 @@ bool CodeSignCodeResources::add_nested_file(const String &p_root, const String & } bool CodeSignCodeResources::add_folder_recursive(const String &p_root, const String &p_path, const String &p_main_exe_path) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - ERR_FAIL_COND_V(!da, false); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + ERR_FAIL_COND_V(da.is_null(), false); Error err = da->change_dir(p_root.plus_file(p_path)); ERR_FAIL_COND_V(err != OK, false); @@ -431,12 +427,11 @@ bool CodeSignCodeResources::save_to_file(const String &p_path) { String text = pl.save_text(); ERR_FAIL_COND_V_MSG(text.is_empty(), false, "CodeSign/CodeResources: Generating resources PList failed."); - FileAccessRef fa = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!fa, false, vformat("CodeSign/CodeResources: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> fa = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("CodeSign/CodeResources: Can't open file: \"%s\".", p_path)); CharString cs = text.utf8(); fa->store_buffer((const uint8_t *)cs.ptr(), cs.length()); - fa->close(); return true; } @@ -809,8 +804,8 @@ int CodeSignRequirements::get_size() const { return blob.size(); } -void CodeSignRequirements::write_to_file(FileAccess *p_file) const { - ERR_FAIL_COND_MSG(!p_file, "CodeSign/Requirements: Invalid file handle."); +void CodeSignRequirements::write_to_file(Ref<FileAccess> p_file) const { + ERR_FAIL_COND_MSG(p_file.is_null(), "CodeSign/Requirements: Invalid file handle."); p_file->store_buffer(blob.ptr(), blob.size()); } @@ -863,8 +858,8 @@ int CodeSignEntitlementsText::get_size() const { return blob.size(); } -void CodeSignEntitlementsText::write_to_file(FileAccess *p_file) const { - ERR_FAIL_COND_MSG(!p_file, "CodeSign/EntitlementsText: Invalid file handle."); +void CodeSignEntitlementsText::write_to_file(Ref<FileAccess> p_file) const { + ERR_FAIL_COND_MSG(p_file.is_null(), "CodeSign/EntitlementsText: Invalid file handle."); p_file->store_buffer(blob.ptr(), blob.size()); } @@ -918,8 +913,8 @@ int CodeSignEntitlementsBinary::get_size() const { return blob.size(); } -void CodeSignEntitlementsBinary::write_to_file(FileAccess *p_file) const { - ERR_FAIL_COND_MSG(!p_file, "CodeSign/EntitlementsBinary: Invalid file handle."); +void CodeSignEntitlementsBinary::write_to_file(Ref<FileAccess> p_file) const { + ERR_FAIL_COND_MSG(p_file.is_null(), "CodeSign/EntitlementsBinary: Invalid file handle."); p_file->store_buffer(blob.ptr(), blob.size()); } @@ -947,7 +942,7 @@ CodeSignCodeDirectory::CodeSignCodeDirectory(uint8_t p_hash_size, uint8_t p_hash } blob.resize(cd_size); memset(blob.ptrw() + 8, 0x00, cd_size - 8); - CodeDirectoryHeader *cd = (CodeDirectoryHeader *)(blob.ptrw() + 8); + CodeDirectoryHeader *cd = reinterpret_cast<CodeDirectoryHeader *>(blob.ptrw() + 8); bool is_64_cl = (p_code_limit >= std::numeric_limits<uint32_t>::max()); @@ -1040,8 +1035,8 @@ int CodeSignCodeDirectory::get_size() const { return blob.size(); } -void CodeSignCodeDirectory::write_to_file(FileAccess *p_file) const { - ERR_FAIL_COND_MSG(!p_file, "CodeSign/CodeDirectory: Invalid file handle."); +void CodeSignCodeDirectory::write_to_file(Ref<FileAccess> p_file) const { + ERR_FAIL_COND_MSG(p_file.is_null(), "CodeSign/CodeDirectory: Invalid file handle."); p_file->store_buffer(blob.ptr(), blob.size()); } @@ -1086,8 +1081,8 @@ int CodeSignSignature::get_size() const { return blob.size(); } -void CodeSignSignature::write_to_file(FileAccess *p_file) const { - ERR_FAIL_COND_MSG(!p_file, "CodeSign/Signature: Invalid file handle."); +void CodeSignSignature::write_to_file(Ref<FileAccess> p_file) const { + ERR_FAIL_COND_MSG(p_file.is_null(), "CodeSign/Signature: Invalid file handle."); p_file->store_buffer(blob.ptr(), blob.size()); } @@ -1115,8 +1110,8 @@ int CodeSignSuperBlob::get_size() const { return size; } -void CodeSignSuperBlob::write_to_file(FileAccess *p_file) const { - ERR_FAIL_COND_MSG(!p_file, "CodeSign/SuperBlob: Invalid file handle."); +void CodeSignSuperBlob::write_to_file(Ref<FileAccess> p_file) const { + ERR_FAIL_COND_MSG(p_file.is_null(), "CodeSign/SuperBlob: Invalid file handle."); uint32_t size = get_size(); uint32_t data_offset = 12 + blobs.size() * 8; @@ -1147,8 +1142,8 @@ void CodeSignSuperBlob::write_to_file(FileAccess *p_file) const { PackedByteArray CodeSign::file_hash_sha1(const String &p_path) { PackedByteArray file_hash; - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, PackedByteArray(), vformat("CodeSign: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), PackedByteArray(), vformat("CodeSign: Can't open file: \"%s\".", p_path)); CryptoCore::SHA1Context ctx; ctx.start(); @@ -1171,8 +1166,8 @@ PackedByteArray CodeSign::file_hash_sha1(const String &p_path) { PackedByteArray CodeSign::file_hash_sha256(const String &p_path) { PackedByteArray file_hash; - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, PackedByteArray(), vformat("CodeSign: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), PackedByteArray(), vformat("CodeSign: Can't open file: \"%s\".", p_path)); CryptoCore::SHA256Context ctx; ctx.start(); @@ -1208,8 +1203,8 @@ Error CodeSign::_codesign_file(bool p_use_hardened_runtime, bool p_force, const String id; String main_exe = p_exe_path; - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - if (!da) { + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (da.is_null()) { r_error_msg = TTR("Can't get filesystem access."); ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CodeSign: Can't get filesystem access."); } @@ -1522,8 +1517,8 @@ Error CodeSign::_codesign_file(bool p_use_hardened_runtime, bool p_force, const } Error CodeSign::codesign(bool p_use_hardened_runtime, bool p_force, const String &p_path, const String &p_ent_path, String &r_error_msg) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); - if (!da) { + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + if (da.is_null()) { r_error_msg = TTR("Can't get filesystem access."); ERR_FAIL_V_MSG(ERR_CANT_CREATE, "CodeSign: Can't get filesystem access."); } diff --git a/platform/osx/export/codesign.h b/platform/osx/export/codesign.h index e5e9be5c28..3a08c0ea86 100644 --- a/platform/osx/export/codesign.h +++ b/platform/osx/export/codesign.h @@ -132,7 +132,7 @@ public: virtual int get_size() const = 0; virtual uint32_t get_index_type() const = 0; - virtual void write_to_file(FileAccess *p_file) const = 0; + virtual void write_to_file(Ref<FileAccess> p_file) const = 0; }; /*************************************************************************/ @@ -168,7 +168,7 @@ public: virtual int get_size() const override; virtual uint32_t get_index_type() const override { return 0x00000002; }; - virtual void write_to_file(FileAccess *p_file) const override; + virtual void write_to_file(Ref<FileAccess> p_file) const override; }; /*************************************************************************/ @@ -190,7 +190,7 @@ public: virtual int get_size() const override; virtual uint32_t get_index_type() const override { return 0x00000005; }; - virtual void write_to_file(FileAccess *p_file) const override; + virtual void write_to_file(Ref<FileAccess> p_file) const override; }; /*************************************************************************/ @@ -212,7 +212,7 @@ public: virtual int get_size() const override; virtual uint32_t get_index_type() const override { return 0x00000007; }; - virtual void write_to_file(FileAccess *p_file) const override; + virtual void write_to_file(Ref<FileAccess> p_file) const override; }; /*************************************************************************/ @@ -314,7 +314,7 @@ public: virtual int get_size() const override; virtual uint32_t get_index_type() const override { return 0x00000000; }; - virtual void write_to_file(FileAccess *p_file) const override; + virtual void write_to_file(Ref<FileAccess> p_file) const override; }; /*************************************************************************/ @@ -333,7 +333,7 @@ public: virtual int get_size() const override; virtual uint32_t get_index_type() const override { return 0x00010000; }; - virtual void write_to_file(FileAccess *p_file) const override; + virtual void write_to_file(Ref<FileAccess> p_file) const override; }; /*************************************************************************/ @@ -347,7 +347,7 @@ public: bool add_blob(const Ref<CodeSignBlob> &p_blob); int get_size() const; - void write_to_file(FileAccess *p_file) const; + void write_to_file(Ref<FileAccess> p_file) const; }; /*************************************************************************/ diff --git a/platform/osx/export/export_plugin.cpp b/platform/osx/export/export_plugin.cpp index 4f06342fac..94ef875072 100644 --- a/platform/osx/export/export_plugin.cpp +++ b/platform/osx/export/export_plugin.cpp @@ -256,22 +256,23 @@ void EditorExportPlatformOSX::_make_icon(const Ref<Image> &p_icon, Vector<uint8_ String path = EditorPaths::get_singleton()->get_cache_dir().plus_file("icon.png"); ResourceSaver::save(path, it); - FileAccess *f = FileAccess::open(path, FileAccess::READ); - if (!f) { - // Clean up generated file. - DirAccess::remove_file_or_error(path); - ERR_FAIL(); - } + { + Ref<FileAccess> f = FileAccess::open(path, FileAccess::READ); + if (f.is_null()) { + // Clean up generated file. + DirAccess::remove_file_or_error(path); + ERR_FAIL(); + } - int ofs = data.size(); - uint64_t len = f->get_length(); - data.resize(data.size() + len + 8); - f->get_buffer(&data.write[ofs + 8], len); - memdelete(f); - len += 8; - len = BSWAP32(len); - memcpy(&data.write[ofs], icon_infos[i].name, 4); - encode_uint32(len, &data.write[ofs + 4]); + int ofs = data.size(); + uint64_t len = f->get_length(); + data.resize(data.size() + len + 8); + f->get_buffer(&data.write[ofs + 8], len); + len += 8; + len = BSWAP32(len); + memcpy(&data.write[ofs], icon_infos[i].name, 4); + encode_uint32(len, &data.write[ofs + 4]); + } // Clean up generated file. DirAccess::remove_file_or_error(path); @@ -565,7 +566,7 @@ Error EditorExportPlatformOSX::_code_sign_directory(const Ref<EditorExportPreset } Error dir_access_error; - DirAccessRef dir_access{ DirAccess::open(p_path, &dir_access_error) }; + Ref<DirAccess> dir_access{ DirAccess::open(p_path, &dir_access_error) }; if (dir_access_error != OK) { return dir_access_error; @@ -603,7 +604,7 @@ Error EditorExportPlatformOSX::_code_sign_directory(const Ref<EditorExportPreset return OK; } -Error EditorExportPlatformOSX::_copy_and_sign_files(DirAccessRef &dir_access, const String &p_src_path, +Error EditorExportPlatformOSX::_copy_and_sign_files(Ref<DirAccess> &dir_access, const String &p_src_path, const String &p_in_app_path, bool p_sign_enabled, const Ref<EditorExportPreset> &p_preset, const String &p_ent_path, bool p_should_error_on_non_code_sign) { @@ -633,7 +634,7 @@ Error EditorExportPlatformOSX::_copy_and_sign_files(DirAccessRef &dir_access, co } Error EditorExportPlatformOSX::_export_osx_plugins_for(Ref<EditorExportPlugin> p_editor_export_plugin, - const String &p_app_path_name, DirAccessRef &dir_access, + const String &p_app_path_name, Ref<DirAccess> &dir_access, bool p_sign_enabled, const Ref<EditorExportPreset> &p_preset, const String &p_ent_path) { Error error{ OK }; @@ -683,8 +684,8 @@ Error EditorExportPlatformOSX::_create_dmg(const String &p_dmg_path, const Strin } Error EditorExportPlatformOSX::_export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path) { - FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V(!f, ERR_CANT_CREATE); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE); f->store_line("#!/bin/sh"); f->store_line("echo -ne '\\033c\\033]0;" + p_app_name + "\\a'"); @@ -721,8 +722,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p return ERR_FILE_BAD_PATH; } - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); if (ep.step(TTR("Creating app bundle"), 0)) { return ERR_SKIP; @@ -778,8 +778,8 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p Error err = OK; - DirAccessRef tmp_app_dir = DirAccess::create_for_path(tmp_base_path_name); - if (!tmp_app_dir) { + Ref<DirAccess> tmp_app_dir = DirAccess::create_for_path(tmp_base_path_name); + if (tmp_app_dir.is_null()) { err = ERR_CANT_CREATE; } @@ -832,7 +832,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p { String fname = tmp_app_path_name + "/Contents/Resources/en.lproj"; tmp_app_dir->make_dir_recursive(fname); - FileAccessRef f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); f->store_line("/* Localized versions of Info.plist keys */"); f->store_line(""); f->store_line("CFBundleDisplayName = \"" + ProjectSettings::get_singleton()->get("application/config/name").operator String() + "\";"); @@ -878,7 +878,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p String lang = tr->get_locale(); String fname = tmp_app_path_name + "/Contents/Resources/" + lang + ".lproj"; tmp_app_dir->make_dir_recursive(fname); - FileAccessRef f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open(fname + "/InfoPlist.strings", FileAccess::WRITE); f->store_line("/* Localized versions of Info.plist keys */"); f->store_line(""); if (appnames.has(lang)) { @@ -935,6 +935,9 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p unz_file_info info; char fname[16384]; ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String file = String::utf8(fname); @@ -993,12 +996,10 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p if (!iconpath.is_empty()) { if (iconpath.get_extension() == "icns") { - FileAccess *icon = FileAccess::open(iconpath, FileAccess::READ); - if (icon) { + Ref<FileAccess> icon = FileAccess::open(iconpath, FileAccess::READ); + if (icon.is_valid()) { data.resize(icon->get_length()); icon->get_buffer(&data.write[0], icon->get_length()); - icon->close(); - memdelete(icon); } } else { Ref<Image> icon; @@ -1039,15 +1040,13 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p err = tmp_app_dir->make_dir_recursive(file.get_base_dir()); } if (err == OK) { - FileAccess *f = FileAccess::open(file, FileAccess::WRITE); - if (f) { + Ref<FileAccess> f = FileAccess::open(file, FileAccess::WRITE); + if (f.is_valid()) { f->store_buffer(data.ptr(), data.size()); - f->close(); if (is_execute) { // chmod with 0755 if the file is executable. FileAccess::set_unix_permissions(file, 0755); } - memdelete(f); } else { err = ERR_CANT_CREATE; } @@ -1091,8 +1090,8 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p if (sign_enabled && (ent_path.is_empty())) { ent_path = EditorPaths::get_singleton()->get_cache_dir().plus_file(pkg_name + ".entitlements"); - FileAccess *ent_f = FileAccess::open(ent_path, FileAccess::WRITE); - if (ent_f) { + Ref<FileAccess> ent_f = FileAccess::open(ent_path, FileAccess::WRITE); + if (ent_f.is_valid()) { ent_f->store_line("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); ent_f->store_line("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"); ent_f->store_line("<plist version=\"1.0\">"); @@ -1213,16 +1212,13 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p ent_f->store_line("</dict>"); ent_f->store_line("</plist>"); - - ent_f->close(); - memdelete(ent_f); } else { err = ERR_CANT_CREATE; } if ((err == OK) && helpers.size() > 0) { ent_f = FileAccess::open(hlp_ent_path, FileAccess::WRITE); - if (ent_f) { + if (ent_f.is_valid()) { ent_f->store_line("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); ent_f->store_line("<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"); ent_f->store_line("<plist version=\"1.0\">"); @@ -1233,9 +1229,6 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p ent_f->store_line("<true/>"); ent_f->store_line("</dict>"); ent_f->store_line("</plist>"); - - ent_f->close(); - memdelete(ent_f); } else { err = ERR_CANT_CREATE; } @@ -1243,7 +1236,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p } if ((err == OK) && helpers.size() > 0) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); for (int i = 0; i < helpers.size(); i++) { String hlp_path = helpers[i]; err = da->copy(hlp_path, tmp_app_path_name + "/Contents/Helpers/" + hlp_path.get_file()); @@ -1270,7 +1263,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p } if (err == OK) { - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); for (int i = 0; i < shared_objects.size(); i++) { String src_path = ProjectSettings::get_singleton()->globalize_path(shared_objects[i].path); if (shared_objects[i].target.is_empty()) { @@ -1334,8 +1327,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p OS::get_singleton()->move_to_trash(p_path); } - FileAccess *dst_f = nullptr; - zlib_filefunc_def io_dst = zipio_create_io_from_file(&dst_f); + zlib_filefunc_def io_dst = zipio_create_io(); zipFile zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, nullptr, &io_dst); _zip_folder_recursive(zip, tmp_base_path_name, "", pkg_name); @@ -1380,7 +1372,7 @@ Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_p void EditorExportPlatformOSX::_zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name) { String dir = p_folder.is_empty() ? p_root_path : p_root_path.plus_file(p_folder); - DirAccessRef da = DirAccess::open(dir); + Ref<DirAccess> da = DirAccess::open(dir); da->list_dir_begin(); String f = da->get_next(); while (!f.is_empty()) { @@ -1471,8 +1463,8 @@ void EditorExportPlatformOSX::_zip_folder_recursive(zipFile &p_zip, const String 0x0314, // "version made by", 0x03 - Unix, 0x14 - ZIP specification version 2.0, required to store Unix file permissions 0); - FileAccessRef fa = FileAccess::open(dir.plus_file(f), FileAccess::READ); - if (!fa) { + Ref<FileAccess> fa = FileAccess::open(dir.plus_file(f), FileAccess::READ); + if (fa.is_null()) { ERR_FAIL_MSG(vformat("Can't open file to read from path \"%s\".", dir.plus_file(f))); } const int bufsize = 16384; diff --git a/platform/osx/export/export_plugin.h b/platform/osx/export/export_plugin.h index b3edfb7f90..013e5eaa71 100644 --- a/platform/osx/export/export_plugin.h +++ b/platform/osx/export/export_plugin.h @@ -58,11 +58,11 @@ class EditorExportPlatformOSX : public EditorExportPlatform { Error _notarize(const Ref<EditorExportPreset> &p_preset, const String &p_path); Error _code_sign(const Ref<EditorExportPreset> &p_preset, const String &p_path, const String &p_ent_path, bool p_warn = true); Error _code_sign_directory(const Ref<EditorExportPreset> &p_preset, const String &p_path, const String &p_ent_path, bool p_should_error_on_non_code = true); - Error _copy_and_sign_files(DirAccessRef &dir_access, const String &p_src_path, const String &p_in_app_path, + Error _copy_and_sign_files(Ref<DirAccess> &dir_access, const String &p_src_path, const String &p_in_app_path, bool p_sign_enabled, const Ref<EditorExportPreset> &p_preset, const String &p_ent_path, bool p_should_error_on_non_code_sign); Error _export_osx_plugins_for(Ref<EditorExportPlugin> p_editor_export_plugin, const String &p_app_path_name, - DirAccessRef &dir_access, bool p_sign_enabled, const Ref<EditorExportPreset> &p_preset, + Ref<DirAccess> &dir_access, bool p_sign_enabled, const Ref<EditorExportPreset> &p_preset, const String &p_ent_path); Error _create_dmg(const String &p_dmg_path, const String &p_pkg_name, const String &p_app_path_name); void _zip_folder_recursive(zipFile &p_zip, const String &p_root_path, const String &p_folder, const String &p_pkg_name); diff --git a/platform/osx/export/lipo.cpp b/platform/osx/export/lipo.cpp index 66d2ecdbcf..82baf18c52 100644 --- a/platform/osx/export/lipo.cpp +++ b/platform/osx/export/lipo.cpp @@ -35,8 +35,8 @@ #ifdef MODULE_REGEX_ENABLED bool LipO::is_lipo(const String &p_path) { - FileAccessRef fb = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!fb, false, vformat("LipO: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("LipO: Can't open file: \"%s\".", p_path)); uint32_t magic = fb->get_32(); return (magic == 0xbebafeca || magic == 0xcafebabe || magic == 0xbfbafeca || magic == 0xcafebabf); } @@ -45,7 +45,7 @@ bool LipO::create_file(const String &p_output_path, const PackedStringArray &p_f close(); fa = FileAccess::open(p_output_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!fa, false, vformat("LipO: Can't open file: \"%s\".", p_output_path)); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("LipO: Can't open file: \"%s\".", p_output_path)); uint64_t max_size = 0; for (int i = 0; i < p_files.size(); i++) { @@ -64,8 +64,8 @@ bool LipO::create_file(const String &p_output_path, const PackedStringArray &p_f archs.push_back(arch); - FileAccessRef fb = FileAccess::open(p_files[i], FileAccess::READ); - if (!fb) { + Ref<FileAccess> fb = FileAccess::open(p_files[i], FileAccess::READ); + if (fb.is_null()) { close(); ERR_FAIL_V_MSG(false, vformat("LipO: Can't open file: \"%s.\"", p_files[i])); } @@ -101,8 +101,8 @@ bool LipO::create_file(const String &p_output_path, const PackedStringArray &p_f // Write files and padding. for (int i = 0; i < archs.size(); i++) { - FileAccessRef fb = FileAccess::open(p_files[i], FileAccess::READ); - if (!fb) { + Ref<FileAccess> fb = FileAccess::open(p_files[i], FileAccess::READ); + if (fb.is_null()) { close(); ERR_FAIL_V_MSG(false, vformat("LipO: Can't open file: \"%s.\"", p_files[i])); } @@ -123,7 +123,6 @@ bool LipO::create_file(const String &p_output_path, const PackedStringArray &p_f if (br > 0) { fa->store_buffer(step, br); } - fb->close(); } return true; } @@ -132,7 +131,7 @@ bool LipO::open_file(const String &p_path) { close(); fa = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!fa, false, vformat("LipO: Can't open file: \"%s\".", p_path)); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("LipO: Can't open file: \"%s\".", p_path)); uint32_t magic = fa->get_32(); if (magic == 0xbebafeca) { @@ -197,16 +196,16 @@ bool LipO::open_file(const String &p_path) { } int LipO::get_arch_count() const { - ERR_FAIL_COND_V_MSG(!fa, 0, "LipO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "LipO: File not opened."); return archs.size(); } bool LipO::extract_arch(int p_index, const String &p_path) { - ERR_FAIL_COND_V_MSG(!fa, false, "LipO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, "LipO: File not opened."); ERR_FAIL_INDEX_V(p_index, archs.size(), false); - FileAccessRef fb = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V_MSG(!fb, false, vformat("LipO: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("LipO: Can't open file: \"%s\".", p_path)); fa->seek(archs[p_index].offset); @@ -223,16 +222,10 @@ bool LipO::extract_arch(int p_index, const String &p_path) { if (br > 0) { fb->store_buffer(step, br); } - fb->close(); return true; } void LipO::close() { - if (fa) { - fa->close(); - memdelete(fa); - fa = nullptr; - } archs.clear(); } diff --git a/platform/osx/export/lipo.h b/platform/osx/export/lipo.h index 68bbe42dd6..0e419be17e 100644 --- a/platform/osx/export/lipo.h +++ b/platform/osx/export/lipo.h @@ -50,7 +50,7 @@ class LipO : public RefCounted { uint32_t align; }; - FileAccess *fa = nullptr; + Ref<FileAccess> fa; Vector<FatArch> archs; static inline size_t PAD(size_t s, size_t a) { diff --git a/platform/osx/export/macho.cpp b/platform/osx/export/macho.cpp index 08f2a855b0..e6e67eff06 100644 --- a/platform/osx/export/macho.cpp +++ b/platform/osx/export/macho.cpp @@ -49,7 +49,7 @@ uint32_t MachO::seg_align(uint64_t p_vmaddr, uint32_t p_min, uint32_t p_max) { } bool MachO::alloc_signature(uint64_t p_size) { - ERR_FAIL_COND_V_MSG(!fa, false, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, "MachO: File not opened."); if (signature_offset != 0) { // Nothing to do, already have signature load command. return true; @@ -103,15 +103,15 @@ bool MachO::alloc_signature(uint64_t p_size) { } bool MachO::is_macho(const String &p_path) { - FileAccessRef fb = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!fb, false, vformat("MachO: Can't open file: \"%s\".", p_path)); + Ref<FileAccess> fb = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(fb.is_null(), false, vformat("MachO: Can't open file: \"%s\".", p_path)); uint32_t magic = fb->get_32(); return (magic == 0xcefaedfe || magic == 0xfeedface || magic == 0xcffaedfe || magic == 0xfeedfacf); } bool MachO::open_file(const String &p_path) { fa = FileAccess::open(p_path, FileAccess::READ_WRITE); - ERR_FAIL_COND_V_MSG(!fa, false, vformat("MachO: Can't open file: \"%s\".", p_path)); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, vformat("MachO: Can't open file: \"%s\".", p_path)); uint32_t magic = fa->get_32(); MachHeader mach_header; @@ -232,37 +232,37 @@ bool MachO::open_file(const String &p_path) { } uint64_t MachO::get_exe_base() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); return exe_base; } uint64_t MachO::get_exe_limit() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); return exe_limit; } int32_t MachO::get_align() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); return align; } uint32_t MachO::get_cputype() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); return cputype; } uint32_t MachO::get_cpusubtype() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); return cpusubtype; } uint64_t MachO::get_size() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); return fa->get_length(); } uint64_t MachO::get_signature_offset() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); ERR_FAIL_COND_V_MSG(signature_offset == 0, 0, "MachO: No signature load command."); fa->seek(signature_offset + 8); @@ -274,7 +274,7 @@ uint64_t MachO::get_signature_offset() { } uint64_t MachO::get_code_limit() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); if (signature_offset == 0) { return fa->get_length() + PAD(fa->get_length(), 16); @@ -284,7 +284,7 @@ uint64_t MachO::get_code_limit() { } uint64_t MachO::get_signature_size() { - ERR_FAIL_COND_V_MSG(!fa, 0, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), 0, "MachO: File not opened."); ERR_FAIL_COND_V_MSG(signature_offset == 0, 0, "MachO: No signature load command."); fa->seek(signature_offset + 12); @@ -296,7 +296,7 @@ uint64_t MachO::get_signature_size() { } bool MachO::is_signed() { - ERR_FAIL_COND_V_MSG(!fa, false, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, "MachO: File not opened."); if (signature_offset == 0) { return false; } @@ -325,7 +325,7 @@ bool MachO::is_signed() { } PackedByteArray MachO::get_cdhash_sha1() { - ERR_FAIL_COND_V_MSG(!fa, PackedByteArray(), "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), PackedByteArray(), "MachO: File not opened."); if (signature_offset == 0) { return PackedByteArray(); } @@ -372,7 +372,7 @@ PackedByteArray MachO::get_cdhash_sha1() { } PackedByteArray MachO::get_cdhash_sha256() { - ERR_FAIL_COND_V_MSG(!fa, PackedByteArray(), "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), PackedByteArray(), "MachO: File not opened."); if (signature_offset == 0) { return PackedByteArray(); } @@ -419,7 +419,7 @@ PackedByteArray MachO::get_cdhash_sha256() { } PackedByteArray MachO::get_requirements() { - ERR_FAIL_COND_V_MSG(!fa, PackedByteArray(), "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), PackedByteArray(), "MachO: File not opened."); if (signature_offset == 0) { return PackedByteArray(); } @@ -451,16 +451,16 @@ PackedByteArray MachO::get_requirements() { return PackedByteArray(); } -const FileAccess *MachO::get_file() const { +const Ref<FileAccess> MachO::get_file() const { return fa; } -FileAccess *MachO::get_file() { +Ref<FileAccess> MachO::get_file() { return fa; } bool MachO::set_signature_size(uint64_t p_size) { - ERR_FAIL_COND_V_MSG(!fa, false, "MachO: File not opened."); + ERR_FAIL_COND_V_MSG(fa.is_null(), false, "MachO: File not opened."); // Ensure signature load command exists. ERR_FAIL_COND_V_MSG(link_edit_offset == 0, false, "MachO: No __LINKEDIT segment found."); @@ -545,12 +545,4 @@ bool MachO::set_signature_size(uint64_t p_size) { return true; } -MachO::~MachO() { - if (fa) { - fa->close(); - memdelete(fa); - fa = nullptr; - } -} - #endif // MODULE_REGEX_ENABLED diff --git a/platform/osx/export/macho.h b/platform/osx/export/macho.h index e09906898b..6cfc3c44f5 100644 --- a/platform/osx/export/macho.h +++ b/platform/osx/export/macho.h @@ -161,7 +161,7 @@ class MachO : public RefCounted { uint32_t reserved3; }; - FileAccess *fa = nullptr; + Ref<FileAccess> fa; bool swap = false; uint64_t lc_limit = 0; @@ -203,13 +203,11 @@ public: PackedByteArray get_requirements(); - const FileAccess *get_file() const; - FileAccess *get_file(); + const Ref<FileAccess> get_file() const; + Ref<FileAccess> get_file(); uint64_t get_signature_size(); bool set_signature_size(uint64_t p_size); - - ~MachO(); }; #endif // MODULE_REGEX_ENABLED diff --git a/platform/osx/export/plist.cpp b/platform/osx/export/plist.cpp index 553b864180..d089233b80 100644 --- a/platform/osx/export/plist.cpp +++ b/platform/osx/export/plist.cpp @@ -343,8 +343,8 @@ PList::PList(const String &p_string) { bool PList::load_file(const String &p_filename) { root = Ref<PListNode>(); - FileAccessRef fb = FileAccess::open(p_filename, FileAccess::READ); - if (!fb) { + Ref<FileAccess> fb = FileAccess::open(p_filename, FileAccess::READ); + if (fb.is_null()) { return false; } @@ -398,7 +398,6 @@ bool PList::load_string(const String &p_string) { } if (token == "/plist") { - in_plist = false; done_plist = true; break; } diff --git a/platform/osx/joypad_osx.cpp b/platform/osx/joypad_osx.cpp index 7d31ede61d..be9567e17c 100644 --- a/platform/osx/joypad_osx.cpp +++ b/platform/osx/joypad_osx.cpp @@ -195,7 +195,7 @@ void joypad::add_hid_element(IOHIDElementRef p_element) { } static void hid_element_added(const void *p_value, void *p_parameter) { - joypad *joy = (joypad *)p_parameter; + joypad *joy = static_cast<joypad *>(p_parameter); joy->add_hid_element((IOHIDElementRef)p_value); } @@ -540,10 +540,10 @@ static CFDictionaryRef create_match_dictionary(const UInt32 page, const UInt32 u CFDictionaryRef retval = nullptr; CFNumberRef pageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page); CFNumberRef usageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage); - const void *keys[2] = { (void *)CFSTR(kIOHIDDeviceUsagePageKey), (void *)CFSTR(kIOHIDDeviceUsageKey) }; - const void *vals[2] = { (void *)pageNumRef, (void *)usageNumRef }; if (pageNumRef && usageNumRef) { + const void *keys[2] = { (void *)CFSTR(kIOHIDDeviceUsagePageKey), (void *)CFSTR(kIOHIDDeviceUsageKey) }; + const void *vals[2] = { (void *)pageNumRef, (void *)usageNumRef }; retval = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } diff --git a/platform/osx/joypad_osx.h b/platform/osx/joypad_osx.h index 4ca7fb1698..b09d5ce34a 100644 --- a/platform/osx/joypad_osx.h +++ b/platform/osx/joypad_osx.h @@ -94,7 +94,7 @@ class JoypadOSX { }; private: - Input *input; + Input *input = nullptr; IOHIDManagerRef hid_manager; Vector<joypad> device_list; diff --git a/platform/osx/os_osx.mm b/platform/osx/os_osx.mm index afbd338832..33fee01c08 100644 --- a/platform/osx/os_osx.mm +++ b/platform/osx/os_osx.mm @@ -47,7 +47,7 @@ _FORCE_INLINE_ String OS_OSX::get_framework_executable(const String &p_path) { // Append framework executable name, or return as is if p_path is not a framework. - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); if (da->dir_exists(p_path) && da->file_exists(p_path.plus_file(p_path.get_file().get_basename()))) { return p_path.plus_file(p_path.get_file().get_basename()); } else { diff --git a/platform/uwp/export/app_packager.cpp b/platform/uwp/export/app_packager.cpp index e7978ff74d..2f70c3e74c 100644 --- a/platform/uwp/export/app_packager.cpp +++ b/platform/uwp/export/app_packager.cpp @@ -46,7 +46,7 @@ String AppxPackager::hash_block(const uint8_t *p_block_data, size_t p_block_len) } void AppxPackager::make_block_map(const String &p_path) { - FileAccess *tmp_file = FileAccess::open(p_path, FileAccess::WRITE); + Ref<FileAccess> tmp_file = FileAccess::open(p_path, FileAccess::WRITE); tmp_file->store_string("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"); tmp_file->store_string("<BlockMap xmlns=\"http://schemas.microsoft.com/appx/2010/blockmap\" HashMethod=\"http://www.w3.org/2001/04/xmlenc#sha256\">"); @@ -69,9 +69,6 @@ void AppxPackager::make_block_map(const String &p_path) { } tmp_file->store_string("</BlockMap>"); - - tmp_file->close(); - memdelete(tmp_file); } String AppxPackager::content_type(String p_extension) { @@ -89,7 +86,7 @@ String AppxPackager::content_type(String p_extension) { } void AppxPackager::make_content_types(const String &p_path) { - FileAccess *tmp_file = FileAccess::open(p_path, FileAccess::WRITE); + Ref<FileAccess> tmp_file = FileAccess::open(p_path, FileAccess::WRITE); tmp_file->store_string("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); tmp_file->store_string("<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">"); @@ -118,9 +115,6 @@ void AppxPackager::make_content_types(const String &p_path) { tmp_file->store_string("<Override PartName=\"/AppxMetadata/CodeIntegrity.cat\" ContentType=\"application/vnd.ms-pkiseccat\" />"); tmp_file->store_string("</Types>"); - - tmp_file->close(); - memdelete(tmp_file); } Vector<uint8_t> AppxPackager::make_file_header(FileMeta p_file_meta) { @@ -285,7 +279,7 @@ Vector<uint8_t> AppxPackager::make_end_of_central_record() { return buf; } -void AppxPackager::init(FileAccess *p_fa) { +void AppxPackager::init(Ref<FileAccess> p_fa) { package = p_fa; central_dir_offset = 0; end_of_central_dir_offset = 0; @@ -301,7 +295,6 @@ Error AppxPackager::add_file(String p_file_name, const uint8_t *p_buffer, size_t FileMeta meta; meta.name = p_file_name; meta.uncompressed_size = p_len; - meta.compressed_size = p_len; meta.compressed = p_compress; meta.zip_offset = package->get_position(); @@ -309,7 +302,6 @@ Error AppxPackager::add_file(String p_file_name, const uint8_t *p_buffer, size_t // Data for compression z_stream strm; - FileAccess *strm_f = nullptr; Vector<uint8_t> strm_in; strm_in.resize(BLOCK_SIZE); Vector<uint8_t> strm_out; @@ -317,7 +309,7 @@ Error AppxPackager::add_file(String p_file_name, const uint8_t *p_buffer, size_t if (p_compress) { strm.zalloc = zipio_alloc; strm.zfree = zipio_free; - strm.opaque = &strm_f; + strm.opaque = Z_NULL; strm_out.resize(BLOCK_SIZE + 8); @@ -419,16 +411,15 @@ void AppxPackager::finish() { const String &tmp_blockmap_file_path = EditorPaths::get_singleton()->get_cache_dir().plus_file("tmpblockmap.xml"); make_block_map(tmp_blockmap_file_path); - FileAccess *blockmap_file = FileAccess::open(tmp_blockmap_file_path, FileAccess::READ); - Vector<uint8_t> blockmap_buffer; - blockmap_buffer.resize(blockmap_file->get_length()); - - blockmap_file->get_buffer(blockmap_buffer.ptrw(), blockmap_buffer.size()); + { + Ref<FileAccess> blockmap_file = FileAccess::open(tmp_blockmap_file_path, FileAccess::READ); + Vector<uint8_t> blockmap_buffer; + blockmap_buffer.resize(blockmap_file->get_length()); - add_file("AppxBlockMap.xml", blockmap_buffer.ptr(), blockmap_buffer.size(), -1, -1, true); + blockmap_file->get_buffer(blockmap_buffer.ptrw(), blockmap_buffer.size()); - blockmap_file->close(); - memdelete(blockmap_file); + add_file("AppxBlockMap.xml", blockmap_buffer.ptr(), blockmap_buffer.size(), -1, -1, true); + } // Add content types @@ -437,16 +428,15 @@ void AppxPackager::finish() { const String &tmp_content_types_file_path = EditorPaths::get_singleton()->get_cache_dir().plus_file("tmpcontenttypes.xml"); make_content_types(tmp_content_types_file_path); - FileAccess *types_file = FileAccess::open(tmp_content_types_file_path, FileAccess::READ); - Vector<uint8_t> types_buffer; - types_buffer.resize(types_file->get_length()); - - types_file->get_buffer(types_buffer.ptrw(), types_buffer.size()); + { + Ref<FileAccess> types_file = FileAccess::open(tmp_content_types_file_path, FileAccess::READ); + Vector<uint8_t> types_buffer; + types_buffer.resize(types_file->get_length()); - add_file("[Content_Types].xml", types_buffer.ptr(), types_buffer.size(), -1, -1, true); + types_file->get_buffer(types_buffer.ptrw(), types_buffer.size()); - types_file->close(); - memdelete(types_file); + add_file("[Content_Types].xml", types_buffer.ptr(), types_buffer.size(), -1, -1, true); + } // Cleanup generated files. DirAccess::remove_file_or_error(tmp_blockmap_file_path); @@ -467,9 +457,7 @@ void AppxPackager::finish() { Vector<uint8_t> end_record = make_end_of_central_record(); package->store_buffer(end_record.ptr(), end_record.size()); - package->close(); - memdelete(package); - package = nullptr; + package.unref(); } AppxPackager::AppxPackager() {} diff --git a/platform/uwp/export/app_packager.h b/platform/uwp/export/app_packager.h index da118449c7..a32b78bf04 100644 --- a/platform/uwp/export/app_packager.h +++ b/platform/uwp/export/app_packager.h @@ -87,7 +87,7 @@ class AppxPackager { }; String progress_task; - FileAccess *package = nullptr; + Ref<FileAccess> package; Set<String> mime_types; @@ -138,7 +138,7 @@ class AppxPackager { public: void set_progress_task(String p_task) { progress_task = p_task; } - void init(FileAccess *p_fa); + void init(Ref<FileAccess> p_fa); Error add_file(String p_file_name, const uint8_t *p_buffer, size_t p_len, int p_file_no, int p_total_files, bool p_compress = false); void finish(); diff --git a/platform/uwp/export/export_plugin.cpp b/platform/uwp/export/export_plugin.cpp index 88343d6f85..7e06bf01e3 100644 --- a/platform/uwp/export/export_plugin.cpp +++ b/platform/uwp/export/export_plugin.cpp @@ -295,14 +295,13 @@ Error EditorExportPlatformUWP::export_project(const Ref<EditorExportPreset> &p_p Error err = OK; - FileAccess *fa_pack = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> fa_pack = FileAccess::open(p_path, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Cannot create file '" + p_path + "'."); AppxPackager packager; packager.init(fa_pack); - FileAccess *src_f = nullptr; - zlib_filefunc_def io = zipio_create_io_from_file(&src_f); + zlib_filefunc_def io = zipio_create_io(); if (ep.step("Creating package...", 0)) { return ERR_SKIP; @@ -332,6 +331,9 @@ Error EditorExportPlatformUWP::export_project(const Ref<EditorExportPreset> &p_p unz_file_info info; char fname[16834]; ret = unzGetCurrentFileInfo(pkg, &info, fname, 16834, nullptr, 0, nullptr, 0); + if (ret != UNZ_OK) { + break; + } String path = String::utf8(fname); diff --git a/platform/uwp/export/export_plugin.h b/platform/uwp/export/export_plugin.h index bf89b10ffa..ceb6d613b3 100644 --- a/platform/uwp/export/export_plugin.h +++ b/platform/uwp/export/export_plugin.h @@ -346,21 +346,21 @@ class EditorExportPlatformUWP : public EditorExportPlatform { ERR_FAIL_V_MSG(data, err_string); } - FileAccess *f = FileAccess::open(tmp_path, FileAccess::READ, &err); + { + Ref<FileAccess> f = FileAccess::open(tmp_path, FileAccess::READ, &err); + + if (err != OK) { + String err_string = "Couldn't open temp logo file."; + // Cleanup generated file. + DirAccess::remove_file_or_error(tmp_path); + EditorNode::add_io_error(err_string); + ERR_FAIL_V_MSG(data, err_string); + } - if (err != OK) { - String err_string = "Couldn't open temp logo file."; - // Cleanup generated file. - DirAccess::remove_file_or_error(tmp_path); - EditorNode::add_io_error(err_string); - ERR_FAIL_V_MSG(data, err_string); + data.resize(f->get_length()); + f->get_buffer(data.ptrw(), data.size()); } - data.resize(f->get_length()); - f->get_buffer(data.ptrw(), data.size()); - - f->close(); - memdelete(f); DirAccess::remove_file_or_error(tmp_path); return data; @@ -417,7 +417,7 @@ class EditorExportPlatformUWP : public EditorExportPlatform { } static Error save_appx_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total, const Vector<String> &p_enc_in_filters, const Vector<String> &p_enc_ex_filters, const Vector<uint8_t> &p_key) { - AppxPackager *packager = (AppxPackager *)p_userdata; + AppxPackager *packager = static_cast<AppxPackager *>(p_userdata); String dst_path = p_path.replace_first("res://", "game/"); return packager->add_file(dst_path, p_data.ptr(), p_data.size(), p_file, p_total, _should_compress_asset(p_path, p_data)); diff --git a/platform/uwp/joypad_uwp.h b/platform/uwp/joypad_uwp.h index 29f5109056..0869f1961d 100644 --- a/platform/uwp/joypad_uwp.h +++ b/platform/uwp/joypad_uwp.h @@ -68,7 +68,7 @@ private: ControllerDevice controllers[MAX_CONTROLLERS]; - InputDefault *input; + InputDefault *input = nullptr; void OnGamepadAdded(Platform::Object ^ sender, Windows::Gaming::Input::Gamepad ^ value); void OnGamepadRemoved(Platform::Object ^ sender, Windows::Gaming::Input::Gamepad ^ value); diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h index 573d86af7c..f955be1da9 100644 --- a/platform/uwp/os_uwp.h +++ b/platform/uwp/os_uwp.h @@ -74,7 +74,7 @@ private: KEY_EVENT_BUFFER_SIZE = 512 }; - FILE *stdo; + FILE *stdo = nullptr; KeyEvent key_event_buffer[KEY_EVENT_BUFFER_SIZE]; int key_event_pos; @@ -87,16 +87,16 @@ private: bool outside; int old_x, old_y; Point2i center; - RenderingServer *rendering_server; + RenderingServer *rendering_server = nullptr; int pressrc; - ContextEGL_UWP *gl_context; + ContextEGL_UWP *gl_context = nullptr; Windows::UI::Core::CoreWindow ^ window; VideoMode video_mode; int video_driver_index; - MainLoop *main_loop; + MainLoop *main_loop = nullptr; AudioDriverXAudio2 audio_driver; @@ -111,7 +111,7 @@ private: CursorShape cursor_shape; - InputDefault *input; + InputDefault *input = nullptr; JoypadUWP ^ joypad; diff --git a/platform/windows/display_server_windows.cpp b/platform/windows/display_server_windows.cpp index 877e82e707..31bad0f053 100644 --- a/platform/windows/display_server_windows.cpp +++ b/platform/windows/display_server_windows.cpp @@ -430,9 +430,8 @@ static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Defau } UINT x = 0, y = 0; - HRESULT hr = E_FAIL; if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) { - hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y); + HRESULT hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y); if (SUCCEEDED(hr) && (x > 0) && (y > 0)) { dpiX = (int)x; dpiY = (int)y; @@ -844,8 +843,8 @@ void DisplayServerWindows::window_set_exclusive(WindowID p_window, bool p_exclus if (wd.exclusive != p_exclusive) { wd.exclusive = p_exclusive; if (wd.transient_parent != INVALID_WINDOW_ID) { - WindowData &wd_parent = windows[wd.transient_parent]; if (wd.exclusive) { + WindowData &wd_parent = windows[wd.transient_parent]; SetWindowLongPtr(wd.hWnd, GWLP_HWNDPARENT, (LONG_PTR)wd_parent.hWnd); } else { SetWindowLongPtr(wd.hWnd, GWLP_HWNDPARENT, (LONG_PTR) nullptr); @@ -1281,7 +1280,7 @@ void DisplayServerWindows::window_request_attention(WindowID p_window) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND(!windows.has(p_window)); - WindowData &wd = windows[p_window]; + const WindowData &wd = windows[p_window]; FLASHWINFO info; info.cbSize = sizeof(FLASHWINFO); @@ -1562,13 +1561,8 @@ void DisplayServerWindows::cursor_set_custom_image(const RES &p_cursor, CursorSh } } - if (hAndMask != nullptr) { - DeleteObject(hAndMask); - } - - if (hXorMask != nullptr) { - DeleteObject(hXorMask); - } + DeleteObject(hAndMask); + DeleteObject(hXorMask); memfree(buffer); DeleteObject(bitmap); @@ -1771,8 +1765,8 @@ void DisplayServerWindows::swap_buffers() { void DisplayServerWindows::set_native_icon(const String &p_filename) { _THREAD_SAFE_METHOD_ - FileAccess *f = FileAccess::open(p_filename, FileAccess::READ); - ERR_FAIL_COND_MSG(!f, "Cannot open file with icon '" + p_filename + "'."); + Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::READ); + ERR_FAIL_COND_MSG(f.is_null(), "Cannot open file with icon '" + p_filename + "'."); ICONDIR *icon_dir = (ICONDIR *)memalloc(sizeof(ICONDIR)); int pos = 0; @@ -1858,7 +1852,6 @@ void DisplayServerWindows::set_native_icon(const String &p_filename) { err = GetLastError(); ERR_FAIL_COND_MSG(err, "Error setting ICON_BIG: " + format_error_message(err) + "."); - memdelete(f); memdelete(icon_dir); } @@ -1994,7 +1987,7 @@ void DisplayServerWindows::_send_window_event(const WindowData &wd, WindowEvent } void DisplayServerWindows::_dispatch_input_events(const Ref<InputEvent> &p_event) { - ((DisplayServerWindows *)(get_singleton()))->_dispatch_input_event(p_event); + static_cast<DisplayServerWindows *>(get_singleton())->_dispatch_input_event(p_event); } void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event) { @@ -2010,7 +2003,7 @@ void DisplayServerWindows::_dispatch_input_event(const Ref<InputEvent> &p_event) Callable::CallError ce; { - List<WindowID>::Element *E = popup_list.front(); + List<WindowID>::Element *E = popup_list.back(); if (E && Object::cast_to<InputEventKey>(*p_event)) { // Redirect keyboard input to active popup. if (windows.has(E->get())) { @@ -2081,20 +2074,24 @@ Rect2i DisplayServerWindows::window_get_popup_safe_rect(WindowID p_window) const } void DisplayServerWindows::popup_open(WindowID p_window) { - WindowData &wd = windows[p_window]; + _THREAD_SAFE_METHOD_ + + const WindowData &wd = windows[p_window]; if (wd.is_popup) { - // Close all popups, up to current popup parent, or every popup if new window is not transient. + // Find current popup parent, or root popup if new window is not transient. + List<WindowID>::Element *C = nullptr; List<WindowID>::Element *E = popup_list.back(); while (E) { if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) { - _send_window_event(windows[E->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST); - List<WindowID>::Element *F = E->prev(); - popup_list.erase(E); - E = F; + C = E; + E = E->prev(); } else { break; } } + if (C) { + _send_window_event(windows[C->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST); + } time_since_popup = OS::get_singleton()->get_ticks_msec(); popup_list.push_back(p_window); @@ -2102,17 +2099,22 @@ void DisplayServerWindows::popup_open(WindowID p_window) { } void DisplayServerWindows::popup_close(WindowID p_window) { + _THREAD_SAFE_METHOD_ + List<WindowID>::Element *E = popup_list.find(p_window); while (E) { - _send_window_event(windows[E->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST); List<WindowID>::Element *F = E->next(); + WindowID win_id = E->get(); popup_list.erase(E); + + _send_window_event(windows[win_id], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST); E = F; } } LRESULT DisplayServerWindows::MouseProc(int code, WPARAM wParam, LPARAM lParam) { _THREAD_SAFE_METHOD_ + uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup; if (delta > 250) { switch (wParam) { @@ -2123,7 +2125,9 @@ LRESULT DisplayServerWindows::MouseProc(int code, WPARAM wParam, LPARAM lParam) case WM_MBUTTONDOWN: { MOUSEHOOKSTRUCT *ms = (MOUSEHOOKSTRUCT *)lParam; Point2i pos = Point2i(ms->pt.x, ms->pt.y); + List<WindowID>::Element *C = nullptr; List<WindowID>::Element *E = popup_list.back(); + // Find top popup to close. while (E) { // Popup window area. Rect2i win_rect = Rect2i(window_get_position(E->get()), window_get_size(E->get())); @@ -2134,13 +2138,13 @@ LRESULT DisplayServerWindows::MouseProc(int code, WPARAM wParam, LPARAM lParam) } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) { break; } else { - _send_window_event(windows[E->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST); - List<WindowID>::Element *F = E->prev(); - popup_list.erase(E); - E = F; + C = E; + E = E->prev(); } } - + if (C) { + _send_window_event(windows[C->get()], DisplayServerWindows::WINDOW_EVENT_CLOSE_REQUEST); + } } break; } } @@ -3483,7 +3487,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win shift_mem = false; control_mem = false; meta_mem = false; - hInstance = ((OS_Windows *)OS::get_singleton())->get_hinstance(); + hInstance = static_cast<OS_Windows *>(OS::get_singleton())->get_hinstance(); pressrc = 0; old_invalid = true; @@ -3651,7 +3655,7 @@ DisplayServerWindows::DisplayServerWindows(const String &p_rendering_driver, Win r_error = OK; - ((OS_Windows *)OS::get_singleton())->set_main_window(windows[MAIN_WINDOW_ID].hWnd); + static_cast<OS_Windows *>(OS::get_singleton())->set_main_window(windows[MAIN_WINDOW_ID].hWnd); Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events); } diff --git a/platform/windows/display_server_windows.h b/platform/windows/display_server_windows.h index 71fedf2bca..fcf4b5a728 100644 --- a/platform/windows/display_server_windows.h +++ b/platform/windows/display_server_windows.h @@ -392,7 +392,7 @@ class DisplayServerWindows : public DisplayServer { Rect2i parent_safe_rect; }; - JoypadWindows *joypad; + JoypadWindows *joypad = nullptr; HHOOK mouse_monitor = nullptr; List<WindowID> popup_list; uint64_t time_since_popup = 0; diff --git a/platform/windows/export/export_plugin.cpp b/platform/windows/export/export_plugin.cpp index e627253739..917a0af90b 100644 --- a/platform/windows/export/export_plugin.cpp +++ b/platform/windows/export/export_plugin.cpp @@ -42,8 +42,8 @@ Error EditorExportPlatformWindows::sign_shared_object(const Ref<EditorExportPres } Error EditorExportPlatformWindows::_export_debug_script(const Ref<EditorExportPreset> &p_preset, const String &p_app_name, const String &p_pkg_name, const String &p_path) { - FileAccessRef f = FileAccess::open(p_path, FileAccess::WRITE); - ERR_FAIL_COND_V(!f, ERR_CANT_CREATE); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE); + ERR_FAIL_COND_V(f.is_null(), ERR_CANT_CREATE); f->store_line("@echo off"); f->store_line("title \"" + p_app_name + "\""); @@ -359,7 +359,7 @@ Error EditorExportPlatformWindows::_code_sign(const Ref<EditorExportPreset> &p_p } #ifndef WINDOWS_ENABLED - DirAccessRef tmp_dir = DirAccess::create_for_path(p_path.get_base_dir()); + Ref<DirAccess> tmp_dir = DirAccess::create_for_path(p_path.get_base_dir()); err = tmp_dir->remove(p_path); ERR_FAIL_COND_V(err != OK, err); @@ -417,8 +417,8 @@ bool EditorExportPlatformWindows::can_export(const Ref<EditorExportPreset> &p_pr Error EditorExportPlatformWindows::fixup_embedded_pck(const String &p_path, int64_t p_embedded_start, int64_t p_embedded_size) const { // Patch the header of the "pck" section in the PE file so that it corresponds to the embedded data - FileAccess *f = FileAccess::open(p_path, FileAccess::READ_WRITE); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ_WRITE); + if (f.is_null()) { return ERR_CANT_OPEN; } @@ -430,7 +430,6 @@ Error EditorExportPlatformWindows::fixup_embedded_pck(const String &p_path, int6 f->seek(pe_pos); uint32_t magic = f->get_32(); if (magic != 0x00004550) { - f->close(); return ERR_FILE_CORRUPT; } } @@ -480,7 +479,5 @@ Error EditorExportPlatformWindows::fixup_embedded_pck(const String &p_path, int6 } } - f->close(); - return found ? OK : ERR_FILE_CORRUPT; } diff --git a/platform/windows/gl_manager_windows.h b/platform/windows/gl_manager_windows.h index 6423c54855..dc411983e8 100644 --- a/platform/windows/gl_manager_windows.h +++ b/platform/windows/gl_manager_windows.h @@ -52,19 +52,18 @@ public: private: // any data specific to the window struct GLWindow { - GLWindow() { in_use = false; } - bool in_use; + bool in_use = false; // the external ID .. should match the GL window number .. unused I think - DisplayServer::WindowID window_id; - int width; - int height; + DisplayServer::WindowID window_id = DisplayServer::INVALID_WINDOW_ID; + int width = 0; + int height = 0; // windows specific HDC hDC; HWND hwnd; - int gldisplay_id; + int gldisplay_id = 0; }; struct GLDisplay { @@ -75,7 +74,7 @@ private: LocalVector<GLWindow> _windows; LocalVector<GLDisplay> _displays; - GLWindow *_current_window; + GLWindow *_current_window = nullptr; PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT; PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT; diff --git a/platform/windows/joypad_windows.cpp b/platform/windows/joypad_windows.cpp index 494e0b9105..d039fd13a7 100644 --- a/platform/windows/joypad_windows.cpp +++ b/platform/windows/joypad_windows.cpp @@ -250,7 +250,7 @@ void JoypadWindows::setup_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_ } BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE *p_instance, void *p_context) { - JoypadWindows *self = (JoypadWindows *)p_context; + JoypadWindows *self = static_cast<JoypadWindows *>(p_context); if (self->is_xinput_device(&p_instance->guidProduct)) { return DIENUM_CONTINUE; } @@ -258,9 +258,9 @@ BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE *p_instance, vo return DIENUM_CONTINUE; } -BOOL CALLBACK JoypadWindows::objectsCallback(const DIDEVICEOBJECTINSTANCE *instance, void *context) { - JoypadWindows *self = (JoypadWindows *)context; - self->setup_joypad_object(instance, self->id_to_change); +BOOL CALLBACK JoypadWindows::objectsCallback(const DIDEVICEOBJECTINSTANCE *p_instance, void *p_context) { + JoypadWindows *self = static_cast<JoypadWindows *>(p_context); + self->setup_joypad_object(p_instance, self->id_to_change); return DIENUM_CONTINUE; } @@ -404,7 +404,7 @@ void JoypadWindows::process_joypads() { // on mingw, these constants are not constants int count = 8; - LONG axes[] = { DIJOFS_X, DIJOFS_Y, DIJOFS_Z, DIJOFS_RX, DIJOFS_RY, DIJOFS_RZ, (LONG)DIJOFS_SLIDER(0), (LONG)DIJOFS_SLIDER(1) }; + const LONG axes[] = { DIJOFS_X, DIJOFS_Y, DIJOFS_Z, DIJOFS_RX, DIJOFS_RY, DIJOFS_RZ, (LONG)DIJOFS_SLIDER(0), (LONG)DIJOFS_SLIDER(1) }; int values[] = { js.lX, js.lY, js.lZ, js.lRx, js.lRy, js.lRz, js.rglSlider[0], js.rglSlider[1] }; for (int j = 0; j < joy->joy_axis.size(); j++) { diff --git a/platform/windows/joypad_windows.h b/platform/windows/joypad_windows.h index 4f15bcf080..d239471a5c 100644 --- a/platform/windows/joypad_windows.h +++ b/platform/windows/joypad_windows.h @@ -105,10 +105,10 @@ private: typedef DWORD(WINAPI *XInputGetState_t)(DWORD dwUserIndex, XINPUT_STATE *pState); typedef DWORD(WINAPI *XInputSetState_t)(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration); - HWND *hWnd; + HWND *hWnd = nullptr; HANDLE xinput_dll; LPDIRECTINPUT8 dinput; - Input *input; + Input *input = nullptr; int id_to_change; int slider_count; diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h index 5bfd24327e..adeecf37c5 100644 --- a/platform/windows/os_windows.h +++ b/platform/windows/os_windows.h @@ -60,14 +60,14 @@ class JoypadWindows; class OS_Windows : public OS { #ifdef STDOUT_FILE - FILE *stdo; + FILE *stdo = nullptr; #endif uint64_t ticks_start; uint64_t ticks_per_second; HINSTANCE hInstance; - MainLoop *main_loop; + MainLoop *main_loop = nullptr; #ifdef WASAPI_ENABLED AudioDriverWASAPI driver_wasapi; diff --git a/scene/2d/collision_object_2d.cpp b/scene/2d/collision_object_2d.cpp index c503de2d59..50863f2c4d 100644 --- a/scene/2d/collision_object_2d.cpp +++ b/scene/2d/collision_object_2d.cpp @@ -81,7 +81,7 @@ void CollisionObject2D::_notification(int p_what) { return; } - Transform2D global_transform = get_global_transform_with_canvas(); + Transform2D global_transform = get_global_transform(); if (area) { PhysicsServer2D::get_singleton()->area_set_transform(rid, global_transform); diff --git a/scene/2d/node_2d.cpp b/scene/2d/node_2d.cpp index dd88bda304..42c8daa4c7 100644 --- a/scene/2d/node_2d.cpp +++ b/scene/2d/node_2d.cpp @@ -133,7 +133,7 @@ void Node2D::_update_transform() { void Node2D::set_position(const Point2 &p_pos) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } position = p_pos; _update_transform(); @@ -141,7 +141,7 @@ void Node2D::set_position(const Point2 &p_pos) { void Node2D::set_rotation(real_t p_radians) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } rotation = p_radians; _update_transform(); @@ -149,7 +149,7 @@ void Node2D::set_rotation(real_t p_radians) { void Node2D::set_skew(real_t p_radians) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } skew = p_radians; _update_transform(); @@ -157,7 +157,7 @@ void Node2D::set_skew(real_t p_radians) { void Node2D::set_scale(const Size2 &p_scale) { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } scale = p_scale; // Avoid having 0 scale values, can lead to errors in physics and rendering. @@ -172,14 +172,14 @@ void Node2D::set_scale(const Size2 &p_scale) { Point2 Node2D::get_position() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return position; } real_t Node2D::get_rotation() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return rotation; @@ -187,7 +187,7 @@ real_t Node2D::get_rotation() const { real_t Node2D::get_skew() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return skew; @@ -195,7 +195,7 @@ real_t Node2D::get_skew() const { Size2 Node2D::get_scale() const { if (_xform_dirty) { - ((Node2D *)this)->_update_xform_values(); + const_cast<Node2D *>(this)->_update_xform_values(); } return scale; diff --git a/scene/2d/physical_bone_2d.h b/scene/2d/physical_bone_2d.h index 9f31c22031..22d329c320 100644 --- a/scene/2d/physical_bone_2d.h +++ b/scene/2d/physical_bone_2d.h @@ -49,7 +49,7 @@ private: NodePath bone2d_nodepath; bool follow_bone_when_simulating = false; - Joint2D *child_joint; + Joint2D *child_joint = nullptr; bool auto_configure_joint = true; bool simulate_physics = false; diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp index f96c7b512f..c0f2b6f07e 100644 --- a/scene/2d/physics_body_2d.cpp +++ b/scene/2d/physics_body_2d.cpp @@ -277,7 +277,7 @@ void AnimatableBody2D::_update_kinematic_motion() { } void AnimatableBody2D::_body_state_changed_callback(void *p_instance, PhysicsDirectBodyState2D *p_state) { - AnimatableBody2D *body = (AnimatableBody2D *)p_instance; + AnimatableBody2D *body = static_cast<AnimatableBody2D *>(p_instance); body->_body_state_changed(p_state); } @@ -443,7 +443,7 @@ struct _RigidDynamicBody2DInOut { }; void RigidDynamicBody2D::_body_state_changed_callback(void *p_instance, PhysicsDirectBodyState2D *p_state) { - RigidDynamicBody2D *body = (RigidDynamicBody2D *)p_instance; + RigidDynamicBody2D *body = static_cast<RigidDynamicBody2D *>(p_instance); body->_body_state_changed(p_state); } diff --git a/scene/2d/position_2d.cpp b/scene/2d/position_2d.cpp index 518593cee1..d946ea63bf 100644 --- a/scene/2d/position_2d.cpp +++ b/scene/2d/position_2d.cpp @@ -30,8 +30,6 @@ #include "position_2d.h" -const real_t DEFAULT_GIZMO_EXTENTS = 10.0; - void Position2D::_draw_cross() { const real_t extents = get_gizmo_extents(); @@ -103,28 +101,19 @@ void Position2D::_notification(int p_what) { } void Position2D::set_gizmo_extents(real_t p_extents) { - if (p_extents == DEFAULT_GIZMO_EXTENTS) { - set_meta("_gizmo_extents_", Variant()); - } else { - set_meta("_gizmo_extents_", p_extents); - } - + gizmo_extents = p_extents; update(); } real_t Position2D::get_gizmo_extents() const { - if (has_meta("_gizmo_extents_")) { - return get_meta("_gizmo_extents_"); - } else { - return DEFAULT_GIZMO_EXTENTS; - } + return gizmo_extents; } void Position2D::_bind_methods() { - ClassDB::bind_method(D_METHOD("_set_gizmo_extents", "extents"), &Position2D::set_gizmo_extents); - ClassDB::bind_method(D_METHOD("_get_gizmo_extents"), &Position2D::get_gizmo_extents); + ClassDB::bind_method(D_METHOD("set_gizmo_extents", "extents"), &Position2D::set_gizmo_extents); + ClassDB::bind_method(D_METHOD("get_gizmo_extents"), &Position2D::get_gizmo_extents); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gizmo_extents", PROPERTY_HINT_RANGE, "0,1000,0.1,or_greater", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_gizmo_extents", "_get_gizmo_extents"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gizmo_extents", PROPERTY_HINT_RANGE, "0,1000,0.1,or_greater"), "set_gizmo_extents", "get_gizmo_extents"); } Position2D::Position2D() { diff --git a/scene/2d/position_2d.h b/scene/2d/position_2d.h index 4ef07eb05c..99b0266130 100644 --- a/scene/2d/position_2d.h +++ b/scene/2d/position_2d.h @@ -36,6 +36,8 @@ class Position2D : public Node2D { GDCLASS(Position2D, Node2D); + real_t gizmo_extents = 10.0; + void _draw_cross(); protected: diff --git a/scene/3d/camera_3d.cpp b/scene/3d/camera_3d.cpp index 4eace17cc0..1f0c9acef5 100644 --- a/scene/3d/camera_3d.cpp +++ b/scene/3d/camera_3d.cpp @@ -509,7 +509,7 @@ void Camera3D::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "projection", PROPERTY_HINT_ENUM, "Perspective,Orthogonal,Frustum"), "set_projection", "get_projection"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "set_current", "is_current"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov", PROPERTY_HINT_RANGE, "1,179,0.1,degrees"), "set_fov", "get_fov"); - ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size", PROPERTY_HINT_RANGE, "0.1,16384,0.01"), "set_size", "get_size"); + ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size", PROPERTY_HINT_RANGE, "0.001,16384,0.001"), "set_size", "get_size"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "frustum_offset"), "set_frustum_offset", "get_frustum_offset"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "near", PROPERTY_HINT_RANGE, "0.001,10,0.001,or_greater,exp"), "set_near", "get_near"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "far", PROPERTY_HINT_RANGE, "0.01,4000,0.01,or_greater,exp"), "set_far", "get_far"); @@ -557,7 +557,7 @@ void Camera3D::set_fov(real_t p_fov) { } void Camera3D::set_size(real_t p_size) { - ERR_FAIL_COND(p_size < 0.1 || p_size > 16384); + ERR_FAIL_COND(p_size < 0.001 || p_size > 16384); size = p_size; _update_camera_mode(); } diff --git a/scene/3d/lightmap_gi.cpp b/scene/3d/lightmap_gi.cpp index 191a04b6a0..8b457b683d 100644 --- a/scene/3d/lightmap_gi.cpp +++ b/scene/3d/lightmap_gi.cpp @@ -884,7 +884,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa Light3D *light = lights_found[i].light; Transform3D xf = lights_found[i].xform; - Color linear_color = light->get_color().to_linear(); + Color linear_color = light->get_color().srgb_to_linear(); if (Object::cast_to<DirectionalLight3D>(light)) { DirectionalLight3D *l = Object::cast_to<DirectionalLight3D>(light); lightmapper->add_directional_light(light->get_bake_mode() == Light3D::BAKE_STATIC, -xf.basis.get_axis(Vector3::AXIS_Z).normalized(), linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_SIZE)); @@ -1101,7 +1101,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa //#define DEBUG_SIMPLICES_AS_OBJ_FILE #ifdef DEBUG_SIMPLICES_AS_OBJ_FILE { - FileAccessRef f = FileAccess::open("res://bsp.obj", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open("res://bsp.obj", FileAccess::WRITE); for (uint32_t i = 0; i < bsp_simplices.size(); i++) { f->store_line("o Simplex" + itos(i)); for (int j = 0; j < 4; j++) { @@ -1118,7 +1118,6 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa f->store_line(vformat("f %d %d %d", 4 * i + face_order[j][0], 4 * i + face_order[j][1], 4 * i + face_order[j][2])); } } - f->close(); } #endif @@ -1150,7 +1149,7 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa } //#define DEBUG_BSP_TREE #ifdef DEBUG_BSP_TREE - FileAccessRef f = FileAccess::open("res://bsp.txt", FileAccess::WRITE); + Ref<FileAccess> f = FileAccess::open("res://bsp.txt", FileAccess::WRITE); for (uint32_t i = 0; i < bsp_nodes.size(); i++) { f->store_line(itos(i) + " - plane: " + bsp_nodes[i].plane + " over: " + itos(bsp_nodes[i].over) + " under: " + itos(bsp_nodes[i].under)); } diff --git a/scene/3d/node_3d.cpp b/scene/3d/node_3d.cpp index 62cc7c143b..bbc977647e 100644 --- a/scene/3d/node_3d.cpp +++ b/scene/3d/node_3d.cpp @@ -181,15 +181,6 @@ void Node3D::_notification(int p_what) { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint() && get_tree()->is_node_being_edited(this)) { get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this); - if (!data.gizmos_disabled) { - for (int i = 0; i < data.gizmos.size(); i++) { - data.gizmos.write[i]->create(); - if (is_visible_in_tree()) { - data.gizmos.write[i]->redraw(); - } - data.gizmos.write[i]->transform(); - } - } } #endif } break; @@ -427,6 +418,7 @@ void Node3D::update_gizmos() { } if (data.gizmos.is_empty()) { + get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this); return; } if (data.gizmos_dirty) { diff --git a/scene/3d/skeleton_3d.h b/scene/3d/skeleton_3d.h index 80ff2a1f79..279c3e49a2 100644 --- a/scene/3d/skeleton_3d.h +++ b/scene/3d/skeleton_3d.h @@ -44,13 +44,13 @@ class SkinReference : public RefCounted { GDCLASS(SkinReference, RefCounted) friend class Skeleton3D; - Skeleton3D *skeleton_node; + Skeleton3D *skeleton_node = nullptr; RID skeleton; Ref<Skin> skin; uint32_t bind_count = 0; uint64_t skeleton_version = 0; Vector<uint32_t> skin_bone_indices; - uint32_t *skin_bone_indices_ptrs; + uint32_t *skin_bone_indices_ptrs = nullptr; void _skin_changed(); protected: diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp index 1ab2e2419e..6949e3681c 100644 --- a/scene/animation/animation_player.cpp +++ b/scene/animation/animation_player.cpp @@ -83,8 +83,31 @@ bool AnimationPlayer::_set(const StringName &p_name, const Variant &p_value) { set_current_animation(p_value); } else if (name.begins_with("anims/")) { + // Backwards compatibility with 3.x, add them to "default" library. String which = name.get_slicec('/', 1); - add_animation(which, p_value); + + Ref<Animation> anim = p_value; + Ref<AnimationLibrary> al; + if (!has_animation_library(StringName())) { + al.instantiate(); + add_animation_library(StringName(), al); + } else { + al = get_animation_library(StringName()); + } + al->add_animation(which, anim); + + } else if (name.begins_with("libraries")) { + Dictionary d = p_value; + while (animation_libraries.size()) { + remove_animation_library(animation_libraries[0].name); + } + List<Variant> keys; + d.get_key_list(&keys); + for (const Variant &K : keys) { + StringName lib_name = K; + Ref<AnimationLibrary> lib = d[lib_name]; + add_animation_library(lib_name, lib); + } } else if (name.begins_with("next/")) { String which = name.get_slicec('/', 1); @@ -117,9 +140,13 @@ bool AnimationPlayer::_get(const StringName &p_name, Variant &r_ret) const { r_ret = get_current_animation(); - } else if (name.begins_with("anims/")) { - String which = name.get_slicec('/', 1); - r_ret = get_animation(which); + } else if (name.begins_with("libraries")) { + Dictionary d; + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + d[animation_libraries[i].name] = animation_libraries[i].library; + } + + r_ret = d; } else if (name.begins_with("next/")) { String which = name.get_slicec('/', 1); @@ -173,8 +200,9 @@ void AnimationPlayer::_validate_property(PropertyInfo &property) const { void AnimationPlayer::_get_property_list(List<PropertyInfo> *p_list) const { List<PropertyInfo> anim_names; + anim_names.push_back(PropertyInfo(Variant::DICTIONARY, "libraries")); + for (const KeyValue<StringName, AnimationData> &E : animation_set) { - anim_names.push_back(PropertyInfo(Variant::OBJECT, "anims/" + String(E.key), PROPERTY_HINT_RESOURCE_TYPE, "Animation", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE)); if (E.value.next != StringName()) { anim_names.push_back(PropertyInfo(Variant::STRING, "next/" + String(E.key), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL)); } @@ -1155,71 +1183,106 @@ void AnimationPlayer::_animation_process(double p_delta) { } } -Error AnimationPlayer::add_animation(const StringName &p_name, const Ref<Animation> &p_animation) { -#ifdef DEBUG_ENABLED - ERR_FAIL_COND_V_MSG(String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("["), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + "."); -#endif +void AnimationPlayer::_animation_set_cache_update() { + // Relatively fast function to update all animations. - ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER); + animation_set_update_pass++; + bool clear_cache_needed = false; - if (animation_set.has(p_name)) { - _unref_anim(animation_set[p_name].animation); - animation_set[p_name].animation = p_animation; - clear_caches(); - } else { - AnimationData ad; - ad.animation = p_animation; - ad.name = p_name; - animation_set[p_name] = ad; - } + // Update changed and add otherwise + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) { + StringName key = animation_libraries[i].name == StringName() ? K.key : StringName(String(animation_libraries[i].name) + "/" + String(K.key)); + if (!animation_set.has(key)) { + AnimationData ad; + ad.animation = K.value; + ad.animation_library = animation_libraries[i].name; + ad.name = key; + ad.last_update = animation_set_update_pass; + animation_set.insert(ad.name, ad); + } else { + AnimationData &ad = animation_set[key]; + if (ad.last_update != animation_set_update_pass) { + // Was not updated, update. If the animation is duplicated, the second one will be ignored. + if (ad.animation != K.value || ad.animation_library != animation_libraries[i].name) { + // Animation changed, update and clear caches. + clear_cache_needed = true; + ad.animation = K.value; + ad.animation_library = animation_libraries[i].name; + } - _ref_anim(p_animation); - notify_property_list_changed(); - return OK; -} + ad.last_update = animation_set_update_pass; + } + } + } + } -void AnimationPlayer::remove_animation(const StringName &p_name) { - ERR_FAIL_COND(!animation_set.has(p_name)); + // Check removed + List<StringName> to_erase; + for (const KeyValue<StringName, AnimationData> &E : animation_set) { + if (E.value.last_update != animation_set_update_pass) { + // Was not updated, must be erased + to_erase.push_back(E.key); + clear_cache_needed = true; + } + } - stop(); - _unref_anim(animation_set[p_name].animation); - animation_set.erase(p_name); + while (to_erase.size()) { + animation_set.erase(to_erase.front()->get()); + to_erase.pop_front(); + } - clear_caches(); - notify_property_list_changed(); + if (clear_cache_needed) { + // If something was modified or removed, caches need to be cleared + clear_caches(); + } } -void AnimationPlayer::_ref_anim(const Ref<Animation> &p_anim) { - Ref<Animation>(p_anim)->connect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed), varray(), CONNECT_REFERENCE_COUNTED); -} +void AnimationPlayer::_animation_added(const StringName &p_name, const StringName &p_library) { + _animation_set_cache_update(); -void AnimationPlayer::_unref_anim(const Ref<Animation> &p_anim) { - Ref<Animation>(p_anim)->disconnect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed)); + update_configuration_warnings(); } -void AnimationPlayer::rename_animation(const StringName &p_name, const StringName &p_new_name) { - ERR_FAIL_COND(!animation_set.has(p_name)); - ERR_FAIL_COND(String(p_new_name).contains("/") || String(p_new_name).contains(":")); - ERR_FAIL_COND(animation_set.has(p_new_name)); +void AnimationPlayer::_animation_removed(const StringName &p_name, const StringName &p_library) { + StringName name = p_library == StringName() ? p_name : StringName(String(p_library) + "/" + String(p_name)); - stop(); - AnimationData ad = animation_set[p_name]; - ad.name = p_new_name; - animation_set.erase(p_name); - animation_set[p_new_name] = ad; + if (!animation_set.has(name)) { + return; // No need to update because not the one from the library being used. + } + _animation_set_cache_update(); + + // Erase blends if needed + List<BlendKey> to_erase; + for (const KeyValue<BlendKey, float> &E : blend_times) { + BlendKey bk = E.key; + if (bk.from == name || bk.to == name) { + to_erase.push_back(bk); + } + } + + while (to_erase.size()) { + blend_times.erase(to_erase.front()->get()); + to_erase.pop_front(); + } + + update_configuration_warnings(); +} +void AnimationPlayer::_rename_animation(const StringName &p_from_name, const StringName &p_to_name) { + // Rename autoplay or blends if needed. List<BlendKey> to_erase; Map<BlendKey, float> to_insert; for (const KeyValue<BlendKey, float> &E : blend_times) { BlendKey bk = E.key; BlendKey new_bk = bk; bool erase = false; - if (bk.from == p_name) { - new_bk.from = p_new_name; + if (bk.from == p_from_name) { + new_bk.from = p_to_name; erase = true; } - if (bk.to == p_name) { - new_bk.to = p_new_name; + if (bk.to == p_from_name) { + new_bk.to = p_to_name; erase = true; } @@ -1239,12 +1302,184 @@ void AnimationPlayer::rename_animation(const StringName &p_name, const StringNam to_insert.erase(to_insert.front()); } - if (autoplay == p_name) { - autoplay = p_new_name; + if (autoplay == p_from_name) { + autoplay = p_to_name; } +} + +void AnimationPlayer::_animation_renamed(const StringName &p_name, const StringName &p_to_name, const StringName &p_library) { + StringName from_name = p_library == StringName() ? p_name : StringName(String(p_library) + "/" + String(p_name)); + StringName to_name = p_library == StringName() ? p_to_name : StringName(String(p_library) + "/" + String(p_to_name)); + + if (!animation_set.has(from_name)) { + return; // No need to update because not the one from the library being used. + } + _animation_set_cache_update(); + + _rename_animation(from_name, to_name); + update_configuration_warnings(); +} + +Error AnimationPlayer::add_animation_library(const StringName &p_name, const Ref<AnimationLibrary> &p_animation_library) { + ERR_FAIL_COND_V(p_animation_library.is_null(), ERR_INVALID_PARAMETER); +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_V_MSG(String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("["), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + "."); +#endif + + int insert_pos = 0; + + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + ERR_FAIL_COND_V_MSG(animation_libraries[i].name == p_name, ERR_ALREADY_EXISTS, "Can't add animation library twice with name: " + String(p_name)); + ERR_FAIL_COND_V_MSG(animation_libraries[i].library == p_animation_library, ERR_ALREADY_EXISTS, "Can't add animation library twice (adding as '" + p_name.operator String() + "', exists as '" + animation_libraries[i].name.operator String() + "'."); + + if (animation_libraries[i].name.operator String() >= p_name.operator String()) { + break; + } + + insert_pos++; + } + + AnimationLibraryData ald; + ald.name = p_name; + ald.library = p_animation_library; + + animation_libraries.insert(insert_pos, ald); + + ald.library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_name)); + ald.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_name)); + ald.library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed), varray(p_name)); + + _animation_set_cache_update(); + + notify_property_list_changed(); + + update_configuration_warnings(); + return OK; +} + +void AnimationPlayer::remove_animation_library(const StringName &p_name) { + int at_pos = -1; + + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + if (animation_libraries[i].name == p_name) { + at_pos = i; + break; + } + } + + ERR_FAIL_COND(at_pos == -1); + + animation_libraries[at_pos].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[at_pos].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[at_pos].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed)); + + stop(); + + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[at_pos].library->animations) { + _unref_anim(K.value); + } + + animation_libraries.remove_at(at_pos); + _animation_set_cache_update(); - clear_caches(); notify_property_list_changed(); + update_configuration_warnings(); +} + +void AnimationPlayer::_ref_anim(const Ref<Animation> &p_anim) { + Ref<Animation>(p_anim)->connect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed), varray(), CONNECT_REFERENCE_COUNTED); +} + +void AnimationPlayer::_unref_anim(const Ref<Animation> &p_anim) { + Ref<Animation>(p_anim)->disconnect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed)); +} + +void AnimationPlayer::rename_animation_library(const StringName &p_name, const StringName &p_new_name) { + if (p_name == p_new_name) { + return; + } +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_MSG(String(p_new_name).contains("/") || String(p_new_name).contains(":") || String(p_new_name).contains(",") || String(p_new_name).contains("["), "Invalid animation library name: " + String(p_new_name) + "."); +#endif + + bool found = false; + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + ERR_FAIL_COND_MSG(animation_libraries[i].name == p_new_name, "Can't rename animation library to another existing name: " + String(p_new_name)); + if (animation_libraries[i].name == p_name) { + found = true; + animation_libraries[i].name = p_new_name; + // rename connections + animation_libraries[i].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[i].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added)); + animation_libraries[i].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed)); + + animation_libraries[i].library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_new_name)); + animation_libraries[i].library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_added), varray(p_new_name)); + animation_libraries[i].library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed), varray(p_new_name)); + + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) { + StringName old_name = p_name == StringName() ? K.key : StringName(String(p_name) + "/" + String(K.key)); + StringName new_name = p_new_name == StringName() ? K.key : StringName(String(p_new_name) + "/" + String(K.key)); + _rename_animation(old_name, new_name); + } + } + } + + ERR_FAIL_COND(!found); + + stop(); + + animation_libraries.sort(); // Must keep alphabetical order. + + _animation_set_cache_update(); // Update cache. + + notify_property_list_changed(); +} + +bool AnimationPlayer::has_animation_library(const StringName &p_name) const { + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + if (animation_libraries[i].name == p_name) { + return true; + } + } + + return false; +} + +Ref<AnimationLibrary> AnimationPlayer::get_animation_library(const StringName &p_name) const { + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + if (animation_libraries[i].name == p_name) { + return animation_libraries[i].library; + } + } + ERR_FAIL_V(Ref<AnimationLibrary>()); +} + +TypedArray<StringName> AnimationPlayer::_get_animation_library_list() const { + TypedArray<StringName> ret; + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + ret.push_back(animation_libraries[i].name); + } + return ret; +} + +void AnimationPlayer::get_animation_library_list(List<StringName> *p_libraries) const { + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + p_libraries->push_back(animation_libraries[i].name); + } +} + +TypedArray<String> AnimationPlayer::get_configuration_warnings() const { + TypedArray<String> warnings = Node::get_configuration_warnings(); + + for (uint32_t i = 0; i < animation_libraries.size(); i++) { + for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) { + if (animation_set.has(K.key) && animation_set[K.key].animation_library != animation_libraries[i].name) { + warnings.push_back(vformat(RTR("Animation '%s' in library '%s' is unused because another animation with the same name exists in library '%s'."), K.key, animation_libraries[i].name, animation_set[K.key].animation_library)); + } + } + } + return warnings; } bool AnimationPlayer::has_animation(const StringName &p_name) const { @@ -1585,7 +1820,16 @@ StringName AnimationPlayer::find_animation(const Ref<Animation> &p_animation) co } } - return ""; + return StringName(); +} + +StringName AnimationPlayer::find_animation_library(const Ref<Animation> &p_animation) const { + for (const KeyValue<StringName, AnimationData> &E : animation_set) { + if (E.value.animation == p_animation) { + return E.value.animation_library; + } + } + return StringName(); } void AnimationPlayer::set_autoplay(const String &p_name) { @@ -1764,7 +2008,10 @@ Ref<AnimatedValuesBackup> AnimationPlayer::apply_reset(bool p_user_initiated) { AnimationPlayer *aux_player = memnew(AnimationPlayer); EditorNode::get_singleton()->add_child(aux_player); - aux_player->add_animation(SceneStringNames::get_singleton()->RESET, reset_anim); + Ref<AnimationLibrary> al; + al.instantiate(); + al->add_animation(SceneStringNames::get_singleton()->RESET, reset_anim); + aux_player->add_animation_library("default", al); aux_player->set_assigned_animation(SceneStringNames::get_singleton()->RESET); // Forcing the use of the original root because the scene where original player belongs may be not the active one Node *root = get_node(get_root()); @@ -1792,9 +2039,13 @@ bool AnimationPlayer::can_apply_reset() const { #endif // TOOLS_ENABLED void AnimationPlayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("add_animation", "name", "animation"), &AnimationPlayer::add_animation); - ClassDB::bind_method(D_METHOD("remove_animation", "name"), &AnimationPlayer::remove_animation); - ClassDB::bind_method(D_METHOD("rename_animation", "name", "newname"), &AnimationPlayer::rename_animation); + ClassDB::bind_method(D_METHOD("add_animation_library", "name", "library"), &AnimationPlayer::add_animation_library); + ClassDB::bind_method(D_METHOD("remove_animation_library", "name"), &AnimationPlayer::remove_animation_library); + ClassDB::bind_method(D_METHOD("rename_animation_library", "name", "newname"), &AnimationPlayer::rename_animation_library); + ClassDB::bind_method(D_METHOD("has_animation_library", "name"), &AnimationPlayer::has_animation_library); + ClassDB::bind_method(D_METHOD("get_animation_library", "name"), &AnimationPlayer::get_animation_library); + ClassDB::bind_method(D_METHOD("get_animation_library_list"), &AnimationPlayer::_get_animation_library_list); + ClassDB::bind_method(D_METHOD("has_animation", "name"), &AnimationPlayer::has_animation); ClassDB::bind_method(D_METHOD("get_animation", "name"), &AnimationPlayer::get_animation); ClassDB::bind_method(D_METHOD("get_animation_list"), &AnimationPlayer::_get_animation_list); @@ -1838,6 +2089,7 @@ void AnimationPlayer::_bind_methods() { ClassDB::bind_method(D_METHOD("get_root"), &AnimationPlayer::get_root); ClassDB::bind_method(D_METHOD("find_animation", "animation"), &AnimationPlayer::find_animation); + ClassDB::bind_method(D_METHOD("find_animation_library", "animation"), &AnimationPlayer::find_animation_library); ClassDB::bind_method(D_METHOD("clear_caches"), &AnimationPlayer::clear_caches); diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h index a68f6b9d5b..1d450175ad 100644 --- a/scene/animation/animation_player.h +++ b/scene/animation/animation_player.h @@ -36,6 +36,7 @@ #include "scene/3d/node_3d.h" #include "scene/3d/skeleton_3d.h" #include "scene/resources/animation.h" +#include "scene/resources/animation_library.h" #ifdef TOOLS_ENABLED class AnimatedValuesBackup : public RefCounted { @@ -184,9 +185,20 @@ private: StringName next; Vector<TrackNodeCache *> node_cache; Ref<Animation> animation; + StringName animation_library; + uint64_t last_update = 0; }; Map<StringName, AnimationData> animation_set; + + struct AnimationLibraryData { + StringName name; + Ref<AnimationLibrary> library; + bool operator<(const AnimationLibraryData &p_data) const { return name.operator String() < p_data.name.operator String(); } + }; + + LocalVector<AnimationLibraryData> animation_libraries; + struct BlendKey { StringName from; StringName to; @@ -261,6 +273,15 @@ private: bool playing = false; + uint64_t animation_set_update_pass = 1; + void _animation_set_cache_update(); + void _animation_added(const StringName &p_name, const StringName &p_library); + void _animation_removed(const StringName &p_name, const StringName &p_library); + void _animation_renamed(const StringName &p_name, const StringName &p_to_name, const StringName &p_library); + void _rename_animation(const StringName &p_from_name, const StringName &p_to_name); + + TypedArray<StringName> _get_animation_library_list() const; + protected: bool _set(const StringName &p_name, const Variant &p_value); bool _get(const StringName &p_name, Variant &r_ret) const; @@ -272,13 +293,18 @@ protected: public: StringName find_animation(const Ref<Animation> &p_animation) const; + StringName find_animation_library(const Ref<Animation> &p_animation) const; + + Error add_animation_library(const StringName &p_name, const Ref<AnimationLibrary> &p_animation_library); + void remove_animation_library(const StringName &p_name); + void rename_animation_library(const StringName &p_name, const StringName &p_new_name); + Ref<AnimationLibrary> get_animation_library(const StringName &p_name) const; + void get_animation_library_list(List<StringName> *p_animations) const; + bool has_animation_library(const StringName &p_name) const; - Error add_animation(const StringName &p_name, const Ref<Animation> &p_animation); - void remove_animation(const StringName &p_name); - void rename_animation(const StringName &p_name, const StringName &p_new_name); - bool has_animation(const StringName &p_name) const; Ref<Animation> get_animation(const StringName &p_name) const; void get_animation_list(List<StringName> *p_animations) const; + bool has_animation(const StringName &p_name) const; void set_blend_time(const StringName &p_animation1, const StringName &p_animation2, float p_time); float get_blend_time(const StringName &p_animation1, const StringName &p_animation2) const; @@ -340,6 +366,8 @@ public: bool can_apply_reset() const; #endif + TypedArray<String> get_configuration_warnings() const override; + AnimationPlayer(); ~AnimationPlayer(); }; diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp index 64c71697a5..60f2623267 100644 --- a/scene/animation/animation_tree.cpp +++ b/scene/animation/animation_tree.cpp @@ -540,6 +540,11 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { List<StringName> sname; player->get_animation_list(&sname); + Ref<Animation> reset_anim; + bool has_reset_anim = player->has_animation("RESET"); + if (has_reset_anim) { + reset_anim = player->get_animation("RESET"); + } for (const StringName &E : sname) { Ref<Animation> anim = player->get_animation(E); for (int i = 0; i < anim->get_track_count(); i++) { @@ -593,6 +598,12 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { track = track_value; + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + track_value->init_value = reset_anim->track_get_key_value(rt, 0); + } + } } break; case Animation::TYPE_POSITION_3D: case Animation::TYPE_ROTATION_3D: @@ -645,6 +656,25 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { } } + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + switch (track_type) { + case Animation::TYPE_POSITION_3D: { + track_xform->init_loc = reset_anim->track_get_key_value(rt, 0); + } break; + case Animation::TYPE_ROTATION_3D: { + track_xform->ref_rot = reset_anim->track_get_key_value(rt, 0); + track_xform->init_rot = track_xform->ref_rot.log(); + } break; + case Animation::TYPE_SCALE_3D: { + track_xform->init_scale = reset_anim->track_get_key_value(rt, 0); + } break; + default: { + } + } + } + } #endif // _3D_DISABLED } break; case Animation::TYPE_BLEND_SHAPE: { @@ -675,6 +705,13 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { track_bshape->object = mesh_3d; track_bshape->object_id = mesh_3d->get_instance_id(); track = track_bshape; + + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + track_bshape->init_value = reset_anim->track_get_key_value(rt, 0); + } + } #endif } break; case Animation::TYPE_METHOD: { @@ -704,6 +741,13 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) { track_bezier->object_id = track_bezier->object->get_instance_id(); track = track_bezier; + + if (has_reset_anim) { + int rt = reset_anim->find_track(path, track_type); + if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) { + track_bezier->init_value = reset_anim->track_get_key_value(rt, 0); + } + } } break; case Animation::TYPE_AUDIO: { TrackCacheAudio *track_audio = memnew(TrackCacheAudio); @@ -950,13 +994,13 @@ void AnimationTree::_process_graph(double p_delta) { case Animation::TYPE_POSITION_3D: { #ifndef _3D_DISABLED TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track); - if (t->process_pass != process_pass) { - t->process_pass = process_pass; - t->loc = t->init_loc; - t->rot = t->init_rot; - t->scale = t->init_scale; - } if (track->root_motion) { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = Vector3(0, 0, 0); + t->rot = Quaternion(0, 0, 0, 0); + t->scale = Vector3(0, 0, 0); + } double prev_time = time - delta; if (!backward) { if (prev_time < 0) { @@ -1026,6 +1070,12 @@ void AnimationTree::_process_graph(double p_delta) { prev_time = !backward ? 0 : (double)a->get_length(); } else { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = t->init_loc; + t->rot = t->init_rot; + t->scale = t->init_scale; + } Vector3 loc; Error err = a->position_track_interpolate(i, time, &loc); @@ -1040,13 +1090,13 @@ void AnimationTree::_process_graph(double p_delta) { case Animation::TYPE_ROTATION_3D: { #ifndef _3D_DISABLED TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track); - if (t->process_pass != process_pass) { - t->process_pass = process_pass; - t->loc = t->init_loc; - t->rot = t->init_rot; - t->scale = t->init_scale; - } if (track->root_motion) { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = Vector3(0, 0, 0); + t->rot = Quaternion(0, 0, 0, 0); + t->scale = Vector3(0, 0, 0); + } double prev_time = time - delta; if (!backward) { if (prev_time < 0) { @@ -1116,6 +1166,12 @@ void AnimationTree::_process_graph(double p_delta) { prev_time = !backward ? 0 : (double)a->get_length(); } else { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = t->init_loc; + t->rot = t->init_rot; + t->scale = t->init_scale; + } Quaternion rot; Error err = a->rotation_track_interpolate(i, time, &rot); @@ -1133,13 +1189,13 @@ void AnimationTree::_process_graph(double p_delta) { case Animation::TYPE_SCALE_3D: { #ifndef _3D_DISABLED TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track); - if (t->process_pass != process_pass) { - t->process_pass = process_pass; - t->loc = t->init_loc; - t->rot = t->init_rot; - t->scale = t->init_scale; - } if (track->root_motion) { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = Vector3(0, 0, 0); + t->rot = Quaternion(0, 0, 0, 0); + t->scale = Vector3(0, 0, 0); + } double prev_time = time - delta; if (!backward) { if (prev_time < 0) { @@ -1209,6 +1265,12 @@ void AnimationTree::_process_graph(double p_delta) { prev_time = !backward ? 0 : (double)a->get_length(); } else { + if (t->process_pass != process_pass) { + t->process_pass = process_pass; + t->loc = t->init_loc; + t->rot = t->init_rot; + t->scale = t->init_scale; + } Vector3 scale; Error err = a->scale_track_interpolate(i, time, &scale); @@ -1226,7 +1288,7 @@ void AnimationTree::_process_graph(double p_delta) { if (t->process_pass != process_pass) { t->process_pass = process_pass; - t->value = 0; + t->value = t->init_value; } float value; @@ -1238,7 +1300,7 @@ void AnimationTree::_process_graph(double p_delta) { continue; } - t->value += value * blend; + t->value += (value - t->init_value) * blend; #endif // _3D_DISABLED } break; case Animation::TYPE_VALUE: { @@ -1256,10 +1318,15 @@ void AnimationTree::_process_graph(double p_delta) { if (t->process_pass != process_pass) { t->process_pass = process_pass; - t->value = value; - t->value.zero(); + if (!t->init_value) { + t->init_value = value; + t->init_value.zero(); + } else { + t->value = t->init_value; + } } + Variant::sub(value, t->init_value, value); Variant::blend(t->value, value, blend, t->value); } else { if (blend < CMP_EPSILON) { @@ -1303,10 +1370,10 @@ void AnimationTree::_process_graph(double p_delta) { if (t->process_pass != process_pass) { t->process_pass = process_pass; - t->value = 0; + t->value = t->init_value; } - t->value += bezier * blend; + t->value += (bezier - t->init_value) * blend; } break; case Animation::TYPE_AUDIO: { if (blend < CMP_EPSILON) { @@ -1521,7 +1588,7 @@ void AnimationTree::_process_graph(double p_delta) { if (t->root_motion) { Transform3D xform; xform.origin = t->loc; - xform.basis.set_quaternion_scale(t->rot, t->scale); + xform.basis.set_quaternion_scale(t->rot, Vector3(1, 1, 1) + t->scale); root_motion_transform = xform; diff --git a/scene/animation/animation_tree.h b/scene/animation/animation_tree.h index 3ccb6be073..524f735894 100644 --- a/scene/animation/animation_tree.h +++ b/scene/animation/animation_tree.h @@ -212,12 +212,14 @@ private: struct TrackCacheBlendShape : public TrackCache { MeshInstance3D *mesh_3d = nullptr; + float init_value = 0; float value = 0; int shape_index = -1; TrackCacheBlendShape() { type = Animation::TYPE_BLEND_SHAPE; } }; struct TrackCacheValue : public TrackCache { + Variant init_value; Variant value; Vector<StringName> subpath; TrackCacheValue() { type = Animation::TYPE_VALUE; } @@ -228,6 +230,7 @@ private: }; struct TrackCacheBezier : public TrackCache { + real_t init_value = 0.0; real_t value = 0.0; Vector<StringName> subpath; TrackCacheBezier() { diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp index ab86face7e..789c01adf3 100644 --- a/scene/gui/base_button.cpp +++ b/scene/gui/base_button.cpp @@ -339,14 +339,14 @@ bool BaseButton::is_keep_pressed_outside() const { void BaseButton::set_shortcut(const Ref<Shortcut> &p_shortcut) { shortcut = p_shortcut; - set_process_unhandled_key_input(shortcut.is_valid()); + set_process_shortcut_input(shortcut.is_valid()); } Ref<Shortcut> BaseButton::get_shortcut() const { return shortcut; } -void BaseButton::unhandled_key_input(const Ref<InputEvent> &p_event) { +void BaseButton::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (!_is_focus_owner_in_shortcut_context()) { diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h index a2b6ee0845..f4f9b88868 100644 --- a/scene/gui/base_button.h +++ b/scene/gui/base_button.h @@ -77,7 +77,7 @@ protected: virtual void toggled(bool p_pressed); static void _bind_methods(); virtual void gui_input(const Ref<InputEvent> &p_event) override; - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; void _notification(int p_what); bool _is_focus_owner_in_shortcut_context() const; diff --git a/scene/gui/dialogs.h b/scene/gui/dialogs.h index 11c701b0d5..41fd9c0a10 100644 --- a/scene/gui/dialogs.h +++ b/scene/gui/dialogs.h @@ -45,10 +45,10 @@ class AcceptDialog : public Window { GDCLASS(AcceptDialog, Window); Window *parent_visible = nullptr; - Panel *bg; - HBoxContainer *hbc; - Label *label; - Button *ok; + Panel *bg = nullptr; + HBoxContainer *hbc = nullptr; + Label *label = nullptr; + Button *ok = nullptr; bool hide_on_ok = true; bool close_on_escape = true; @@ -103,7 +103,7 @@ public: class ConfirmationDialog : public AcceptDialog { GDCLASS(ConfirmationDialog, AcceptDialog); - Button *cancel; + Button *cancel = nullptr; protected: static void _bind_methods(); diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp index e71ab64535..c953dbf4c3 100644 --- a/scene/gui/file_dialog.cpp +++ b/scene/gui/file_dialog.cpp @@ -95,7 +95,7 @@ void FileDialog::_notification(int p_what) { switch (p_what) { case NOTIFICATION_VISIBILITY_CHANGED: { if (!is_visible()) { - set_process_unhandled_input(false); + set_process_shortcut_input(false); } } break; @@ -119,7 +119,7 @@ void FileDialog::_notification(int p_what) { } } -void FileDialog::unhandled_input(const Ref<InputEvent> &p_event) { +void FileDialog::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); Ref<InputEventKey> k = p_event; @@ -217,7 +217,7 @@ void FileDialog::_post_popup() { tree->grab_focus(); } - set_process_unhandled_input(true); + set_process_shortcut_input(true); // For open dir mode, deselect all items on file dialog open. if (mode == FILE_MODE_OPEN_DIR) { @@ -798,7 +798,6 @@ void FileDialog::set_access(Access p_access) { if (access == p_access) { return; } - memdelete(dir_access); switch (p_access) { case ACCESS_FILESYSTEM: { dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM); @@ -1091,5 +1090,4 @@ FileDialog::~FileDialog() { if (unregister_func) { unregister_func(this); } - memdelete(dir_access); } diff --git a/scene/gui/file_dialog.h b/scene/gui/file_dialog.h index 7a50efe40f..2e326d2949 100644 --- a/scene/gui/file_dialog.h +++ b/scene/gui/file_dialog.h @@ -65,34 +65,34 @@ public: static RegisterFunc unregister_func; private: - ConfirmationDialog *makedialog; - LineEdit *makedirname; + ConfirmationDialog *makedialog = nullptr; + LineEdit *makedirname = nullptr; - Button *makedir; + Button *makedir = nullptr; Access access = ACCESS_RESOURCES; - VBoxContainer *vbox; + VBoxContainer *vbox = nullptr; FileMode mode; - LineEdit *dir; - HBoxContainer *drives_container; - HBoxContainer *shortcuts_container; - OptionButton *drives; - Tree *tree; - HBoxContainer *file_box; - LineEdit *file; - OptionButton *filter; - AcceptDialog *mkdirerr; - AcceptDialog *exterr; - DirAccess *dir_access; - ConfirmationDialog *confirm_save; - - Label *message; - - Button *dir_prev; - Button *dir_next; - Button *dir_up; - - Button *refresh; - Button *show_hidden; + LineEdit *dir = nullptr; + HBoxContainer *drives_container = nullptr; + HBoxContainer *shortcuts_container = nullptr; + OptionButton *drives = nullptr; + Tree *tree = nullptr; + HBoxContainer *file_box = nullptr; + LineEdit *file = nullptr; + OptionButton *filter = nullptr; + AcceptDialog *mkdirerr = nullptr; + AcceptDialog *exterr = nullptr; + Ref<DirAccess> dir_access; + ConfirmationDialog *confirm_save = nullptr; + + Label *message = nullptr; + + Button *dir_prev = nullptr; + Button *dir_next = nullptr; + Button *dir_up = nullptr; + + Button *refresh = nullptr; + Button *show_hidden = nullptr; Vector<String> filters; @@ -133,7 +133,7 @@ private: void _update_drives(bool p_select = true); - virtual void unhandled_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; bool _is_open_should_be_disabled(); diff --git a/scene/gui/gradient_edit.h b/scene/gui/gradient_edit.h index 67531d4f4a..4e3c6525f9 100644 --- a/scene/gui/gradient_edit.h +++ b/scene/gui/gradient_edit.h @@ -38,8 +38,8 @@ class GradientEdit : public Control { GDCLASS(GradientEdit, Control); - PopupPanel *popup; - ColorPicker *picker; + PopupPanel *popup = nullptr; + ColorPicker *picker = nullptr; bool grabbing = false; int grabbed = -1; diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp index 1394b4192f..8b7e0f22b9 100644 --- a/scene/gui/graph_edit.cpp +++ b/scene/gui/graph_edit.cpp @@ -696,7 +696,7 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) { for (int j = 0; j < gn->get_connection_output_count(); j++) { Vector2 pos = gn->get_connection_output_position(j) + gn->get_position(); int type = gn->get_connection_output_type(j); - if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && is_in_output_hotzone(gn, j, mpos, port_size)) { + if ((type == connecting_type || valid_connection_types.has(ConnType(connecting_type, type))) && is_in_output_hotzone(gn, j, mpos, port_size)) { connecting_target = true; connecting_to = pos; connecting_target_to = gn->get_name(); @@ -708,7 +708,7 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) { for (int j = 0; j < gn->get_connection_input_count(); j++) { Vector2 pos = gn->get_connection_input_position(j) + gn->get_position(); int type = gn->get_connection_input_type(j); - if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && is_in_input_hotzone(gn, j, mpos, port_size)) { + if ((type == connecting_type || valid_connection_types.has(ConnType(connecting_type, type))) && is_in_input_hotzone(gn, j, mpos, port_size)) { connecting_target = true; connecting_to = pos; connecting_target_to = gn->get_name(); @@ -1568,26 +1568,17 @@ void GraphEdit::_update_zoom_label() { } void GraphEdit::add_valid_connection_type(int p_type, int p_with_type) { - ConnType ct; - ct.type_a = p_type; - ct.type_b = p_with_type; - + ConnType ct(p_type, p_with_type); valid_connection_types.insert(ct); } void GraphEdit::remove_valid_connection_type(int p_type, int p_with_type) { - ConnType ct; - ct.type_a = p_type; - ct.type_b = p_with_type; - + ConnType ct(p_type, p_with_type); valid_connection_types.erase(ct); } bool GraphEdit::is_valid_connection_type(int p_type, int p_with_type) const { - ConnType ct; - ct.type_a = p_type; - ct.type_b = p_with_type; - + ConnType ct(p_type, p_with_type); return valid_connection_types.has(ct); } @@ -1646,6 +1637,7 @@ float GraphEdit::get_minimap_opacity() const { void GraphEdit::set_minimap_enabled(bool p_enable) { minimap_button->set_pressed(p_enable); + _minimap_toggled(); minimap->update(); } diff --git a/scene/gui/graph_edit.h b/scene/gui/graph_edit.h index b0d1944d6e..18b9eeebd4 100644 --- a/scene/gui/graph_edit.h +++ b/scene/gui/graph_edit.h @@ -46,7 +46,7 @@ class GraphEditFilter : public Control { friend class GraphEdit; friend class GraphEditMinimap; - GraphEdit *ge; + GraphEdit *ge = nullptr; virtual bool has_point(const Point2 &p_point) const override; public: @@ -58,7 +58,7 @@ class GraphEditMinimap : public Control { friend class GraphEdit; friend class GraphEditFilter; - GraphEdit *ge; + GraphEdit *ge = nullptr; protected: public: @@ -109,20 +109,20 @@ public: }; private: - Label *zoom_label; - Button *zoom_minus; - Button *zoom_reset; - Button *zoom_plus; + Label *zoom_label = nullptr; + Button *zoom_minus = nullptr; + Button *zoom_reset = nullptr; + Button *zoom_plus = nullptr; - Button *snap_button; - SpinBox *snap_amount; + Button *snap_button = nullptr; + SpinBox *snap_amount = nullptr; - Button *minimap_button; + Button *minimap_button = nullptr; - Button *layout_button; + Button *layout_button = nullptr; - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; float port_grab_distance_horizontal = 0.0; float port_grab_distance_vertical; @@ -190,9 +190,9 @@ private: void _scroll_moved(double); virtual void gui_input(const Ref<InputEvent> &p_ev) override; - Control *connections_layer; - GraphEditFilter *top_layer; - GraphEditMinimap *minimap; + Control *connections_layer = nullptr; + GraphEditFilter *top_layer = nullptr; + GraphEditMinimap *minimap = nullptr; void _top_layer_input(const Ref<InputEvent> &p_ev); bool is_in_input_hotzone(GraphNode *p_graph_node, int p_slot_index, const Vector2 &p_mouse_pos, const Vector2i &p_port_size); @@ -236,7 +236,7 @@ private: void _set_drag_comment_enclosed_nodes(GraphNode *p_node, HashMap<StringName, Vector<GraphNode *>> &p_comment_enclosed_nodes, bool p_drag); void _set_position_of_comment_enclosed_nodes(GraphNode *p_node, HashMap<StringName, Vector<GraphNode *>> &p_comment_enclosed_nodes, Vector2 p_pos); - HBoxContainer *zoom_hb; + HBoxContainer *zoom_hb = nullptr; friend class GraphEditFilter; bool _filter_input(const Point2 &p_point); diff --git a/scene/gui/graph_node.cpp b/scene/gui/graph_node.cpp index ef0ac75cb4..51fb26b459 100644 --- a/scene/gui/graph_node.cpp +++ b/scene/gui/graph_node.cpp @@ -393,7 +393,6 @@ void GraphNode::_notification(int p_what) { w -= close->get_width(); } - title_buf->set_width(w); title_buf->draw(get_canvas_item(), Point2(sb->get_margin(SIDE_LEFT) + title_h_offset, -title_buf->get_size().y + title_offset), title_color); if (show_close) { Vector2 cpos = Point2(w + sb->get_margin(SIDE_LEFT) + close_h_offset, -close->get_height() + close_offset); diff --git a/scene/gui/item_list.h b/scene/gui/item_list.h index 96735678c1..ffbe7d055a 100644 --- a/scene/gui/item_list.h +++ b/scene/gui/item_list.h @@ -98,7 +98,7 @@ private: SelectMode select_mode = SELECT_SINGLE; IconMode icon_mode = ICON_MODE_LEFT; - VScrollBar *scroll_bar; + VScrollBar *scroll_bar = nullptr; TextParagraph::OverrunBehavior text_overrun_behavior = TextParagraph::OVERRUN_TRIM_ELLIPSIS; uint64_t search_time_msec = 0; diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp index e063d3aeba..b3f051bb75 100644 --- a/scene/gui/line_edit.cpp +++ b/scene/gui/line_edit.cpp @@ -215,6 +215,27 @@ void LineEdit::_delete(bool p_word, bool p_all_to_right) { } } +void LineEdit::unhandled_key_input(const Ref<InputEvent> &p_event) { + Ref<InputEventKey> k = p_event; + + if (k.is_valid()) { + if (!k->is_pressed()) { + return; + } + // Handle Unicode (with modifiers active, process after shortcuts). + if (has_focus() && editable && (k->get_unicode() >= 32)) { + selection_delete(); + char32_t ucodestr[2] = { (char32_t)k->get_unicode(), 0 }; + int prev_len = text.length(); + insert_text_at_caret(ucodestr); + if (text.length() != prev_len) { + _text_changed(); + } + accept_event(); + } + } +} + void LineEdit::gui_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); @@ -2445,6 +2466,7 @@ LineEdit::LineEdit(const String &p_placeholder) { set_focus_mode(FOCUS_ALL); set_default_cursor_shape(CURSOR_IBEAM); set_mouse_filter(MOUSE_FILTER_STOP); + set_process_unhandled_key_input(true); caret_blink_timer = memnew(Timer); add_child(caret_blink_timer, false, INTERNAL_MODE_FRONT); diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h index 444c9a1c50..b86ccd6421 100644 --- a/scene/gui/line_edit.h +++ b/scene/gui/line_edit.h @@ -202,6 +202,7 @@ private: protected: void _notification(int p_what); static void _bind_methods(); + virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; virtual void gui_input(const Ref<InputEvent> &p_event) override; bool _set(const StringName &p_name, const Variant &p_value); diff --git a/scene/gui/menu_button.cpp b/scene/gui/menu_button.cpp index 7e724e4d71..1feee017c2 100644 --- a/scene/gui/menu_button.cpp +++ b/scene/gui/menu_button.cpp @@ -33,7 +33,7 @@ #include "core/os/keyboard.h" #include "scene/main/window.h" -void MenuButton::unhandled_key_input(const Ref<InputEvent> &p_event) { +void MenuButton::shortcut_input(const Ref<InputEvent> &p_event) { ERR_FAIL_COND(p_event.is_null()); if (!_is_focus_owner_in_shortcut_context()) { @@ -232,7 +232,7 @@ MenuButton::MenuButton(const String &p_text) : set_flat(true); set_toggle_mode(true); set_disable_shortcuts(false); - set_process_unhandled_key_input(true); + set_process_shortcut_input(true); set_focus_mode(FOCUS_NONE); set_action_mode(ACTION_MODE_BUTTON_PRESS); diff --git a/scene/gui/menu_button.h b/scene/gui/menu_button.h index 9cfb780255..0a6b46c796 100644 --- a/scene/gui/menu_button.h +++ b/scene/gui/menu_button.h @@ -40,7 +40,7 @@ class MenuButton : public Button { bool clicked = false; bool switch_on_hover = false; bool disable_shortcuts = false; - PopupMenu *popup; + PopupMenu *popup = nullptr; Vector2i mouse_pos_adjusted; @@ -54,7 +54,7 @@ protected: bool _get(const StringName &p_name, Variant &r_ret) const; void _get_property_list(List<PropertyInfo> *p_list) const; static void _bind_methods(); - virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; public: virtual void pressed() override; diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp index 1e8a149e11..307696c44a 100644 --- a/scene/gui/option_button.cpp +++ b/scene/gui/option_button.cpp @@ -203,16 +203,18 @@ void OptionButton::pressed() { } void OptionButton::add_icon_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id) { + bool first_selectable = !has_selectable_items(); popup->add_icon_radio_check_item(p_icon, p_label, p_id); - if (popup->get_item_count() == 1) { - select(0); + if (first_selectable) { + select(get_item_count() - 1); } } void OptionButton::add_item(const String &p_label, int p_id) { + bool first_selectable = !has_selectable_items(); popup->add_radio_check_item(p_label, p_id); - if (popup->get_item_count() == 1) { - select(0); + if (first_selectable) { + select(get_item_count() - 1); } } @@ -280,6 +282,9 @@ bool OptionButton::is_item_disabled(int p_idx) const { return popup->is_item_disabled(p_idx); } +bool OptionButton::is_item_separator(int p_idx) const { + return popup->is_item_separator(p_idx); +} void OptionButton::set_item_count(int p_count) { ERR_FAIL_COND(p_count < 0); @@ -299,12 +304,37 @@ void OptionButton::set_item_count(int p_count) { notify_property_list_changed(); } +bool OptionButton::has_selectable_items() const { + for (int i = 0; i < get_item_count(); i++) { + if (!is_item_disabled(i) && !is_item_separator(i)) { + return true; + } + } + return false; +} +int OptionButton::get_selectable_item(bool p_from_last) const { + if (!p_from_last) { + for (int i = 0; i < get_item_count(); i++) { + if (!is_item_disabled(i) && !is_item_separator(i)) { + return i; + } + } + } else { + for (int i = get_item_count() - 1; i >= 0; i++) { + if (!is_item_disabled(i) && !is_item_separator(i)) { + return i; + } + } + } + return -1; +} + int OptionButton::get_item_count() const { return popup->get_item_count(); } -void OptionButton::add_separator() { - popup->add_separator(); +void OptionButton::add_separator(const String &p_text) { + popup->add_separator(p_text); } void OptionButton::clear() { @@ -407,7 +437,8 @@ void OptionButton::_bind_methods() { ClassDB::bind_method(D_METHOD("get_item_metadata", "idx"), &OptionButton::get_item_metadata); ClassDB::bind_method(D_METHOD("get_item_tooltip", "idx"), &OptionButton::get_item_tooltip); ClassDB::bind_method(D_METHOD("is_item_disabled", "idx"), &OptionButton::is_item_disabled); - ClassDB::bind_method(D_METHOD("add_separator"), &OptionButton::add_separator); + ClassDB::bind_method(D_METHOD("is_item_separator", "idx"), &OptionButton::is_item_separator); + ClassDB::bind_method(D_METHOD("add_separator", "text"), &OptionButton::add_separator, DEFVAL(String())); ClassDB::bind_method(D_METHOD("clear"), &OptionButton::clear); ClassDB::bind_method(D_METHOD("select", "idx"), &OptionButton::select); ClassDB::bind_method(D_METHOD("get_selected"), &OptionButton::get_selected); @@ -420,6 +451,8 @@ void OptionButton::_bind_methods() { ClassDB::bind_method(D_METHOD("set_item_count", "count"), &OptionButton::set_item_count); ClassDB::bind_method(D_METHOD("get_item_count"), &OptionButton::get_item_count); + ClassDB::bind_method(D_METHOD("has_selectable_items"), &OptionButton::has_selectable_items); + ClassDB::bind_method(D_METHOD("get_selectable_item", "from_last"), &OptionButton::get_selectable_item, DEFVAL(false)); // "selected" property must come after "item_count", otherwise GH-10213 occurs. ADD_ARRAY_COUNT("Items", "item_count", "set_item_count", "get_item_count", "popup/item_"); diff --git a/scene/gui/option_button.h b/scene/gui/option_button.h index 732730e0f4..7896132626 100644 --- a/scene/gui/option_button.h +++ b/scene/gui/option_button.h @@ -37,7 +37,7 @@ class OptionButton : public Button { GDCLASS(OptionButton, Button); - PopupMenu *popup; + PopupMenu *popup = nullptr; int current = -1; void _focused(int p_which); @@ -77,12 +77,16 @@ public: int get_item_index(int p_id) const; Variant get_item_metadata(int p_idx) const; bool is_item_disabled(int p_idx) const; + bool is_item_separator(int p_idx) const; String get_item_tooltip(int p_idx) const; + bool has_selectable_items() const; + int get_selectable_item(bool p_from_last = false) const; + void set_item_count(int p_count); int get_item_count() const; - void add_separator(); + void add_separator(const String &p_text = ""); void clear(); diff --git a/scene/gui/popup.h b/scene/gui/popup.h index c45f4ddc24..6211af4d20 100644 --- a/scene/gui/popup.h +++ b/scene/gui/popup.h @@ -65,7 +65,7 @@ public: class PopupPanel : public Popup { GDCLASS(PopupPanel, Popup); - Panel *panel; + Panel *panel = nullptr; protected: void _update_child_rects(); diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp index 9fc1fb072c..b01f45e9ab 100644 --- a/scene/gui/popup_menu.cpp +++ b/scene/gui/popup_menu.cpp @@ -169,7 +169,7 @@ int PopupMenu::_get_mouse_over(const Point2 &p_over) const { return -1; } -void PopupMenu::_activate_submenu(int p_over) { +void PopupMenu::_activate_submenu(int p_over, bool p_by_keyboard) { Node *n = get_node(items[p_over].submenu); ERR_FAIL_COND_MSG(!n, "Item subnode does not exist: " + items[p_over].submenu + "."); Popup *submenu_popup = Object::cast_to<Popup>(n); @@ -213,8 +213,10 @@ void PopupMenu::_activate_submenu(int p_over) { return; } + submenu_pum->activated_by_keyboard = p_by_keyboard; + // If not triggered by the mouse, start the popup with its first item selected. - if (submenu_pum->get_item_count() > 0 && Input::get_singleton()->is_action_just_pressed("ui_accept")) { + if (submenu_pum->get_item_count() > 0 && p_by_keyboard) { submenu_pum->set_current_index(0); } @@ -323,14 +325,14 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) { set_input_as_handled(); } } else if (p_event->is_action("ui_right") && p_event->is_pressed()) { - if (mouse_over >= 0 && mouse_over < items.size() && !!items[mouse_over].separator && items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) { - _activate_submenu(mouse_over); + if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator && !items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) { + _activate_submenu(mouse_over, true); set_input_as_handled(); } } else if (p_event->is_action("ui_accept") && p_event->is_pressed()) { if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator) { if (!items[mouse_over].submenu.is_empty() && submenu_over != mouse_over) { - _activate_submenu(mouse_over); + _activate_submenu(mouse_over, true); } else { activate_item(mouse_over); } @@ -396,6 +398,11 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseMotion> m = p_event; if (m.is_valid()) { + if (m->get_velocity().is_equal_approx(Vector2())) { + return; + } + activated_by_keyboard = false; + for (const Rect2 &E : autohide_areas) { if (!Rect2(Point2(), get_size()).has_point(m->get_position()) && E.has_point(m->get_position())) { _close_pressed(); @@ -687,7 +694,7 @@ void PopupMenu::_draw_background() { void PopupMenu::_minimum_lifetime_timeout() { close_allowed = true; // If the mouse still isn't in this popup after timer expires, close. - if (!get_visible_rect().has_point(get_mouse_position())) { + if (!activated_by_keyboard && !get_visible_rect().has_point(get_mouse_position())) { _close_pressed(); } } @@ -772,7 +779,7 @@ void PopupMenu::_notification(int p_what) { case NOTIFICATION_INTERNAL_PROCESS: { // Only used when using operating system windows. - if (!is_embedded() && autohide_areas.size()) { + if (!activated_by_keyboard && !is_embedded() && autohide_areas.size()) { Point2 mouse_pos = DisplayServer::get_singleton()->mouse_get_position(); mouse_pos -= get_position(); diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h index 5ce55209d4..98d76875cb 100644 --- a/scene/gui/popup_menu.h +++ b/scene/gui/popup_menu.h @@ -87,9 +87,10 @@ class PopupMenu : public Popup { }; bool close_allowed = false; + bool activated_by_keyboard = false; Timer *minimum_lifetime_timer = nullptr; - Timer *submenu_timer; + Timer *submenu_timer = nullptr; List<Rect2> autohide_areas; Vector<Item> items; MouseButton initial_button_mask = MouseButton::NONE; @@ -107,7 +108,7 @@ class PopupMenu : public Popup { void _shape_item(int p_item); virtual void gui_input(const Ref<InputEvent> &p_event); - void _activate_submenu(int p_over); + void _activate_submenu(int p_over, bool p_by_keyboard = false); void _submenu_timeout(); uint64_t popup_time_msec = 0; @@ -125,9 +126,9 @@ class PopupMenu : public Popup { uint64_t search_time_msec = 0; String search_string = ""; - MarginContainer *margin_container; - ScrollContainer *scroll_container; - Control *control; + MarginContainer *margin_container = nullptr; + ScrollContainer *scroll_container = nullptr; + Control *control = nullptr; void _draw_items(); void _draw_background(); diff --git a/scene/gui/range.h b/scene/gui/range.h index 597c50ca26..46b0d39202 100644 --- a/scene/gui/range.h +++ b/scene/gui/range.h @@ -50,7 +50,7 @@ class Range : public Control { void emit_changed(const char *p_what = ""); }; - Shared *shared; + Shared *shared = nullptr; void _ref_shared(Shared *p_shared); void _unref_shared(); diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp index 70755a2870..ec13399f82 100644 --- a/scene/gui/rich_text_label.cpp +++ b/scene/gui/rich_text_label.cpp @@ -30,6 +30,7 @@ #include "rich_text_label.h" +#include "core/input/input_map.h" #include "core/math/math_defs.h" #include "core/os/keyboard.h" #include "core/os/os.h" @@ -142,7 +143,7 @@ RichTextLabel::Item *RichTextLabel::_get_item_at_pos(RichTextLabel::Item *p_item for (Item *it = p_item_from; it && it != p_item_to; it = _get_next_item(it)) { switch (it->type) { case ITEM_TEXT: { - ItemText *t = (ItemText *)it; + ItemText *t = static_cast<ItemText *>(it); offset += t->text.length(); if (offset > p_position) { return it; @@ -166,16 +167,16 @@ String RichTextLabel::_roman(int p_num, bool p_capitalize) const { }; String s; if (p_capitalize) { - String M[] = { "", "M", "MM", "MMM" }; - String C[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; - String X[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; - String I[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; + const String M[] = { "", "M", "MM", "MMM" }; + const String C[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; + const String X[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; + const String I[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; s = M[p_num / 1000] + C[(p_num % 1000) / 100] + X[(p_num % 100) / 10] + I[p_num % 10]; } else { - String M[] = { "", "m", "mm", "mmm" }; - String C[] = { "", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm" }; - String X[] = { "", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc" }; - String I[] = { "", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix" }; + const String M[] = { "", "m", "mm", "mmm" }; + const String C[] = { "", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm" }; + const String X[] = { "", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc" }; + const String I[] = { "", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix" }; s = M[p_num / 1000] + C[(p_num % 1000) / 100] + X[(p_num % 100) / 10] + I[p_num % 10]; } return s; @@ -215,7 +216,7 @@ void RichTextLabel::_update_line_font(ItemFrame *p_frame, int p_line, const Ref< RID t = l.text_buf->get_rid(); int spans = TS->shaped_get_span_count(t); for (int i = 0; i < spans; i++) { - ItemText *it = (ItemText *)(uint64_t)TS->shaped_get_span_meta(t, i); + ItemText *it = reinterpret_cast<ItemText *>((uint64_t)TS->shaped_get_span_meta(t, i)); if (it) { Ref<Font> font = _find_font(it); if (font.is_null()) { @@ -466,15 +467,11 @@ void RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font> switch (it->type) { case ITEM_DROPCAP: { // Add dropcap. - const ItemDropcap *dc = (ItemDropcap *)it; - if (dc != nullptr) { - l.text_buf->set_dropcap(dc->text, dc->font, dc->font_size, dc->dropcap_margins); - l.dc_color = dc->color; - l.dc_ol_size = dc->ol_size; - l.dc_ol_color = dc->ol_color; - } else { - l.text_buf->clear_dropcap(); - } + const ItemDropcap *dc = static_cast<ItemDropcap *>(it); + l.text_buf->set_dropcap(dc->text, dc->font, dc->font_size, dc->dropcap_margins); + l.dc_color = dc->color; + l.dc_ol_size = dc->ol_size; + l.dc_ol_color = dc->ol_color; } break; case ITEM_NEWLINE: { Ref<Font> font = _find_font(it); @@ -491,7 +488,7 @@ void RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font> remaining_characters--; } break; case ITEM_TEXT: { - ItemText *t = (ItemText *)it; + ItemText *t = static_cast<ItemText *>(it); Ref<Font> font = _find_font(it); if (font.is_null()) { font = p_base_font; @@ -513,7 +510,7 @@ void RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font> l.char_count += tx.length(); } break; case ITEM_IMAGE: { - ItemImage *img = (ItemImage *)it; + ItemImage *img = static_cast<ItemImage *>(it); l.text_buf->add_object((uint64_t)it, img->size, img->inline_align, 1); text += String::chr(0xfffc); l.char_count++; @@ -842,7 +839,7 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o // Draw inlined objects. Array objects = TS->shaped_text_get_objects(rid); for (int i = 0; i < objects.size(); i++) { - Item *it = (Item *)(uint64_t)objects[i]; + Item *it = reinterpret_cast<Item *>((uint64_t)objects[i]); if (it != nullptr) { Rect2 rect = TS->shaped_text_get_object_rect(rid, objects[i]); //draw_rect(rect, Color(1,0,0), false, 2); //DEBUG_RECTS @@ -944,8 +941,8 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o } //Apply fx. - float faded_visibility = 1.0f; if (fade) { + float faded_visibility = 1.0f; if (glyphs[i].start >= fade->starting_index) { faded_visibility -= (float)(glyphs[i].start - fade->starting_index) / (float)fade->length; faded_visibility = faded_visibility < 0.0f ? 0.0f : faded_visibility; @@ -1160,8 +1157,8 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o } //Apply fx. - float faded_visibility = 1.0f; if (fade) { + float faded_visibility = 1.0f; if (glyphs[i].start >= fade->starting_index) { faded_visibility -= (float)(glyphs[i].start - fade->starting_index) / (float)fade->length; faded_visibility = faded_visibility < 0.0f ? 0.0f : faded_visibility; @@ -1330,14 +1327,22 @@ void RichTextLabel::_find_click(ItemFrame *p_frame, const Point2i &p_click, Item } } -float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char) { +float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame, int *r_click_line, Item **r_click_item, int *r_click_char, bool p_table) { Vector2 off; int char_pos = -1; Line &l = p_frame->lines.write[p_line]; bool rtl = (l.text_buf->get_direction() == TextServer::DIRECTION_RTL); bool lrtl = is_layout_rtl(); + + // Table hit test results. bool table_hit = false; + Vector2i table_range; + float table_offy = 0.f; + ItemFrame *table_click_frame = nullptr; + int table_click_line = -1; + Item *table_click_item = nullptr; + int table_click_char = -1; for (int line = 0; line < l.text_buf->get_line_count(); line++) { RID rid = l.text_buf->get_line_rid(line); @@ -1378,10 +1383,11 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V Array objects = TS->shaped_text_get_objects(rid); for (int i = 0; i < objects.size(); i++) { - Item *it = (Item *)(uint64_t)objects[i]; + Item *it = reinterpret_cast<Item *>((uint64_t)objects[i]); if (it != nullptr) { Rect2 rect = TS->shaped_text_get_object_rect(rid, objects[i]); - if (rect.has_point(p_click - p_ofs - off)) { + rect.position += p_ofs + off; + if (p_click.y >= rect.position.y && p_click.y <= rect.position.y + rect.size.y) { switch (it->type) { case ITEM_TABLE: { int hseparation = get_theme_constant(SNAME("table_hseparation")); @@ -1389,8 +1395,6 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V ItemTable *table = static_cast<ItemTable *>(it); - table_hit = true; - int idx = 0; int col_count = table->columns.size(); int row_count = table->rows.size(); @@ -1406,7 +1410,7 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V if (rtl) { coff.x = rect.size.width - table->columns[col].width - coff.x; } - Rect2 crect = Rect2(p_ofs + off + rect.position + coff - frame->padding.position, Size2(table->columns[col].width + hseparation, table->rows[row] + vseparation) + frame->padding.position + frame->padding.size); + Rect2 crect = Rect2(rect.position + coff - frame->padding.position, Size2(table->columns[col].width + hseparation, table->rows[row] + vseparation) + frame->padding.position + frame->padding.size); if (col == col_count - 1) { if (rtl) { crect.size.x = crect.position.x + crect.size.x; @@ -1417,9 +1421,19 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V } if (crect.has_point(p_click)) { for (int j = 0; j < frame->lines.size(); j++) { - _find_click_in_line(frame, j, p_ofs + off + rect.position + Vector2(0, frame->lines[j].offset.y), rect.size.x, p_click, r_click_frame, r_click_line, r_click_item, r_click_char); - if (((r_click_item != nullptr) && ((*r_click_item) != nullptr)) || ((r_click_frame != nullptr) && ((*r_click_frame) != nullptr))) { - return off.y; + _find_click_in_line(frame, j, rect.position + Vector2(0, frame->lines[j].offset.y), rect.size.x, p_click, &table_click_frame, &table_click_line, &table_click_item, &table_click_char, true); + if (table_click_frame && table_click_item) { + // Save cell detected cell hit data. + table_range = Vector2i(INT32_MAX, 0); + for (Item *F : table->subitems) { + ItemFrame *sub_frame = static_cast<ItemFrame *>(F); + for (int k = 0; k < sub_frame->lines.size(); k++) { + table_range.x = MIN(table_range.x, sub_frame->lines[k].char_offset); + table_range.y = MAX(table_range.y, sub_frame->lines[k].char_offset + sub_frame->lines[k].char_count); + } + } + table_offy = off.y; + table_hit = true; } } } @@ -1433,14 +1447,39 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V } } } - Rect2 rect = Rect2(p_ofs + off - Vector2(0, TS->shaped_text_get_ascent(rid)), Size2(get_size().x, TS->shaped_text_get_size(rid).y)); + Rect2 rect = Rect2(p_ofs + off - Vector2(0, TS->shaped_text_get_ascent(rid)) - p_frame->padding.position, TS->shaped_text_get_size(rid) + p_frame->padding.position + p_frame->padding.size); + if (p_table) { + rect.size.y += get_theme_constant(SNAME("table_vseparation")); + } - if (rect.has_point(p_click) && !table_hit) { + if (p_click.y >= rect.position.y && p_click.y <= rect.position.y + rect.size.y) { char_pos = TS->shaped_text_hit_test_position(rid, p_click.x - rect.position.x); } + + // If table hit was detected, and line hit is in the table bounds use table hit. + if (table_hit && (((char_pos + p_frame->lines[p_line].char_offset) >= table_range.x && (char_pos + p_frame->lines[p_line].char_offset) <= table_range.y) || char_pos == -1)) { + if (r_click_frame != nullptr) { + *r_click_frame = table_click_frame; + } + + if (r_click_line != nullptr) { + *r_click_line = table_click_line; + } + + if (r_click_item != nullptr) { + *r_click_item = table_click_item; + } + + if (r_click_char != nullptr) { + *r_click_char = table_click_char; + } + return table_offy; + } + off.y += TS->shaped_text_get_descent(rid) + l.text_buf->get_spacing_bottom() + get_theme_constant(SNAME("line_separation")); } + // Text line hit. if (char_pos >= 0) { // Find item. if (r_click_item != nullptr) { @@ -1451,7 +1490,7 @@ float RichTextLabel::_find_click_in_line(ItemFrame *p_frame, int p_line, const V if (it_to != nullptr) { *r_click_item = _get_prev_item(it_to); } else { - for (Item *i = it; i && i != it_to; i = _get_next_item(i)) { + for (Item *i = it; i; i = _get_next_item(i)) { *r_click_item = i; } } @@ -1650,8 +1689,7 @@ void RichTextLabel::_notification(int p_what) { case NOTIFICATION_FOCUS_EXIT: { if (deselect_on_focus_loss_enabled) { - selection.active = false; - update(); + deselect(); } } break; @@ -1684,9 +1722,9 @@ Control::CursorShape RichTextLabel::get_cursor_shape(const Point2 &p_pos) const Item *item = nullptr; bool outside = true; - ((RichTextLabel *)(this))->_find_click(main, p_pos, nullptr, nullptr, &item, nullptr, &outside); + const_cast<RichTextLabel *>(this)->_find_click(main, p_pos, nullptr, nullptr, &item, nullptr, &outside); - if (item && !outside && ((RichTextLabel *)(this))->_find_meta(item, nullptr)) { + if (item && !outside && const_cast<RichTextLabel *>(this)->_find_meta(item, nullptr)) { return CURSOR_POINTING_HAND; } @@ -1742,9 +1780,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { selection.to_line = 0; selection.to_item = nullptr; selection.to_char = 0; - selection.active = false; - - update(); + deselect(); } } } @@ -1802,9 +1838,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { selection.to_line = 0; selection.to_item = nullptr; selection.to_char = 0; - selection.active = false; - - update(); + deselect(); } } @@ -1835,6 +1869,13 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { vscroll->set_value(vscroll->get_value() + vscroll->get_page() * b->get_factor() * 0.5 / 8); } } + if (b->get_button_index() == MouseButton::RIGHT && context_menu_enabled) { + _generate_context_menu(); + menu->set_position(get_screen_position() + b->get_position()); + menu->reset_size(); + menu->popup(); + grab_focus(); + } } Ref<InputEventPanGesture> pan_gesture = p_event; @@ -1876,8 +1917,24 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { vscroll->set_value(vscroll->get_max()); handled = true; } - if (k->is_action("ui_copy")) { - selection_copy(); + if (is_shortcut_keys_enabled()) { + if (k->is_action("ui_text_select_all")) { + select_all(); + handled = true; + } + if (k->is_action("ui_copy")) { + selection_copy(); + handled = true; + } + } + if (k->is_action("ui_menu", true)) { + if (context_menu_enabled) { + _generate_context_menu(); + menu->set_position(get_screen_position()); + menu->reset_size(); + menu->popup(); + menu->grab_focus(); + } handled = true; } @@ -1919,14 +1976,13 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) { selection.to_char = c_index; bool swap = false; - if (selection.from_item->index > selection.to_item->index) { - swap = true; - } else if (selection.from_item->index == selection.to_item->index) { - if (selection.from_char > selection.to_char) { + if (selection.click_frame && c_frame) { + const Line &l1 = c_frame->lines[c_line]; + const Line &l2 = selection.click_frame->lines[selection.click_line]; + if (l1.char_offset + c_index < l2.char_offset + selection.click_char) { swap = true; - } else if (selection.from_char == selection.to_char) { - selection.active = false; - update(); + } else if (l1.char_offset + c_index == l2.char_offset + selection.click_char) { + deselect(); return; } } @@ -1988,7 +2044,7 @@ void RichTextLabel::_find_frame(Item *p_item, ItemFrame **r_frame, int *r_line) while (item) { if (item->parent != nullptr && item->parent->type == ITEM_FRAME) { if (r_frame != nullptr) { - *r_frame = (ItemFrame *)item->parent; + *r_frame = static_cast<ItemFrame *>(item->parent); } if (r_line != nullptr) { *r_line = item->line; @@ -2523,7 +2579,7 @@ void RichTextLabel::_add_item(Item *p_item, bool p_enter, bool p_ensure_newline) p_item->index = current_idx++; p_item->char_ofs = current_char_ofs; if (p_item->type == ITEM_TEXT) { - ItemText *t = (ItemText *)p_item; + ItemText *t = static_cast<ItemText *>(p_item); current_char_ofs += t->text.length(); } else if (p_item->type == ITEM_IMAGE) { current_char_ofs++; @@ -2977,11 +3033,10 @@ void RichTextLabel::clear() { main->lines.clear(); main->lines.resize(1); main->first_invalid_line = 0; - update(); selection.click_frame = nullptr; selection.click_item = nullptr; - selection.active = false; + deselect(); current_idx = 1; current_char_ofs = 0; @@ -3890,8 +3945,7 @@ void RichTextLabel::set_selection_enabled(bool p_enabled) { selection.enabled = p_enabled; if (!p_enabled) { if (selection.active) { - selection.active = false; - update(); + deselect(); } set_focus_mode(FOCUS_NONE); } else { @@ -3902,8 +3956,7 @@ void RichTextLabel::set_selection_enabled(bool p_enabled) { void RichTextLabel::set_deselect_on_focus_loss_enabled(const bool p_enabled) { deselect_on_focus_loss_enabled = p_enabled; if (p_enabled && selection.active && !has_focus()) { - selection.active = false; - update(); + deselect(); } } @@ -3967,7 +4020,7 @@ bool RichTextLabel::_search_line(ItemFrame *p_frame, int p_line, const String &p text += "\n"; } break; case ITEM_TEXT: { - ItemText *t = (ItemText *)it; + ItemText *t = static_cast<ItemText *>(it); text += t->text; } break; case ITEM_IMAGE: { @@ -4100,7 +4153,7 @@ String RichTextLabel::_get_line_text(ItemFrame *p_frame, int p_line, Selection p if (it_to != nullptr) { end_idx = it_to->index; } else { - for (Item *it = l.from; it && it != it_to; it = _get_next_item(it)) { + for (Item *it = l.from; it; it = _get_next_item(it)) { end_idx = it->index + 1; } } @@ -4142,6 +4195,32 @@ String RichTextLabel::_get_line_text(ItemFrame *p_frame, int p_line, Selection p return text; } +void RichTextLabel::set_context_menu_enabled(bool p_enabled) { + context_menu_enabled = p_enabled; +} + +bool RichTextLabel::is_context_menu_enabled() const { + return context_menu_enabled; +} + +void RichTextLabel::set_shortcut_keys_enabled(bool p_enabled) { + shortcut_keys_enabled = p_enabled; +} + +bool RichTextLabel::is_shortcut_keys_enabled() const { + return shortcut_keys_enabled; +} + +// Context menu. +PopupMenu *RichTextLabel::get_menu() const { + const_cast<RichTextLabel *>(this)->_generate_context_menu(); + return menu; +} + +bool RichTextLabel::is_menu_visible() const { + return menu && menu->is_visible(); +} + String RichTextLabel::get_selected_text() const { if (!selection.active || !selection.enabled) { return ""; @@ -4154,6 +4233,11 @@ String RichTextLabel::get_selected_text() const { return text; } +void RichTextLabel::deselect() { + selection.active = false; + update(); +} + void RichTextLabel::selection_copy() { String text = get_selected_text(); @@ -4162,6 +4246,53 @@ void RichTextLabel::selection_copy() { } } +void RichTextLabel::select_all() { + if (!selection.enabled) { + return; + } + + Item *it = main; + Item *from_item = nullptr; + Item *to_item = nullptr; + + while (it) { + if (it->type != ITEM_FRAME) { + if (!from_item) { + from_item = it; + } else { + to_item = it; + } + } + it = _get_next_item(it, true); + } + if (!from_item || !to_item) { + return; + } + + ItemFrame *from_frame = nullptr; + int from_line = 0; + _find_frame(from_item, &from_frame, &from_line); + if (!from_frame) { + return; + } + ItemFrame *to_frame = nullptr; + int to_line = 0; + _find_frame(to_item, &to_frame, &to_line); + if (!to_frame) { + return; + } + selection.from_line = from_line; + selection.from_frame = from_frame; + selection.from_char = 0; + selection.from_item = from_item; + selection.to_line = to_line; + selection.to_frame = to_frame; + selection.to_char = to_frame->lines[to_line].char_count; + selection.to_item = to_item; + selection.active = true; + update(); +} + bool RichTextLabel::is_selection_enabled() const { return selection.enabled; } @@ -4218,10 +4349,8 @@ String RichTextLabel::get_parsed_text() const { Item *it = main; while (it) { if (it->type == ITEM_DROPCAP) { - const ItemDropcap *dc = (ItemDropcap *)it; - if (dc != nullptr) { - text += dc->text; - } + ItemDropcap *dc = static_cast<ItemDropcap *>(it); + text += dc->text; } else if (it->type == ITEM_TEXT) { ItemText *t = static_cast<ItemText *>(it); text += t->text; @@ -4453,13 +4582,21 @@ void RichTextLabel::_bind_methods() { ClassDB::bind_method(D_METHOD("set_selection_enabled", "enabled"), &RichTextLabel::set_selection_enabled); ClassDB::bind_method(D_METHOD("is_selection_enabled"), &RichTextLabel::is_selection_enabled); + ClassDB::bind_method(D_METHOD("set_context_menu_enabled", "enabled"), &RichTextLabel::set_context_menu_enabled); + ClassDB::bind_method(D_METHOD("is_context_menu_enabled"), &RichTextLabel::is_context_menu_enabled); + + ClassDB::bind_method(D_METHOD("set_shortcut_keys_enabled", "enabled"), &RichTextLabel::set_shortcut_keys_enabled); + ClassDB::bind_method(D_METHOD("is_shortcut_keys_enabled"), &RichTextLabel::is_shortcut_keys_enabled); + ClassDB::bind_method(D_METHOD("set_deselect_on_focus_loss_enabled", "enable"), &RichTextLabel::set_deselect_on_focus_loss_enabled); ClassDB::bind_method(D_METHOD("is_deselect_on_focus_loss_enabled"), &RichTextLabel::is_deselect_on_focus_loss_enabled); ClassDB::bind_method(D_METHOD("get_selection_from"), &RichTextLabel::get_selection_from); ClassDB::bind_method(D_METHOD("get_selection_to"), &RichTextLabel::get_selection_to); + ClassDB::bind_method(D_METHOD("select_all"), &RichTextLabel::select_all); ClassDB::bind_method(D_METHOD("get_selected_text"), &RichTextLabel::get_selected_text); + ClassDB::bind_method(D_METHOD("deselect"), &RichTextLabel::deselect); ClassDB::bind_method(D_METHOD("parse_bbcode", "bbcode"), &RichTextLabel::parse_bbcode); ClassDB::bind_method(D_METHOD("append_text", "bbcode"), &RichTextLabel::append_text); @@ -4500,6 +4637,9 @@ void RichTextLabel::_bind_methods() { ClassDB::bind_method(D_METHOD("get_effects"), &RichTextLabel::get_effects); ClassDB::bind_method(D_METHOD("install_effect", "effect"), &RichTextLabel::install_effect); + ClassDB::bind_method(D_METHOD("get_menu"), &RichTextLabel::get_menu); + ClassDB::bind_method(D_METHOD("is_menu_visible"), &RichTextLabel::is_menu_visible); + // Note: set "bbcode_enabled" first, to avoid unnecessary "text" resets. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bbcode_enabled"), "set_use_bbcode", "is_using_bbcode"); @@ -4521,6 +4661,9 @@ void RichTextLabel::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "visible_characters_behavior", PROPERTY_HINT_ENUM, "Characters Before Shaping,Characters After Shaping,Glyphs (Layout Direction),Glyphs (Left-to-Right),Glyphs (Right-to-Left)"), "set_visible_characters_behavior", "get_visible_characters_behavior"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "percent_visible", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_percent_visible", "get_percent_visible"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "context_menu_enabled"), "set_context_menu_enabled", "is_context_menu_enabled"); + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_keys_enabled"), "set_shortcut_keys_enabled", "is_shortcut_keys_enabled"); + ADD_GROUP("Locale", ""); ADD_PROPERTY(PropertyInfo(Variant::INT, "text_direction", PROPERTY_HINT_ENUM, "Auto,Left-to-Right,Right-to-Left,Inherited"), "set_text_direction", "get_text_direction"); ADD_PROPERTY(PropertyInfo(Variant::STRING, "language", PROPERTY_HINT_LOCALE_ID, ""), "set_language", "get_language"); @@ -4700,6 +4843,59 @@ Size2 RichTextLabel::get_minimum_size() const { return size; } +// Context menu. +void RichTextLabel::_generate_context_menu() { + if (!menu) { + menu = memnew(PopupMenu); + add_child(menu, false, INTERNAL_MODE_FRONT); + + menu->connect("id_pressed", callable_mp(this, &RichTextLabel::_menu_option)); + } + + // Reorganize context menu. + menu->clear(); + if (selection.enabled) { + menu->add_item(RTR("Copy"), MENU_COPY, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_copy") : Key::NONE); + menu->add_item(RTR("Select All"), MENU_SELECT_ALL, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_text_select_all") : Key::NONE); + } +} + +Key RichTextLabel::_get_menu_action_accelerator(const String &p_action) { + const List<Ref<InputEvent>> *events = InputMap::get_singleton()->action_get_events(p_action); + if (!events) { + return Key::NONE; + } + + // Use first event in the list for the accelerator. + const List<Ref<InputEvent>>::Element *first_event = events->front(); + if (!first_event) { + return Key::NONE; + } + + const Ref<InputEventKey> event = first_event->get(); + if (event.is_null()) { + return Key::NONE; + } + + // Use physical keycode if non-zero + if (event->get_physical_keycode() != Key::NONE) { + return event->get_physical_keycode_with_modifiers(); + } else { + return event->get_keycode_with_modifiers(); + } +} + +void RichTextLabel::_menu_option(int p_option) { + switch (p_option) { + case MENU_COPY: { + selection_copy(); + } break; + case MENU_SELECT_ALL: { + select_all(); + } break; + } +} + void RichTextLabel::_draw_fbg_boxes(RID p_ci, RID p_rid, Vector2 line_off, Item *it_from, Item *it_to, int start, int end, int fbg_flag) { Vector2i fbg_index = Vector2i(end, start); Color last_color = Color(0, 0, 0, 0); @@ -4707,7 +4903,7 @@ void RichTextLabel::_draw_fbg_boxes(RID p_ci, RID p_rid, Vector2 line_off, Item // Draw a box based on color tags associated with glyphs for (int i = start; i < end; i++) { Item *it = _get_item_at_pos(it_from, it_to, i); - Color color = Color(0, 0, 0, 0); + Color color; if (fbg_flag == 0) { color = _find_bgcolor(it); diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h index c9cbbe9d15..856dd52b6e 100644 --- a/scene/gui/rich_text_label.h +++ b/scene/gui/rich_text_label.h @@ -32,6 +32,7 @@ #define RICH_TEXT_LABEL_H #include "rich_text_effect.h" +#include "scene/gui/popup_menu.h" #include "scene/gui/scroll_bar.h" #include "scene/resources/text_paragraph.h" @@ -91,6 +92,11 @@ public: VC_GLYPHS_RTL, }; + enum MenuItems { + MENU_COPY, + MENU_SELECT_ALL, + }; + protected: void _notification(int p_what); static void _bind_methods(); @@ -420,6 +426,15 @@ private: Selection selection; bool deselect_on_focus_loss_enabled = true; + bool context_menu_enabled = false; + bool shortcut_keys_enabled = true; + + // Context menu. + PopupMenu *menu = nullptr; + void _generate_context_menu(); + Key _get_menu_action_accelerator(const String &p_action); + void _menu_option(int p_option); + int visible_characters = -1; float percent_visible = 1.0; VisibleCharactersBehavior visible_chars_behavior = VC_CHARS_BEFORE_SHAPING; @@ -435,7 +450,7 @@ private: void _resize_line(ItemFrame *p_frame, int p_line, const Ref<Font> &p_base_font, int p_base_font_size, int p_width); void _update_line_font(ItemFrame *p_frame, int p_line, const Ref<Font> &p_base_font, int p_base_font_size); int _draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Color &p_base_color, int p_outline_size, const Color &p_outline_color, const Color &p_font_shadow_color, int p_shadow_outline_size, const Point2 &p_shadow_ofs, int &r_processed_glyphs); - float _find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr); + float _find_click_in_line(ItemFrame *p_frame, int p_line, const Vector2 &p_ofs, int p_width, const Point2i &p_click, ItemFrame **r_click_frame = nullptr, int *r_click_line = nullptr, Item **r_click_item = nullptr, int *r_click_char = nullptr, bool p_table = false); String _roman(int p_num, bool p_capitalize) const; String _letters(int p_num, bool p_capitalize) const; @@ -555,6 +570,12 @@ public: void set_tab_size(int p_spaces); int get_tab_size() const; + void set_context_menu_enabled(bool p_enabled); + bool is_context_menu_enabled() const; + + void set_shortcut_keys_enabled(bool p_enabled); + bool is_shortcut_keys_enabled() const; + void set_fit_content_height(bool p_enabled); bool is_fit_content_height_enabled() const; @@ -584,9 +605,15 @@ public: int get_selection_from() const; int get_selection_to() const; String get_selected_text() const; + void select_all(); void selection_copy(); void set_deselect_on_focus_loss_enabled(const bool p_enabled); bool is_deselect_on_focus_loss_enabled() const; + void deselect(); + + // Context menu. + PopupMenu *get_menu() const; + bool is_menu_visible() const; void parse_bbcode(const String &p_bbcode); void append_text(const String &p_bbcode); diff --git a/scene/gui/scroll_container.h b/scene/gui/scroll_container.h index c00df87b18..b9fcf64db6 100644 --- a/scene/gui/scroll_container.h +++ b/scene/gui/scroll_container.h @@ -47,8 +47,8 @@ public: }; private: - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; Size2 child_max_size; diff --git a/scene/gui/spin_box.h b/scene/gui/spin_box.h index a15e3fe5f5..d118b28334 100644 --- a/scene/gui/spin_box.h +++ b/scene/gui/spin_box.h @@ -38,11 +38,11 @@ class SpinBox : public Range { GDCLASS(SpinBox, Range); - LineEdit *line_edit; + LineEdit *line_edit = nullptr; int last_w = 0; bool update_on_text_changed = false; - Timer *range_click_timer; + Timer *range_click_timer = nullptr; void _range_click_timeout(); void _release_mouse(); diff --git a/scene/gui/tab_container.h b/scene/gui/tab_container.h index 225c24c25e..9adaa0d844 100644 --- a/scene/gui/tab_container.h +++ b/scene/gui/tab_container.h @@ -38,7 +38,7 @@ class TabContainer : public Container { GDCLASS(TabContainer, Container); - TabBar *tab_bar; + TabBar *tab_bar = nullptr; bool tabs_visible = true; bool all_tabs_in_front = false; bool menu_hovered = false; diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp index 66c3048f32..ff23e44cb7 100644 --- a/scene/gui/text_edit.cpp +++ b/scene/gui/text_edit.cpp @@ -1542,6 +1542,21 @@ void TextEdit::_notification(int p_what) { } } +void TextEdit::unhandled_key_input(const Ref<InputEvent> &p_event) { + Ref<InputEventKey> k = p_event; + + if (k.is_valid()) { + if (!k->is_pressed()) { + return; + } + // Handle Unicode (with modifiers active, process after shortcuts). + if (has_focus() && editable && (k->get_unicode() >= 32)) { + handle_unicode_input(k->get_unicode()); + accept_event(); + } + } +} + void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) { ERR_FAIL_COND(p_gui_input.is_null()); @@ -1929,44 +1944,45 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) { return; } - // SELECT ALL, SELECT WORD UNDER CARET, CUT, COPY, PASTE. - - if (k->is_action("ui_text_select_all", true)) { - select_all(); - accept_event(); - return; - } - if (k->is_action("ui_text_select_word_under_caret", true)) { - select_word_under_caret(); - accept_event(); - return; - } - if (k->is_action("ui_cut", true)) { - cut(); - accept_event(); - return; - } - if (k->is_action("ui_copy", true)) { - copy(); - accept_event(); - return; - } - if (k->is_action("ui_paste", true)) { - paste(); - accept_event(); - return; - } + if (is_shortcut_keys_enabled()) { + // SELECT ALL, SELECT WORD UNDER CARET, CUT, COPY, PASTE. + if (k->is_action("ui_text_select_all", true)) { + select_all(); + accept_event(); + return; + } + if (k->is_action("ui_text_select_word_under_caret", true)) { + select_word_under_caret(); + accept_event(); + return; + } + if (k->is_action("ui_cut", true)) { + cut(); + accept_event(); + return; + } + if (k->is_action("ui_copy", true)) { + copy(); + accept_event(); + return; + } + if (k->is_action("ui_paste", true)) { + paste(); + accept_event(); + return; + } - // UNDO/REDO. - if (k->is_action("ui_undo", true)) { - undo(); - accept_event(); - return; - } - if (k->is_action("ui_redo", true)) { - redo(); - accept_event(); - return; + // UNDO/REDO. + if (k->is_action("ui_undo", true)) { + undo(); + accept_event(); + return; + } + if (k->is_action("ui_redo", true)) { + redo(); + accept_event(); + return; + } } // MISC. @@ -2138,16 +2154,21 @@ void TextEdit::_move_caret_left(bool p_select, bool p_move_by_word) { if (p_move_by_word) { int cc = caret.column; - + // If the caret is at the start of the line, and not on the first line, move it up to the end of the previous line. if (cc == 0 && caret.line > 0) { set_caret_line(caret.line - 1); set_caret_column(text[caret.line].length()); } else { PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(caret.line)->get_rid()); - for (int i = words.size() - 2; i >= 0; i = i - 2) { - if (words[i] < cc) { - cc = words[i]; - break; + if (words.is_empty() || cc <= words[0]) { + // This solves the scenario where there are no words but glyfs that can be ignored. + cc = 0; + } else { + for (int i = words.size() - 2; i >= 0; i = i - 2) { + if (words[i] < cc) { + cc = words[i]; + break; + } } } set_caret_column(cc); @@ -2189,16 +2210,21 @@ void TextEdit::_move_caret_right(bool p_select, bool p_move_by_word) { if (p_move_by_word) { int cc = caret.column; - + // If the caret is at the end of the line, and not on the last line, move it down to the beginning of the next line. if (cc == text[caret.line].length() && caret.line < text.size() - 1) { set_caret_line(caret.line + 1); set_caret_column(0); } else { PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(caret.line)->get_rid()); - for (int i = 1; i < words.size(); i = i + 2) { - if (words[i] > cc) { - cc = words[i]; - break; + if (words.is_empty() || cc >= words[words.size() - 1]) { + // This solves the scenario where there are no words but glyfs that can be ignored. + cc = text[caret.line].length(); + } else { + for (int i = 1; i < words.size(); i = i + 2) { + if (words[i] > cc) { + cc = words[i]; + break; + } } } set_caret_column(cc); @@ -2369,11 +2395,11 @@ void TextEdit::_move_caret_page_down(bool p_select) { } void TextEdit::_do_backspace(bool p_word, bool p_all_to_left) { - if (!editable) { + if (!editable || (caret.column == 0 && caret.line == 0)) { return; } - if (has_selection() || (!p_all_to_left && !p_word)) { + if (has_selection() || (!p_all_to_left && !p_word) || caret.column == 0) { backspace(); return; } @@ -2386,20 +2412,30 @@ void TextEdit::_do_backspace(bool p_word, bool p_all_to_left) { } if (p_word) { - int line = caret.line; int column = caret.column; - - PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(line)->get_rid()); - for (int i = words.size() - 2; i >= 0; i = i - 2) { - if (words[i] < column) { - column = words[i]; - break; + // Check for the case "<word><space><caret>" and ignore the space. + // No need to check for column being 0 since it is cheked above. + if (is_whitespace(text[caret.line][caret.column - 1])) { + column -= 1; + } + // Get a list with the indices of the word bounds of the given text line. + const PackedInt32Array words = TS->shaped_text_get_word_breaks(text.get_line_data(caret.line)->get_rid()); + if (words.is_empty() || column <= words[0]) { + // If "words" is empty, meaning no words are left, we can remove everything until the begining of the line. + column = 0; + } else { + // Otherwise search for the first word break that is smaller than the index from we're currentlu deleteing + for (int i = words.size() - 2; i >= 0; i = i - 2) { + if (words[i] < column) { + column = words[i]; + break; + } } } - _remove_text(line, column, caret.line, caret.column); + _remove_text(caret.line, column, caret.line, caret.column); - set_caret_line(line, false); + set_caret_line(caret.line, false); set_caret_column(column); return; } @@ -3466,9 +3502,6 @@ void TextEdit::undo() { TextOperation op = undo_stack_pos->get(); _do_text_op(op, true); - if (op.type != TextOperation::TYPE_INSERT && (op.from_line != op.to_line || op.to_column != op.from_column + 1)) { - select(op.from_line, op.from_column, op.to_line, op.to_column); - } current_op.version = op.prev_version; if (undo_stack_pos->get().chain_backward) { @@ -3484,6 +3517,10 @@ void TextEdit::undo() { } } + if (op.type != TextOperation::TYPE_INSERT && (op.from_line != op.to_line || op.to_column != op.from_column + 1)) { + select(op.from_line, op.from_column, op.to_line, op.to_column); + } + _update_scrollbars(); if (undo_stack_pos->get().type == TextOperation::TYPE_REMOVE) { set_caret_line(undo_stack_pos->get().to_line, false); @@ -6599,6 +6636,7 @@ TextEdit::TextEdit(const String &p_placeholder) { set_focus_mode(FOCUS_ALL); _update_caches(); set_default_cursor_shape(CURSOR_IBEAM); + set_process_unhandled_key_input(true); text.set_tab_size(text.get_tab_size()); diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h index 6deaf76e5e..b365e9c61c 100644 --- a/scene/gui/text_edit.h +++ b/scene/gui/text_edit.h @@ -325,7 +325,7 @@ private: List<TextOperation> undo_stack; List<TextOperation>::Element *undo_stack_pos = nullptr; - Timer *idle_detect; + Timer *idle_detect = nullptr; uint32_t version = 0; uint32_t saved_version = 0; @@ -380,7 +380,7 @@ private: bool draw_caret = true; bool caret_blink_enabled = false; - Timer *caret_blink_timer; + Timer *caret_blink_timer = nullptr; bool move_caret_on_right_click = true; @@ -426,7 +426,7 @@ private: bool dragging_selection = false; - Timer *click_select_held; + Timer *click_select_held = nullptr; uint64_t last_dblclk = 0; Vector2 last_dblclk_pos; void _click_selection_held(); @@ -449,8 +449,8 @@ private: void _update_caret_wrap_offset(); /* Viewport. */ - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; bool scroll_past_end_of_file_enabled = false; @@ -623,6 +623,7 @@ protected: public: /* General overrides. */ + virtual void unhandled_key_input(const Ref<InputEvent> &p_event) override; virtual void gui_input(const Ref<InputEvent> &p_gui_input) override; virtual Size2 get_minimum_size() const override; virtual bool is_text_field() const override; diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp index ccd24ed2cf..3c8ea4d6df 100644 --- a/scene/gui/tree.cpp +++ b/scene/gui/tree.cpp @@ -101,6 +101,7 @@ void TreeItem::_change_tree(Tree *p_tree) { if (tree->popup_edited_item == this) { tree->popup_edited_item = nullptr; + tree->popup_pressing_edited_item = nullptr; tree->pressing_for_editor = false; } @@ -2088,7 +2089,6 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 } if (!p_item->collapsed) { /* if not collapsed, check the children */ - TreeItem *c = p_item->first_child; int base_ofs = children_pos.y - cache.offset.y + p_draw_ofs.y; @@ -2096,82 +2096,97 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 int prev_hl_ofs = base_ofs; while (c) { + int child_h = -1; if (htotal >= 0) { - int child_h = draw_item(children_pos, p_draw_ofs, p_draw_size, c); + child_h = draw_item(children_pos, p_draw_ofs, p_draw_size, c); + } - // Draw relationship lines. - if (cache.draw_relationship_lines > 0 && (!hide_root || c->parent != root)) { - int root_ofs = children_pos.x + ((p_item->disable_folding || hide_folding) ? cache.hseparation : cache.item_margin); - int parent_ofs = p_pos.x + cache.item_margin; - Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h / 2) - cache.offset + p_draw_ofs; + // Draw relationship lines. + if (cache.draw_relationship_lines > 0 && (!hide_root || c->parent != root)) { + int root_ofs = children_pos.x + ((p_item->disable_folding || hide_folding) ? cache.hseparation : cache.item_margin); + int parent_ofs = p_pos.x + cache.item_margin; + Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h / 2) - cache.offset + p_draw_ofs; - if (c->get_first_child() != nullptr) { - root_pos -= Point2i(cache.arrow->get_width(), 0); - } + if (c->get_first_child() != nullptr) { + root_pos -= Point2i(cache.arrow->get_width(), 0); + } - float line_width = cache.relationship_line_width * Math::round(cache.base_scale); - float parent_line_width = cache.parent_hl_line_width * Math::round(cache.base_scale); - float children_line_width = cache.children_hl_line_width * Math::round(cache.base_scale); + float line_width = cache.relationship_line_width * Math::round(cache.base_scale); + float parent_line_width = cache.parent_hl_line_width * Math::round(cache.base_scale); + float children_line_width = cache.children_hl_line_width * Math::round(cache.base_scale); - Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width() / 2, p_pos.y + label_h / 2 + cache.arrow->get_height() / 2) - cache.offset + p_draw_ofs; + Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width() / 2, p_pos.y + label_h / 2 + cache.arrow->get_height() / 2) - cache.offset + p_draw_ofs; - int more_prev_ofs = 0; + int more_prev_ofs = 0; - if (root_pos.y + line_width >= 0) { - if (rtl) { - root_pos.x = get_size().width - root_pos.x; - parent_pos.x = get_size().width - parent_pos.x; - } + if (root_pos.y + line_width >= 0) { + if (rtl) { + root_pos.x = get_size().width - root_pos.x; + parent_pos.x = get_size().width - parent_pos.x; + } - // Order of parts on this bend: the horizontal line first, then the vertical line. - if (_is_branch_selected(c)) { - // If this item or one of its children is selected, we draw the line using parent highlight style. + // Order of parts on this bend: the horizontal line first, then the vertical line. + if (_is_branch_selected(c)) { + // If this item or one of its children is selected, we draw the line using parent highlight style. + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(parent_line_width / 2), root_pos.y), cache.parent_hl_line_color, parent_line_width); + } + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); + + more_prev_ofs = cache.parent_hl_line_margin; + prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); + } else if (p_item->is_selected(0)) { + // If parent item is selected (but this item is not), we draw the line using children highlight style. + // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. + if (_is_sibling_branch_selected(c)) { + if (htotal >= 0) { + RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(parent_line_width / 2), root_pos.y), cache.children_hl_line_color, children_line_width); + } RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); - more_prev_ofs = cache.parent_hl_line_margin; prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); - } else if (p_item->is_selected(0)) { - // If parent item is selected (but this item is not), we draw the line using children highlight style. - // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. - if (_is_sibling_branch_selected(c)) { - RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(parent_line_width / 2), root_pos.y), cache.children_hl_line_color, children_line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); - - prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); - } else { + } else { + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(children_line_width / 2), root_pos.y), cache.children_hl_line_color, children_line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(children_line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(children_line_width / 2)), cache.children_hl_line_color, children_line_width); } - } else { - // If nothing of the above is true, we draw the line using normal style. - // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. - if (_is_sibling_branch_selected(c)) { + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(children_line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(children_line_width / 2)), cache.children_hl_line_color, children_line_width); + } + } else { + // If nothing of the above is true, we draw the line using normal style. + // Siblings of the selected branch can be drawn with a slight offset and their vertical line must appear as highlighted. + if (_is_sibling_branch_selected(c)) { + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + cache.parent_hl_line_margin, root_pos.y), cache.relationship_line_color, line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); + } + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(parent_line_width / 2)), Point2i(parent_pos.x, prev_hl_ofs), cache.parent_hl_line_color, parent_line_width); - prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); - } else { + prev_hl_ofs = root_pos.y + Math::floor(parent_line_width / 2); + } else { + if (htotal >= 0) { RenderingServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x + Math::floor(line_width / 2), root_pos.y), cache.relationship_line_color, line_width); - RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(line_width / 2)), cache.relationship_line_color, line_width); } + RenderingServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y + Math::floor(line_width / 2)), Point2i(parent_pos.x, prev_ofs + Math::floor(line_width / 2)), cache.relationship_line_color, line_width); } } - - prev_ofs = root_pos.y + more_prev_ofs; } - if (child_h < 0) { - if (cache.draw_relationship_lines == 0) { - return -1; // break, stop drawing, no need to anymore - } + prev_ofs = root_pos.y + more_prev_ofs; + } - htotal = -1; - children_pos.y = cache.offset.y + p_draw_size.height; - } else { - htotal += child_h; - children_pos.y += child_h; + if (child_h < 0) { + if (htotal == -1) { + break; // Last loop done, stop. + } + + if (cache.draw_relationship_lines == 0) { + return -1; // No need to draw anymore, full stop. } + + htotal = -1; + children_pos.y = cache.offset.y + p_draw_size.height; + } else { + htotal += child_h; + children_pos.y += child_h; } c = c->next; @@ -2670,8 +2685,8 @@ int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, int } click_handled = true; - popup_edited_item = p_item; - popup_edited_item_col = col; + popup_pressing_edited_item = p_item; + popup_pressing_edited_item_column = col; pressing_item_rect = Rect2(get_global_position() + Point2i(col_ofs, _get_title_button_height() + y_ofs) - cache.offset, Size2(col_width, item_h)); pressing_for_editor_text = editor_text; @@ -3206,10 +3221,16 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) { update(); } - if (pressing_for_editor && popup_edited_item && (popup_edited_item->get_cell_mode(popup_edited_item_col) == TreeItem::CELL_MODE_RANGE)) { - //range drag + if (pressing_for_editor && popup_pressing_edited_item && (popup_pressing_edited_item->get_cell_mode(popup_pressing_edited_item_column) == TreeItem::CELL_MODE_RANGE)) { + /* This needs to happen now, because the popup can be closed when pressing another item, and must remain the popup edited item until it actually closes */ + popup_edited_item = popup_pressing_edited_item; + popup_edited_item_col = popup_pressing_edited_item_column; + + popup_pressing_edited_item = nullptr; + popup_pressing_edited_item_column = -1; if (!range_drag_enabled) { + //range drag Vector2 cpos = mm->get_position(); if (rtl) { cpos.x = get_size().width - cpos.x; @@ -3994,6 +4015,7 @@ void Tree::clear() { selected_item = nullptr; edited_item = nullptr; popup_edited_item = nullptr; + popup_pressing_edited_item = nullptr; update(); }; @@ -4309,12 +4331,16 @@ int Tree::get_pressed_button() const { return pressed_button; } -Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column) const { +Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column, int p_button) const { ERR_FAIL_NULL_V(p_item, Rect2()); ERR_FAIL_COND_V(p_item->tree != this, Rect2()); if (p_column != -1) { ERR_FAIL_INDEX_V(p_column, columns.size(), Rect2()); } + if (p_button != -1) { + ERR_FAIL_COND_V(p_column == -1, Rect2()); // pass a column if you want to pass a button + ERR_FAIL_INDEX_V(p_button, p_item->cells[p_column].buttons.size(), Rect2()); + } int ofs = get_item_offset(p_item); int height = compute_item_height(p_item); @@ -4332,6 +4358,19 @@ Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column) const { } r.position.x = accum; r.size.x = get_column_width(p_column); + if (p_button != -1) { + const TreeItem::Cell &c = p_item->cells[p_column]; + Vector2 ofst = Vector2(r.position.x + r.size.x, r.position.y); + for (int j = c.buttons.size() - 1; j >= 0; j--) { + Ref<Texture2D> b = c.buttons[j].texture; + Size2 size = b->get_size() + cache.button_pressed->get_minimum_size(); + ofst.x -= size.x; + + if (j == p_button) { + return Rect2(ofst, size); + } + } + } } return r; @@ -4870,7 +4909,7 @@ void Tree::_bind_methods() { ClassDB::bind_method(D_METHOD("get_edited_column"), &Tree::get_edited_column); ClassDB::bind_method(D_METHOD("edit_selected"), &Tree::edit_selected); ClassDB::bind_method(D_METHOD("get_custom_popup_rect"), &Tree::get_custom_popup_rect); - ClassDB::bind_method(D_METHOD("get_item_area_rect", "item", "column"), &Tree::get_item_rect, DEFVAL(-1)); + ClassDB::bind_method(D_METHOD("get_item_area_rect", "item", "column", "button_index"), &Tree::get_item_rect, DEFVAL(-1), DEFVAL(-1)); ClassDB::bind_method(D_METHOD("get_item_at_position", "position"), &Tree::get_item_at_position); ClassDB::bind_method(D_METHOD("get_column_at_position", "position"), &Tree::get_column_at_position); ClassDB::bind_method(D_METHOD("get_drop_section_at_position", "position"), &Tree::get_drop_section_at_position); diff --git a/scene/gui/tree.h b/scene/gui/tree.h index 04d4b9b935..b704495444 100644 --- a/scene/gui/tree.h +++ b/scene/gui/tree.h @@ -134,7 +134,7 @@ private: Vector<TreeItem *> children_cache; bool is_root = false; // for tree root - Tree *tree; // tree (for reference) + Tree *tree = nullptr; // tree (for reference) TreeItem(Tree *p_tree); @@ -379,6 +379,9 @@ private: TreeItem *selected_item = nullptr; TreeItem *edited_item = nullptr; + TreeItem *popup_pressing_edited_item = nullptr; // Candidate. + int popup_pressing_edited_item_column = -1; + TreeItem *drop_mode_over = nullptr; int drop_mode_section = 0; @@ -428,18 +431,18 @@ private: bool show_column_titles = false; - VBoxContainer *popup_editor_vb; + VBoxContainer *popup_editor_vb = nullptr; - Popup *popup_editor; + Popup *popup_editor = nullptr; LineEdit *text_editor = nullptr; - HSlider *value_editor; + HSlider *value_editor = nullptr; bool updating_value_editor = false; uint64_t focus_in_id = 0; PopupMenu *popup_menu = nullptr; Vector<ColumnInfo> columns; - Timer *range_click_timer; + Timer *range_click_timer = nullptr; TreeItem *range_item_last = nullptr; bool range_up_last = false; void _range_click_timeout(); @@ -553,8 +556,8 @@ private: int _get_title_button_height() const; void _scroll_moved(float p_value); - HScrollBar *h_scroll; - VScrollBar *v_scroll; + HScrollBar *h_scroll = nullptr; + VScrollBar *v_scroll = nullptr; bool h_scroll_enabled = true; bool v_scroll_enabled = true; @@ -673,7 +676,7 @@ public: Rect2 get_custom_popup_rect() const; int get_item_offset(TreeItem *p_item) const; - Rect2 get_item_rect(TreeItem *p_item, int p_column = -1) const; + Rect2 get_item_rect(TreeItem *p_item, int p_column = -1, int p_button = -1) const; bool edit_selected(); bool is_editing(); diff --git a/scene/gui/video_stream_player.cpp b/scene/gui/video_stream_player.cpp index d7c76aa070..ca2dad71af 100644 --- a/scene/gui/video_stream_player.cpp +++ b/scene/gui/video_stream_player.cpp @@ -60,7 +60,7 @@ int VideoStreamPlayer::_audio_mix_callback(void *p_udata, const float *p_data, i ERR_FAIL_NULL_V(p_udata, 0); ERR_FAIL_NULL_V(p_data, 0); - VideoStreamPlayer *vp = (VideoStreamPlayer *)p_udata; + VideoStreamPlayer *vp = static_cast<VideoStreamPlayer *>(p_udata); int todo = MIN(vp->resampler.get_writer_space(), p_frames); @@ -77,7 +77,7 @@ int VideoStreamPlayer::_audio_mix_callback(void *p_udata, const float *p_data, i void VideoStreamPlayer::_mix_audios(void *p_self) { ERR_FAIL_NULL(p_self); - reinterpret_cast<VideoStreamPlayer *>(p_self)->_mix_audio(); + static_cast<VideoStreamPlayer *>(p_self)->_mix_audio(); } // Called from audio thread diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp index 15d36d8230..708359f106 100644 --- a/scene/main/canvas_item.cpp +++ b/scene/main/canvas_item.cpp @@ -463,10 +463,10 @@ void CanvasItem::draw_dashed_line(const Point2 &p_from, const Point2 &p_to, cons RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, off, p_to, p_color, p_width); } -void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width) { +void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width, bool p_antialiased) { ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal."); - RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, p_from, p_to, p_color, p_width); + RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, p_from, p_to, p_color, p_width, p_antialiased); } void CanvasItem::draw_polyline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width, bool p_antialiased) { @@ -883,10 +883,7 @@ void CanvasItem::_bind_methods() { ClassDB::bind_method(D_METHOD("set_draw_behind_parent", "enable"), &CanvasItem::set_draw_behind_parent); ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"), &CanvasItem::is_draw_behind_parent_enabled); - ClassDB::bind_method(D_METHOD("_set_on_top", "on_top"), &CanvasItem::_set_on_top); - ClassDB::bind_method(D_METHOD("_is_on_top"), &CanvasItem::_is_on_top); - - ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width"), &CanvasItem::draw_line, DEFVAL(1.0)); + ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width", "antialiased"), &CanvasItem::draw_line, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("draw_dashed_line", "from", "to", "color", "width", "dash"), &CanvasItem::draw_dashed_line, DEFVAL(1.0), DEFVAL(2.0)); ClassDB::bind_method(D_METHOD("draw_polyline", "points", "color", "width", "antialiased"), &CanvasItem::draw_polyline, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("draw_polyline_colors", "points", "colors", "width", "antialiased"), &CanvasItem::draw_polyline_colors, DEFVAL(1.0), DEFVAL(false)); @@ -959,7 +956,6 @@ void CanvasItem::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::COLOR, "self_modulate"), "set_self_modulate", "get_self_modulate"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_behind_parent"), "set_draw_behind_parent", "is_draw_behind_parent_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "top_level"), "set_as_top_level", "is_set_as_top_level"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_on_top", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "_set_on_top", "_is_on_top"); //compatibility ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_children"), "set_clip_children", "is_clipping_children"); ADD_PROPERTY(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask", "get_light_mask"); diff --git a/scene/main/canvas_item.h b/scene/main/canvas_item.h index dbc833aa5b..ad64f1ab5e 100644 --- a/scene/main/canvas_item.h +++ b/scene/main/canvas_item.h @@ -120,9 +120,6 @@ private: void _notify_transform(CanvasItem *p_node); - void _set_on_top(bool p_on_top) { set_draw_behind_parent(!p_on_top); } - bool _is_on_top() const { return !is_draw_behind_parent_enabled(); } - static CanvasItem *current_item_drawn; friend class Viewport; void _update_texture_repeat_changed(bool p_propagate); @@ -218,7 +215,7 @@ public: /* DRAWING API */ void draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, real_t p_dash = 2.0); - void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0); + void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); void draw_polyline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); void draw_polyline_colors(const Vector<Point2> &p_points, const Vector<Color> &p_colors, real_t p_width = 1.0, bool p_antialiased = false); void draw_arc(const Vector2 &p_center, real_t p_radius, real_t p_start_angle, real_t p_end_angle, int p_point_count, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false); diff --git a/scene/main/http_request.cpp b/scene/main/http_request.cpp index ac10c2bad8..34b0e19d31 100644 --- a/scene/main/http_request.cpp +++ b/scene/main/http_request.cpp @@ -164,7 +164,7 @@ Error HTTPRequest::request_raw(const String &p_url, const Vector<String> &p_cust } void HTTPRequest::_thread_func(void *p_userdata) { - HTTPRequest *hr = (HTTPRequest *)p_userdata; + HTTPRequest *hr = static_cast<HTTPRequest *>(p_userdata); Error err = hr->_request(); @@ -197,10 +197,7 @@ void HTTPRequest::cancel_request() { thread.wait_to_finish(); } - if (file) { - memdelete(file); - file = nullptr; - } + file.unref(); client->close(); body.clear(); got_response = false; @@ -365,7 +362,7 @@ bool HTTPRequest::_update_connection() { if (!download_to_file.is_empty()) { file = FileAccess::open(download_to_file, FileAccess::WRITE); - if (!file) { + if (file.is_null()) { call_deferred(SNAME("_request_done"), RESULT_DOWNLOAD_FILE_CANT_OPEN, response_code, response_headers, PackedByteArray()); return true; } @@ -381,7 +378,7 @@ bool HTTPRequest::_update_connection() { if (chunk.size()) { downloaded.add(chunk.size()); - if (file) { + if (file.is_valid()) { const uint8_t *r = chunk.ptr(); file->store_buffer(r, chunk.size()); if (file->get_error() != OK) { @@ -642,9 +639,3 @@ HTTPRequest::HTTPRequest() { timer->connect("timeout", callable_mp(this, &HTTPRequest::_timeout)); add_child(timer); } - -HTTPRequest::~HTTPRequest() { - if (file) { - memdelete(file); - } -} diff --git a/scene/main/http_request.h b/scene/main/http_request.h index 26d648458f..49b4b1b30c 100644 --- a/scene/main/http_request.h +++ b/scene/main/http_request.h @@ -84,7 +84,7 @@ private: String download_to_file; - FileAccess *file = nullptr; + Ref<FileAccess> file; int body_len = -1; SafeNumeric<int> downloaded; @@ -144,7 +144,7 @@ public: void set_max_redirects(int p_max); int get_max_redirects() const; - Timer *timer; + Timer *timer = nullptr; void set_timeout(double p_timeout); double get_timeout(); @@ -158,7 +158,6 @@ public: void set_https_proxy(const String &p_host, int p_port); HTTPRequest(); - ~HTTPRequest(); }; VARIANT_ENUM_CAST(HTTPRequest::Result); diff --git a/scene/main/node.cpp b/scene/main/node.cpp index 7933045c5f..34bb1cde05 100644 --- a/scene/main/node.cpp +++ b/scene/main/node.cpp @@ -79,6 +79,9 @@ void Node::_notification(int p_notification) { if (data.input) { add_to_group("_vp_input" + itos(get_viewport()->get_instance_id())); } + if (data.shortcut_input) { + add_to_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } if (data.unhandled_input) { add_to_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } @@ -100,6 +103,9 @@ void Node::_notification(int p_notification) { if (data.input) { remove_from_group("_vp_input" + itos(get_viewport()->get_instance_id())); } + if (data.shortcut_input) { + remove_from_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } if (data.unhandled_input) { remove_from_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } @@ -126,6 +132,10 @@ void Node::_notification(int p_notification) { set_process_input(true); } + if (GDVIRTUAL_IS_OVERRIDDEN(_shortcut_input)) { + set_process_shortcut_input(true); + } + if (GDVIRTUAL_IS_OVERRIDDEN(_unhandled_input)) { set_process_unhandled_input(true); } @@ -835,6 +845,26 @@ bool Node::is_processing_input() const { return data.input; } +void Node::set_process_shortcut_input(bool p_enable) { + if (p_enable == data.shortcut_input) { + return; + } + data.shortcut_input = p_enable; + if (!is_inside_tree()) { + return; + } + + if (p_enable) { + add_to_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } else { + remove_from_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); + } +} + +bool Node::is_processing_shortcut_input() const { + return data.shortcut_input; +} + void Node::set_process_unhandled_input(bool p_enable) { if (p_enable == data.unhandled_input) { return; @@ -2615,6 +2645,15 @@ void Node::_call_input(const Ref<InputEvent> &p_event) { } input(p_event); } + +void Node::_call_shortcut_input(const Ref<InputEvent> &p_event) { + GDVIRTUAL_CALL(_shortcut_input, p_event); + if (!is_inside_tree() || !get_viewport() || get_viewport()->is_input_handled()) { + return; + } + shortcut_input(p_event); +} + void Node::_call_unhandled_input(const Ref<InputEvent> &p_event) { GDVIRTUAL_CALL(_unhandled_input, p_event); if (!is_inside_tree() || !get_viewport() || get_viewport()->is_input_handled()) { @@ -2622,6 +2661,7 @@ void Node::_call_unhandled_input(const Ref<InputEvent> &p_event) { } unhandled_input(p_event); } + void Node::_call_unhandled_key_input(const Ref<InputEvent> &p_event) { GDVIRTUAL_CALL(_unhandled_key_input, p_event); if (!is_inside_tree() || !get_viewport() || get_viewport()->is_input_handled()) { @@ -2633,6 +2673,9 @@ void Node::_call_unhandled_key_input(const Ref<InputEvent> &p_event) { void Node::input(const Ref<InputEvent> &p_event) { } +void Node::shortcut_input(const Ref<InputEvent> &p_key_event) { +} + void Node::unhandled_input(const Ref<InputEvent> &p_event) { } @@ -2694,6 +2737,8 @@ void Node::_bind_methods() { ClassDB::bind_method(D_METHOD("is_processing"), &Node::is_processing); ClassDB::bind_method(D_METHOD("set_process_input", "enable"), &Node::set_process_input); ClassDB::bind_method(D_METHOD("is_processing_input"), &Node::is_processing_input); + ClassDB::bind_method(D_METHOD("set_process_shortcut_input", "enable"), &Node::set_process_shortcut_input); + ClassDB::bind_method(D_METHOD("is_processing_shortcut_input"), &Node::is_processing_shortcut_input); ClassDB::bind_method(D_METHOD("set_process_unhandled_input", "enable"), &Node::set_process_unhandled_input); ClassDB::bind_method(D_METHOD("is_processing_unhandled_input"), &Node::is_processing_unhandled_input); ClassDB::bind_method(D_METHOD("set_process_unhandled_key_input", "enable"), &Node::set_process_unhandled_key_input); @@ -2854,6 +2899,7 @@ void Node::_bind_methods() { GDVIRTUAL_BIND(_ready); GDVIRTUAL_BIND(_get_configuration_warnings); GDVIRTUAL_BIND(_input, "event"); + GDVIRTUAL_BIND(_shortcut_input, "event"); GDVIRTUAL_BIND(_unhandled_input, "event"); GDVIRTUAL_BIND(_unhandled_key_input, "event"); } diff --git a/scene/main/node.h b/scene/main/node.h index 1f973a0cb4..57b150e29a 100644 --- a/scene/main/node.h +++ b/scene/main/node.h @@ -136,6 +136,7 @@ private: bool process_internal = false; bool input = false; + bool shortcut_input = false; bool unhandled_input = false; bool unhandled_key_input = false; @@ -215,11 +216,13 @@ protected: //call from SceneTree void _call_input(const Ref<InputEvent> &p_event); + void _call_shortcut_input(const Ref<InputEvent> &p_event); void _call_unhandled_input(const Ref<InputEvent> &p_event); void _call_unhandled_key_input(const Ref<InputEvent> &p_event); protected: virtual void input(const Ref<InputEvent> &p_event); + virtual void shortcut_input(const Ref<InputEvent> &p_key_event); virtual void unhandled_input(const Ref<InputEvent> &p_event); virtual void unhandled_key_input(const Ref<InputEvent> &p_key_event); @@ -231,6 +234,7 @@ protected: GDVIRTUAL0RC(Vector<String>, _get_configuration_warnings) GDVIRTUAL1(_input, Ref<InputEvent>) + GDVIRTUAL1(_shortcut_input, Ref<InputEvent>) GDVIRTUAL1(_unhandled_input, Ref<InputEvent>) GDVIRTUAL1(_unhandled_key_input, Ref<InputEvent>) @@ -395,6 +399,9 @@ public: void set_process_input(bool p_enable); bool is_processing_input() const; + void set_process_shortcut_input(bool p_enable); + bool is_processing_shortcut_input() const; + void set_process_unhandled_input(bool p_enable); bool is_processing_unhandled_input() const; diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp index 8eeedf51a9..151239c9e7 100644 --- a/scene/main/scene_tree.cpp +++ b/scene/main/scene_tree.cpp @@ -897,6 +897,9 @@ void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_cal case CALL_INPUT_TYPE_INPUT: n->_call_input(p_input); break; + case CALL_INPUT_TYPE_SHORTCUT_INPUT: + n->_call_shortcut_input(p_input); + break; case CALL_INPUT_TYPE_UNHANDLED_INPUT: n->_call_unhandled_input(p_input); break; @@ -1259,7 +1262,7 @@ void SceneTree::add_idle_callback(IdleCallback p_callback) { void SceneTree::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { if (p_function == "change_scene") { - DirAccessRef dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES); List<String> directories; directories.push_back(dir_access->get_current_dir()); diff --git a/scene/main/scene_tree.h b/scene/main/scene_tree.h index 10839ca425..705ca6ebd3 100644 --- a/scene/main/scene_tree.h +++ b/scene/main/scene_tree.h @@ -115,7 +115,7 @@ private: int node_count = 0; #ifdef TOOLS_ENABLED - Node *edited_scene_root; + Node *edited_scene_root = nullptr; #endif struct UGCall { StringName group; @@ -138,7 +138,7 @@ private: Array _get_nodes_in_group(const StringName &p_group); - Node *current_scene; + Node *current_scene = nullptr; Color debug_collisions_color; Color debug_collision_contact_color; @@ -204,6 +204,7 @@ private: enum CallInputType { CALL_INPUT_TYPE_INPUT, + CALL_INPUT_TYPE_SHORTCUT_INPUT, CALL_INPUT_TYPE_UNHANDLED_INPUT, CALL_INPUT_TYPE_UNHANDLED_KEY_INPUT, }; diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp index a38bed71d1..d93e7b4b0b 100644 --- a/scene/main/viewport.cpp +++ b/scene/main/viewport.cpp @@ -2744,11 +2744,18 @@ void Viewport::push_unhandled_input(const Ref<InputEvent> &p_event, bool p_local ev = p_event; } + // Shortcut Input. + if (Object::cast_to<InputEventKey>(*ev) != nullptr || Object::cast_to<InputEventShortcut>(*ev) != nullptr) { + get_tree()->_call_input_pause(shortcut_input_group, SceneTree::CALL_INPUT_TYPE_SHORTCUT_INPUT, ev, this); + } + // Unhandled Input. - get_tree()->_call_input_pause(unhandled_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_INPUT, ev, this); + if (!is_input_handled()) { + get_tree()->_call_input_pause(unhandled_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_INPUT, ev, this); + } - // Unhandled key Input - used for performance reasons - This is called a lot less than _unhandled_input since it ignores MouseMotion, etc. - if (!is_input_handled() && (Object::cast_to<InputEventKey>(*ev) != nullptr || Object::cast_to<InputEventShortcut>(*ev) != nullptr)) { + // Unhandled key Input - Used for performance reasons - This is called a lot less than _unhandled_input since it ignores MouseMotion, and to handle Unicode input with Alt / Ctrl modifiers after handling shortcuts. + if (!is_input_handled() && (Object::cast_to<InputEventKey>(*ev) != nullptr)) { get_tree()->_call_input_pause(unhandled_key_input_group, SceneTree::CALL_INPUT_TYPE_UNHANDLED_KEY_INPUT, ev, this); } @@ -3737,7 +3744,7 @@ void Viewport::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::INT, "debug_draw", PROPERTY_HINT_ENUM, "Disabled,Unshaded,Overdraw,Wireframe"), "set_debug_draw", "get_debug_draw"); #ifndef _3D_DISABLED ADD_GROUP("Scaling 3D", ""); - ADD_PROPERTY(PropertyInfo(Variant::INT, "scaling_3d_mode", PROPERTY_HINT_ENUM, "Disabled (Slowest),Bilinear (Fastest),FSR (Fast)"), "set_scaling_3d_mode", "get_scaling_3d_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "scaling_3d_mode", PROPERTY_HINT_ENUM, "Bilinear (Fastest),FSR 1.0 (Fast)"), "set_scaling_3d_mode", "get_scaling_3d_mode"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "scaling_3d_scale", PROPERTY_HINT_RANGE, "0.25,2.0,0.01"), "set_scaling_3d_scale", "get_scaling_3d_scale"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fsr_mipmap_bias", PROPERTY_HINT_RANGE, "-2,2,0.1"), "set_fsr_mipmap_bias", "get_fsr_mipmap_bias"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fsr_sharpness", PROPERTY_HINT_RANGE, "0,2,0.1"), "set_fsr_sharpness", "get_fsr_sharpness"); @@ -3879,6 +3886,7 @@ Viewport::Viewport() { input_group = "_vp_input" + id; gui_input_group = "_vp_gui_input" + id; unhandled_input_group = "_vp_unhandled_input" + id; + shortcut_input_group = "_vp_shortcut_input" + id; unhandled_key_input_group = "_vp_unhandled_key_input" + id; // Window tooltip. diff --git a/scene/main/viewport.h b/scene/main/viewport.h index 80be53fab8..32882fbb68 100644 --- a/scene/main/viewport.h +++ b/scene/main/viewport.h @@ -270,6 +270,7 @@ private: Rect2i to_screen_rect; StringName input_group; StringName gui_input_group; + StringName shortcut_input_group; StringName unhandled_input_group; StringName unhandled_key_input_group; diff --git a/scene/main/window.cpp b/scene/main/window.cpp index 2faa107fb4..8b1a4680d2 100644 --- a/scene/main/window.cpp +++ b/scene/main/window.cpp @@ -981,7 +981,7 @@ void Window::_window_input_text(const String &p_text) { } void Window::_window_drop_files(const Vector<String> &p_files) { - emit_signal(SNAME("files_dropped"), p_files, current_screen); + emit_signal(SNAME("files_dropped"), p_files); } Viewport *Window::get_parent_viewport() const { @@ -1066,11 +1066,9 @@ void Window::popup_centered(const Size2i &p_minsize) { } Rect2i popup_rect; - if (p_minsize == Size2i()) { - popup_rect.size = _get_contents_minimum_size(); - } else { - popup_rect.size = p_minsize; - } + Size2 contents_minsize = _get_contents_minimum_size(); + popup_rect.size.x = MAX(p_minsize.x, contents_minsize.x); + popup_rect.size.y = MAX(p_minsize.y, contents_minsize.y); popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2; popup(popup_rect); @@ -1079,6 +1077,7 @@ void Window::popup_centered(const Size2i &p_minsize) { void Window::popup_centered_ratio(float p_ratio) { ERR_FAIL_COND(!is_inside_tree()); ERR_FAIL_COND_MSG(window_id == DisplayServer::MAIN_WINDOW_ID, "Can't popup the main window."); + ERR_FAIL_COND_MSG(p_ratio <= 0.0 || p_ratio > 1.0, "Ratio must be between 0.0 and 1.0!"); Rect2 parent_rect; diff --git a/scene/multiplayer/scene_cache_interface.h b/scene/multiplayer/scene_cache_interface.h index c709d26b51..d53cf387fb 100644 --- a/scene/multiplayer/scene_cache_interface.h +++ b/scene/multiplayer/scene_cache_interface.h @@ -37,7 +37,7 @@ class SceneCacheInterface : public MultiplayerCacheInterface { GDCLASS(SceneCacheInterface, MultiplayerCacheInterface); private: - MultiplayerAPI *multiplayer; + MultiplayerAPI *multiplayer = nullptr; //path sent caches struct PathSentCache { diff --git a/scene/multiplayer/scene_replication_interface.h b/scene/multiplayer/scene_replication_interface.h index 855878d029..60ac95c93c 100644 --- a/scene/multiplayer/scene_replication_interface.h +++ b/scene/multiplayer/scene_replication_interface.h @@ -47,7 +47,7 @@ private: void _free_remotes(int p_peer); Ref<SceneReplicationState> rep_state; - MultiplayerAPI *multiplayer; + MultiplayerAPI *multiplayer = nullptr; PackedByteArray packet_cache; int sync_mtu = 1350; // Highly dependent on underlying protocol. diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index 032f43d9b9..127e734e6c 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -139,6 +139,7 @@ #include "scene/multiplayer/scene_cache_interface.h" #include "scene/multiplayer/scene_replication_interface.h" #include "scene/multiplayer/scene_rpc_interface.h" +#include "scene/resources/animation_library.h" #include "scene/resources/audio_stream_sample.h" #include "scene/resources/bit_map.h" #include "scene/resources/box_shape_3d.h" @@ -834,6 +835,7 @@ void register_scene_types() { GDREGISTER_CLASS(CompressedTexture2DArray); GDREGISTER_CLASS(Animation); + GDREGISTER_CLASS(AnimationLibrary); GDREGISTER_CLASS(FontData); GDREGISTER_CLASS(Font); GDREGISTER_CLASS(Curve); @@ -896,18 +898,16 @@ void register_scene_types() { #ifndef DISABLE_DEPRECATED // Dropped in 4.0, near approximation. ClassDB::add_compatibility_class("AnimationTreePlayer", "AnimationTree"); - ClassDB::add_compatibility_class("AStar", "AStar3D"); + ClassDB::add_compatibility_class("BakedLightmap", "LightmapGI"); + ClassDB::add_compatibility_class("BakedLightmapData", "LightmapGIData"); ClassDB::add_compatibility_class("BitmapFont", "Font"); ClassDB::add_compatibility_class("DynamicFont", "Font"); ClassDB::add_compatibility_class("DynamicFontData", "FontData"); - ClassDB::add_compatibility_class("ToolButton", "Button"); ClassDB::add_compatibility_class("Navigation3D", "Node3D"); ClassDB::add_compatibility_class("Navigation2D", "Node2D"); + ClassDB::add_compatibility_class("OpenSimplexNoise", "FastNoiseLite"); + ClassDB::add_compatibility_class("ToolButton", "Button"); ClassDB::add_compatibility_class("YSort", "Node2D"); - ClassDB::add_compatibility_class("GIProbe", "VoxelGI"); - ClassDB::add_compatibility_class("GIProbeData", "VoxelGIData"); - ClassDB::add_compatibility_class("BakedLightmap", "LightmapGI"); - ClassDB::add_compatibility_class("BakedLightmapData", "LightmapGIData"); // Portal and room occlusion was replaced by raster occlusion (OccluderInstance3D node). ClassDB::add_compatibility_class("Portal", "Node3D"); ClassDB::add_compatibility_class("Room", "Node3D"); @@ -928,6 +928,7 @@ void register_scene_types() { ClassDB::add_compatibility_class("ARVROrigin", "XROrigin3D"); ClassDB::add_compatibility_class("ARVRPositionalTracker", "XRPositionalTracker"); ClassDB::add_compatibility_class("ARVRServer", "XRServer"); + ClassDB::add_compatibility_class("AStar", "AStar3D"); ClassDB::add_compatibility_class("BoneAttachment", "BoneAttachment3D"); ClassDB::add_compatibility_class("BoxShape", "BoxShape3D"); ClassDB::add_compatibility_class("Camera", "Camera3D"); @@ -955,6 +956,8 @@ void register_scene_types() { ClassDB::add_compatibility_class("EditorSpatialGizmo", "EditorNode3DGizmo"); ClassDB::add_compatibility_class("EditorSpatialGizmoPlugin", "EditorNode3DGizmoPlugin"); ClassDB::add_compatibility_class("Generic6DOFJoint", "Generic6DOFJoint3D"); + ClassDB::add_compatibility_class("GIProbe", "VoxelGI"); + ClassDB::add_compatibility_class("GIProbeData", "VoxelGIData"); ClassDB::add_compatibility_class("GradientTexture", "GradientTexture1D"); ClassDB::add_compatibility_class("HeightMapShape", "HeightMapShape3D"); ClassDB::add_compatibility_class("HingeJoint", "HingeJoint3D"); diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp index f6e0df0265..e045a379d2 100644 --- a/scene/resources/animation.cpp +++ b/scene/resources/animation.cpp @@ -3428,7 +3428,6 @@ real_t Animation::bezier_track_interpolate(int p_track, double p_time) const { real_t duration = bt->values[idx + 1].time - bt->values[idx].time; // time duration between our two keyframes real_t low = 0.0; // 0% of the current animation segment real_t high = 1.0; // 100% of the current animation segment - real_t middle; Vector2 start(0, bt->values[idx].value.value); Vector2 start_out = start + bt->values[idx].value.out_handle; @@ -3437,7 +3436,7 @@ real_t Animation::bezier_track_interpolate(int p_track, double p_time) const { //narrow high and low as much as possible for (int i = 0; i < iterations; i++) { - middle = (low + high) / 2; + real_t middle = (low + high) / 2; Vector2 interp = _bezier_interp(middle, start, start_out, end_in, end); @@ -3829,7 +3828,7 @@ void Animation::_bind_methods() { ClassDB::bind_method(D_METHOD("compress", "page_size", "fps", "split_tolerance"), &Animation::compress, DEFVAL(8192), DEFVAL(120), DEFVAL(4.0)); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "length", PROPERTY_HINT_RANGE, "0.001,99999,0.001"), "set_length", "get_length"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode"), "set_loop_mode", "get_loop_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode", PROPERTY_HINT_ENUM, "None,Linear,Ping-Pong"), "set_loop_mode", "get_loop_mode"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "step", PROPERTY_HINT_RANGE, "0,4096,0.001"), "set_step", "get_step"); ADD_SIGNAL(MethodInfo("tracks_changed")); diff --git a/scene/resources/animation_library.cpp b/scene/resources/animation_library.cpp new file mode 100644 index 0000000000..229d9ab218 --- /dev/null +++ b/scene/resources/animation_library.cpp @@ -0,0 +1,134 @@ +/*************************************************************************/ +/* animation_library.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "animation_library.h" + +Error AnimationLibrary::add_animation(const StringName &p_name, const Ref<Animation> &p_animation) { + ERR_FAIL_COND_V_MSG(String(p_name).contains("/") || String(p_name).contains(":") || String(p_name).contains(",") || String(p_name).contains("["), ERR_INVALID_PARAMETER, "Invalid animation name: " + String(p_name) + "."); + ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER); + + if (animations.has(p_name)) { + animations.erase(p_name); + emit_signal(SNAME("animation_removed"), p_name); + } + + animations.insert(p_name, p_animation); + emit_signal(SNAME("animation_added"), p_name); + notify_property_list_changed(); + return OK; +} + +void AnimationLibrary::remove_animation(const StringName &p_name) { + ERR_FAIL_COND(!animations.has(p_name)); + + animations.erase(p_name); + emit_signal(SNAME("animation_removed"), p_name); + notify_property_list_changed(); +} + +void AnimationLibrary::rename_animation(const StringName &p_name, const StringName &p_new_name) { + ERR_FAIL_COND(!animations.has(p_name)); + ERR_FAIL_COND_MSG(String(p_new_name).contains("/") || String(p_new_name).contains(":") || String(p_new_name).contains(",") || String(p_new_name).contains("["), "Invalid animation name: " + String(p_new_name) + "."); + ERR_FAIL_COND(animations.has(p_new_name)); + + animations.insert(p_new_name, animations[p_name]); + animations.erase(p_name); + emit_signal(SNAME("animation_renamed"), p_name, p_new_name); +} + +bool AnimationLibrary::has_animation(const StringName &p_name) const { + return animations.has(p_name); +} + +Ref<Animation> AnimationLibrary::get_animation(const StringName &p_name) const { + ERR_FAIL_COND_V(!animations.has(p_name), Ref<Animation>()); + + return animations[p_name]; +} + +TypedArray<StringName> AnimationLibrary::_get_animation_list() const { + TypedArray<StringName> ret; + List<StringName> names; + get_animation_list(&names); + for (const StringName &K : names) { + ret.push_back(K); + } + return ret; +} + +void AnimationLibrary::get_animation_list(List<StringName> *p_animations) const { + List<StringName> anims; + + for (const KeyValue<StringName, Ref<Animation>> &E : animations) { + anims.push_back(E.key); + } + + anims.sort_custom<StringName::AlphCompare>(); + + for (const StringName &E : anims) { + p_animations->push_back(E); + } +} + +void AnimationLibrary::_set_data(const Dictionary &p_data) { + animations.clear(); + List<Variant> keys; + p_data.get_key_list(&keys); + for (const Variant &K : keys) { + add_animation(K, p_data[K]); + } +} + +Dictionary AnimationLibrary::_get_data() const { + Dictionary ret; + for (const KeyValue<StringName, Ref<Animation>> &K : animations) { + ret[K.key] = K.value; + } + return ret; +} + +void AnimationLibrary::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_animation", "name", "animation"), &AnimationLibrary::add_animation); + ClassDB::bind_method(D_METHOD("remove_animation", "name"), &AnimationLibrary::remove_animation); + ClassDB::bind_method(D_METHOD("rename_animation", "name", "newname"), &AnimationLibrary::rename_animation); + ClassDB::bind_method(D_METHOD("has_animation", "name"), &AnimationLibrary::has_animation); + ClassDB::bind_method(D_METHOD("get_animation", "name"), &AnimationLibrary::get_animation); + ClassDB::bind_method(D_METHOD("get_animation_list"), &AnimationLibrary::_get_animation_list); + + ClassDB::bind_method(D_METHOD("_set_data", "data"), &AnimationLibrary::_set_data); + ClassDB::bind_method(D_METHOD("_get_data"), &AnimationLibrary::_get_data); + + ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "_set_data", "_get_data"); + ADD_SIGNAL(MethodInfo("animation_added", PropertyInfo(Variant::OBJECT, "name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"))); + ADD_SIGNAL(MethodInfo("animation_removed", PropertyInfo(Variant::OBJECT, "name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"))); + ADD_SIGNAL(MethodInfo("animation_renamed", PropertyInfo(Variant::OBJECT, "name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"), PropertyInfo(Variant::OBJECT, "to_name", PROPERTY_HINT_RESOURCE_TYPE, "Animation"))); +} +AnimationLibrary::AnimationLibrary() { +} diff --git a/tests/core/templates/test_oa_hash_map.h b/scene/resources/animation_library.h index d4b72af2ac..69ac5a97d2 100644 --- a/tests/core/templates/test_oa_hash_map.h +++ b/scene/resources/animation_library.h @@ -1,5 +1,5 @@ /*************************************************************************/ -/* test_oa_hash_map.h */ +/* animation_library.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ @@ -28,14 +28,35 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef TEST_OA_HASH_MAP_H -#define TEST_OA_HASH_MAP_H +#ifndef ANIMATION_LIBRARY_H +#define ANIMATION_LIBRARY_H -class MainLoop; +#include "core/variant/typed_array.h" +#include "scene/resources/animation.h" -namespace TestOAHashMap { +class AnimationLibrary : public Resource { + GDCLASS(AnimationLibrary, Resource) -MainLoop *test(); -} + void _set_data(const Dictionary &p_data); + Dictionary _get_data() const; -#endif // TEST_OA_HASH_MAP_H + TypedArray<StringName> _get_animation_list() const; + + friend class AnimationPlayer; //for faster access + Map<StringName, Ref<Animation>> animations; + +protected: + static void _bind_methods(); + +public: + Error add_animation(const StringName &p_name, const Ref<Animation> &p_animation); + void remove_animation(const StringName &p_name); + void rename_animation(const StringName &p_name, const StringName &p_new_name); + bool has_animation(const StringName &p_name) const; + Ref<Animation> get_animation(const StringName &p_name) const; + void get_animation_list(List<StringName> *p_animations) const; + + AnimationLibrary(); +}; + +#endif // ANIMATIONLIBRARY_H diff --git a/scene/resources/audio_stream_sample.cpp b/scene/resources/audio_stream_sample.cpp index 56786ac4b1..30c222bdff 100644 --- a/scene/resources/audio_stream_sample.cpp +++ b/scene/resources/audio_stream_sample.cpp @@ -556,9 +556,9 @@ Error AudioStreamSample::save_to_wav(const String &p_path) { file_path += ".wav"; } - FileAccessRef file = FileAccess::open(file_path, FileAccess::WRITE); //Overrides existing file if present + Ref<FileAccess> file = FileAccess::open(file_path, FileAccess::WRITE); //Overrides existing file if present - ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE); + ERR_FAIL_COND_V(file.is_null(), ERR_FILE_CANT_WRITE); // Create WAV Header file->store_string("RIFF"); //ChunkID @@ -596,8 +596,6 @@ Error AudioStreamSample::save_to_wav(const String &p_path) { break; } - file->close(); - return OK; } diff --git a/scene/resources/convex_polygon_shape_2d.cpp b/scene/resources/convex_polygon_shape_2d.cpp index 667399ee75..c416a03f38 100644 --- a/scene/resources/convex_polygon_shape_2d.cpp +++ b/scene/resources/convex_polygon_shape_2d.cpp @@ -82,7 +82,7 @@ void ConvexPolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) { if (is_collision_outline_enabled()) { RenderingServer::get_singleton()->canvas_item_add_polyline(p_to_rid, points, col); // Draw the last segment as it's not drawn by `canvas_item_add_polyline()`. - RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], p_color); + RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], p_color, 1.0, true); } } diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp index 78698835fc..d92d34437e 100644 --- a/scene/resources/environment.cpp +++ b/scene/resources/environment.cpp @@ -189,6 +189,7 @@ void Environment::_update_ambient_light() { void Environment::set_tonemapper(ToneMapper p_tone_mapper) { tone_mapper = p_tone_mapper; _update_tonemap(); + notify_property_list_changed(); } Environment::ToneMapper Environment::get_tonemapper() const { @@ -1049,6 +1050,10 @@ void Environment::_validate_property(PropertyInfo &property) const { } } + if (property.name == "tonemap_white" && tone_mapper == TONE_MAPPER_LINEAR) { + property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL; + } + if (property.name == "glow_intensity" && glow_blend_mode == GLOW_BLEND_MODE_MIX) { property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL; } @@ -1081,6 +1086,7 @@ void Environment::_validate_property(PropertyInfo &property) const { "auto_exposure_", "ssr_", "ssao_", + "ssil_", "sdfgi_", "glow_", "adjustment_", diff --git a/scene/resources/font.cpp b/scene/resources/font.cpp index 6e6ee7d3ac..efbe9c93f7 100644 --- a/scene/resources/font.cpp +++ b/scene/resources/font.cpp @@ -740,8 +740,8 @@ Error FontData::load_bitmap_font(const String &p_path) { hinting = TextServer::HINTING_NONE; oversampling = 1.0f; - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_CREATE, vformat(RTR("Cannot open font from file: %s."), p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_CREATE, vformat(RTR("Cannot open font from file: %s."), p_path)); int base_size = 16; int height = 0; diff --git a/scene/resources/importer_mesh.cpp b/scene/resources/importer_mesh.cpp index 30deb5ccd5..60a9200176 100644 --- a/scene/resources/importer_mesh.cpp +++ b/scene/resources/importer_mesh.cpp @@ -419,7 +419,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli continue; } - if (new_index_count <= 0 || (new_index_count >= (index_count * 0.75f))) { + if (new_index_count == 0 || (new_index_count >= (index_count * 0.75f))) { break; } @@ -521,7 +521,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli Vector3 normal = n0 * w + n1 * u + n2 * v; Vector2 orig_uv = ray_uvs[j]; - real_t orig_bary[3] = { 1.0f - orig_uv.x - orig_uv.y, orig_uv.x, orig_uv.y }; + const real_t orig_bary[3] = { 1.0f - orig_uv.x - orig_uv.y, orig_uv.x, orig_uv.y }; for (int k = 0; k < 3; k++) { int idx = orig_tri_id * 3 + k; real_t weight = orig_bary[k]; diff --git a/scene/resources/navigation_mesh.cpp b/scene/resources/navigation_mesh.cpp index 47a87bdea5..552fa84bad 100644 --- a/scene/resources/navigation_mesh.cpp +++ b/scene/resources/navigation_mesh.cpp @@ -388,6 +388,10 @@ Ref<Mesh> NavigationMesh::get_debug_mesh() { debug_mesh = Ref<ArrayMesh>(memnew(ArrayMesh)); + if (!lines.size()) { + return debug_mesh; + } + Array arr; arr.resize(Mesh::ARRAY_MAX); arr[Mesh::ARRAY_VERTEX] = varr; diff --git a/scene/resources/primitive_meshes.cpp b/scene/resources/primitive_meshes.cpp index 781e219f1f..40edc5f198 100644 --- a/scene/resources/primitive_meshes.cpp +++ b/scene/resources/primitive_meshes.cpp @@ -270,6 +270,10 @@ PrimitiveMesh::~PrimitiveMesh() { */ void CapsuleMesh::_create_mesh_array(Array &p_arr) const { + create_mesh_array(p_arr, radius, height, radial_segments, rings); +} + +void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const float height, const int radial_segments, const int rings) { int i, j, prevrow, thisrow, point; float x, y, z, u, v, w; float onethird = 1.0 / 3.0; @@ -481,6 +485,10 @@ CapsuleMesh::CapsuleMesh() {} */ void BoxMesh::_create_mesh_array(Array &p_arr) const { + BoxMesh::create_mesh_array(p_arr, size, subdivide_w, subdivide_h, subdivide_d); +} + +void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int subdivide_h, int subdivide_d) { int i, j, prevrow, thisrow, point; float x, y, z; float onethird = 1.0 / 3.0; @@ -732,6 +740,10 @@ BoxMesh::BoxMesh() {} */ void CylinderMesh::_create_mesh_array(Array &p_arr) const { + create_mesh_array(p_arr, top_radius, bottom_radius, height, radial_segments, rings); +} + +void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments, int rings) { int i, j, prevrow, thisrow, point; float x, y, z, u, v, radius; @@ -1431,6 +1443,10 @@ Vector3 QuadMesh::get_center_offset() const { */ void SphereMesh::_create_mesh_array(Array &p_arr) const { + create_mesh_array(p_arr, radius, height, radial_segments, rings, is_hemisphere); +} + +void SphereMesh::create_mesh_array(Array &p_arr, float radius, float height, int radial_segments, int rings, bool is_hemisphere) { int i, j, prevrow, thisrow, point; float x, y, z; diff --git a/scene/resources/primitive_meshes.h b/scene/resources/primitive_meshes.h index eef5eb3f7d..8cd05c1740 100644 --- a/scene/resources/primitive_meshes.h +++ b/scene/resources/primitive_meshes.h @@ -117,6 +117,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 8); + void set_radius(const float p_radius); float get_radius() const; @@ -149,6 +151,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w = 0, int subdivide_h = 0, int subdivide_d = 0); + void set_size(const Vector3 &p_size); Vector3 get_size() const; @@ -183,6 +187,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments = 64, int rings = 4); + void set_top_radius(const float p_radius); float get_top_radius() const; @@ -314,6 +320,8 @@ protected: virtual void _create_mesh_array(Array &p_arr) const override; public: + static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 32, bool is_hemisphere = false); + void set_radius(const float p_radius); float get_radius() const; diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp index fd6f018651..4b0456681b 100644 --- a/scene/resources/resource_format_text.cpp +++ b/scene/resources/resource_format_text.cpp @@ -738,11 +738,7 @@ void ResourceLoaderText::set_translation_remapped(bool p_remapped) { ResourceLoaderText::ResourceLoaderText() {} -ResourceLoaderText::~ResourceLoaderText() { - memdelete(f); -} - -void ResourceLoaderText::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) { +void ResourceLoaderText::get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types) { open(p_f); ignore_resource_parsing = true; ERR_FAIL_COND(error != OK); @@ -798,13 +794,13 @@ void ResourceLoaderText::get_dependencies(FileAccess *p_f, List<String> *p_depen } } -Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map) { +Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const Map<String, String> &p_map) { open(p_f, true); ERR_FAIL_COND_V(error != OK, error); ignore_resource_parsing = true; //FileAccess - FileAccess *fw = nullptr; + Ref<FileAccess> fw; String base_path = local_path.get_base_dir(); @@ -814,23 +810,20 @@ Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_p Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp); if (err != OK) { - if (fw) { - memdelete(fw); - } error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } if (next_tag.name != "ext_resource") { //nothing was done - if (!fw) { + if (fw.is_null()) { return OK; } break; } else { - if (!fw) { + if (fw.is_null()) { fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE); if (is_scene) { fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n"); @@ -840,7 +833,6 @@ Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_p } if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) { - memdelete(fw); error = ERR_FILE_CORRUPT; ERR_FAIL_V(error); } @@ -898,24 +890,22 @@ Error ResourceLoaderText::rename_dependencies(FileAccess *p_f, const String &p_p fw->store_8(c); c = f->get_8(); } - f->close(); + f.unref(); bool all_ok = fw->get_error() == OK; - memdelete(fw); - if (!all_ok) { return ERR_CANT_CREATE; } - DirAccessRef da = DirAccess::create(DirAccess::ACCESS_RESOURCES); + Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES); da->remove(p_path); da->rename(p_path + ".depren", p_path); return OK; } -void ResourceLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) { +void ResourceLoaderText::open(Ref<FileAccess> p_f, bool p_skip_first_tag) { error = OK; lines = 1; @@ -992,23 +982,23 @@ void ResourceLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) { rp.userdata = this; } -static void bs_save_unicode_string(FileAccess *f, const String &p_string, bool p_bit_on_len = false) { +static void bs_save_unicode_string(Ref<FileAccess> p_f, const String &p_string, bool p_bit_on_len = false) { CharString utf8 = p_string.utf8(); if (p_bit_on_len) { - f->store_32((utf8.length() + 1) | 0x80000000); + p_f->store_32((utf8.length() + 1) | 0x80000000); } else { - f->store_32(utf8.length() + 1); + p_f->store_32(utf8.length() + 1); } - f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); + p_f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1); } -Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) { +Error ResourceLoaderText::save_as_binary(Ref<FileAccess> p_f, const String &p_path) { if (error) { return error; } - FileAccessRef wf = FileAccess::open(p_path, FileAccess::WRITE); - if (!wf) { + Ref<FileAccess> wf = FileAccess::open(p_path, FileAccess::WRITE); + if (wf.is_null()) { return ERR_CANT_OPEN; } @@ -1023,7 +1013,7 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) static const int save_format_version = 3; //use format version 3 for saving wf->store_32(save_format_version); - bs_save_unicode_string(wf.f, is_scene ? "PackedScene" : resource_type); + bs_save_unicode_string(wf, is_scene ? "PackedScene" : resource_type); wf->store_64(0); //offset to import metadata, this is no longer used wf->store_32(ResourceFormatSaverBinaryInstance::FORMAT_FLAG_NAMED_SCENE_IDS | ResourceFormatSaverBinaryInstance::FORMAT_FLAG_UIDS); @@ -1078,8 +1068,8 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) uid = ResourceUID::get_singleton()->text_to_id(uidt); } - bs_save_unicode_string(wf.f, type); - bs_save_unicode_string(wf.f, path); + bs_save_unicode_string(wf, type); + bs_save_unicode_string(wf, path); wf->store_64(uid); int lindex = dummy_read.external_resources.size(); @@ -1108,146 +1098,145 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) wf->store_32(0); //zero sub resources, still parsing them String temp_file = p_path + ".temp"; - FileAccessRef wf2 = FileAccess::open(temp_file, FileAccess::WRITE); - if (!wf2) { - return ERR_CANT_OPEN; - } - Vector<uint64_t> local_offsets; Vector<uint64_t> local_pointers_pos; + { + Ref<FileAccess> wf2 = FileAccess::open(temp_file, FileAccess::WRITE); + if (wf2.is_null()) { + return ERR_CANT_OPEN; + } - while (next_tag.name == "sub_resource" || next_tag.name == "resource") { - String type; - int id = -1; - bool main_res; + while (next_tag.name == "sub_resource" || next_tag.name == "resource") { + String type; + int id = -1; + bool main_res; - if (next_tag.name == "sub_resource") { - if (!next_tag.fields.has("type")) { - error = ERR_FILE_CORRUPT; - error_text = "Missing 'type' in external resource tag"; - _printerr(); - return error; - } + if (next_tag.name == "sub_resource") { + if (!next_tag.fields.has("type")) { + error = ERR_FILE_CORRUPT; + error_text = "Missing 'type' in external resource tag"; + _printerr(); + return error; + } - if (!next_tag.fields.has("id")) { - error = ERR_FILE_CORRUPT; - error_text = "Missing 'id' in external resource tag"; - _printerr(); - return error; + if (!next_tag.fields.has("id")) { + error = ERR_FILE_CORRUPT; + error_text = "Missing 'id' in external resource tag"; + _printerr(); + return error; + } + + type = next_tag.fields["type"]; + id = next_tag.fields["id"]; + main_res = false; + } else { + type = res_type; + id = 0; //used for last anyway + main_res = true; } - type = next_tag.fields["type"]; - id = next_tag.fields["id"]; - main_res = false; - } else { - type = res_type; - id = 0; //used for last anyway - main_res = true; - } + local_offsets.push_back(wf2->get_position()); - local_offsets.push_back(wf2->get_position()); + bs_save_unicode_string(wf, "local://" + itos(id)); + local_pointers_pos.push_back(wf->get_position()); + wf->store_64(0); //temp local offset - bs_save_unicode_string(wf, "local://" + itos(id)); - local_pointers_pos.push_back(wf->get_position()); - wf->store_64(0); //temp local offset + bs_save_unicode_string(wf2, type); + uint64_t propcount_ofs = wf2->get_position(); + wf2->store_32(0); - bs_save_unicode_string(wf2, type); - uint64_t propcount_ofs = wf2->get_position(); - wf2->store_32(0); + int prop_count = 0; - int prop_count = 0; + while (true) { + String assign; + Variant value; - while (true) { - String assign; - Variant value; + error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp); - error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp); + if (error) { + if (main_res && error == ERR_FILE_EOF) { + next_tag.name = ""; //exit + break; + } - if (error) { - if (main_res && error == ERR_FILE_EOF) { - next_tag.name = ""; //exit - break; + _printerr(); + return error; } - _printerr(); - return error; + if (!assign.is_empty()) { + Map<StringName, int> empty_string_map; //unused + bs_save_unicode_string(wf2, assign, true); + ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); + prop_count++; + + } else if (!next_tag.name.is_empty()) { + error = OK; + break; + } else { + error = ERR_FILE_CORRUPT; + error_text = "Premature end of file while parsing [sub_resource]"; + _printerr(); + return error; + } } - if (!assign.is_empty()) { - Map<StringName, int> empty_string_map; //unused - bs_save_unicode_string(wf2, assign, true); - ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); - prop_count++; + wf2->seek(propcount_ofs); + wf2->store_32(prop_count); + wf2->seek_end(); + } - } else if (!next_tag.name.is_empty()) { - error = OK; - break; - } else { - error = ERR_FILE_CORRUPT; - error_text = "Premature end of file while parsing [sub_resource]"; + if (next_tag.name == "node") { + //this is a node, must save one more! + + if (!is_scene) { + error_text += "found the 'node' tag on a resource file!"; _printerr(); + error = ERR_FILE_CORRUPT; return error; } - } - - wf2->seek(propcount_ofs); - wf2->store_32(prop_count); - wf2->seek_end(); - } - if (next_tag.name == "node") { - //this is a node, must save one more! + Ref<PackedScene> packed_scene = _parse_node_tag(rp); - if (!is_scene) { - error_text += "found the 'node' tag on a resource file!"; - _printerr(); - error = ERR_FILE_CORRUPT; - return error; - } + if (!packed_scene.is_valid()) { + return error; + } - Ref<PackedScene> packed_scene = _parse_node_tag(rp); + error = OK; + //get it here + List<PropertyInfo> props; + packed_scene->get_property_list(&props); - if (!packed_scene.is_valid()) { - return error; - } + bs_save_unicode_string(wf, "local://0"); + local_pointers_pos.push_back(wf->get_position()); + wf->store_64(0); //temp local offset - error = OK; - //get it here - List<PropertyInfo> props; - packed_scene->get_property_list(&props); + local_offsets.push_back(wf2->get_position()); + bs_save_unicode_string(wf2, "PackedScene"); + uint64_t propcount_ofs = wf2->get_position(); + wf2->store_32(0); - bs_save_unicode_string(wf, "local://0"); - local_pointers_pos.push_back(wf->get_position()); - wf->store_64(0); //temp local offset + int prop_count = 0; - local_offsets.push_back(wf2->get_position()); - bs_save_unicode_string(wf2, "PackedScene"); - uint64_t propcount_ofs = wf2->get_position(); - wf2->store_32(0); + for (const PropertyInfo &E : props) { + if (!(E.usage & PROPERTY_USAGE_STORAGE)) { + continue; + } - int prop_count = 0; + String name = E.name; + Variant value = packed_scene->get(name); - for (const PropertyInfo &E : props) { - if (!(E.usage & PROPERTY_USAGE_STORAGE)) { - continue; + Map<StringName, int> empty_string_map; //unused + bs_save_unicode_string(wf2, name, true); + ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); + prop_count++; } - String name = E.name; - Variant value = packed_scene->get(name); - - Map<StringName, int> empty_string_map; //unused - bs_save_unicode_string(wf2, name, true); - ResourceFormatSaverBinaryInstance::write_variant(wf2, value, dummy_read.resource_index_map, dummy_read.external_resources, empty_string_map); - prop_count++; + wf2->seek(propcount_ofs); + wf2->store_32(prop_count); + wf2->seek_end(); } - - wf2->seek(propcount_ofs); - wf2->store_32(prop_count); - wf2->seek_end(); } - wf2->close(); - uint64_t offset_from = wf->get_position(); wf->seek(sub_res_count_pos); //plus one because the saved one wf->store_32(local_offsets.size()); @@ -1262,18 +1251,16 @@ Error ResourceLoaderText::save_as_binary(FileAccess *p_f, const String &p_path) Vector<uint8_t> data = FileAccess::get_file_as_array(temp_file); wf->store_buffer(data.ptr(), data.size()); { - DirAccessRef dar = DirAccess::open(temp_file.get_base_dir()); + Ref<DirAccess> dar = DirAccess::open(temp_file.get_base_dir()); dar->remove(temp_file); } wf->store_buffer((const uint8_t *)"RSRC", 4); //magic at end - wf->close(); - return OK; } -String ResourceLoaderText::recognize(FileAccess *p_f) { +String ResourceLoaderText::recognize(Ref<FileAccess> p_f) { error = OK; lines = 1; @@ -1317,7 +1304,7 @@ String ResourceLoaderText::recognize(FileAccess *p_f) { return tag.fields["type"]; } -ResourceUID::ID ResourceLoaderText::get_uid(FileAccess *p_f) { +ResourceUID::ID ResourceLoaderText::get_uid(Ref<FileAccess> p_f) { error = OK; lines = 1; @@ -1352,7 +1339,7 @@ RES ResourceFormatLoaderText::load(const String &p_path, const String &p_origina Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot open file '" + p_path + "'."); @@ -1407,8 +1394,8 @@ String ResourceFormatLoaderText::get_resource_type(const String &p_path) const { // ...for anything else must test... - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { return ""; //could not read } @@ -1426,8 +1413,8 @@ ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) return ResourceUID::INVALID_ID; } - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { return ResourceUID::INVALID_ID; //could not read } @@ -1438,8 +1425,8 @@ ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) } void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { ERR_FAIL(); } @@ -1450,8 +1437,8 @@ void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<Strin } Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const Map<String, String> &p_map) { - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + if (f.is_null()) { ERR_FAIL_V(ERR_CANT_OPEN); } @@ -1465,7 +1452,7 @@ ResourceFormatLoaderText *ResourceFormatLoaderText::singleton = nullptr; Error ResourceFormatLoaderText::convert_file_to_binary(const String &p_src_path, const String &p_dst_path) { Error err; - FileAccess *f = FileAccess::open(p_src_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_src_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_OPEN, "Cannot open file '" + p_src_path + "'."); @@ -1489,7 +1476,7 @@ Error ResourceFormatLoaderText::convert_file_to_binary(const String &p_src_path, /*****************************************************************************************************/ String ResourceFormatSaverTextInstance::_write_resources(void *ud, const RES &p_resource) { - ResourceFormatSaverTextInstance *rsi = (ResourceFormatSaverTextInstance *)ud; + ResourceFormatSaverTextInstance *rsi = static_cast<ResourceFormatSaverTextInstance *>(ud); return rsi->_write_resource(p_resource); } @@ -1603,9 +1590,9 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_r } Error err; - f = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err, ERR_CANT_OPEN, "Cannot save file '" + p_path + "'."); - FileAccessRef _fref(f); + Ref<FileAccess> _fref(f); local_path = ProjectSettings::get_singleton()->localize_path(p_path); @@ -1942,12 +1929,9 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_r } if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) { - f->close(); return ERR_CANT_CREATE; } - f->close(); - return OK; } diff --git a/scene/resources/resource_format_text.h b/scene/resources/resource_format_text.h index 9585b9040f..c6543e616d 100644 --- a/scene/resources/resource_format_text.h +++ b/scene/resources/resource_format_text.h @@ -43,7 +43,7 @@ class ResourceLoaderText { String res_path; String error_text; - FileAccess *f = nullptr; + Ref<FileAccess> f; VariantParser::StreamFile stream; @@ -96,8 +96,8 @@ class ResourceLoaderText { Map<String, RES> resource_map; }; - static Error _parse_sub_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_sub_resource_dummy((DummyReadData *)(p_self), p_stream, r_res, line, r_err_str); } - static Error _parse_ext_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_ext_resource_dummy((DummyReadData *)(p_self), p_stream, r_res, line, r_err_str); } + static Error _parse_sub_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_sub_resource_dummy(static_cast<DummyReadData *>(p_self), p_stream, r_res, line, r_err_str); } + static Error _parse_ext_resource_dummys(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return _parse_ext_resource_dummy(static_cast<DummyReadData *>(p_self), p_stream, r_res, line, r_err_str); } static Error _parse_sub_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str); static Error _parse_ext_resource_dummy(DummyReadData *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str); @@ -120,15 +120,14 @@ public: int get_stage_count() const; void set_translation_remapped(bool p_remapped); - void open(FileAccess *p_f, bool p_skip_first_tag = false); - String recognize(FileAccess *p_f); - ResourceUID::ID get_uid(FileAccess *p_f); - void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types); - Error rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map); + void open(Ref<FileAccess> p_f, bool p_skip_first_tag = false); + String recognize(Ref<FileAccess> p_f); + ResourceUID::ID get_uid(Ref<FileAccess> p_f); + void get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types); + Error rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const Map<String, String> &p_map); - Error save_as_binary(FileAccess *p_f, const String &p_path); + Error save_as_binary(Ref<FileAccess> p_f, const String &p_path); ResourceLoaderText(); - ~ResourceLoaderText(); }; class ResourceFormatLoaderText : public ResourceFormatLoader { @@ -157,7 +156,6 @@ class ResourceFormatSaverTextInstance { bool relative_paths = false; bool bundle_resources = false; bool skip_editor = false; - FileAccess *f = nullptr; struct NonPersistentKey { //for resource properties generated on the fly RES base; diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp index ce7fcb199d..25a9278e66 100644 --- a/scene/resources/shader.cpp +++ b/scene/resources/shader.cpp @@ -217,17 +217,14 @@ Error ResourceFormatSaverShader::save(const String &p_path, const RES &p_resourc String source = shader->get_code(); Error err; - FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); + Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err); ERR_FAIL_COND_V_MSG(err, err, "Cannot save shader '" + p_path + "'."); file->store_string(source); if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { - memdelete(file); return ERR_CANT_CREATE; } - file->close(); - memdelete(file); return OK; } diff --git a/scene/resources/skeleton_modification_2d.h b/scene/resources/skeleton_modification_2d.h index d49f9e7f51..3b9235ffd8 100644 --- a/scene/resources/skeleton_modification_2d.h +++ b/scene/resources/skeleton_modification_2d.h @@ -49,7 +49,7 @@ class SkeletonModification2D : public Resource { protected: static void _bind_methods(); - SkeletonModificationStack2D *stack; + SkeletonModificationStack2D *stack = nullptr; int execution_mode = 0; // 0 = process bool enabled = true; diff --git a/scene/resources/skeleton_modification_3d.h b/scene/resources/skeleton_modification_3d.h index a81c0c38bd..ab736fcbd2 100644 --- a/scene/resources/skeleton_modification_3d.h +++ b/scene/resources/skeleton_modification_3d.h @@ -44,7 +44,7 @@ class SkeletonModification3D : public Resource { protected: static void _bind_methods(); - SkeletonModificationStack3D *stack; + SkeletonModificationStack3D *stack = nullptr; int execution_mode = 0; // 0 = process bool enabled = true; diff --git a/scene/resources/sky_material.cpp b/scene/resources/sky_material.cpp index 54543782f6..4681d3d6e3 100644 --- a/scene/resources/sky_material.cpp +++ b/scene/resources/sky_material.cpp @@ -404,8 +404,11 @@ void PanoramaSkyMaterial::_update_shader() { // Add a comment to describe the shader origin (useful when converting to ShaderMaterial). RS::get_singleton()->shader_set_code(shader_cache[i], vformat(R"( // NOTE: Shader automatically converted from )" VERSION_NAME " " VERSION_FULL_CONFIG R"('s PanoramaSkyMaterial. + shader_type sky; -uniform sampler2D source_panorama : %s, hint_albedo; + +uniform sampler2D source_panorama : %s, hint_black_albedo; + void sky() { COLOR = texture(source_panorama, SKY_COORDS).rgb; } diff --git a/scene/resources/text_file.cpp b/scene/resources/text_file.cpp index cbfee754e2..96a47c37c4 100644 --- a/scene/resources/text_file.cpp +++ b/scene/resources/text_file.cpp @@ -51,7 +51,7 @@ void TextFile::reload_from_file() { Error TextFile::load_text(const String &p_path) { Vector<uint8_t> sourcef; Error err; - FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ, &err); ERR_FAIL_COND_V_MSG(err, err, "Cannot open TextFile '" + p_path + "'."); @@ -59,8 +59,7 @@ Error TextFile::load_text(const String &p_path) { sourcef.resize(len + 1); uint8_t *w = sourcef.ptrw(); uint64_t r = f->get_buffer(w, len); - f->close(); - memdelete(f); + ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); w[len] = 0; diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp index a66d9d9f27..4c20e07976 100644 --- a/scene/resources/texture.cpp +++ b/scene/resources/texture.cpp @@ -646,7 +646,7 @@ PortableCompressedTexture2D::~PortableCompressedTexture2D() { ////////////////////////////////////////// -Ref<Image> CompressedTexture2D::load_image_from_file(FileAccess *f, int p_size_limit) { +Ref<Image> CompressedTexture2D::load_image_from_file(Ref<FileAccess> f, int p_size_limit) { uint32_t data_format = f->get_32(); uint32_t w = f->get_16(); uint32_t h = f->get_16(); @@ -821,20 +821,18 @@ Error CompressedTexture2D::_load_data(const String &p_path, int &r_width, int &r ERR_FAIL_COND_V(image.is_null(), ERR_INVALID_PARAMETER); - FileAccess *f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); uint8_t header[4]; f->get_buffer(header, 4); if (header[0] != 'G' || header[1] != 'S' || header[2] != 'T' || header[3] != '2') { - memdelete(f); ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Compressed texture file is corrupt (Bad header)."); } uint32_t version = f->get_32(); if (version > FORMAT_VERSION) { - memdelete(f); ERR_FAIL_V_MSG(ERR_FILE_CORRUPT, "Compressed texture file is too new."); } r_width = f->get_32(); @@ -867,8 +865,6 @@ Error CompressedTexture2D::_load_data(const String &p_path, int &r_width, int &r image = load_image_from_file(f, p_size_limit); - memdelete(f); - if (image.is_null() || image->is_empty()) { return ERR_CANT_OPEN; } @@ -1142,7 +1138,7 @@ bool Texture3D::has_mipmaps() const { if (GDVIRTUAL_REQUIRED_CALL(_has_mipmaps, ret)) { return ret; } - return 0; + return false; } Vector<Ref<Image>> Texture3D::get_data() const { @@ -1272,8 +1268,8 @@ Image::Format CompressedTexture3D::get_format() const { } Error CompressedTexture3D::_load_data(const String &p_path, Vector<Ref<Image>> &r_data, Image::Format &r_format, int &r_width, int &r_height, int &r_depth, bool &r_mipmaps) { - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); uint8_t header[4]; f->get_buffer(header, 4); @@ -3092,8 +3088,8 @@ Image::Format CompressedTextureLayered::get_format() const { Error CompressedTextureLayered::_load_data(const String &p_path, Vector<Ref<Image>> &images, int &mipmap_limit, int p_size_limit) { ERR_FAIL_COND_V(images.size() != 0, ERR_INVALID_PARAMETER); - FileAccessRef f = FileAccess::open(p_path, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!f, ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); + Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ); + ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Unable to open file: %s.", p_path)); uint8_t header[4]; f->get_buffer(header, 4); diff --git a/scene/resources/texture.h b/scene/resources/texture.h index 7e194fd21d..525e3ff979 100644 --- a/scene/resources/texture.h +++ b/scene/resources/texture.h @@ -253,7 +253,7 @@ protected: void _validate_property(PropertyInfo &property) const override; public: - static Ref<Image> load_image_from_file(FileAccess *p_file, int p_size_limit); + static Ref<Image> load_image_from_file(Ref<FileAccess> p_file, int p_size_limit); typedef void (*TextureFormatRequestCallback)(const Ref<CompressedTexture2D> &); typedef void (*TextureFormatRoughnessRequestCallback)(const Ref<CompressedTexture2D> &, const String &p_normal_path, RS::TextureDetectRoughnessChannel p_roughness_channel); diff --git a/servers/audio/audio_driver_dummy.cpp b/servers/audio/audio_driver_dummy.cpp index 1ba0afd8a1..635e4601c7 100644 --- a/servers/audio/audio_driver_dummy.cpp +++ b/servers/audio/audio_driver_dummy.cpp @@ -54,7 +54,7 @@ Error AudioDriverDummy::init() { }; void AudioDriverDummy::thread_func(void *p_udata) { - AudioDriverDummy *ad = (AudioDriverDummy *)p_udata; + AudioDriverDummy *ad = static_cast<AudioDriverDummy *>(p_udata); uint64_t usdelay = (ad->buffer_frames / float(ad->mix_rate)) * 1000000; diff --git a/servers/audio/audio_driver_dummy.h b/servers/audio/audio_driver_dummy.h index 6324e2f5d3..68b523e086 100644 --- a/servers/audio/audio_driver_dummy.h +++ b/servers/audio/audio_driver_dummy.h @@ -40,7 +40,7 @@ class AudioDriverDummy : public AudioDriver { Thread thread; Mutex mutex; - int32_t *samples_in; + int32_t *samples_in = nullptr; static void thread_func(void *p_udata); diff --git a/servers/audio/audio_filter_sw.h b/servers/audio/audio_filter_sw.h index 9e55662d0a..1ec1abd4d5 100644 --- a/servers/audio/audio_filter_sw.h +++ b/servers/audio/audio_filter_sw.h @@ -57,7 +57,7 @@ public: class Processor { // simple filter processor - AudioFilterSW *filter; + AudioFilterSW *filter = nullptr; Coeffs coeffs; float ha1, ha2, hb1, hb2; //history Coeffs incr_coeffs; diff --git a/servers/audio/audio_rb_resampler.h b/servers/audio/audio_rb_resampler.h index 3fbe684c3e..81ac6332e2 100644 --- a/servers/audio/audio_rb_resampler.h +++ b/servers/audio/audio_rb_resampler.h @@ -55,8 +55,8 @@ struct AudioRBResampler { MIX_FRAC_MASK = MIX_FRAC_LEN - 1, }; - float *read_buf; - float *rb; + float *read_buf = nullptr; + float *rb = nullptr; template <int C> uint32_t _resample(AudioFrame *p_dest, int p_todo, int32_t p_increment); diff --git a/servers/audio/effects/audio_effect_record.cpp b/servers/audio/effects/audio_effect_record.cpp index 0069f6ad85..d68522e5b9 100644 --- a/servers/audio/effects/audio_effect_record.cpp +++ b/servers/audio/effects/audio_effect_record.cpp @@ -62,7 +62,7 @@ void AudioEffectRecordInstance::_update_buffer() { } void AudioEffectRecordInstance::_update(void *userdata) { - AudioEffectRecordInstance *ins = (AudioEffectRecordInstance *)userdata; + AudioEffectRecordInstance *ins = static_cast<AudioEffectRecordInstance *>(userdata); ins->_update_buffer(); } diff --git a/servers/audio/effects/audio_effect_stereo_enhance.h b/servers/audio/effects/audio_effect_stereo_enhance.h index 8b8b7b47a0..1f93d1cf9f 100644 --- a/servers/audio/effects/audio_effect_stereo_enhance.h +++ b/servers/audio/effects/audio_effect_stereo_enhance.h @@ -44,7 +44,7 @@ class AudioEffectStereoEnhanceInstance : public AudioEffectInstance { MAX_DELAY_MS = 50 }; - float *delay_ringbuff; + float *delay_ringbuff = nullptr; unsigned int ringbuff_pos; unsigned int ringbuff_mask; diff --git a/servers/audio/effects/audio_stream_generator.h b/servers/audio/effects/audio_stream_generator.h index 51288262b3..2ce4b95fcf 100644 --- a/servers/audio/effects/audio_stream_generator.h +++ b/servers/audio/effects/audio_stream_generator.h @@ -65,7 +65,7 @@ class AudioStreamGeneratorPlayback : public AudioStreamPlaybackResampled { int skips; bool active; float mixed; - AudioStreamGenerator *generator; + AudioStreamGenerator *generator = nullptr; protected: virtual int _mix_internal(AudioFrame *p_buffer, int p_frames) override; diff --git a/servers/audio/effects/reverb.h b/servers/audio/effects/reverb.h index ff59ab8d82..de25e8c52b 100644 --- a/servers/audio/effects/reverb.h +++ b/servers/audio/effects/reverb.h @@ -75,7 +75,7 @@ private: Comb comb[MAX_COMBS]; AllPass allpass[MAX_ALLPASS]; - float *input_buffer; + float *input_buffer = nullptr; float *echo_buffer = nullptr; int echo_buffer_size; int echo_buffer_pos; diff --git a/servers/audio_server.h b/servers/audio_server.h index 0c150427f2..5563d60e4a 100644 --- a/servers/audio_server.h +++ b/servers/audio_server.h @@ -284,7 +284,7 @@ private: struct CallbackItem { AudioCallback callback; - void *userdata; + void *userdata = nullptr; }; SafeList<CallbackItem *> update_callback_list; diff --git a/servers/extensions/physics_server_3d_extension.h b/servers/extensions/physics_server_3d_extension.h index 77e867a05a..ce6bed41c9 100644 --- a/servers/extensions/physics_server_3d_extension.h +++ b/servers/extensions/physics_server_3d_extension.h @@ -193,7 +193,7 @@ typedef PhysicsServer3D::MotionCollision PhysicsServer3DExtensionMotionCollision typedef PhysicsServer3D::MotionResult PhysicsServer3DExtensionMotionResult; struct PhysicsServer3DExtensionStateCallback { - void *instance; + void *instance = nullptr; void (*callback)(void *p_instance, PhysicsDirectBodyState3D *p_state); }; diff --git a/servers/navigation_server_2d.cpp b/servers/navigation_server_2d.cpp index ee196673a3..0fef416680 100644 --- a/servers/navigation_server_2d.cpp +++ b/servers/navigation_server_2d.cpp @@ -193,7 +193,7 @@ void NavigationServer2D::_bind_methods() { ClassDB::bind_method(D_METHOD("agent_is_map_changed", "agent"), &NavigationServer2D::agent_is_map_changed); ClassDB::bind_method(D_METHOD("agent_set_callback", "agent", "receiver", "method", "userdata"), &NavigationServer2D::agent_set_callback, DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("free", "object"), &NavigationServer2D::free); + ClassDB::bind_method(D_METHOD("free_rid", "rid"), &NavigationServer2D::free); ADD_SIGNAL(MethodInfo("map_changed", PropertyInfo(Variant::RID, "map"))); } diff --git a/servers/navigation_server_3d.cpp b/servers/navigation_server_3d.cpp index d18777869a..46192772f6 100644 --- a/servers/navigation_server_3d.cpp +++ b/servers/navigation_server_3d.cpp @@ -72,7 +72,7 @@ void NavigationServer3D::_bind_methods() { ClassDB::bind_method(D_METHOD("agent_is_map_changed", "agent"), &NavigationServer3D::agent_is_map_changed); ClassDB::bind_method(D_METHOD("agent_set_callback", "agent", "receiver", "method", "userdata"), &NavigationServer3D::agent_set_callback, DEFVAL(Variant())); - ClassDB::bind_method(D_METHOD("free", "object"), &NavigationServer3D::free); + ClassDB::bind_method(D_METHOD("free_rid", "rid"), &NavigationServer3D::free); ClassDB::bind_method(D_METHOD("set_active", "active"), &NavigationServer3D::set_active); ClassDB::bind_method(D_METHOD("process", "delta_time"), &NavigationServer3D::process); diff --git a/servers/physics_2d/godot_area_2d.h b/servers/physics_2d/godot_area_2d.h index 6e8078909b..dadd9747b1 100644 --- a/servers/physics_2d/godot_area_2d.h +++ b/servers/physics_2d/godot_area_2d.h @@ -96,7 +96,7 @@ class GodotArea2D : public GodotCollisionObject2D { Set<GodotConstraint2D *> constraints; - virtual void _shapes_changed(); + virtual void _shapes_changed() override; void _queue_monitor_update(); void _set_space_override_mode(PhysicsServer2D::AreaSpaceOverrideMode &r_mode, PhysicsServer2D::AreaSpaceOverrideMode p_new_mode); @@ -151,7 +151,7 @@ public: void set_transform(const Transform2D &p_transform); - void set_space(GodotSpace2D *p_space); + void set_space(GodotSpace2D *p_space) override; void call_queries(); diff --git a/servers/physics_2d/godot_body_2d.h b/servers/physics_2d/godot_body_2d.h index 1335a19126..4b87a69d5c 100644 --- a/servers/physics_2d/godot_body_2d.h +++ b/servers/physics_2d/godot_body_2d.h @@ -103,7 +103,7 @@ class GodotBody2D : public GodotCollisionObject2D { bool can_sleep = true; bool first_time_kinematic = false; void _mass_properties_changed(); - virtual void _shapes_changed(); + virtual void _shapes_changed() override; Transform2D new_transform; List<Pair<GodotConstraint2D *, int>> constraint_list; @@ -302,7 +302,7 @@ public: _FORCE_INLINE_ void set_continuous_collision_detection_mode(PhysicsServer2D::CCDMode p_mode) { continuous_cd_mode = p_mode; } _FORCE_INLINE_ PhysicsServer2D::CCDMode get_continuous_collision_detection_mode() const { return continuous_cd_mode; } - void set_space(GodotSpace2D *p_space); + void set_space(GodotSpace2D *p_space) override; void update_mass_properties(); void reset_mass_properties(); diff --git a/servers/physics_2d/godot_body_pair_2d.cpp b/servers/physics_2d/godot_body_pair_2d.cpp index 2bf1e5a1d4..6e76697a1b 100644 --- a/servers/physics_2d/godot_body_pair_2d.cpp +++ b/servers/physics_2d/godot_body_pair_2d.cpp @@ -39,7 +39,7 @@ #define MAX_BIAS_ROTATION (Math_PI / 8) void GodotBodyPair2D::_add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self) { - GodotBodyPair2D *self = (GodotBodyPair2D *)p_self; + GodotBodyPair2D *self = static_cast<GodotBodyPair2D *>(p_self); self->_contact_added_callback(p_point_A, p_point_B); } diff --git a/servers/physics_2d/godot_broad_phase_2d_bvh.cpp b/servers/physics_2d/godot_broad_phase_2d_bvh.cpp index 2cc60fc765..c545fec113 100644 --- a/servers/physics_2d/godot_broad_phase_2d_bvh.cpp +++ b/servers/physics_2d/godot_broad_phase_2d_bvh.cpp @@ -82,7 +82,7 @@ int GodotBroadPhase2DBVH::cull_aabb(const Rect2 &p_aabb, GodotCollisionObject2D } void *GodotBroadPhase2DBVH::_pair_callback(void *self, uint32_t p_A, GodotCollisionObject2D *p_object_A, int subindex_A, uint32_t p_B, GodotCollisionObject2D *p_object_B, int subindex_B) { - GodotBroadPhase2DBVH *bpo = (GodotBroadPhase2DBVH *)(self); + GodotBroadPhase2DBVH *bpo = static_cast<GodotBroadPhase2DBVH *>(self); if (!bpo->pair_callback) { return nullptr; } @@ -91,7 +91,7 @@ void *GodotBroadPhase2DBVH::_pair_callback(void *self, uint32_t p_A, GodotCollis } void GodotBroadPhase2DBVH::_unpair_callback(void *self, uint32_t p_A, GodotCollisionObject2D *p_object_A, int subindex_A, uint32_t p_B, GodotCollisionObject2D *p_object_B, int subindex_B, void *pairdata) { - GodotBroadPhase2DBVH *bpo = (GodotBroadPhase2DBVH *)(self); + GodotBroadPhase2DBVH *bpo = static_cast<GodotBroadPhase2DBVH *>(self); if (!bpo->unpair_callback) { return; } diff --git a/servers/physics_2d/godot_broad_phase_2d_bvh.h b/servers/physics_2d/godot_broad_phase_2d_bvh.h index b11ad0e75e..512111f948 100644 --- a/servers/physics_2d/godot_broad_phase_2d_bvh.h +++ b/servers/physics_2d/godot_broad_phase_2d_bvh.h @@ -77,22 +77,22 @@ class GodotBroadPhase2DBVH : public GodotBroadPhase2D { public: // 0 is an invalid ID - virtual ID create(GodotCollisionObject2D *p_object, int p_subindex = 0, const Rect2 &p_aabb = Rect2(), bool p_static = false); - virtual void move(ID p_id, const Rect2 &p_aabb); - virtual void set_static(ID p_id, bool p_static); - virtual void remove(ID p_id); + virtual ID create(GodotCollisionObject2D *p_object, int p_subindex = 0, const Rect2 &p_aabb = Rect2(), bool p_static = false) override; + virtual void move(ID p_id, const Rect2 &p_aabb) override; + virtual void set_static(ID p_id, bool p_static) override; + virtual void remove(ID p_id) override; - virtual GodotCollisionObject2D *get_object(ID p_id) const; - virtual bool is_static(ID p_id) const; - virtual int get_subindex(ID p_id) const; + virtual GodotCollisionObject2D *get_object(ID p_id) const override; + virtual bool is_static(ID p_id) const override; + virtual int get_subindex(ID p_id) const override; - virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, GodotCollisionObject2D **p_results, int p_max_results, int *p_result_indices = nullptr); - virtual int cull_aabb(const Rect2 &p_aabb, GodotCollisionObject2D **p_results, int p_max_results, int *p_result_indices = nullptr); + virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, GodotCollisionObject2D **p_results, int p_max_results, int *p_result_indices = nullptr) override; + virtual int cull_aabb(const Rect2 &p_aabb, GodotCollisionObject2D **p_results, int p_max_results, int *p_result_indices = nullptr) override; - virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata); - virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata); + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata) override; + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) override; - virtual void update(); + virtual void update() override; static GodotBroadPhase2D *_create(); GodotBroadPhase2DBVH(); diff --git a/servers/physics_2d/godot_collision_object_2d.h b/servers/physics_2d/godot_collision_object_2d.h index 19d6e91561..1a683a7b0f 100644 --- a/servers/physics_2d/godot_collision_object_2d.h +++ b/servers/physics_2d/godot_collision_object_2d.h @@ -104,7 +104,7 @@ public: _FORCE_INLINE_ void set_canvas_instance_id(const ObjectID &p_canvas_instance_id) { canvas_instance_id = p_canvas_instance_id; } _FORCE_INLINE_ ObjectID get_canvas_instance_id() const { return canvas_instance_id; } - void _shape_changed(); + void _shape_changed() override; _FORCE_INLINE_ Type get_type() const { return type; } void add_shape(GodotShape2D *p_shape, const Transform2D &p_transform = Transform2D(), bool p_disabled = false); @@ -166,7 +166,7 @@ public: } _FORCE_INLINE_ uint32_t get_collision_layer() const { return collision_layer; } - void remove_shape(GodotShape2D *p_shape); + void remove_shape(GodotShape2D *p_shape) override; void remove_shape(int p_index); virtual void set_space(GodotSpace2D *p_space) = 0; diff --git a/servers/physics_2d/godot_collision_solver_2d.cpp b/servers/physics_2d/godot_collision_solver_2d.cpp index 263d6d939f..383c6a915c 100644 --- a/servers/physics_2d/godot_collision_solver_2d.cpp +++ b/servers/physics_2d/godot_collision_solver_2d.cpp @@ -150,7 +150,7 @@ struct _ConcaveCollisionInfo2D { }; bool GodotCollisionSolver2D::concave_callback(void *p_userdata, GodotShape2D *p_convex) { - _ConcaveCollisionInfo2D &cinfo = *(_ConcaveCollisionInfo2D *)(p_userdata); + _ConcaveCollisionInfo2D &cinfo = *(static_cast<_ConcaveCollisionInfo2D *>(p_userdata)); cinfo.aabb_tests++; bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, cinfo.motion_A, p_convex, *cinfo.transform_B, cinfo.motion_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, cinfo.sep_axis, cinfo.margin_A, cinfo.margin_B); diff --git a/servers/physics_2d/godot_physics_server_2d.cpp b/servers/physics_2d/godot_physics_server_2d.cpp index a9b499c6b5..650a95c914 100644 --- a/servers/physics_2d/godot_physics_server_2d.cpp +++ b/servers/physics_2d/godot_physics_server_2d.cpp @@ -144,7 +144,7 @@ real_t GodotPhysicsServer2D::shape_get_custom_solver_bias(RID p_shape) const { } void GodotPhysicsServer2D::_shape_col_cbk(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) { - CollCbkData *cbk = (CollCbkData *)p_userdata; + CollCbkData *cbk = static_cast<CollCbkData *>(p_userdata); if (cbk->max == 0) { return; @@ -1212,7 +1212,7 @@ void GodotPhysicsServer2D::free(RID p_rid) { GodotSpace2D *space = space_owner.get_or_null(p_rid); while (space->get_objects().size()) { - GodotCollisionObject2D *co = (GodotCollisionObject2D *)space->get_objects().front()->get(); + GodotCollisionObject2D *co = static_cast<GodotCollisionObject2D *>(space->get_objects().front()->get()); co->set_space(nullptr); } @@ -1251,7 +1251,7 @@ void GodotPhysicsServer2D::step(real_t p_step) { active_objects = 0; collision_pairs = 0; for (Set<const GodotSpace2D *>::Element *E = active_spaces.front(); E; E = E->next()) { - stepper->step((GodotSpace2D *)E->get(), p_step); + stepper->step(const_cast<GodotSpace2D *>(E->get()), p_step); island_count += E->get()->get_island_count(); active_objects += E->get()->get_active_objects(); collision_pairs += E->get()->get_collision_pairs(); @@ -1272,7 +1272,7 @@ void GodotPhysicsServer2D::flush_queries() { uint64_t time_beg = OS::get_singleton()->get_ticks_usec(); for (Set<const GodotSpace2D *>::Element *E = active_spaces.front(); E; E = E->next()) { - GodotSpace2D *space = (GodotSpace2D *)E->get(); + GodotSpace2D *space = const_cast<GodotSpace2D *>(E->get()); space->call_queries(); } diff --git a/servers/physics_2d/godot_shape_2d.cpp b/servers/physics_2d/godot_shape_2d.cpp index b5dbb8a2dd..6c020f9e72 100644 --- a/servers/physics_2d/godot_shape_2d.cpp +++ b/servers/physics_2d/godot_shape_2d.cpp @@ -37,7 +37,7 @@ void GodotShape2D::configure(const Rect2 &p_aabb) { aabb = p_aabb; configured = true; for (const KeyValue<GodotShapeOwner2D *, int> &E : owners) { - GodotShapeOwner2D *co = (GodotShapeOwner2D *)E.key; + GodotShapeOwner2D *co = const_cast<GodotShapeOwner2D *>(E.key); co->_shape_changed(); } } diff --git a/servers/physics_2d/godot_space_2d.cpp b/servers/physics_2d/godot_space_2d.cpp index 99c0566fb1..63e3af1395 100644 --- a/servers/physics_2d/godot_space_2d.cpp +++ b/servers/physics_2d/godot_space_2d.cpp @@ -403,7 +403,7 @@ struct _RestCallbackData2D { }; static void _rest_cbk_result(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) { - _RestCallbackData2D *rd = (_RestCallbackData2D *)p_userdata; + _RestCallbackData2D *rd = static_cast<_RestCallbackData2D *>(p_userdata); Vector2 contact_rel = p_point_B - p_point_A; real_t len = contact_rel.length(); @@ -1005,7 +1005,7 @@ void *GodotSpace2D::_broadphase_pair(GodotCollisionObject2D *A, int p_subindex_A SWAP(type_A, type_B); } - GodotSpace2D *self = (GodotSpace2D *)p_self; + GodotSpace2D *self = static_cast<GodotSpace2D *>(p_self); self->collision_pairs++; if (type_A == GodotCollisionObject2D::TYPE_AREA) { @@ -1021,7 +1021,7 @@ void *GodotSpace2D::_broadphase_pair(GodotCollisionObject2D *A, int p_subindex_A } } else { - GodotBodyPair2D *b = memnew(GodotBodyPair2D((GodotBody2D *)A, p_subindex_A, (GodotBody2D *)B, p_subindex_B)); + GodotBodyPair2D *b = memnew(GodotBodyPair2D(static_cast<GodotBody2D *>(A), p_subindex_A, static_cast<GodotBody2D *>(B), p_subindex_B)); return b; } diff --git a/servers/physics_2d/godot_step_2d.cpp b/servers/physics_2d/godot_step_2d.cpp index 866c415440..fd72038be3 100644 --- a/servers/physics_2d/godot_step_2d.cpp +++ b/servers/physics_2d/godot_step_2d.cpp @@ -47,7 +47,7 @@ void GodotStep2D::_populate_island(GodotBody2D *p_body, LocalVector<GodotBody2D } for (const Pair<GodotConstraint2D *, int> &E : p_body->get_constraint_list()) { - GodotConstraint2D *constraint = (GodotConstraint2D *)E.first; + GodotConstraint2D *constraint = const_cast<GodotConstraint2D *>(E.first); if (constraint->get_island_step() == _step) { continue; // Already processed. } diff --git a/servers/physics_3d/godot_area_3d.h b/servers/physics_3d/godot_area_3d.h index ce64fc802a..d15f8ec0a6 100644 --- a/servers/physics_3d/godot_area_3d.h +++ b/servers/physics_3d/godot_area_3d.h @@ -102,7 +102,7 @@ class GodotArea3D : public GodotCollisionObject3D { Set<GodotConstraint3D *> constraints; - virtual void _shapes_changed(); + virtual void _shapes_changed() override; void _queue_monitor_update(); void _set_space_override_mode(PhysicsServer3D::AreaSpaceOverrideMode &r_mode, PhysicsServer3D::AreaSpaceOverrideMode p_new_mode); @@ -172,7 +172,7 @@ public: void set_transform(const Transform3D &p_transform); - void set_space(GodotSpace3D *p_space); + void set_space(GodotSpace3D *p_space) override; void call_queries(); diff --git a/servers/physics_3d/godot_area_pair_3d.h b/servers/physics_3d/godot_area_pair_3d.h index c416477204..64b43a3b51 100644 --- a/servers/physics_3d/godot_area_pair_3d.h +++ b/servers/physics_3d/godot_area_pair_3d.h @@ -37,8 +37,8 @@ #include "godot_soft_body_3d.h" class GodotAreaPair3D : public GodotConstraint3D { - GodotBody3D *body; - GodotArea3D *area; + GodotBody3D *body = nullptr; + GodotArea3D *area = nullptr; int body_shape; int area_shape; bool colliding = false; @@ -55,8 +55,8 @@ public: }; class GodotArea2Pair3D : public GodotConstraint3D { - GodotArea3D *area_a; - GodotArea3D *area_b; + GodotArea3D *area_a = nullptr; + GodotArea3D *area_b = nullptr; int shape_a; int shape_b; bool colliding_a = false; @@ -76,8 +76,8 @@ public: }; class GodotAreaSoftBodyPair3D : public GodotConstraint3D { - GodotSoftBody3D *soft_body; - GodotArea3D *area; + GodotSoftBody3D *soft_body = nullptr; + GodotArea3D *area = nullptr; int soft_body_shape; int area_shape; bool colliding = false; diff --git a/servers/physics_3d/godot_body_3d.h b/servers/physics_3d/godot_body_3d.h index 1906e8aab1..c0c847d920 100644 --- a/servers/physics_3d/godot_body_3d.h +++ b/servers/physics_3d/godot_body_3d.h @@ -109,7 +109,7 @@ class GodotBody3D : public GodotCollisionObject3D { bool first_time_kinematic = false; void _mass_properties_changed(); - virtual void _shapes_changed(); + virtual void _shapes_changed() override; Transform3D new_transform; Map<GodotConstraint3D *, int> constraint_map; @@ -301,7 +301,7 @@ public: _FORCE_INLINE_ void set_continuous_collision_detection(bool p_enable) { continuous_cd = p_enable; } _FORCE_INLINE_ bool is_continuous_collision_detection_enabled() const { return continuous_cd; } - void set_space(GodotSpace3D *p_space); + void set_space(GodotSpace3D *p_space) override; void update_mass_properties(); void reset_mass_properties(); diff --git a/servers/physics_3d/godot_body_pair_3d.cpp b/servers/physics_3d/godot_body_pair_3d.cpp index 89d5d59161..eebbe0196d 100644 --- a/servers/physics_3d/godot_body_pair_3d.cpp +++ b/servers/physics_3d/godot_body_pair_3d.cpp @@ -39,7 +39,7 @@ #define MAX_BIAS_ROTATION (Math_PI / 8) void GodotBodyPair3D::_contact_added_callback(const Vector3 &p_point_A, int p_index_A, const Vector3 &p_point_B, int p_index_B, void *p_userdata) { - GodotBodyPair3D *pair = (GodotBodyPair3D *)p_userdata; + GodotBodyPair3D *pair = static_cast<GodotBodyPair3D *>(p_userdata); pair->contact_added_callback(p_point_A, p_index_A, p_point_B, p_index_B); } @@ -562,7 +562,7 @@ GodotBodyPair3D::~GodotBodyPair3D() { } void GodotBodySoftBodyPair3D::_contact_added_callback(const Vector3 &p_point_A, int p_index_A, const Vector3 &p_point_B, int p_index_B, void *p_userdata) { - GodotBodySoftBodyPair3D *pair = (GodotBodySoftBodyPair3D *)p_userdata; + GodotBodySoftBodyPair3D *pair = static_cast<GodotBodySoftBodyPair3D *>(p_userdata); pair->contact_added_callback(p_point_A, p_index_A, p_point_B, p_index_B); } diff --git a/servers/physics_3d/godot_broad_phase_3d_bvh.cpp b/servers/physics_3d/godot_broad_phase_3d_bvh.cpp index b34f9d214f..435c1e8aec 100644 --- a/servers/physics_3d/godot_broad_phase_3d_bvh.cpp +++ b/servers/physics_3d/godot_broad_phase_3d_bvh.cpp @@ -87,7 +87,7 @@ int GodotBroadPhase3DBVH::cull_aabb(const AABB &p_aabb, GodotCollisionObject3D * } void *GodotBroadPhase3DBVH::_pair_callback(void *self, uint32_t p_A, GodotCollisionObject3D *p_object_A, int subindex_A, uint32_t p_B, GodotCollisionObject3D *p_object_B, int subindex_B) { - GodotBroadPhase3DBVH *bpo = (GodotBroadPhase3DBVH *)(self); + GodotBroadPhase3DBVH *bpo = static_cast<GodotBroadPhase3DBVH *>(self); if (!bpo->pair_callback) { return nullptr; } @@ -96,7 +96,7 @@ void *GodotBroadPhase3DBVH::_pair_callback(void *self, uint32_t p_A, GodotCollis } void GodotBroadPhase3DBVH::_unpair_callback(void *self, uint32_t p_A, GodotCollisionObject3D *p_object_A, int subindex_A, uint32_t p_B, GodotCollisionObject3D *p_object_B, int subindex_B, void *pairdata) { - GodotBroadPhase3DBVH *bpo = (GodotBroadPhase3DBVH *)(self); + GodotBroadPhase3DBVH *bpo = static_cast<GodotBroadPhase3DBVH *>(self); if (!bpo->unpair_callback) { return; } diff --git a/servers/physics_3d/godot_broad_phase_3d_bvh.h b/servers/physics_3d/godot_broad_phase_3d_bvh.h index 7660030195..ae5a18d955 100644 --- a/servers/physics_3d/godot_broad_phase_3d_bvh.h +++ b/servers/physics_3d/godot_broad_phase_3d_bvh.h @@ -75,23 +75,23 @@ class GodotBroadPhase3DBVH : public GodotBroadPhase3D { public: // 0 is an invalid ID - virtual ID create(GodotCollisionObject3D *p_object, int p_subindex = 0, const AABB &p_aabb = AABB(), bool p_static = false); - virtual void move(ID p_id, const AABB &p_aabb); - virtual void set_static(ID p_id, bool p_static); - virtual void remove(ID p_id); + virtual ID create(GodotCollisionObject3D *p_object, int p_subindex = 0, const AABB &p_aabb = AABB(), bool p_static = false) override; + virtual void move(ID p_id, const AABB &p_aabb) override; + virtual void set_static(ID p_id, bool p_static) override; + virtual void remove(ID p_id) override; - virtual GodotCollisionObject3D *get_object(ID p_id) const; - virtual bool is_static(ID p_id) const; - virtual int get_subindex(ID p_id) const; + virtual GodotCollisionObject3D *get_object(ID p_id) const override; + virtual bool is_static(ID p_id) const override; + virtual int get_subindex(ID p_id) const override; - virtual int cull_point(const Vector3 &p_point, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices = nullptr); - virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices = nullptr); - virtual int cull_aabb(const AABB &p_aabb, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices = nullptr); + virtual int cull_point(const Vector3 &p_point, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices = nullptr) override; + virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices = nullptr) override; + virtual int cull_aabb(const AABB &p_aabb, GodotCollisionObject3D **p_results, int p_max_results, int *p_result_indices = nullptr) override; - virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata); - virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata); + virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata) override; + virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) override; - virtual void update(); + virtual void update() override; static GodotBroadPhase3D *_create(); GodotBroadPhase3DBVH(); diff --git a/servers/physics_3d/godot_collision_object_3d.h b/servers/physics_3d/godot_collision_object_3d.h index 515b945564..0f09f21962 100644 --- a/servers/physics_3d/godot_collision_object_3d.h +++ b/servers/physics_3d/godot_collision_object_3d.h @@ -112,7 +112,7 @@ public: _FORCE_INLINE_ void set_instance_id(const ObjectID &p_instance_id) { instance_id = p_instance_id; } _FORCE_INLINE_ ObjectID get_instance_id() const { return instance_id; } - void _shape_changed(); + void _shape_changed() override; _FORCE_INLINE_ Type get_type() const { return type; } void add_shape(GodotShape3D *p_shape, const Transform3D &p_transform = Transform3D(), bool p_disabled = false); @@ -173,7 +173,7 @@ public: return collision_layer & p_other->collision_mask || p_other->collision_layer & collision_mask; } - void remove_shape(GodotShape3D *p_shape); + void remove_shape(GodotShape3D *p_shape) override; void remove_shape(int p_index); virtual void set_space(GodotSpace3D *p_space) = 0; diff --git a/servers/physics_3d/godot_collision_solver_3d.cpp b/servers/physics_3d/godot_collision_solver_3d.cpp index 81e1a88366..0adfabef78 100644 --- a/servers/physics_3d/godot_collision_solver_3d.cpp +++ b/servers/physics_3d/godot_collision_solver_3d.cpp @@ -141,7 +141,7 @@ struct _SoftBodyContactCollisionInfo { }; void GodotCollisionSolver3D::soft_body_contact_callback(const Vector3 &p_point_A, int p_index_A, const Vector3 &p_point_B, int p_index_B, void *p_userdata) { - _SoftBodyContactCollisionInfo &cinfo = *(_SoftBodyContactCollisionInfo *)(p_userdata); + _SoftBodyContactCollisionInfo &cinfo = *(static_cast<_SoftBodyContactCollisionInfo *>(p_userdata)); ++cinfo.contact_count; @@ -170,7 +170,7 @@ struct _SoftBodyQueryInfo { }; bool GodotCollisionSolver3D::soft_body_query_callback(uint32_t p_node_index, void *p_userdata) { - _SoftBodyQueryInfo &query_cinfo = *(_SoftBodyQueryInfo *)(p_userdata); + _SoftBodyQueryInfo &query_cinfo = *(static_cast<_SoftBodyQueryInfo *>(p_userdata)); Vector3 node_position = query_cinfo.soft_body->get_node_position(p_node_index); @@ -189,7 +189,7 @@ bool GodotCollisionSolver3D::soft_body_query_callback(uint32_t p_node_index, voi } bool GodotCollisionSolver3D::soft_body_concave_callback(void *p_userdata, GodotShape3D *p_convex) { - _SoftBodyQueryInfo &query_cinfo = *(_SoftBodyQueryInfo *)(p_userdata); + _SoftBodyQueryInfo &query_cinfo = *(static_cast<_SoftBodyQueryInfo *>(p_userdata)); query_cinfo.shape_A = p_convex; @@ -292,7 +292,7 @@ struct _ConcaveCollisionInfo { }; bool GodotCollisionSolver3D::concave_callback(void *p_userdata, GodotShape3D *p_convex) { - _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo *)(p_userdata); + _ConcaveCollisionInfo &cinfo = *(static_cast<_ConcaveCollisionInfo *>(p_userdata)); cinfo.aabb_tests++; bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, p_convex, *cinfo.transform_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, nullptr, cinfo.margin_A, cinfo.margin_B); @@ -422,7 +422,7 @@ bool GodotCollisionSolver3D::solve_static(const GodotShape3D *p_shape_A, const T } bool GodotCollisionSolver3D::concave_distance_callback(void *p_userdata, GodotShape3D *p_convex) { - _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo *)(p_userdata); + _ConcaveCollisionInfo &cinfo = *(static_cast<_ConcaveCollisionInfo *>(p_userdata)); cinfo.aabb_tests++; Vector3 close_A, close_B; diff --git a/servers/physics_3d/godot_physics_server_3d.cpp b/servers/physics_3d/godot_physics_server_3d.cpp index f7270713e0..e5107be74b 100644 --- a/servers/physics_3d/godot_physics_server_3d.cpp +++ b/servers/physics_3d/godot_physics_server_3d.cpp @@ -1570,7 +1570,7 @@ void GodotPhysicsServer3D::free(RID p_rid) { GodotSpace3D *space = space_owner.get_or_null(p_rid); while (space->get_objects().size()) { - GodotCollisionObject3D *co = (GodotCollisionObject3D *)space->get_objects().front()->get(); + GodotCollisionObject3D *co = static_cast<GodotCollisionObject3D *>(space->get_objects().front()->get()); co->set_space(nullptr); } @@ -1612,7 +1612,7 @@ void GodotPhysicsServer3D::step(real_t p_step) { active_objects = 0; collision_pairs = 0; for (Set<const GodotSpace3D *>::Element *E = active_spaces.front(); E; E = E->next()) { - stepper->step((GodotSpace3D *)E->get(), p_step); + stepper->step(const_cast<GodotSpace3D *>(E->get()), p_step); island_count += E->get()->get_island_count(); active_objects += E->get()->get_active_objects(); collision_pairs += E->get()->get_collision_pairs(); @@ -1636,7 +1636,7 @@ void GodotPhysicsServer3D::flush_queries() { uint64_t time_beg = OS::get_singleton()->get_ticks_usec(); for (Set<const GodotSpace3D *>::Element *E = active_spaces.front(); E; E = E->next()) { - GodotSpace3D *space = (GodotSpace3D *)E->get(); + GodotSpace3D *space = const_cast<GodotSpace3D *>(E->get()); space->call_queries(); } @@ -1709,7 +1709,7 @@ void GodotPhysicsServer3D::_update_shapes() { } void GodotPhysicsServer3D::_shape_col_cbk(const Vector3 &p_point_A, int p_index_A, const Vector3 &p_point_B, int p_index_B, void *p_userdata) { - CollCbkData *cbk = (CollCbkData *)p_userdata; + CollCbkData *cbk = static_cast<CollCbkData *>(p_userdata); if (cbk->max == 0) { return; diff --git a/servers/physics_3d/godot_physics_server_3d.h b/servers/physics_3d/godot_physics_server_3d.h index 00ed763e01..d2078a912c 100644 --- a/servers/physics_3d/godot_physics_server_3d.h +++ b/servers/physics_3d/godot_physics_server_3d.h @@ -74,7 +74,7 @@ public: struct CollCbkData { int max; int amount; - Vector3 *ptr; + Vector3 *ptr = nullptr; }; static void _shape_col_cbk(const Vector3 &p_point_A, int p_index_A, const Vector3 &p_point_B, int p_index_B, void *p_userdata); diff --git a/servers/physics_3d/godot_shape_3d.cpp b/servers/physics_3d/godot_shape_3d.cpp index 7762c4829e..21595c9612 100644 --- a/servers/physics_3d/godot_shape_3d.cpp +++ b/servers/physics_3d/godot_shape_3d.cpp @@ -62,7 +62,7 @@ void GodotShape3D::configure(const AABB &p_aabb) { aabb = p_aabb; configured = true; for (const KeyValue<GodotShapeOwner3D *, int> &E : owners) { - GodotShapeOwner3D *co = (GodotShapeOwner3D *)E.key; + GodotShapeOwner3D *co = const_cast<GodotShapeOwner3D *>(E.key); co->_shape_changed(); } } diff --git a/servers/physics_3d/godot_soft_body_3d.cpp b/servers/physics_3d/godot_soft_body_3d.cpp index f09da92cae..be4b41292d 100644 --- a/servers/physics_3d/godot_soft_body_3d.cpp +++ b/servers/physics_3d/godot_soft_body_3d.cpp @@ -1272,7 +1272,7 @@ struct _SoftBodyIntersectSegmentInfo { real_t hit_dist_sq = INFINITY; static bool process_hit(uint32_t p_face_index, void *p_userdata) { - _SoftBodyIntersectSegmentInfo &query_info = *(_SoftBodyIntersectSegmentInfo *)(p_userdata); + _SoftBodyIntersectSegmentInfo &query_info = *(static_cast<_SoftBodyIntersectSegmentInfo *>(p_userdata)); Vector3 points[3]; query_info.soft_body->get_face_points(p_face_index, points[0], points[1], points[2]); diff --git a/servers/physics_3d/godot_soft_body_3d.h b/servers/physics_3d/godot_soft_body_3d.h index d9f5078313..96f63e5819 100644 --- a/servers/physics_3d/godot_soft_body_3d.h +++ b/servers/physics_3d/godot_soft_body_3d.h @@ -153,7 +153,7 @@ public: } } - virtual void set_space(GodotSpace3D *p_space); + virtual void set_space(GodotSpace3D *p_space) override; void set_mesh(RID p_mesh); @@ -204,8 +204,8 @@ public: void predict_motion(real_t p_delta); void solve_constraints(real_t p_delta); - _FORCE_INLINE_ uint32_t get_node_index(void *p_node) const { return ((Node *)p_node)->index; } - _FORCE_INLINE_ uint32_t get_face_index(void *p_face) const { return ((Face *)p_face)->index; } + _FORCE_INLINE_ uint32_t get_node_index(void *p_node) const { return static_cast<Node *>(p_node)->index; } + _FORCE_INLINE_ uint32_t get_face_index(void *p_face) const { return static_cast<Face *>(p_face)->index; } // Return true to stop the query. // p_index is the node index for AABB query, face index for Ray query. @@ -215,7 +215,7 @@ public: void query_ray(const Vector3 &p_from, const Vector3 &p_to, QueryResultCallback p_result_callback, void *p_userdata); protected: - virtual void _shapes_changed(); + virtual void _shapes_changed() override; private: void update_normals_and_centroids(); diff --git a/servers/physics_3d/godot_space_3d.cpp b/servers/physics_3d/godot_space_3d.cpp index e8af2d7283..0b84520c39 100644 --- a/servers/physics_3d/godot_space_3d.cpp +++ b/servers/physics_3d/godot_space_3d.cpp @@ -445,7 +445,7 @@ struct _RestCallbackData { }; static void _rest_cbk_result(const Vector3 &p_point_A, int p_index_A, const Vector3 &p_point_B, int p_index_B, void *p_userdata) { - _RestCallbackData *rd = (_RestCallbackData *)p_userdata; + _RestCallbackData *rd = static_cast<_RestCallbackData *>(p_userdata); Vector3 contact_rel = p_point_B - p_point_A; real_t len = contact_rel.length(); @@ -1017,7 +1017,7 @@ void *GodotSpace3D::_broadphase_pair(GodotCollisionObject3D *A, int p_subindex_A SWAP(type_A, type_B); } - GodotSpace3D *self = (GodotSpace3D *)p_self; + GodotSpace3D *self = static_cast<GodotSpace3D *>(p_self); self->collision_pairs++; @@ -1038,10 +1038,10 @@ void *GodotSpace3D::_broadphase_pair(GodotCollisionObject3D *A, int p_subindex_A } } else if (type_A == GodotCollisionObject3D::TYPE_BODY) { if (type_B == GodotCollisionObject3D::TYPE_SOFT_BODY) { - GodotBodySoftBodyPair3D *soft_pair = memnew(GodotBodySoftBodyPair3D((GodotBody3D *)A, p_subindex_A, (GodotSoftBody3D *)B)); + GodotBodySoftBodyPair3D *soft_pair = memnew(GodotBodySoftBodyPair3D(static_cast<GodotBody3D *>(A), p_subindex_A, static_cast<GodotSoftBody3D *>(B))); return soft_pair; } else { - GodotBodyPair3D *b = memnew(GodotBodyPair3D((GodotBody3D *)A, p_subindex_A, (GodotBody3D *)B, p_subindex_B)); + GodotBodyPair3D *b = memnew(GodotBodyPair3D(static_cast<GodotBody3D *>(A), p_subindex_A, static_cast<GodotBody3D *>(B), p_subindex_B)); return b; } } else { @@ -1056,9 +1056,9 @@ void GodotSpace3D::_broadphase_unpair(GodotCollisionObject3D *A, int p_subindex_ return; } - GodotSpace3D *self = (GodotSpace3D *)p_self; + GodotSpace3D *self = static_cast<GodotSpace3D *>(p_self); self->collision_pairs--; - GodotConstraint3D *c = (GodotConstraint3D *)p_data; + GodotConstraint3D *c = static_cast<GodotConstraint3D *>(p_data); memdelete(c); } diff --git a/servers/physics_3d/godot_space_3d.h b/servers/physics_3d/godot_space_3d.h index ac54c8bf69..6308ede9a9 100644 --- a/servers/physics_3d/godot_space_3d.h +++ b/servers/physics_3d/godot_space_3d.h @@ -47,7 +47,7 @@ class GodotPhysicsDirectSpaceState3D : public PhysicsDirectSpaceState3D { GDCLASS(GodotPhysicsDirectSpaceState3D, PhysicsDirectSpaceState3D); public: - GodotSpace3D *space; + GodotSpace3D *space = nullptr; virtual int intersect_point(const PointParameters &p_parameters, ShapeResult *r_results, int p_result_max) override; virtual bool intersect_ray(const RayParameters &p_parameters, RayResult &r_result) override; diff --git a/servers/physics_3d/godot_step_3d.cpp b/servers/physics_3d/godot_step_3d.cpp index 63635b224b..204adae450 100644 --- a/servers/physics_3d/godot_step_3d.cpp +++ b/servers/physics_3d/godot_step_3d.cpp @@ -49,7 +49,7 @@ void GodotStep3D::_populate_island(GodotBody3D *p_body, LocalVector<GodotBody3D } for (const KeyValue<GodotConstraint3D *, int> &E : p_body->get_constraint_map()) { - GodotConstraint3D *constraint = (GodotConstraint3D *)E.key; + GodotConstraint3D *constraint = const_cast<GodotConstraint3D *>(E.key); if (constraint->get_island_step() == _step) { continue; // Already processed. } @@ -88,7 +88,7 @@ void GodotStep3D::_populate_island_soft_body(GodotSoftBody3D *p_soft_body, Local p_soft_body->set_island_step(_step); for (Set<GodotConstraint3D *>::Element *E = p_soft_body->get_constraints().front(); E; E = E->next()) { - GodotConstraint3D *constraint = (GodotConstraint3D *)E->get(); + GodotConstraint3D *constraint = const_cast<GodotConstraint3D *>(E->get()); if (constraint->get_island_step() == _step) { continue; // Already processed. } diff --git a/servers/rendering/dummy/rasterizer_dummy.h b/servers/rendering/dummy/rasterizer_dummy.h index 069b2e6695..f7bd7d0d18 100644 --- a/servers/rendering/dummy/rasterizer_dummy.h +++ b/servers/rendering/dummy/rasterizer_dummy.h @@ -40,6 +40,7 @@ #include "servers/rendering/dummy/storage/canvas_texture_storage.h" #include "servers/rendering/dummy/storage/decal_atlas_storage.h" #include "servers/rendering/dummy/storage/material_storage.h" +#include "servers/rendering/dummy/storage/mesh_storage.h" #include "servers/rendering/dummy/storage/texture_storage.h" #include "servers/rendering/renderer_compositor.h" #include "servers/rendering_server.h" @@ -53,6 +54,7 @@ protected: RasterizerCanvasDummy canvas; RendererDummy::CanvasTextureStorage canvas_texture_storage; RendererDummy::MaterialStorage material_storage; + RendererDummy::MeshStorage mesh_storage; RendererDummy::TextureStorage texture_storage; RendererDummy::DecalAtlasStorage decal_atlas_storage; RasterizerStorageDummy storage; @@ -61,6 +63,7 @@ protected: public: RendererCanvasTextureStorage *get_canvas_texture_storage() override { return &canvas_texture_storage; }; RendererMaterialStorage *get_material_storage() override { return &material_storage; }; + RendererMeshStorage *get_mesh_storage() override { return &mesh_storage; }; RendererTextureStorage *get_texture_storage() override { return &texture_storage; }; RendererDecalAtlasStorage *get_decal_atlas_storage() override { return &decal_atlas_storage; }; RendererStorage *get_storage() override { return &storage; } diff --git a/servers/rendering/dummy/rasterizer_storage_dummy.h b/servers/rendering/dummy/rasterizer_storage_dummy.h index 4ae2a51c7d..ea69d2f9a6 100644 --- a/servers/rendering/dummy/rasterizer_storage_dummy.h +++ b/servers/rendering/dummy/rasterizer_storage_dummy.h @@ -36,82 +36,6 @@ class RasterizerStorageDummy : public RendererStorage { public: - /* MESH API */ - - RID mesh_allocate() override { return RID(); } - void mesh_initialize(RID p_rid) override {} - void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) override {} - bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) override { return false; } - RID mesh_instance_create(RID p_base) override { return RID(); } - void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) override {} - void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) override {} - void mesh_instance_check_for_update(RID p_mesh_instance) override {} - void update_mesh_instances() override {} - void reflection_probe_set_mesh_lod_threshold(RID p_probe, float p_ratio) override {} - float reflection_probe_get_mesh_lod_threshold(RID p_probe) const override { return 0.0; } - - void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) override {} - - int mesh_get_blend_shape_count(RID p_mesh) const override { return 0; } - - void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) override {} - RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const override { return RS::BLEND_SHAPE_MODE_NORMALIZED; } - - void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override {} - void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override {} - void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override {} - - void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) override {} - RID mesh_surface_get_material(RID p_mesh, int p_surface) const override { return RID(); } - - RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const override { return RS::SurfaceData(); } - int mesh_get_surface_count(RID p_mesh) const override { return 0; } - - void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) override {} - AABB mesh_get_custom_aabb(RID p_mesh) const override { return AABB(); } - - AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) override { return AABB(); } - void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) override {} - void mesh_clear(RID p_mesh) override {} - - /* MULTIMESH API */ - - RID multimesh_allocate() override { return RID(); } - void multimesh_initialize(RID p_rid) override {} - void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) override {} - int multimesh_get_instance_count(RID p_multimesh) const override { return 0; } - - void multimesh_set_mesh(RID p_multimesh, RID p_mesh) override {} - void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) override {} - void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) override {} - void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) override {} - void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) override {} - - RID multimesh_get_mesh(RID p_multimesh) const override { return RID(); } - AABB multimesh_get_aabb(RID p_multimesh) const override { return AABB(); } - - Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const override { return Transform3D(); } - Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const override { return Transform2D(); } - Color multimesh_instance_get_color(RID p_multimesh, int p_index) const override { return Color(); } - Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const override { return Color(); } - void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) override {} - Vector<float> multimesh_get_buffer(RID p_multimesh) const override { return Vector<float>(); } - - void multimesh_set_visible_instances(RID p_multimesh, int p_visible) override {} - int multimesh_get_visible_instances(RID p_multimesh) const override { return 0; } - - /* SKELETON API */ - - RID skeleton_allocate() override { return RID(); } - void skeleton_initialize(RID p_rid) override {} - void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) override {} - void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) override {} - int skeleton_get_bone_count(RID p_skeleton) const override { return 0; } - void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) override {} - Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const override { return Transform3D(); } - void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) override {} - Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const override { return Transform2D(); } - /* Light API */ RID directional_light_allocate() override { return RID(); } @@ -171,6 +95,8 @@ public: void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) override {} void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) override {} void reflection_probe_set_resolution(RID p_probe, int p_resolution) override {} + void reflection_probe_set_mesh_lod_threshold(RID p_probe, float p_ratio) override {} + float reflection_probe_get_mesh_lod_threshold(RID p_probe) const override { return 0.0; } AABB reflection_probe_get_aabb(RID p_probe) const override { return AABB(); } RS::ReflectionProbeUpdateMode reflection_probe_get_update_mode(RID p_probe) const override { return RenderingServer::REFLECTION_PROBE_UPDATE_ONCE; } @@ -181,7 +107,6 @@ public: bool reflection_probe_renders_shadows(RID p_probe) const override { return false; } void base_update_dependency(RID p_base, DependencyTracker *p_instance) override {} - void skeleton_update_dependency(RID p_base, DependencyTracker *p_instance) override {} /* VOXEL GI API */ diff --git a/servers/rendering/dummy/storage/mesh_storage.h b/servers/rendering/dummy/storage/mesh_storage.h new file mode 100644 index 0000000000..dfbd265bba --- /dev/null +++ b/servers/rendering/dummy/storage/mesh_storage.h @@ -0,0 +1,129 @@ +/*************************************************************************/ +/* mesh_storage.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef MESH_STORAGE_DUMMY_H +#define MESH_STORAGE_DUMMY_H + +#include "servers/rendering/storage/mesh_storage.h" + +namespace RendererDummy { + +class MeshStorage : public RendererMeshStorage { +public: + /* MESH API */ + + virtual RID mesh_allocate() override { return RID(); } + virtual void mesh_initialize(RID p_rid) override {} + virtual void mesh_free(RID p_rid) override {} + + virtual void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) override {} + virtual bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) override { return false; } + + virtual void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) override {} + + virtual int mesh_get_blend_shape_count(RID p_mesh) const override { return 0; } + + virtual void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) override {} + virtual RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const override { return RS::BLEND_SHAPE_MODE_NORMALIZED; } + + virtual void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override {} + virtual void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override {} + virtual void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override {} + + virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) override {} + virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const override { return RID(); } + + virtual RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const override { return RS::SurfaceData(); } + virtual int mesh_get_surface_count(RID p_mesh) const override { return 0; } + + virtual void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) override {} + virtual AABB mesh_get_custom_aabb(RID p_mesh) const override { return AABB(); } + + virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) override { return AABB(); } + virtual void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) override {} + virtual void mesh_clear(RID p_mesh) override {} + + /* MESH INSTANCE */ + + virtual RID mesh_instance_create(RID p_base) override { return RID(); } + virtual void mesh_instance_free(RID p_rid) override {} + + virtual void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) override {} + virtual void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) override {} + virtual void mesh_instance_check_for_update(RID p_mesh_instance) override {} + virtual void update_mesh_instances() override {} + + /* MULTIMESH API */ + + virtual RID multimesh_allocate() override { return RID(); } + virtual void multimesh_initialize(RID p_rid) override {} + virtual void multimesh_free(RID p_rid) override {} + + virtual void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) override {} + virtual int multimesh_get_instance_count(RID p_multimesh) const override { return 0; } + + virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) override {} + virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) override {} + virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) override {} + virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) override {} + virtual void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) override {} + + virtual RID multimesh_get_mesh(RID p_multimesh) const override { return RID(); } + virtual AABB multimesh_get_aabb(RID p_multimesh) const override { return AABB(); } + + virtual Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const override { return Transform3D(); } + virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const override { return Transform2D(); } + virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const override { return Color(); } + virtual Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const override { return Color(); } + virtual void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) override {} + virtual Vector<float> multimesh_get_buffer(RID p_multimesh) const override { return Vector<float>(); } + + virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) override {} + virtual int multimesh_get_visible_instances(RID p_multimesh) const override { return 0; } + + /* SKELETON API */ + + virtual RID skeleton_allocate() override { return RID(); } + virtual void skeleton_initialize(RID p_rid) override {} + virtual void skeleton_free(RID p_rid) override {} + virtual void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) override {} + virtual void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) override {} + virtual int skeleton_get_bone_count(RID p_skeleton) const override { return 0; } + virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) override {} + virtual Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const override { return Transform3D(); } + virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) override {} + virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const override { return Transform2D(); } + + virtual void skeleton_update_dependency(RID p_base, RendererStorage::DependencyTracker *p_instance) override {} +}; + +} // namespace RendererDummy + +#endif // !MESH_STORAGE_DUMMY_H diff --git a/servers/rendering/renderer_canvas_cull.cpp b/servers/rendering/renderer_canvas_cull.cpp index 22149c9e43..41034d4a02 100644 --- a/servers/rendering/renderer_canvas_cull.cpp +++ b/servers/rendering/renderer_canvas_cull.cpp @@ -552,27 +552,188 @@ void RendererCanvasCull::canvas_item_set_update_when_visible(RID p_item, bool p_ canvas_item->update_when_visible = p_update; } -void RendererCanvasCull::canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width) { +void RendererCanvasCull::canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width, bool p_antialiased) { Item *canvas_item = canvas_item_owner.get_or_null(p_item); ERR_FAIL_COND(!canvas_item); Item::CommandPrimitive *line = canvas_item->alloc_command<Item::CommandPrimitive>(); ERR_FAIL_COND(!line); + + Vector2 diff = (p_from - p_to); + Vector2 dir = diff.orthogonal().normalized(); + Vector2 t = dir * p_width * 0.5; + + Vector2 begin_left; + Vector2 begin_right; + Vector2 end_left; + Vector2 end_right; + if (p_width > 1.001) { - Vector2 t = (p_from - p_to).orthogonal().normalized() * p_width * 0.5; - line->points[0] = p_from + t; - line->points[1] = p_from - t; - line->points[2] = p_to - t; - line->points[3] = p_to + t; + begin_left = p_from + t; + begin_right = p_from - t; + end_left = p_to + t; + end_right = p_to - t; + + line->points[0] = begin_left; + line->points[1] = begin_right; + line->points[2] = end_right; + line->points[3] = end_left; line->point_count = 4; } else { - line->point_count = 2; + begin_left = p_from; + begin_right = p_from; + end_left = p_to; + end_right = p_to; + line->points[0] = p_from; line->points[1] = p_to; + line->point_count = 2; } for (uint32_t i = 0; i < line->point_count; i++) { line->colors[i] = p_color; } + + if (p_antialiased) { + float border_size = 2.0; + if (p_width < border_size) { + border_size = p_width; + } + Vector2 dir2 = diff.normalized(); + + Vector2 border = dir * border_size; + Vector2 border2 = dir2 * border_size; + + Color transparent = Color(p_color.r, p_color.g, p_color.b, 0.0); + + { + Item::CommandPrimitive *left_border = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!left_border); + + left_border->points[0] = begin_left; + left_border->points[1] = begin_left + border; + left_border->points[2] = end_left + border; + left_border->points[3] = end_left; + + left_border->colors[0] = p_color; + left_border->colors[1] = transparent; + left_border->colors[2] = transparent; + left_border->colors[3] = p_color; + + left_border->point_count = 4; + } + { + Item::CommandPrimitive *right_border = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!right_border); + + right_border->points[0] = begin_right; + right_border->points[1] = begin_right - border; + right_border->points[2] = end_right - border; + right_border->points[3] = end_right; + + right_border->colors[0] = p_color; + right_border->colors[1] = transparent; + right_border->colors[2] = transparent; + right_border->colors[3] = p_color; + + right_border->point_count = 4; + } + { + Item::CommandPrimitive *top_border = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!top_border); + + top_border->points[0] = begin_left; + top_border->points[1] = begin_left + border2; + top_border->points[2] = begin_right + border2; + top_border->points[3] = begin_right; + + top_border->colors[0] = p_color; + top_border->colors[1] = transparent; + top_border->colors[2] = transparent; + top_border->colors[3] = p_color; + + top_border->point_count = 4; + } + { + Item::CommandPrimitive *bottom_border = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!bottom_border); + + bottom_border->points[0] = end_left; + bottom_border->points[1] = end_left - border2; + bottom_border->points[2] = end_right - border2; + bottom_border->points[3] = end_right; + + bottom_border->colors[0] = p_color; + bottom_border->colors[1] = transparent; + bottom_border->colors[2] = transparent; + bottom_border->colors[3] = p_color; + + bottom_border->point_count = 4; + } + { + Item::CommandPrimitive *top_left_corner = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!top_left_corner); + + top_left_corner->points[0] = begin_left; + top_left_corner->points[1] = begin_left + border2; + top_left_corner->points[2] = begin_left + border + border2; + top_left_corner->points[3] = begin_left + border; + + top_left_corner->colors[0] = p_color; + top_left_corner->colors[1] = transparent; + top_left_corner->colors[2] = transparent; + top_left_corner->colors[3] = transparent; + + top_left_corner->point_count = 4; + } + { + Item::CommandPrimitive *top_right_corner = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!top_right_corner); + + top_right_corner->points[0] = begin_right; + top_right_corner->points[1] = begin_right + border2; + top_right_corner->points[2] = begin_right - border + border2; + top_right_corner->points[3] = begin_right - border; + + top_right_corner->colors[0] = p_color; + top_right_corner->colors[1] = transparent; + top_right_corner->colors[2] = transparent; + top_right_corner->colors[3] = transparent; + + top_right_corner->point_count = 4; + } + { + Item::CommandPrimitive *bottom_left_corner = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!bottom_left_corner); + + bottom_left_corner->points[0] = end_left; + bottom_left_corner->points[1] = end_left - border2; + bottom_left_corner->points[2] = end_left + border - border2; + bottom_left_corner->points[3] = end_left + border; + + bottom_left_corner->colors[0] = p_color; + bottom_left_corner->colors[1] = transparent; + bottom_left_corner->colors[2] = transparent; + bottom_left_corner->colors[3] = transparent; + + bottom_left_corner->point_count = 4; + } + { + Item::CommandPrimitive *bottom_right_corner = canvas_item->alloc_command<Item::CommandPrimitive>(); + ERR_FAIL_COND(!bottom_right_corner); + + bottom_right_corner->points[0] = end_right; + bottom_right_corner->points[1] = end_right - border2; + bottom_right_corner->points[2] = end_right - border - border2; + bottom_right_corner->points[3] = end_right - border; + + bottom_right_corner->colors[0] = p_color; + bottom_right_corner->colors[1] = transparent; + bottom_right_corner->colors[2] = transparent; + bottom_right_corner->colors[3] = transparent; + + bottom_right_corner->point_count = 4; + } + } } void RendererCanvasCull::canvas_item_add_polyline(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, float p_width, bool p_antialiased) { @@ -602,42 +763,119 @@ void RendererCanvasCull::canvas_item_add_polyline(RID p_item, const Vector<Point Color *colors_ptr = colors.ptrw(); if (p_antialiased) { + float border_size = 2.0; + if (p_width < border_size) { + border_size = p_width; + } Color color2 = Color(1, 1, 1, 0); - PackedColorArray colors_top; - PackedVector2Array points_top; + PackedColorArray colors_begin; + PackedVector2Array points_begin; + + colors_begin.resize(4); + points_begin.resize(4); + + PackedColorArray colors_begin_left_corner; + PackedVector2Array points_begin_left_corner; + + colors_begin_left_corner.resize(4); + points_begin_left_corner.resize(4); + + PackedColorArray colors_begin_right_corner; + PackedVector2Array points_begin_right_corner; + + colors_begin_right_corner.resize(4); + points_begin_right_corner.resize(4); + + PackedColorArray colors_end; + PackedVector2Array points_end; + + colors_end.resize(4); + points_end.resize(4); + + PackedColorArray colors_end_left_corner; + PackedVector2Array points_end_left_corner; + + colors_end_left_corner.resize(4); + points_end_left_corner.resize(4); + + PackedColorArray colors_end_right_corner; + PackedVector2Array points_end_right_corner; + + colors_end_right_corner.resize(4); + points_end_right_corner.resize(4); - colors_top.resize(pc2); - points_top.resize(pc2); + PackedColorArray colors_left; + PackedVector2Array points_left; - PackedColorArray colors_bottom; - PackedVector2Array points_bottom; + colors_left.resize(pc2); + points_left.resize(pc2); - colors_bottom.resize(pc2); - points_bottom.resize(pc2); + PackedColorArray colors_right; + PackedVector2Array points_right; - Item::CommandPolygon *pline_top = canvas_item->alloc_command<Item::CommandPolygon>(); - ERR_FAIL_COND(!pline_top); + colors_right.resize(pc2); + points_right.resize(pc2); - Item::CommandPolygon *pline_bottom = canvas_item->alloc_command<Item::CommandPolygon>(); - ERR_FAIL_COND(!pline_bottom); + Item::CommandPolygon *pline_begin = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_begin); - //make three trianglestrip's for drawing the antialiased line... + Item::CommandPolygon *pline_begin_left_corner = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_begin_left_corner); - Vector2 *points_top_ptr = points_top.ptrw(); - Vector2 *points_bottom_ptr = points_bottom.ptrw(); + Item::CommandPolygon *pline_begin_right_corner = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_begin_right_corner); - Color *colors_top_ptr = colors_top.ptrw(); - Color *colors_bottom_ptr = colors_bottom.ptrw(); + Item::CommandPolygon *pline_end = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_end); + + Item::CommandPolygon *pline_end_left_corner = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_end_left_corner); + + Item::CommandPolygon *pline_end_right_corner = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_end_right_corner); + + Item::CommandPolygon *pline_left = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_left); + + Item::CommandPolygon *pline_right = canvas_item->alloc_command<Item::CommandPolygon>(); + ERR_FAIL_COND(!pline_right); + + // Makes nine triangle strips for drawing the antialiased line. + + Vector2 *points_begin_ptr = points_begin.ptrw(); + Vector2 *points_begin_left_corner_ptr = points_begin_left_corner.ptrw(); + Vector2 *points_begin_right_corner_ptr = points_begin_right_corner.ptrw(); + Vector2 *points_end_ptr = points_end.ptrw(); + Vector2 *points_end_left_corner_ptr = points_end_left_corner.ptrw(); + Vector2 *points_end_right_corner_ptr = points_end_right_corner.ptrw(); + Vector2 *points_left_ptr = points_left.ptrw(); + Vector2 *points_right_ptr = points_right.ptrw(); + + Color *colors_begin_ptr = colors_begin.ptrw(); + Color *colors_begin_left_corner_ptr = colors_begin_left_corner.ptrw(); + Color *colors_begin_right_corner_ptr = colors_begin_right_corner.ptrw(); + Color *colors_end_ptr = colors_end.ptrw(); + Color *colors_end_left_corner_ptr = colors_end_left_corner.ptrw(); + Color *colors_end_right_corner_ptr = colors_end_right_corner.ptrw(); + Color *colors_left_ptr = colors_left.ptrw(); + Color *colors_right_ptr = colors_right.ptrw(); for (int i = 0, j = 0; i < pc; i++, j += 2) { + bool is_begin = i == 0; + bool is_end = i == pc - 1; + Vector2 t; - if (i == pc - 1) { + Vector2 end_border; + Vector2 begin_border; + if (is_end) { t = prev_t; + end_border = (p_points[i] - p_points[i - 1]).normalized() * border_size; } else { t = (p_points[i + 1] - p_points[i]).normalized().orthogonal(); - if (i == 0) { + if (is_begin) { prev_t = t; + begin_border = (p_points[i] - p_points[i + 1]).normalized() * border_size; } } @@ -645,17 +883,17 @@ void RendererCanvasCull::canvas_item_add_polyline(RID p_item, const Vector<Point Vector2 dir = (t + prev_t).normalized(); Vector2 tangent = dir * p_width * 0.5; - Vector2 border = dir * 2.0; + Vector2 border = dir * border_size; Vector2 pos = p_points[i]; points_ptr[j] = pos + tangent; points_ptr[j2] = pos - tangent; - points_top_ptr[j] = pos + tangent + border; - points_top_ptr[j2] = pos + tangent; + points_left_ptr[j] = pos + tangent + border; + points_left_ptr[j2] = pos + tangent; - points_bottom_ptr[j] = pos - tangent; - points_bottom_ptr[j2] = pos - tangent - border; + points_right_ptr[j] = pos - tangent; + points_right_ptr[j2] = pos - tangent - border; if (i < p_colors.size()) { color = p_colors[i]; @@ -665,22 +903,104 @@ void RendererCanvasCull::canvas_item_add_polyline(RID p_item, const Vector<Point colors_ptr[j] = color; colors_ptr[j2] = color; - colors_top_ptr[j] = color2; - colors_top_ptr[j2] = color; + colors_left_ptr[j] = color2; + colors_left_ptr[j2] = color; + + colors_right_ptr[j] = color; + colors_right_ptr[j2] = color2; + + if (is_begin) { + points_begin_ptr[0] = pos + tangent + begin_border; + points_begin_ptr[1] = pos - tangent + begin_border; + points_begin_ptr[2] = pos + tangent; + points_begin_ptr[3] = pos - tangent; + + colors_begin_ptr[0] = color2; + colors_begin_ptr[1] = color2; + colors_begin_ptr[2] = color; + colors_begin_ptr[3] = color; + + points_begin_left_corner_ptr[0] = pos - tangent - border; + points_begin_left_corner_ptr[1] = pos - tangent + begin_border - border; + points_begin_left_corner_ptr[2] = pos - tangent; + points_begin_left_corner_ptr[3] = pos - tangent + begin_border; + + colors_begin_left_corner_ptr[0] = color2; + colors_begin_left_corner_ptr[1] = color2; + colors_begin_left_corner_ptr[2] = color; + colors_begin_left_corner_ptr[3] = color2; + + points_begin_right_corner_ptr[0] = pos + tangent + begin_border; + points_begin_right_corner_ptr[1] = pos + tangent + begin_border + border; + points_begin_right_corner_ptr[2] = pos + tangent; + points_begin_right_corner_ptr[3] = pos + tangent + border; + + colors_begin_right_corner_ptr[0] = color2; + colors_begin_right_corner_ptr[1] = color2; + colors_begin_right_corner_ptr[2] = color; + colors_begin_right_corner_ptr[3] = color2; + } - colors_bottom_ptr[j] = color; - colors_bottom_ptr[j2] = color2; + if (is_end) { + points_end_ptr[0] = pos + tangent + end_border; + points_end_ptr[1] = pos - tangent + end_border; + points_end_ptr[2] = pos + tangent; + points_end_ptr[3] = pos - tangent; + + colors_end_ptr[0] = color2; + colors_end_ptr[1] = color2; + colors_end_ptr[2] = color; + colors_end_ptr[3] = color; + + points_end_left_corner_ptr[0] = pos - tangent - border; + points_end_left_corner_ptr[1] = pos - tangent + end_border - border; + points_end_left_corner_ptr[2] = pos - tangent; + points_end_left_corner_ptr[3] = pos - tangent + end_border; + + colors_end_left_corner_ptr[0] = color2; + colors_end_left_corner_ptr[1] = color2; + colors_end_left_corner_ptr[2] = color; + colors_end_left_corner_ptr[3] = color2; + + points_end_right_corner_ptr[0] = pos + tangent + end_border; + points_end_right_corner_ptr[1] = pos + tangent + end_border + border; + points_end_right_corner_ptr[2] = pos + tangent; + points_end_right_corner_ptr[3] = pos + tangent + border; + + colors_end_right_corner_ptr[0] = color2; + colors_end_right_corner_ptr[1] = color2; + colors_end_right_corner_ptr[2] = color; + colors_end_right_corner_ptr[3] = color2; + } prev_t = t; } - pline_top->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; - pline_top->polygon.create(indices, points_top, colors_top); + pline_begin->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_begin->polygon.create(indices, points_begin, colors_begin); + + pline_begin_left_corner->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_begin_left_corner->polygon.create(indices, points_begin_left_corner, colors_begin_left_corner); + + pline_begin_right_corner->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_begin_right_corner->polygon.create(indices, points_begin_right_corner, colors_begin_right_corner); + + pline_end->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_end->polygon.create(indices, points_end, colors_end); + + pline_end_left_corner->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_end_left_corner->polygon.create(indices, points_end_left_corner, colors_end_left_corner); + + pline_end_right_corner->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_end_right_corner->polygon.create(indices, points_end_right_corner, colors_end_right_corner); + + pline_left->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_left->polygon.create(indices, points_left, colors_left); - pline_bottom->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; - pline_bottom->polygon.create(indices, points_bottom, colors_bottom); + pline_right->primitive = RS::PRIMITIVE_TRIANGLE_STRIP; + pline_right->polygon.create(indices, points_right, colors_right); } else { - //make a trianglestrip for drawing the line... + // Makes a single triangle strip for drawing the line. for (int i = 0, j = 0; i < pc; i++, j += 2) { Vector2 t; @@ -997,8 +1317,8 @@ void RendererCanvasCull::canvas_item_add_mesh(RID p_item, const RID &p_mesh, con ERR_FAIL_COND(!m); m->mesh = p_mesh; if (canvas_item->skeleton.is_valid()) { - m->mesh_instance = RSG::storage->mesh_instance_create(p_mesh); - RSG::storage->mesh_instance_set_skeleton(m->mesh_instance, canvas_item->skeleton); + m->mesh_instance = RSG::mesh_storage->mesh_instance_create(p_mesh); + RSG::mesh_storage->mesh_instance_set_skeleton(m->mesh_instance, canvas_item->skeleton); } m->texture = p_texture; @@ -1093,12 +1413,12 @@ void RendererCanvasCull::canvas_item_attach_skeleton(RID p_item, RID p_skeleton) Item::CommandMesh *cm = static_cast<Item::CommandMesh *>(c); if (canvas_item->skeleton.is_valid()) { if (cm->mesh_instance.is_null()) { - cm->mesh_instance = RSG::storage->mesh_instance_create(cm->mesh); + cm->mesh_instance = RSG::mesh_storage->mesh_instance_create(cm->mesh); } - RSG::storage->mesh_instance_set_skeleton(cm->mesh_instance, canvas_item->skeleton); + RSG::mesh_storage->mesh_instance_set_skeleton(cm->mesh_instance, canvas_item->skeleton); } else { if (cm->mesh_instance.is_valid()) { - RSG::storage->free(cm->mesh_instance); + RSG::mesh_storage->mesh_instance_free(cm->mesh_instance); cm->mesh_instance = RID(); } } diff --git a/servers/rendering/renderer_canvas_cull.h b/servers/rendering/renderer_canvas_cull.h index fc53ce2327..637245502d 100644 --- a/servers/rendering/renderer_canvas_cull.h +++ b/servers/rendering/renderer_canvas_cull.h @@ -124,7 +124,7 @@ public: Set<RID> viewports; struct ChildItem { Point2 mirror; - Item *item; + Item *item = nullptr; bool operator<(const ChildItem &p_item) const { return item->index < p_item.item->index; } @@ -215,7 +215,7 @@ public: void canvas_item_set_update_when_visible(RID p_item, bool p_update); - void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0); + void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false); void canvas_item_add_polyline(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, float p_width = 1.0, bool p_antialiased = false); void canvas_item_add_multiline(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, float p_width = 1.0); void canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color); diff --git a/servers/rendering/renderer_canvas_render.h b/servers/rendering/renderer_canvas_render.h index 1840925f78..46ca3b0da8 100644 --- a/servers/rendering/renderer_canvas_render.h +++ b/servers/rendering/renderer_canvas_render.h @@ -31,6 +31,7 @@ #ifndef RENDERINGSERVERCANVASRENDER_H #define RENDERINGSERVERCANVASRENDER_H +#include "servers/rendering/renderer_rd/storage_rd/mesh_storage.h" #include "servers/rendering/renderer_storage.h" class RendererCanvasRender { @@ -82,10 +83,10 @@ public: Transform2D light_shader_xform; //Vector2 light_shader_pos; - Light *shadows_next_ptr; - Light *filter_next_ptr; - Light *next_ptr; - Light *directional_next_ptr; + Light *shadows_next_ptr = nullptr; + Light *filter_next_ptr = nullptr; + Light *next_ptr = nullptr; + Light *directional_next_ptr = nullptr; RID light_internal; uint64_t version; @@ -167,7 +168,7 @@ public: MAX_SIZE = 4096 }; uint32_t usage; - uint8_t *memory; + uint8_t *memory = nullptr; }; struct Command { @@ -184,7 +185,7 @@ public: TYPE_ANIMATION_SLICE, }; - Command *next; + Command *next = nullptr; Type type; virtual ~Command() {} }; @@ -304,8 +305,8 @@ public: }; struct ViewportRender { - RenderingServer *owner; - void *udata; + RenderingServer *owner = nullptr; + void *udata = nullptr; Rect2 rect; }; @@ -333,22 +334,22 @@ public: RID material; RID skeleton; - Item *next; + Item *next = nullptr; struct CopyBackBuffer { Rect2 rect; Rect2 screen_rect; bool full; }; - CopyBackBuffer *copy_back_buffer; + CopyBackBuffer *copy_back_buffer = nullptr; Color final_modulate; Transform2D final_transform; Rect2 final_clip_rect; - Item *final_clip_owner; - Item *material_owner; - Item *canvas_group_owner; - ViewportRender *vp_render; + Item *final_clip_owner = nullptr; + Item *material_owner = nullptr; + Item *canvas_group_owner = nullptr; + ViewportRender *vp_render = nullptr; bool distance_field; bool light_masked; @@ -403,14 +404,14 @@ public: } break; case Item::Command::TYPE_MESH: { const Item::CommandMesh *mesh = static_cast<const Item::CommandMesh *>(c); - AABB aabb = RendererStorage::base_singleton->mesh_get_aabb(mesh->mesh, RID()); + AABB aabb = RendererRD::MeshStorage::get_singleton()->mesh_get_aabb(mesh->mesh, RID()); r = Rect2(aabb.position.x, aabb.position.y, aabb.size.x, aabb.size.y); } break; case Item::Command::TYPE_MULTIMESH: { const Item::CommandMultiMesh *multimesh = static_cast<const Item::CommandMultiMesh *>(c); - AABB aabb = RendererStorage::base_singleton->multimesh_get_aabb(multimesh->multimesh); + AABB aabb = RendererRD::MeshStorage::get_singleton()->multimesh_get_aabb(multimesh->multimesh); r = Rect2(aabb.position.x, aabb.position.y, aabb.size.x, aabb.size.y); @@ -452,14 +453,14 @@ public: return rect; } - Command *commands; - Command *last_command; + Command *commands = nullptr; + Command *last_command = nullptr; Vector<CommandBlock> blocks; uint32_t current_block; template <class T> T *alloc_command() { - T *command; + T *command = nullptr; if (commands == nullptr) { // As the most common use case of canvas items is to // use only one command, the first is done with it's @@ -589,7 +590,7 @@ public: bool sdf_collision; RS::CanvasOccluderPolygonCullMode cull_cache; - LightOccluderInstance *next; + LightOccluderInstance *next = nullptr; LightOccluderInstance() { enabled = true; diff --git a/servers/rendering/renderer_compositor.h b/servers/rendering/renderer_compositor.h index 28d4a9d75d..74eff4bb40 100644 --- a/servers/rendering/renderer_compositor.h +++ b/servers/rendering/renderer_compositor.h @@ -37,6 +37,7 @@ #include "servers/rendering/storage/canvas_texture_storage.h" #include "servers/rendering/storage/decal_atlas_storage.h" #include "servers/rendering/storage/material_storage.h" +#include "servers/rendering/storage/mesh_storage.h" #include "servers/rendering/storage/texture_storage.h" #include "servers/rendering_server.h" @@ -76,6 +77,7 @@ public: virtual RendererCanvasTextureStorage *get_canvas_texture_storage() = 0; virtual RendererMaterialStorage *get_material_storage() = 0; + virtual RendererMeshStorage *get_mesh_storage() = 0; virtual RendererTextureStorage *get_texture_storage() = 0; virtual RendererDecalAtlasStorage *get_decal_atlas_storage() = 0; virtual RendererStorage *get_storage() = 0; diff --git a/servers/rendering/renderer_rd/cluster_builder_rd.cpp b/servers/rendering/renderer_rd/cluster_builder_rd.cpp index 24108b3a59..0b36fe3964 100644 --- a/servers/rendering/renderer_rd/cluster_builder_rd.cpp +++ b/servers/rendering/renderer_rd/cluster_builder_rd.cpp @@ -269,7 +269,7 @@ void ClusterBuilderRD::setup(Size2i p_screen_size, uint32_t p_max_elements, RID cluster_render_buffer = RD::get_singleton()->storage_buffer_create(cluster_render_buffer_size); cluster_buffer = RD::get_singleton()->storage_buffer_create(cluster_buffer_size); - render_elements = (RenderElementData *)memalloc(sizeof(RenderElementData *) * render_element_max); + render_elements = static_cast<RenderElementData *>(memalloc(sizeof(RenderElementData *) * render_element_max)); render_element_count = 0; element_buffer = RD::get_singleton()->storage_buffer_create(sizeof(RenderElementData) * render_element_max); diff --git a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp index 2b3ed4ffad..b541e6ca88 100644 --- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp +++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp @@ -31,6 +31,7 @@ #include "render_forward_clustered.h" #include "core/config/project_settings.h" #include "servers/rendering/renderer_rd/storage_rd/decal_atlas_storage.h" +#include "servers/rendering/renderer_rd/storage_rd/mesh_storage.h" #include "servers/rendering/renderer_rd/uniform_set_cache_rd.h" #include "servers/rendering/rendering_device.h" #include "servers/rendering/rendering_server_default.h" @@ -316,6 +317,7 @@ bool RenderForwardClustered::free(RID p_rid) { template <RenderForwardClustered::PassMode p_pass_mode, uint32_t p_color_pass_flags> void RenderForwardClustered::_render_list_template(RenderingDevice::DrawListID p_draw_list, RenderingDevice::FramebufferFormatID p_framebuffer_Format, RenderListParameters *p_params, uint32_t p_from_element, uint32_t p_to_element) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); RD::DrawListID draw_list = p_draw_list; RD::FramebufferFormatID framebuffer_format = p_framebuffer_Format; @@ -491,12 +493,12 @@ void RenderForwardClustered::_render_list_template(RenderingDevice::DrawListID p //skeleton and blend shape if (surf->owner->mesh_instance.is_valid()) { - storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); + mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); } else { - storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); + mesh_storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); } - index_array_rd = storage->mesh_surface_get_index_array(mesh_surface, element_info.lod_index); + index_array_rd = mesh_storage->mesh_surface_get_index_array(mesh_surface, element_info.lod_index); if (prev_vertex_array_rd != vertex_array_rd) { RD::get_singleton()->draw_list_bind_vertex_array(draw_list, vertex_array_rd); @@ -682,7 +684,7 @@ void RenderForwardClustered::_setup_environment(const RenderDataRD *p_render_dat scene_state.ubo.fog_enabled = false; if (p_render_data->render_buffers.is_valid()) { - RenderBufferDataForwardClustered *render_buffers = (RenderBufferDataForwardClustered *)render_buffers_get_data(p_render_data->render_buffers); + RenderBufferDataForwardClustered *render_buffers = static_cast<RenderBufferDataForwardClustered *>(render_buffers_get_data(p_render_data->render_buffers)); if (render_buffers->msaa != RS::VIEWPORT_MSAA_DISABLED) { scene_state.ubo.gi_upscale_for_msaa = true; } @@ -781,7 +783,7 @@ void RenderForwardClustered::_setup_environment(const RenderDataRD *p_render_dat //ambient if (ambient_src == RS::ENV_AMBIENT_SOURCE_BG && (env_bg == RS::ENV_BG_CLEAR_COLOR || env_bg == RS::ENV_BG_COLOR)) { Color color = env_bg == RS::ENV_BG_CLEAR_COLOR ? p_default_bg_color : environment_get_bg_color(p_render_data->environment); - color = color.to_linear(); + color = color.srgb_to_linear(); scene_state.ubo.ambient_light_color_energy[0] = color.r * bg_energy; scene_state.ubo.ambient_light_color_energy[1] = color.g * bg_energy; @@ -791,7 +793,7 @@ void RenderForwardClustered::_setup_environment(const RenderDataRD *p_render_dat } else { float energy = environment_get_ambient_light_energy(p_render_data->environment); Color color = environment_get_ambient_light_color(p_render_data->environment); - color = color.to_linear(); + color = color.srgb_to_linear(); scene_state.ubo.ambient_light_color_energy[0] = color.r * energy; scene_state.ubo.ambient_light_color_energy[1] = color.g * energy; scene_state.ubo.ambient_light_color_energy[2] = color.b * energy; @@ -827,7 +829,7 @@ void RenderForwardClustered::_setup_environment(const RenderDataRD *p_render_dat scene_state.ubo.fog_height_density = environment_get_fog_height_density(p_render_data->environment); scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_render_data->environment); - Color fog_color = environment_get_fog_light_color(p_render_data->environment).to_linear(); + Color fog_color = environment_get_fog_light_color(p_render_data->environment).srgb_to_linear(); float fog_energy = environment_get_fog_light_energy(p_render_data->environment); scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy; @@ -842,7 +844,7 @@ void RenderForwardClustered::_setup_environment(const RenderDataRD *p_render_dat } else { scene_state.ubo.use_ambient_light = true; Color clear_color = p_default_bg_color; - clear_color = clear_color.to_linear(); + clear_color = clear_color.srgb_to_linear(); scene_state.ubo.ambient_light_color_energy[0] = clear_color.r; scene_state.ubo.ambient_light_color_energy[1] = clear_color.g; scene_state.ubo.ambient_light_color_energy[2] = clear_color.b; @@ -963,6 +965,8 @@ _FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primit return (p_indices - subtractor[p_primitive]) / divisor[p_primitive]; } void RenderForwardClustered::_fill_render_list(RenderListType p_render_list, const RenderDataRD *p_render_data, PassMode p_pass_mode, bool p_using_sdfgi, bool p_using_opaque_gi, bool p_append) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); + if (p_render_list == RENDER_LIST_OPAQUE) { scene_state.used_sss = false; scene_state.used_screen_texture = false; @@ -1099,7 +1103,7 @@ void RenderForwardClustered::_fill_render_list(RenderListType p_render_list, con // LOD - if (p_render_data->screen_mesh_lod_threshold > 0.0 && storage->mesh_surface_has_lod(surf->surface)) { + if (p_render_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) { //lod Vector3 lod_support_min = inst->transformed_aabb.get_support(-p_render_data->lod_camera_plane.normal); Vector3 lod_support_max = inst->transformed_aabb.get_support(p_render_data->lod_camera_plane.normal); @@ -1123,7 +1127,7 @@ void RenderForwardClustered::_fill_render_list(RenderListType p_render_list, con } uint32_t indices; - surf->sort.lod_index = storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, &indices); + surf->sort.lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, &indices); if (p_render_data->render_info) { indices = _indices_to_primitives(surf->primitive, indices); if (p_render_list == RENDER_LIST_OPAQUE) { //opaque @@ -1135,13 +1139,13 @@ void RenderForwardClustered::_fill_render_list(RenderListType p_render_list, con } else { surf->sort.lod_index = 0; if (p_render_data->render_info) { - uint32_t to_draw = storage->mesh_surface_get_vertices_drawn_count(surf->surface); + uint32_t to_draw = mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface); to_draw = _indices_to_primitives(surf->primitive, to_draw); to_draw *= inst->instance_count; if (p_render_list == RENDER_LIST_OPAQUE) { //opaque - p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += storage->mesh_surface_get_vertices_drawn_count(surf->surface); + p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface); } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow - p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += storage->mesh_surface_get_vertices_drawn_count(surf->surface); + p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface); } } } @@ -1238,7 +1242,7 @@ void RenderForwardClustered::_setup_lightmaps(const PagedArray<RID> &p_lightmaps void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Color &p_default_bg_color) { RenderBufferDataForwardClustered *render_buffer = nullptr; if (p_render_data->render_buffers.is_valid()) { - render_buffer = (RenderBufferDataForwardClustered *)render_buffers_get_data(p_render_data->render_buffers); + render_buffer = static_cast<RenderBufferDataForwardClustered *>(render_buffers_get_data(p_render_data->render_buffers)); } RendererSceneEnvironmentRD *env = get_environment(p_render_data->environment); static const int texture_multisamples[RS::VIEWPORT_MSAA_MAX] = { 1, 2, 4, 8 }; @@ -1387,7 +1391,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co clear_color.b *= bg_energy; if (render_buffers_has_volumetric_fog(p_render_data->render_buffers) || environment_is_fog_enabled(p_render_data->environment)) { draw_sky_fog_only = true; - RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.to_linear())); + RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.srgb_to_linear())); } } break; case RS::ENV_BG_COLOR: { @@ -1397,7 +1401,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co clear_color.b *= bg_energy; if (render_buffers_has_volumetric_fog(p_render_data->render_buffers) || environment_is_fog_enabled(p_render_data->environment)) { draw_sky_fog_only = true; - RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.to_linear())); + RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.srgb_to_linear())); } } break; case RS::ENV_BG_SKY: { @@ -1516,7 +1520,7 @@ void RenderForwardClustered::_render_scene(RenderDataRD *p_render_data, const Co Vector<Color> c; { - Color cc = clear_color.to_linear(); + Color cc = clear_color.srgb_to_linear(); if (using_separate_specular) { cc.a = 0; //subsurf scatter must be 0 } @@ -1940,7 +1944,7 @@ void RenderForwardClustered::_render_sdfgi(RID p_render_buffers, const Vector3i _update_render_base_uniform_set(); - RenderBufferDataForwardClustered *render_buffer = (RenderBufferDataForwardClustered *)render_buffers_get_data(p_render_buffers); + RenderBufferDataForwardClustered *render_buffer = static_cast<RenderBufferDataForwardClustered *>(render_buffers_get_data(p_render_buffers)); ERR_FAIL_COND(!render_buffer); PassMode pass_mode = PASS_MODE_SDF; @@ -2208,7 +2212,7 @@ RID RenderForwardClustered::_setup_render_pass_uniform_set(RenderListType p_rend RenderBufferDataForwardClustered *rb = nullptr; if (p_render_data && p_render_data->render_buffers.is_valid()) { - rb = (RenderBufferDataForwardClustered *)render_buffers_get_data(p_render_data->render_buffers); + rb = static_cast<RenderBufferDataForwardClustered *>(render_buffers_get_data(p_render_data->render_buffers)); } //default render buffer and scene state uniform set @@ -2269,7 +2273,7 @@ RID RenderForwardClustered::_setup_render_pass_uniform_set(RenderListType p_rend texture = shadow_atlas_get_texture(p_render_data->shadow_atlas); } if (!texture.is_valid()) { - texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE); + texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH); } u.append_id(texture); uniforms.push_back(u); @@ -2281,7 +2285,7 @@ RID RenderForwardClustered::_setup_render_pass_uniform_set(RenderListType p_rend if (p_use_directional_shadow_atlas && directional_shadow_get_texture().is_valid()) { u.append_id(directional_shadow_get_texture()); } else { - u.append_id(texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE)); + u.append_id(texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH)); } uniforms.push_back(u); } @@ -2338,7 +2342,7 @@ RID RenderForwardClustered::_setup_render_pass_uniform_set(RenderListType p_rend u.binding = 9; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; RID dbt = rb ? render_buffers_get_back_depth_texture(p_render_data->render_buffers) : RID(); - RID texture = (dbt.is_valid()) ? dbt : texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE); + RID texture = (dbt.is_valid()) ? dbt : texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH); u.append_id(texture); uniforms.push_back(u); } @@ -2495,7 +2499,7 @@ RID RenderForwardClustered::_setup_sdfgi_render_pass_uniform_set(RID p_albedo_te RD::Uniform u; u.binding = 4; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; - RID texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE); + RID texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH); u.append_id(texture); uniforms.push_back(u); } @@ -2505,7 +2509,7 @@ RID RenderForwardClustered::_setup_sdfgi_render_pass_uniform_set(RID p_albedo_te RD::Uniform u; u.binding = 5; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; - RID texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE); + RID texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH); u.append_id(texture); uniforms.push_back(u); } @@ -2582,7 +2586,7 @@ RID RenderForwardClustered::_setup_sdfgi_render_pass_uniform_set(RID p_albedo_te } RID RenderForwardClustered::_render_buffers_get_normal_texture(RID p_render_buffers) { - RenderBufferDataForwardClustered *rb = (RenderBufferDataForwardClustered *)render_buffers_get_data(p_render_buffers); + RenderBufferDataForwardClustered *rb = static_cast<RenderBufferDataForwardClustered *>(render_buffers_get_data(p_render_buffers)); return rb->normal_roughness_buffer; } @@ -2610,6 +2614,8 @@ void RenderForwardClustered::_geometry_instance_mark_dirty(GeometryInstance *p_g } void RenderForwardClustered::_geometry_instance_add_surface_with_material(GeometryInstanceForwardClustered *ginstance, uint32_t p_surface, SceneShaderForwardClustered::MaterialData *p_material, uint32_t p_material_id, uint32_t p_shader_id, RID p_mesh) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); + bool has_read_screen_alpha = p_material->shader_data->uses_screen_texture || p_material->shader_data->uses_depth_texture || p_material->shader_data->uses_normal_texture; bool has_base_alpha = (p_material->shader_data->uses_alpha && !p_material->shader_data->uses_alpha_clip) || has_read_screen_alpha; bool has_blend_alpha = p_material->shader_data->uses_blend_alpha; @@ -2658,12 +2664,12 @@ void RenderForwardClustered::_geometry_instance_add_surface_with_material(Geomet void *surface_shadow = nullptr; if (!p_material->shader_data->uses_particle_trails && !p_material->shader_data->writes_modelview_or_projection && !p_material->shader_data->uses_vertex && !p_material->shader_data->uses_position && !p_material->shader_data->uses_discard && !p_material->shader_data->uses_depth_pre_pass && !p_material->shader_data->uses_alpha_clip) { flags |= GeometryInstanceSurfaceDataCache::FLAG_USES_SHARED_SHADOW_MATERIAL; - material_shadow = (SceneShaderForwardClustered::MaterialData *)RendererRD::MaterialStorage::get_singleton()->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D); + material_shadow = static_cast<SceneShaderForwardClustered::MaterialData *>(RendererRD::MaterialStorage::get_singleton()->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D)); - RID shadow_mesh = storage->mesh_get_shadow_mesh(p_mesh); + RID shadow_mesh = mesh_storage->mesh_get_shadow_mesh(p_mesh); if (shadow_mesh.is_valid()) { - surface_shadow = storage->mesh_get_surface(shadow_mesh, p_surface); + surface_shadow = mesh_storage->mesh_get_surface(shadow_mesh, p_surface); } } else { @@ -2676,8 +2682,8 @@ void RenderForwardClustered::_geometry_instance_add_surface_with_material(Geomet sdcache->shader = p_material->shader_data; sdcache->material_uniform_set = p_material->uniform_set; - sdcache->surface = storage->mesh_get_surface(p_mesh, p_surface); - sdcache->primitive = storage->mesh_surface_get_primitive(sdcache->surface); + sdcache->surface = mesh_storage->mesh_get_surface(p_mesh, p_surface); + sdcache->primitive = mesh_storage->mesh_surface_get_primitive(sdcache->surface); sdcache->surface_index = p_surface; if (ginstance->data->dirty_dependencies) { @@ -2719,7 +2725,7 @@ void RenderForwardClustered::_geometry_instance_add_surface_with_material_chain( while (material->next_pass.is_valid()) { RID next_pass = material->next_pass; - material = (SceneShaderForwardClustered::MaterialData *)material_storage->material_get_data(next_pass, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardClustered::MaterialData *>(material_storage->material_get_data(next_pass, RendererRD::SHADER_TYPE_3D)); if (!material || !material->shader_data->valid) { break; } @@ -2739,7 +2745,7 @@ void RenderForwardClustered::_geometry_instance_add_surface(GeometryInstanceForw SceneShaderForwardClustered::MaterialData *material = nullptr; if (m_src.is_valid()) { - material = (SceneShaderForwardClustered::MaterialData *)material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardClustered::MaterialData *>(material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -2750,7 +2756,7 @@ void RenderForwardClustered::_geometry_instance_add_surface(GeometryInstanceForw material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker); } } else { - material = (SceneShaderForwardClustered::MaterialData *)material_storage->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardClustered::MaterialData *>(material_storage->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D)); m_src = scene_shader.default_material; } @@ -2761,7 +2767,7 @@ void RenderForwardClustered::_geometry_instance_add_surface(GeometryInstanceForw if (ginstance->data->material_overlay.is_valid()) { m_src = ginstance->data->material_overlay; - material = (SceneShaderForwardClustered::MaterialData *)material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardClustered::MaterialData *>(material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D)); if (material && material->shader_data->valid) { if (ginstance->data->dirty_dependencies) { material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker); @@ -2773,6 +2779,7 @@ void RenderForwardClustered::_geometry_instance_add_surface(GeometryInstanceForw } void RenderForwardClustered::_geometry_instance_update(GeometryInstance *p_geometry_instance) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); GeometryInstanceForwardClustered *ginstance = static_cast<GeometryInstanceForwardClustered *>(p_geometry_instance); if (ginstance->data->dirty_dependencies) { @@ -2786,7 +2793,7 @@ void RenderForwardClustered::_geometry_instance_update(GeometryInstance *p_geome uint32_t surface_count; RID mesh = ginstance->data->base; - materials = storage->mesh_get_surface_count_and_materials(mesh, surface_count); + materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count); if (materials) { //if no materials, no surfaces. const RID *inst_materials = ginstance->data->surface_materials.ptr(); @@ -2803,19 +2810,19 @@ void RenderForwardClustered::_geometry_instance_update(GeometryInstance *p_geome } break; case RS::INSTANCE_MULTIMESH: { - RID mesh = storage->multimesh_get_mesh(ginstance->data->base); + RID mesh = mesh_storage->multimesh_get_mesh(ginstance->data->base); if (mesh.is_valid()) { const RID *materials = nullptr; uint32_t surface_count; - materials = storage->mesh_get_surface_count_and_materials(mesh, surface_count); + materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count); if (materials) { for (uint32_t j = 0; j < surface_count; j++) { _geometry_instance_add_surface(ginstance, j, materials[j], mesh); } } - ginstance->instance_count = storage->multimesh_get_instances_to_draw(ginstance->data->base); + ginstance->instance_count = mesh_storage->multimesh_get_instances_to_draw(ginstance->data->base); } } break; @@ -2840,7 +2847,7 @@ void RenderForwardClustered::_geometry_instance_update(GeometryInstance *p_geome const RID *materials = nullptr; uint32_t surface_count; - materials = storage->mesh_get_surface_count_and_materials(mesh, surface_count); + materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count); if (materials) { for (uint32_t k = 0; k < surface_count; k++) { _geometry_instance_add_surface(ginstance, k, materials[k], mesh); @@ -2864,17 +2871,17 @@ void RenderForwardClustered::_geometry_instance_update(GeometryInstance *p_geome if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH; - if (storage->multimesh_get_transform_format(ginstance->data->base) == RS::MULTIMESH_TRANSFORM_2D) { + if (mesh_storage->multimesh_get_transform_format(ginstance->data->base) == RS::MULTIMESH_TRANSFORM_2D) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D; } - if (storage->multimesh_uses_colors(ginstance->data->base)) { + if (mesh_storage->multimesh_uses_colors(ginstance->data->base)) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR; } - if (storage->multimesh_uses_custom_data(ginstance->data->base)) { + if (mesh_storage->multimesh_uses_custom_data(ginstance->data->base)) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA; } - ginstance->transforms_uniform_set = storage->multimesh_get_3d_uniform_set(ginstance->data->base, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); + ginstance->transforms_uniform_set = mesh_storage->multimesh_get_3d_uniform_set(ginstance->data->base, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); } else if (ginstance->data->base_type == RS::INSTANCE_PARTICLES) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH; @@ -2891,10 +2898,10 @@ void RenderForwardClustered::_geometry_instance_update(GeometryInstance *p_geome ginstance->transforms_uniform_set = storage->particles_get_instance_buffer_uniform_set(ginstance->data->base, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); } else if (ginstance->data->base_type == RS::INSTANCE_MESH) { - if (storage->skeleton_is_valid(ginstance->data->skeleton)) { - ginstance->transforms_uniform_set = storage->skeleton_get_3d_uniform_set(ginstance->data->skeleton, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); + if (mesh_storage->skeleton_is_valid(ginstance->data->skeleton)) { + ginstance->transforms_uniform_set = mesh_storage->skeleton_get_3d_uniform_set(ginstance->data->skeleton, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); if (ginstance->data->dirty_dependencies) { - storage->skeleton_update_dependency(ginstance->data->skeleton, &ginstance->data->dependency_tracker); + mesh_storage->skeleton_update_dependency(ginstance->data->skeleton, &ginstance->data->dependency_tracker); } } } @@ -2934,7 +2941,7 @@ void RenderForwardClustered::_geometry_instance_dependency_changed(RendererStora case RendererStorage::DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES: { GeometryInstanceForwardClustered *ginstance = static_cast<GeometryInstanceForwardClustered *>(p_tracker->userdata); if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) { - ginstance->instance_count = static_cast<RenderForwardClustered *>(singleton)->storage->multimesh_get_instances_to_draw(ginstance->data->base); + ginstance->instance_count = RendererRD::MeshStorage::get_singleton()->multimesh_get_instances_to_draw(ginstance->data->base); } } break; default: { diff --git a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h index 11016968ed..37366d3e14 100644 --- a/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h +++ b/servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.h @@ -332,7 +332,7 @@ class RenderForwardClustered : public RendererSceneRenderRD { uint32_t instance_buffer_size[RENDER_LIST_MAX] = { 0, 0, 0 }; LocalVector<InstanceData> instance_data[RENDER_LIST_MAX]; - LightmapCaptureData *lightmap_captures; + LightmapCaptureData *lightmap_captures = nullptr; uint32_t max_lightmap_captures; RID lightmap_capture_buffer; diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp index c42ac98a84..6b0d245e44 100644 --- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp +++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.cpp @@ -293,16 +293,16 @@ void SceneShaderForwardClustered::ShaderData::set_code(const String &p_code) { raster_state.cull_mode = cull_mode_rd; raster_state.wireframe = wireframe; - RD::PipelineColorBlendState blend_state; - RD::PipelineDepthStencilState depth_stencil = depth_stencil_state; - RD::PipelineMultisampleState multisample_state; - if (k == PIPELINE_VERSION_COLOR_PASS) { for (int l = 0; l < PIPELINE_COLOR_PASS_FLAG_COUNT; l++) { if (!shader_singleton->valid_color_pass_pipelines.has(l)) { continue; } + RD::PipelineColorBlendState blend_state; + RD::PipelineDepthStencilState depth_stencil = depth_stencil_state; + RD::PipelineMultisampleState multisample_state; + int shader_flags = 0; if (l & PIPELINE_COLOR_PASS_FLAG_TRANSPARENT) { if (alpha_antialiasing_mode == ALPHA_ANTIALIASING_ALPHA_TO_COVERAGE) { @@ -338,6 +338,10 @@ void SceneShaderForwardClustered::ShaderData::set_code(const String &p_code) { color_pipelines[i][j][l].setup(shader_variant, primitive_rd, raster_state, multisample_state, depth_stencil, blend_state, 0, singleton->default_specialization_constants); } } else { + RD::PipelineColorBlendState blend_state; + RD::PipelineDepthStencilState depth_stencil = depth_stencil_state; + RD::PipelineMultisampleState multisample_state; + if (k == PIPELINE_VERSION_DEPTH_PASS || k == PIPELINE_VERSION_DEPTH_PASS_DP || k == PIPELINE_VERSION_DEPTH_PASS_MULTIVIEW) { //none, leave empty } else if (k == PIPELINE_VERSION_DEPTH_PASS_WITH_NORMAL_AND_ROUGHNESS) { @@ -762,7 +766,7 @@ void fragment() { material_storage->material_initialize(default_material); material_storage->material_set_shader(default_material, default_shader); - MaterialData *md = (MaterialData *)material_storage->material_get_data(default_material, RendererRD::SHADER_TYPE_3D); + MaterialData *md = static_cast<MaterialData *>(material_storage->material_get_data(default_material, RendererRD::SHADER_TYPE_3D)); default_shader_rd = shader.version_get_shader(md->shader_data->version, SHADER_VERSION_COLOR_PASS); default_shader_sdfgi_rd = shader.version_get_shader(md->shader_data->version, SHADER_VERSION_DEPTH_PASS_WITH_SDF); @@ -790,7 +794,7 @@ void fragment() { material_storage->material_initialize(overdraw_material); material_storage->material_set_shader(overdraw_material, overdraw_material_shader); - MaterialData *md = (MaterialData *)material_storage->material_get_data(overdraw_material, RendererRD::SHADER_TYPE_3D); + MaterialData *md = static_cast<MaterialData *>(material_storage->material_get_data(overdraw_material, RendererRD::SHADER_TYPE_3D)); overdraw_material_shader_ptr = md->shader_data; overdraw_material_uniform_set = md->uniform_set; } @@ -824,6 +828,9 @@ void SceneShaderForwardClustered::set_default_specialization_constants(const Vec for (int k = 0; k < SHADER_VERSION_MAX; k++) { E->self()->pipelines[i][j][k].update_specialization_constants(default_specialization_constants); } + for (int k = 0; k < PIPELINE_COLOR_PASS_FLAG_COUNT; k++) { + E->self()->color_pipelines[i][j][k].update_specialization_constants(default_specialization_constants); + } } } } diff --git a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h index c3039e2f7f..1b7709bedb 100644 --- a/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h +++ b/servers/rendering/renderer_rd/forward_clustered/scene_shader_forward_clustered.h @@ -42,7 +42,7 @@ private: static SceneShaderForwardClustered *singleton; public: - RendererStorageRD *storage; + RendererStorageRD *storage = nullptr; enum ShaderVersion { SHADER_VERSION_DEPTH_PASS, @@ -199,7 +199,7 @@ public: } struct MaterialData : public RendererRD::MaterialData { - ShaderData *shader_data; + ShaderData *shader_data = nullptr; RID uniform_set; uint64_t last_pass = 0; uint32_t index = 0; diff --git a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp index 1153a33a27..6988e3c1dd 100644 --- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp +++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.cpp @@ -31,6 +31,7 @@ #include "render_forward_mobile.h" #include "core/config/project_settings.h" #include "servers/rendering/renderer_rd/storage_rd/decal_atlas_storage.h" +#include "servers/rendering/renderer_rd/storage_rd/mesh_storage.h" #include "servers/rendering/rendering_device.h" #include "servers/rendering/rendering_server_default.h" @@ -297,7 +298,7 @@ RID RenderForwardMobile::_setup_render_pass_uniform_set(RenderListType p_render_ RenderBufferDataForwardMobile *rb = nullptr; if (p_render_data && p_render_data->render_buffers.is_valid()) { - rb = (RenderBufferDataForwardMobile *)render_buffers_get_data(p_render_data->render_buffers); + rb = static_cast<RenderBufferDataForwardMobile *>(render_buffers_get_data(p_render_data->render_buffers)); } // default render buffer and scene state uniform set @@ -349,7 +350,7 @@ RID RenderForwardMobile::_setup_render_pass_uniform_set(RenderListType p_render_ texture = shadow_atlas_get_texture(p_render_data->shadow_atlas); } if (!texture.is_valid()) { - texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE); + texture = texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH); } u.append_id(texture); uniforms.push_back(u); @@ -361,7 +362,7 @@ RID RenderForwardMobile::_setup_render_pass_uniform_set(RenderListType p_render_ if (p_use_directional_shadow_atlas && directional_shadow_get_texture().is_valid()) { u.append_id(directional_shadow_get_texture()); } else { - u.append_id(texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE)); + u.append_id(texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH)); } uniforms.push_back(u); } @@ -424,7 +425,7 @@ RID RenderForwardMobile::_setup_render_pass_uniform_set(RenderListType p_render_ u.binding = 9; u.uniform_type = RD::UNIFORM_TYPE_TEXTURE; RID dbt = rb ? render_buffers_get_back_depth_texture(p_render_data->render_buffers) : RID(); - RID texture = (dbt.is_valid()) ? dbt : texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_WHITE); + RID texture = (dbt.is_valid()) ? dbt : texture_storage->texture_rd_get_default(RendererRD::DEFAULT_RD_TEXTURE_DEPTH); u.append_id(texture); uniforms.push_back(u); } @@ -476,7 +477,7 @@ void RenderForwardMobile::_setup_lightmaps(const PagedArray<RID> &p_lightmaps, c void RenderForwardMobile::_render_scene(RenderDataRD *p_render_data, const Color &p_default_bg_color) { RenderBufferDataForwardMobile *render_buffer = nullptr; if (p_render_data->render_buffers.is_valid()) { - render_buffer = (RenderBufferDataForwardMobile *)render_buffers_get_data(p_render_data->render_buffers); + render_buffer = static_cast<RenderBufferDataForwardMobile *>(render_buffers_get_data(p_render_data->render_buffers)); } RendererSceneEnvironmentRD *env = get_environment(p_render_data->environment); @@ -595,7 +596,7 @@ void RenderForwardMobile::_render_scene(RenderDataRD *p_render_data, const Color /* if (render_buffers_has_volumetric_fog(p_render_data->render_buffers) || environment_is_fog_enabled(p_render_data->environment)) { draw_sky_fog_only = true; - RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.to_linear())); + RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.srgb_to_linear())); } */ } break; @@ -607,7 +608,7 @@ void RenderForwardMobile::_render_scene(RenderDataRD *p_render_data, const Color /* if (render_buffers_has_volumetric_fog(p_render_data->render_buffers) || environment_is_fog_enabled(p_render_data->environment)) { draw_sky_fog_only = true; - RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.to_linear())); + RendererRD::MaterialStorage::get_singleton()->material_set_param(sky.sky_scene_state.fog_material, "clear_color", Variant(clear_color.srgb_to_linear())); } */ } break; @@ -722,10 +723,10 @@ void RenderForwardMobile::_render_scene(RenderDataRD *p_render_data, const Color { // regular forward for now Vector<Color> c; - c.push_back(clear_color.to_linear()); // our render buffer + c.push_back(clear_color.srgb_to_linear()); // our render buffer if (render_buffer) { if (render_buffer->msaa != RS::VIEWPORT_MSAA_DISABLED) { - c.push_back(clear_color.to_linear()); // our resolve buffer + c.push_back(clear_color.srgb_to_linear()); // our resolve buffer } if (using_subpass_post_process) { c.push_back(Color()); // our 2D buffer we're copying into @@ -1325,6 +1326,8 @@ _FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primit } void RenderForwardMobile::_fill_render_list(RenderListType p_render_list, const RenderDataRD *p_render_data, PassMode p_pass_mode, bool p_append) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); + if (p_render_list == RENDER_LIST_OPAQUE) { scene_state.used_sss = false; scene_state.used_screen_texture = false; @@ -1414,7 +1417,7 @@ void RenderForwardMobile::_fill_render_list(RenderListType p_render_list, const // LOD - if (p_render_data->screen_mesh_lod_threshold > 0.0 && storage->mesh_surface_has_lod(surf->surface)) { + if (p_render_data->screen_mesh_lod_threshold > 0.0 && mesh_storage->mesh_surface_has_lod(surf->surface)) { //lod Vector3 lod_support_min = inst->transformed_aabb.get_support(-p_render_data->lod_camera_plane.normal); Vector3 lod_support_max = inst->transformed_aabb.get_support(p_render_data->lod_camera_plane.normal); @@ -1438,7 +1441,7 @@ void RenderForwardMobile::_fill_render_list(RenderListType p_render_list, const } uint32_t indices; - surf->lod_index = storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, &indices); + surf->lod_index = mesh_storage->mesh_surface_get_lod(surf->surface, inst->lod_model_scale * inst->lod_bias, distance * p_render_data->lod_distance_multiplier, p_render_data->screen_mesh_lod_threshold, &indices); if (p_render_data->render_info) { indices = _indices_to_primitives(surf->primitive, indices); if (p_render_list == RENDER_LIST_OPAQUE) { //opaque @@ -1450,13 +1453,13 @@ void RenderForwardMobile::_fill_render_list(RenderListType p_render_list, const } else { surf->lod_index = 0; if (p_render_data->render_info) { - uint32_t to_draw = storage->mesh_surface_get_vertices_drawn_count(surf->surface); + uint32_t to_draw = mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface); to_draw = _indices_to_primitives(surf->primitive, to_draw); to_draw *= inst->instance_count; if (p_render_list == RENDER_LIST_OPAQUE) { //opaque - p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += storage->mesh_surface_get_vertices_drawn_count(surf->surface); + p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_VISIBLE][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface); } else if (p_render_list == RENDER_LIST_SECONDARY) { //shadow - p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += storage->mesh_surface_get_vertices_drawn_count(surf->surface); + p_render_data->render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_SHADOW][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += mesh_storage->mesh_surface_get_vertices_drawn_count(surf->surface); } } } @@ -1566,7 +1569,7 @@ void RenderForwardMobile::_setup_environment(const RenderDataRD *p_render_data, scene_state.ubo.fog_enabled = false; if (p_render_data->render_buffers.is_valid()) { - RenderBufferDataForwardMobile *render_buffers = (RenderBufferDataForwardMobile *)render_buffers_get_data(p_render_data->render_buffers); + RenderBufferDataForwardMobile *render_buffers = static_cast<RenderBufferDataForwardMobile *>(render_buffers_get_data(p_render_data->render_buffers)); if (render_buffers->msaa != RS::VIEWPORT_MSAA_DISABLED) { scene_state.ubo.gi_upscale_for_msaa = true; } @@ -1613,7 +1616,7 @@ void RenderForwardMobile::_setup_environment(const RenderDataRD *p_render_data, //ambient if (ambient_src == RS::ENV_AMBIENT_SOURCE_BG && (env_bg == RS::ENV_BG_CLEAR_COLOR || env_bg == RS::ENV_BG_COLOR)) { Color color = env_bg == RS::ENV_BG_CLEAR_COLOR ? p_default_bg_color : environment_get_bg_color(p_render_data->environment); - color = color.to_linear(); + color = color.srgb_to_linear(); scene_state.ubo.ambient_light_color_energy[0] = color.r * bg_energy; scene_state.ubo.ambient_light_color_energy[1] = color.g * bg_energy; @@ -1623,7 +1626,7 @@ void RenderForwardMobile::_setup_environment(const RenderDataRD *p_render_data, } else { float energy = environment_get_ambient_light_energy(p_render_data->environment); Color color = environment_get_ambient_light_color(p_render_data->environment); - color = color.to_linear(); + color = color.srgb_to_linear(); scene_state.ubo.ambient_light_color_energy[0] = color.r * energy; scene_state.ubo.ambient_light_color_energy[1] = color.g * energy; scene_state.ubo.ambient_light_color_energy[2] = color.b * energy; @@ -1654,7 +1657,7 @@ void RenderForwardMobile::_setup_environment(const RenderDataRD *p_render_data, scene_state.ubo.fog_height_density = environment_get_fog_height_density(p_render_data->environment); scene_state.ubo.fog_aerial_perspective = environment_get_fog_aerial_perspective(p_render_data->environment); - Color fog_color = environment_get_fog_light_color(p_render_data->environment).to_linear(); + Color fog_color = environment_get_fog_light_color(p_render_data->environment).srgb_to_linear(); float fog_energy = environment_get_fog_light_energy(p_render_data->environment); scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy; @@ -1669,7 +1672,7 @@ void RenderForwardMobile::_setup_environment(const RenderDataRD *p_render_data, } else { scene_state.ubo.use_ambient_light = true; Color clear_color = p_default_bg_color; - clear_color = clear_color.to_linear(); + clear_color = clear_color.srgb_to_linear(); scene_state.ubo.ambient_light_color_energy[0] = clear_color.r; scene_state.ubo.ambient_light_color_energy[1] = clear_color.g; scene_state.ubo.ambient_light_color_energy[2] = clear_color.b; @@ -1814,6 +1817,8 @@ void RenderForwardMobile::_fill_push_constant_instance_indices(GeometryInstanceF template <RenderForwardMobile::PassMode p_pass_mode> void RenderForwardMobile::_render_list_template(RenderingDevice::DrawListID p_draw_list, RenderingDevice::FramebufferFormatID p_framebuffer_Format, RenderListParameters *p_params, uint32_t p_from_element, uint32_t p_to_element) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); + RD::DrawListID draw_list = p_draw_list; RD::FramebufferFormatID framebuffer_format = p_framebuffer_Format; @@ -1956,12 +1961,12 @@ void RenderForwardMobile::_render_list_template(RenderingDevice::DrawListID p_dr //skeleton and blend shape if (surf->owner->mesh_instance.is_valid()) { - storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); + mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(surf->owner->mesh_instance, surf->surface_index, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); } else { - storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); + mesh_storage->mesh_surface_get_vertex_arrays_and_format(mesh_surface, pipeline->get_vertex_input_mask(), vertex_array_rd, vertex_format); } - index_array_rd = storage->mesh_surface_get_index_array(mesh_surface, element_info.lod_index); + index_array_rd = mesh_storage->mesh_surface_get_index_array(mesh_surface, element_info.lod_index); if (prev_vertex_array_rd != vertex_array_rd) { RD::get_singleton()->draw_list_bind_vertex_array(draw_list, vertex_array_rd); @@ -2280,6 +2285,8 @@ void RenderForwardMobile::_geometry_instance_mark_dirty(GeometryInstance *p_geom } void RenderForwardMobile::_geometry_instance_add_surface_with_material(GeometryInstanceForwardMobile *ginstance, uint32_t p_surface, SceneShaderForwardMobile::MaterialData *p_material, uint32_t p_material_id, uint32_t p_shader_id, RID p_mesh) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); + bool has_read_screen_alpha = p_material->shader_data->uses_screen_texture || p_material->shader_data->uses_depth_texture || p_material->shader_data->uses_normal_texture; bool has_base_alpha = ((p_material->shader_data->uses_alpha && !p_material->shader_data->uses_alpha_clip) || has_read_screen_alpha); bool has_blend_alpha = p_material->shader_data->uses_blend_alpha; @@ -2328,12 +2335,12 @@ void RenderForwardMobile::_geometry_instance_add_surface_with_material(GeometryI void *surface_shadow = nullptr; if (!p_material->shader_data->uses_particle_trails && !p_material->shader_data->writes_modelview_or_projection && !p_material->shader_data->uses_vertex && !p_material->shader_data->uses_discard && !p_material->shader_data->uses_depth_pre_pass && !p_material->shader_data->uses_alpha_clip) { flags |= GeometryInstanceSurfaceDataCache::FLAG_USES_SHARED_SHADOW_MATERIAL; - material_shadow = (SceneShaderForwardMobile::MaterialData *)RendererRD::MaterialStorage::get_singleton()->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D); + material_shadow = static_cast<SceneShaderForwardMobile::MaterialData *>(RendererRD::MaterialStorage::get_singleton()->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D)); - RID shadow_mesh = storage->mesh_get_shadow_mesh(p_mesh); + RID shadow_mesh = mesh_storage->mesh_get_shadow_mesh(p_mesh); if (shadow_mesh.is_valid()) { - surface_shadow = storage->mesh_get_surface(shadow_mesh, p_surface); + surface_shadow = mesh_storage->mesh_get_surface(shadow_mesh, p_surface); } } else { @@ -2346,8 +2353,8 @@ void RenderForwardMobile::_geometry_instance_add_surface_with_material(GeometryI sdcache->shader = p_material->shader_data; sdcache->material_uniform_set = p_material->uniform_set; - sdcache->surface = storage->mesh_get_surface(p_mesh, p_surface); - sdcache->primitive = storage->mesh_surface_get_primitive(sdcache->surface); + sdcache->surface = mesh_storage->mesh_get_surface(p_mesh, p_surface); + sdcache->primitive = mesh_storage->mesh_surface_get_primitive(sdcache->surface); sdcache->surface_index = p_surface; if (ginstance->data->dirty_dependencies) { @@ -2387,7 +2394,7 @@ void RenderForwardMobile::_geometry_instance_add_surface_with_material_chain(Geo while (material->next_pass.is_valid()) { RID next_pass = material->next_pass; - material = (SceneShaderForwardMobile::MaterialData *)material_storage->material_get_data(next_pass, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardMobile::MaterialData *>(material_storage->material_get_data(next_pass, RendererRD::SHADER_TYPE_3D)); if (!material || !material->shader_data->valid) { break; } @@ -2407,7 +2414,7 @@ void RenderForwardMobile::_geometry_instance_add_surface(GeometryInstanceForward SceneShaderForwardMobile::MaterialData *material = nullptr; if (m_src.is_valid()) { - material = (SceneShaderForwardMobile::MaterialData *)material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardMobile::MaterialData *>(material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -2418,7 +2425,7 @@ void RenderForwardMobile::_geometry_instance_add_surface(GeometryInstanceForward material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker); } } else { - material = (SceneShaderForwardMobile::MaterialData *)material_storage->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardMobile::MaterialData *>(material_storage->material_get_data(scene_shader.default_material, RendererRD::SHADER_TYPE_3D)); m_src = scene_shader.default_material; } @@ -2429,7 +2436,7 @@ void RenderForwardMobile::_geometry_instance_add_surface(GeometryInstanceForward if (ginstance->data->material_overlay.is_valid()) { m_src = ginstance->data->material_overlay; - material = (SceneShaderForwardMobile::MaterialData *)material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D); + material = static_cast<SceneShaderForwardMobile::MaterialData *>(material_storage->material_get_data(m_src, RendererRD::SHADER_TYPE_3D)); if (material && material->shader_data->valid) { if (ginstance->data->dirty_dependencies) { material_storage->material_update_dependency(m_src, &ginstance->data->dependency_tracker); @@ -2441,6 +2448,7 @@ void RenderForwardMobile::_geometry_instance_add_surface(GeometryInstanceForward } void RenderForwardMobile::_geometry_instance_update(GeometryInstance *p_geometry_instance) { + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); GeometryInstanceForwardMobile *ginstance = static_cast<GeometryInstanceForwardMobile *>(p_geometry_instance); if (ginstance->data->dirty_dependencies) { @@ -2454,7 +2462,7 @@ void RenderForwardMobile::_geometry_instance_update(GeometryInstance *p_geometry uint32_t surface_count; RID mesh = ginstance->data->base; - materials = storage->mesh_get_surface_count_and_materials(mesh, surface_count); + materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count); if (materials) { //if no materials, no surfaces. const RID *inst_materials = ginstance->data->surface_materials.ptr(); @@ -2471,19 +2479,19 @@ void RenderForwardMobile::_geometry_instance_update(GeometryInstance *p_geometry } break; case RS::INSTANCE_MULTIMESH: { - RID mesh = storage->multimesh_get_mesh(ginstance->data->base); + RID mesh = mesh_storage->multimesh_get_mesh(ginstance->data->base); if (mesh.is_valid()) { const RID *materials = nullptr; uint32_t surface_count; - materials = storage->mesh_get_surface_count_and_materials(mesh, surface_count); + materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count); if (materials) { for (uint32_t j = 0; j < surface_count; j++) { _geometry_instance_add_surface(ginstance, j, materials[j], mesh); } } - ginstance->instance_count = storage->multimesh_get_instances_to_draw(ginstance->data->base); + ginstance->instance_count = mesh_storage->multimesh_get_instances_to_draw(ginstance->data->base); } } break; @@ -2508,7 +2516,7 @@ void RenderForwardMobile::_geometry_instance_update(GeometryInstance *p_geometry const RID *materials = nullptr; uint32_t surface_count; - materials = storage->mesh_get_surface_count_and_materials(mesh, surface_count); + materials = mesh_storage->mesh_get_surface_count_and_materials(mesh, surface_count); if (materials) { for (uint32_t k = 0; k < surface_count; k++) { _geometry_instance_add_surface(ginstance, k, materials[k], mesh); @@ -2531,17 +2539,17 @@ void RenderForwardMobile::_geometry_instance_update(GeometryInstance *p_geometry if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH; - if (storage->multimesh_get_transform_format(ginstance->data->base) == RS::MULTIMESH_TRANSFORM_2D) { + if (mesh_storage->multimesh_get_transform_format(ginstance->data->base) == RS::MULTIMESH_TRANSFORM_2D) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_FORMAT_2D; } - if (storage->multimesh_uses_colors(ginstance->data->base)) { + if (mesh_storage->multimesh_uses_colors(ginstance->data->base)) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_COLOR; } - if (storage->multimesh_uses_custom_data(ginstance->data->base)) { + if (mesh_storage->multimesh_uses_custom_data(ginstance->data->base)) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH_HAS_CUSTOM_DATA; } - ginstance->transforms_uniform_set = storage->multimesh_get_3d_uniform_set(ginstance->data->base, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); + ginstance->transforms_uniform_set = mesh_storage->multimesh_get_3d_uniform_set(ginstance->data->base, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); } else if (ginstance->data->base_type == RS::INSTANCE_PARTICLES) { ginstance->base_flags |= INSTANCE_DATA_FLAG_MULTIMESH; @@ -2561,10 +2569,10 @@ void RenderForwardMobile::_geometry_instance_update(GeometryInstance *p_geometry ginstance->transforms_uniform_set = storage->particles_get_instance_buffer_uniform_set(ginstance->data->base, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); } else if (ginstance->data->base_type == RS::INSTANCE_MESH) { - if (storage->skeleton_is_valid(ginstance->data->skeleton)) { - ginstance->transforms_uniform_set = storage->skeleton_get_3d_uniform_set(ginstance->data->skeleton, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); + if (mesh_storage->skeleton_is_valid(ginstance->data->skeleton)) { + ginstance->transforms_uniform_set = mesh_storage->skeleton_get_3d_uniform_set(ginstance->data->skeleton, scene_shader.default_shader_rd, TRANSFORMS_UNIFORM_SET); if (ginstance->data->dirty_dependencies) { - storage->skeleton_update_dependency(ginstance->data->skeleton, &ginstance->data->dependency_tracker); + mesh_storage->skeleton_update_dependency(ginstance->data->skeleton, &ginstance->data->dependency_tracker); } } } @@ -2597,7 +2605,7 @@ void RenderForwardMobile::_geometry_instance_dependency_changed(RendererStorage: case RendererStorage::DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES: { GeometryInstanceForwardMobile *ginstance = static_cast<GeometryInstanceForwardMobile *>(p_tracker->userdata); if (ginstance->data->base_type == RS::INSTANCE_MULTIMESH) { - ginstance->instance_count = static_cast<RenderForwardMobile *>(singleton)->storage->multimesh_get_instances_to_draw(ginstance->data->base); + ginstance->instance_count = RendererRD::MeshStorage::get_singleton()->multimesh_get_instances_to_draw(ginstance->data->base); } } break; default: { diff --git a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h index 6162ca55af..0ddfe89eea 100644 --- a/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h +++ b/servers/rendering/renderer_rd/forward_mobile/render_forward_mobile.h @@ -328,7 +328,7 @@ protected: uint32_t max_lightmaps; RID lightmap_buffer; - LightmapCaptureData *lightmap_captures; + LightmapCaptureData *lightmap_captures = nullptr; uint32_t max_lightmap_captures; RID lightmap_capture_buffer; diff --git a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp index 2f56dc0af6..60badbdfee 100644 --- a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp +++ b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.cpp @@ -700,7 +700,7 @@ void fragment() { material_storage->material_initialize(default_material); material_storage->material_set_shader(default_material, default_shader); - MaterialData *md = (MaterialData *)material_storage->material_get_data(default_material, RendererRD::SHADER_TYPE_3D); + MaterialData *md = static_cast<MaterialData *>(material_storage->material_get_data(default_material, RendererRD::SHADER_TYPE_3D)); default_shader_rd = shader.version_get_shader(md->shader_data->version, SHADER_VERSION_COLOR_PASS); default_material_shader_ptr = md->shader_data; @@ -727,7 +727,7 @@ void fragment() { material_storage->material_initialize(overdraw_material); material_storage->material_set_shader(overdraw_material, overdraw_material_shader); - MaterialData *md = (MaterialData *)material_storage->material_get_data(overdraw_material, RendererRD::SHADER_TYPE_3D); + MaterialData *md = static_cast<MaterialData *>(material_storage->material_get_data(overdraw_material, RendererRD::SHADER_TYPE_3D)); overdraw_material_shader_ptr = md->shader_data; overdraw_material_uniform_set = md->uniform_set; } diff --git a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h index 0f5017dba1..b89fe908d3 100644 --- a/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h +++ b/servers/rendering/renderer_rd/forward_mobile/scene_shader_forward_mobile.h @@ -40,7 +40,7 @@ namespace RendererSceneRenderImplementation { class SceneShaderForwardMobile { private: static SceneShaderForwardMobile *singleton; - RendererStorageRD *storage; + RendererStorageRD *storage = nullptr; public: enum ShaderVersion { @@ -163,7 +163,7 @@ public: } struct MaterialData : public RendererRD::MaterialData { - ShaderData *shader_data; + ShaderData *shader_data = nullptr; RID uniform_set; uint64_t last_pass = 0; uint32_t index = 0; diff --git a/servers/rendering/renderer_rd/pipeline_cache_rd.cpp b/servers/rendering/renderer_rd/pipeline_cache_rd.cpp index e812a48d3d..9151c53823 100644 --- a/servers/rendering/renderer_rd/pipeline_cache_rd.cpp +++ b/servers/rendering/renderer_rd/pipeline_cache_rd.cpp @@ -58,7 +58,7 @@ RID PipelineCacheRD::_generate_version(RD::VertexFormatID p_vertex_format_id, RD RID pipeline = RD::get_singleton()->render_pipeline_create(shader, p_framebuffer_format_id, p_vertex_format_id, render_primitive, raster_state_version, multisample_state_version, depth_stencil_state, blend_state, dynamic_state_flags, p_render_pass, specialization_constants); ERR_FAIL_COND_V(pipeline.is_null(), RID()); - versions = (Version *)memrealloc(versions, sizeof(Version) * (version_count + 1)); + versions = static_cast<Version *>(memrealloc(versions, sizeof(Version) * (version_count + 1))); versions[version_count].framebuffer_id = p_framebuffer_format_id; versions[version_count].vertex_id = p_vertex_format_id; versions[version_count].wireframe = wireframe; diff --git a/servers/rendering/renderer_rd/pipeline_cache_rd.h b/servers/rendering/renderer_rd/pipeline_cache_rd.h index 8d82480b38..1e80381d88 100644 --- a/servers/rendering/renderer_rd/pipeline_cache_rd.h +++ b/servers/rendering/renderer_rd/pipeline_cache_rd.h @@ -57,7 +57,7 @@ class PipelineCacheRD { RID pipeline; }; - Version *versions; + Version *versions = nullptr; uint32_t version_count; RID _generate_version(RD::VertexFormatID p_vertex_format_id, RD::FramebufferFormatID p_framebuffer_format_id, bool p_wireframe, uint32_t p_render_pass, uint32_t p_bool_specializations = 0); diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp index 8c8532d367..5b5a39c215 100644 --- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp @@ -109,6 +109,8 @@ RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Ve // This dramatically reduces the amount of pipeline objects // that need to be created for these formats. + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); + uint32_t vertex_count = p_points.size(); uint32_t stride = 2; //vertices always repeat if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) { @@ -191,7 +193,7 @@ RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Ve vd.stride = 0; descriptions.write[1] = vd; - buffers.write[1] = storage->mesh_get_default_rd_buffer(RendererStorageRD::DEFAULT_RD_BUFFER_COLOR); + buffers.write[1] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::DEFAULT_RD_BUFFER_COLOR); } //uvs @@ -219,7 +221,7 @@ RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Ve vd.stride = 0; descriptions.write[2] = vd; - buffers.write[2] = storage->mesh_get_default_rd_buffer(RendererStorageRD::DEFAULT_RD_BUFFER_TEX_UV); + buffers.write[2] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::DEFAULT_RD_BUFFER_TEX_UV); } //bones @@ -252,7 +254,7 @@ RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Ve vd.stride = 0; descriptions.write[3] = vd; - buffers.write[3] = storage->mesh_get_default_rd_buffer(RendererStorageRD::DEFAULT_RD_BUFFER_BONES); + buffers.write[3] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::DEFAULT_RD_BUFFER_BONES); } //weights @@ -285,7 +287,7 @@ RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Ve vd.stride = 0; descriptions.write[4] = vd; - buffers.write[4] = storage->mesh_get_default_rd_buffer(RendererStorageRD::DEFAULT_RD_BUFFER_WEIGHTS); + buffers.write[4] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::DEFAULT_RD_BUFFER_WEIGHTS); } //check that everything is as it should be @@ -399,6 +401,7 @@ void RendererCanvasRenderRD::_bind_canvas_texture(RD::DrawListID p_draw_list, RI void RendererCanvasRenderRD::_render_item(RD::DrawListID p_draw_list, RID p_render_target, const Item *p_item, RD::FramebufferFormatID p_framebuffer_format, const Transform2D &p_canvas_transform_inverse, Item *¤t_clip, Light *p_lights, PipelineVariants *p_pipeline_variants) { //create an empty push constant + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); RS::CanvasItemTextureFilter current_filter = default_filter; RS::CanvasItemTextureRepeat current_repeat = default_repeat; @@ -753,26 +756,26 @@ void RendererCanvasRenderRD::_render_item(RD::DrawListID p_draw_list, RID p_rend } else if (c->type == Item::Command::TYPE_MULTIMESH) { const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(c); RID multimesh = mm->multimesh; - mesh = storage->multimesh_get_mesh(multimesh); + mesh = mesh_storage->multimesh_get_mesh(multimesh); texture = mm->texture; - if (storage->multimesh_get_transform_format(multimesh) != RS::MULTIMESH_TRANSFORM_2D) { + if (mesh_storage->multimesh_get_transform_format(multimesh) != RS::MULTIMESH_TRANSFORM_2D) { break; } - instance_count = storage->multimesh_get_instances_to_draw(multimesh); + instance_count = mesh_storage->multimesh_get_instances_to_draw(multimesh); if (instance_count == 0) { break; } - RID uniform_set = storage->multimesh_get_2d_uniform_set(multimesh, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET); + RID uniform_set = mesh_storage->multimesh_get_2d_uniform_set(multimesh, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET); RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, uniform_set, TRANSFORMS_UNIFORM_SET); push_constant.flags |= 1; //multimesh, trails disabled - if (storage->multimesh_uses_colors(multimesh)) { + if (mesh_storage->multimesh_uses_colors(multimesh)) { push_constant.flags |= FLAGS_INSTANCING_HAS_COLORS; } - if (storage->multimesh_uses_custom_data(multimesh)) { + if (mesh_storage->multimesh_uses_custom_data(multimesh)) { push_constant.flags |= FLAGS_INSTANCING_HAS_CUSTOM_DATA; } } else if (c->type == Item::Command::TYPE_PARTICLES) { @@ -837,7 +840,7 @@ void RendererCanvasRenderRD::_render_item(RD::DrawListID p_draw_list, RID p_rend _bind_canvas_texture(p_draw_list, texture, current_filter, current_repeat, last_texture, push_constant, texpixel_size); - uint32_t surf_count = storage->mesh_get_surface_count(mesh); + uint32_t surf_count = mesh_storage->mesh_get_surface_count(mesh); static const PipelineVariant variant[RS::PRIMITIVE_MAX] = { PIPELINE_VARIANT_ATTRIBUTE_POINTS, PIPELINE_VARIANT_ATTRIBUTE_LINES, PIPELINE_VARIANT_ATTRIBUTE_LINES_STRIP, PIPELINE_VARIANT_ATTRIBUTE_TRIANGLES, PIPELINE_VARIANT_ATTRIBUTE_TRIANGLE_STRIP }; push_constant.modulation[0] = base_color.r * modulate.r; @@ -852,9 +855,9 @@ void RendererCanvasRenderRD::_render_item(RD::DrawListID p_draw_list, RID p_rend } for (uint32_t j = 0; j < surf_count; j++) { - void *surface = storage->mesh_get_surface(mesh, j); + void *surface = mesh_storage->mesh_get_surface(mesh, j); - RS::PrimitiveType primitive = storage->mesh_surface_get_primitive(surface); + RS::PrimitiveType primitive = mesh_storage->mesh_surface_get_primitive(surface); ERR_CONTINUE(primitive < 0 || primitive >= RS::PRIMITIVE_MAX); uint32_t input_mask = pipeline_variants->variants[light_mode][variant[primitive]].get_vertex_input_mask(); @@ -863,15 +866,15 @@ void RendererCanvasRenderRD::_render_item(RD::DrawListID p_draw_list, RID p_rend RD::VertexFormatID vertex_format = RD::INVALID_FORMAT_ID; if (mesh_instance.is_valid()) { - storage->mesh_instance_surface_get_vertex_arrays_and_format(mesh_instance, j, input_mask, vertex_array, vertex_format); + mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(mesh_instance, j, input_mask, vertex_array, vertex_format); } else { - storage->mesh_surface_get_vertex_arrays_and_format(surface, input_mask, vertex_array, vertex_format); + mesh_storage->mesh_surface_get_vertex_arrays_and_format(surface, input_mask, vertex_array, vertex_format); } RID pipeline = pipeline_variants->variants[light_mode][variant[primitive]].get_render_pipeline(vertex_format, p_framebuffer_format); RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline); - RID index_array = storage->mesh_surface_get_index_array(surface, 0); + RID index_array = mesh_storage->mesh_surface_get_index_array(surface, 0); if (index_array.is_valid()) { RD::get_singleton()->draw_list_bind_index_array(p_draw_list, index_array); @@ -1106,7 +1109,7 @@ void RendererCanvasRenderRD::_render_items(RID p_to_render_target, int p_item_co if (material != prev_material) { CanvasMaterialData *material_data = nullptr; if (material.is_valid()) { - material_data = (CanvasMaterialData *)material_storage->material_get_data(material, RendererRD::SHADER_TYPE_2D); + material_data = static_cast<CanvasMaterialData *>(material_storage->material_get_data(material, RendererRD::SHADER_TYPE_2D)); } if (material_data) { @@ -1134,6 +1137,7 @@ void RendererCanvasRenderRD::_render_items(RID p_to_render_target, int p_item_co void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_light_list, const Transform2D &p_canvas_transform, RenderingServer::CanvasItemTextureFilter p_default_filter, RenderingServer::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used) { RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton(); + RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton(); r_sdf_used = false; int item_count = 0; @@ -1370,7 +1374,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material; if (material.is_valid()) { - CanvasMaterialData *md = (CanvasMaterialData *)material_storage->material_get_data(material, RendererRD::SHADER_TYPE_2D); + CanvasMaterialData *md = static_cast<CanvasMaterialData *>(material_storage->material_get_data(material, RendererRD::SHADER_TYPE_2D)); if (md && md->shader_data->valid) { if (md->shader_data->uses_screen_texture && canvas_group_owner == nullptr) { if (!material_screen_texture_found) { @@ -1395,7 +1399,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p if (c->type == Item::Command::TYPE_MESH) { const Item::CommandMesh *cm = static_cast<const Item::CommandMesh *>(c); if (cm->mesh_instance.is_valid()) { - storage->mesh_instance_check_for_update(cm->mesh_instance); + mesh_storage->mesh_instance_check_for_update(cm->mesh_instance); update_skeletons = true; } } @@ -1407,7 +1411,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p if (canvas_group_owner == nullptr) { //Canvas group begins here, render until before this item if (update_skeletons) { - storage->update_mesh_instances(); + mesh_storage->update_mesh_instances(); update_skeletons = false; } _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list); @@ -1430,7 +1434,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p if (ci == canvas_group_owner) { if (update_skeletons) { - storage->update_mesh_instances(); + mesh_storage->update_mesh_instances(); update_skeletons = false; } @@ -1447,7 +1451,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p if (backbuffer_copy) { //render anything pending, including clearing if no items if (update_skeletons) { - storage->update_mesh_instances(); + mesh_storage->update_mesh_instances(); update_skeletons = false; } _render_items(p_to_render_target, item_count, canvas_transform_inverse, p_light_list); @@ -1463,7 +1467,7 @@ void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p if (!ci->next || item_count == MAX_RENDER_ITEMS - 1) { if (update_skeletons) { - storage->update_mesh_instances(); + mesh_storage->update_mesh_instances(); update_skeletons = false; } @@ -1982,7 +1986,7 @@ void RendererCanvasRenderRD::CanvasShaderData::set_code(const String &p_code) { actions.uniforms = &uniforms; - RendererCanvasRenderRD *canvas_singleton = (RendererCanvasRenderRD *)RendererCanvasRender::singleton; + RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton); Error err = canvas_singleton->shader.compiler.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code); ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed."); @@ -2205,7 +2209,7 @@ Variant RendererCanvasRenderRD::CanvasShaderData::get_default_parameter(const St } RS::ShaderNativeSourceCode RendererCanvasRenderRD::CanvasShaderData::get_native_source_code() const { - RendererCanvasRenderRD *canvas_singleton = (RendererCanvasRenderRD *)RendererCanvasRender::singleton; + RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton); return canvas_singleton->shader.canvas_shader.version_get_native_source_code(version); } @@ -2216,7 +2220,7 @@ RendererCanvasRenderRD::CanvasShaderData::CanvasShaderData() { } RendererCanvasRenderRD::CanvasShaderData::~CanvasShaderData() { - RendererCanvasRenderRD *canvas_singleton = (RendererCanvasRenderRD *)RendererCanvasRender::singleton; + RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton); ERR_FAIL_COND(!canvas_singleton); //pipeline variants will clear themselves if shader is gone if (version.is_valid()) { @@ -2230,7 +2234,7 @@ RendererRD::ShaderData *RendererCanvasRenderRD::_create_shader_func() { } bool RendererCanvasRenderRD::CanvasMaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) { - RendererCanvasRenderRD *canvas_singleton = (RendererCanvasRenderRD *)RendererCanvasRender::singleton; + RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton); return update_parameters_uniform_set(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, uniform_set, canvas_singleton->shader.canvas_shader.version_get_shader(shader_data->version, 0), MATERIAL_UNIFORM_SET); } @@ -2579,7 +2583,7 @@ RendererCanvasRenderRD::RendererCanvasRenderRD(RendererStorageRD *p_storage) { RD::Uniform u; u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; u.binding = 0; - u.append_id(storage->get_default_rd_storage_buffer()); + u.append_id(RendererRD::MeshStorage::get_singleton()->get_default_rd_storage_buffer()); uniforms.push_back(u); } diff --git a/servers/rendering/renderer_rd/renderer_canvas_render_rd.h b/servers/rendering/renderer_rd/renderer_canvas_render_rd.h index b33ee3fbfe..6448e1a664 100644 --- a/servers/rendering/renderer_rd/renderer_canvas_render_rd.h +++ b/servers/rendering/renderer_rd/renderer_canvas_render_rd.h @@ -41,7 +41,7 @@ #include "servers/rendering/shader_compiler.h" class RendererCanvasRenderRD : public RendererCanvasRender { - RendererStorageRD *storage; + RendererStorageRD *storage = nullptr; enum { BASE_UNIFORM_SET = 0, @@ -200,7 +200,7 @@ class RendererCanvasRenderRD : public RendererCanvasRender { } struct CanvasMaterialData : public RendererRD::MaterialData { - CanvasShaderData *shader_data; + CanvasShaderData *shader_data = nullptr; RID uniform_set; virtual void set_render_priority(int p_priority) {} @@ -361,7 +361,7 @@ class RendererCanvasRenderRD : public RendererCanvasRender { uint32_t pad2; }; - LightUniform *light_uniforms; + LightUniform *light_uniforms = nullptr; RID lights_uniform_buffer; RID canvas_state_buffer; diff --git a/servers/rendering/renderer_rd/renderer_compositor_rd.cpp b/servers/rendering/renderer_rd/renderer_compositor_rd.cpp index cfec5dac5d..ba4796e19d 100644 --- a/servers/rendering/renderer_rd/renderer_compositor_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_compositor_rd.cpp @@ -156,6 +156,7 @@ void RendererCompositorRD::finalize() { memdelete(canvas); memdelete(storage); memdelete(decal_atlas_storage); + memdelete(mesh_storage); memdelete(material_storage); memdelete(texture_storage); memdelete(canvas_texture_storage); @@ -252,8 +253,8 @@ RendererCompositorRD::RendererCompositorRD() { if (shader_cache_dir.is_empty()) { shader_cache_dir = "user://"; } - DirAccessRef da = DirAccess::open(shader_cache_dir); - if (!da) { + Ref<DirAccess> da = DirAccess::open(shader_cache_dir); + if (da.is_null()) { ERR_PRINT("Can't create shader cache folder, no shader caching will happen: " + shader_cache_dir); } else { Error err = da->change_dir("shader_cache"); @@ -291,6 +292,7 @@ RendererCompositorRD::RendererCompositorRD() { texture_storage = memnew(RendererRD::TextureStorage); decal_atlas_storage = memnew(RendererRD::DecalAtlasStorage); material_storage = memnew(RendererRD::MaterialStorage); + mesh_storage = memnew(RendererRD::MeshStorage); storage = memnew(RendererStorageRD); canvas = memnew(RendererCanvasRenderRD(storage)); diff --git a/servers/rendering/renderer_rd/renderer_compositor_rd.h b/servers/rendering/renderer_rd/renderer_compositor_rd.h index f2d7679e23..542cff0159 100644 --- a/servers/rendering/renderer_rd/renderer_compositor_rd.h +++ b/servers/rendering/renderer_rd/renderer_compositor_rd.h @@ -42,19 +42,21 @@ #include "servers/rendering/renderer_rd/storage_rd/canvas_texture_storage.h" #include "servers/rendering/renderer_rd/storage_rd/decal_atlas_storage.h" #include "servers/rendering/renderer_rd/storage_rd/material_storage.h" +#include "servers/rendering/renderer_rd/storage_rd/mesh_storage.h" #include "servers/rendering/renderer_rd/storage_rd/texture_storage.h" #include "servers/rendering/renderer_rd/uniform_set_cache_rd.h" class RendererCompositorRD : public RendererCompositor { protected: - UniformSetCacheRD *uniform_set_cache; - RendererCanvasRenderRD *canvas; + UniformSetCacheRD *uniform_set_cache = nullptr; + RendererCanvasRenderRD *canvas = nullptr; RendererRD::CanvasTextureStorage *canvas_texture_storage; RendererRD::MaterialStorage *material_storage; + RendererRD::MeshStorage *mesh_storage; RendererRD::TextureStorage *texture_storage; RendererRD::DecalAtlasStorage *decal_atlas_storage; - RendererStorageRD *storage; - RendererSceneRenderRD *scene; + RendererStorageRD *storage = nullptr; + RendererSceneRenderRD *scene = nullptr; enum BlitMode { BLIT_MODE_NORMAL, @@ -99,6 +101,7 @@ public: RendererCanvasTextureStorage *get_canvas_texture_storage() { return canvas_texture_storage; } RendererDecalAtlasStorage *get_decal_atlas_storage() { return decal_atlas_storage; } RendererMaterialStorage *get_material_storage() { return material_storage; }; + RendererMeshStorage *get_mesh_storage() { return mesh_storage; }; RendererTextureStorage *get_texture_storage() { return texture_storage; }; RendererStorage *get_storage() { return storage; } RendererCanvasRender *get_canvas() { return canvas; } diff --git a/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp index 75202d5abb..c735fda5f8 100644 --- a/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_gi_rd.cpp @@ -921,7 +921,7 @@ void RendererSceneGIRD::SDFGI::update_probes(RendererSceneEnvironmentRD *p_env, if (p_env->background == RS::ENV_BG_CLEAR_COLOR) { push_constant.sky_mode = SDFGIShader::IntegratePushConstant::SKY_MODE_COLOR; - Color c = storage->get_default_clear_color().to_linear(); + Color c = storage->get_default_clear_color().srgb_to_linear(); push_constant.sky_color[0] = c.r; push_constant.sky_color[1] = c.g; push_constant.sky_color[2] = c.b; @@ -1469,7 +1469,7 @@ void RendererSceneGIRD::SDFGI::pre_process_gi(const Transform3D &p_transform, Re lights[idx].direction[1] = dir.y; lights[idx].direction[2] = dir.z; Color color = storage->light_get_color(li->light); - color = color.to_linear(); + color = color.srgb_to_linear(); lights[idx].color[0] = color.r; lights[idx].color[1] = color.g; lights[idx].color[2] = color.b; @@ -1514,7 +1514,7 @@ void RendererSceneGIRD::SDFGI::pre_process_gi(const Transform3D &p_transform, Re lights[idx].position[1] = pos.y; lights[idx].position[2] = pos.z; Color color = storage->light_get_color(li->light); - color = color.to_linear(); + color = color.srgb_to_linear(); lights[idx].color[0] = color.r; lights[idx].color[1] = color.g; lights[idx].color[2] = color.b; @@ -1953,7 +1953,7 @@ void RendererSceneGIRD::SDFGI::render_static_lights(RID p_render_buffers, uint32 lights[idx].position[1] = pos.y; lights[idx].position[2] = pos.z; Color color = storage->light_get_color(li->light); - color = color.to_linear(); + color = color.srgb_to_linear(); lights[idx].color[0] = color.r; lights[idx].color[1] = color.g; lights[idx].color[2] = color.b; @@ -2396,7 +2396,7 @@ void RendererSceneGIRD::VoxelGIInstance::update(bool p_update_light_instances, c l.attenuation = storage->light_get_param(light, RS::LIGHT_PARAM_ATTENUATION); l.energy = storage->light_get_param(light, RS::LIGHT_PARAM_ENERGY) * storage->light_get_param(light, RS::LIGHT_PARAM_INDIRECT_ENERGY); l.radius = to_cell.basis.xform(Vector3(storage->light_get_param(light, RS::LIGHT_PARAM_RANGE), 0, 0)).length(); - Color color = storage->light_get_color(light).to_linear(); + Color color = storage->light_get_color(light).srgb_to_linear(); l.color[0] = color.r; l.color[1] = color.g; l.color[2] = color.b; diff --git a/servers/rendering/renderer_rd/renderer_scene_gi_rd.h b/servers/rendering/renderer_rd/renderer_scene_gi_rd.h index d51b1bf691..ed60bc4362 100644 --- a/servers/rendering/renderer_rd/renderer_scene_gi_rd.h +++ b/servers/rendering/renderer_rd/renderer_scene_gi_rd.h @@ -55,7 +55,7 @@ class RendererSceneRenderRD; class RendererSceneGIRD { private: - RendererStorageRD *storage; + RendererStorageRD *storage = nullptr; /* VOXEL_GI INSTANCE */ @@ -331,8 +331,8 @@ public: struct VoxelGIInstance { // access to our containers - RendererStorageRD *storage; - RendererSceneGIRD *gi; + RendererStorageRD *storage = nullptr; + RendererSceneGIRD *gi = nullptr; RID probe; RID texture; @@ -455,8 +455,8 @@ public: }; // access to our containers - RendererStorageRD *storage; - RendererSceneGIRD *gi; + RendererStorageRD *storage = nullptr; + RendererSceneGIRD *gi = nullptr; // used for rendering (voxelization) RID render_albedo; diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp index b5a40f6c86..b342e8f043 100644 --- a/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.cpp @@ -517,7 +517,7 @@ Ref<Image> RendererSceneRenderRD::environment_bake_panorama(RID p_env, bool p_ba ambient_color_sky_mix = env->ambient_sky_contribution; const float ambient_energy = env->ambient_light_energy; ambient_color = env->ambient_light; - ambient_color = ambient_color.to_linear(); + ambient_color = ambient_color.srgb_to_linear(); ambient_color.r *= ambient_energy; ambient_color.g *= ambient_energy; ambient_color.b *= ambient_energy; @@ -536,7 +536,7 @@ Ref<Image> RendererSceneRenderRD::environment_bake_panorama(RID p_env, bool p_ba } else { const float bg_energy = env->bg_energy; Color panorama_color = ((environment_background == RS::ENV_BG_CLEAR_COLOR) ? storage->get_default_clear_color() : env->bg_color); - panorama_color = panorama_color.to_linear(); + panorama_color = panorama_color.srgb_to_linear(); panorama_color.r *= bg_energy; panorama_color.g *= bg_energy; panorama_color.b *= bg_energy; @@ -3245,7 +3245,7 @@ void RendererSceneRenderRD::_setup_reflections(const PagedArray<RID> &p_reflecti reflection_ubo.exterior = !storage->reflection_probe_is_interior(base_probe); reflection_ubo.box_project = storage->reflection_probe_is_box_projection(base_probe); - Color ambient_linear = storage->reflection_probe_get_ambient_color(base_probe).to_linear(); + Color ambient_linear = storage->reflection_probe_get_ambient_color(base_probe).srgb_to_linear(); float interior_ambient_energy = storage->reflection_probe_get_ambient_color_energy(base_probe); reflection_ubo.ambient[0] = ambient_linear.r * interior_ambient_energy; reflection_ubo.ambient[1] = ambient_linear.g * interior_ambient_energy; @@ -3312,7 +3312,7 @@ void RendererSceneRenderRD::_setup_lights(const PagedArray<RID> &p_lights, const light_data.energy = sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY) * Math_PI; - Color linear_col = storage->light_get_color(base).to_linear(); + Color linear_col = storage->light_get_color(base).srgb_to_linear(); light_data.color[0] = linear_col.r; light_data.color[1] = linear_col.g; light_data.color[2] = linear_col.b; @@ -3491,7 +3491,7 @@ void RendererSceneRenderRD::_setup_lights(const PagedArray<RID> &p_lights, const Transform3D light_transform = li->transform; float sign = storage->light_is_negative(base) ? -1 : 1; - Color linear_col = storage->light_get_color(base).to_linear(); + Color linear_col = storage->light_get_color(base).srgb_to_linear(); light_data.attenuation = storage->light_get_param(base, RS::LIGHT_PARAM_ATTENUATION); @@ -3865,7 +3865,7 @@ void RendererSceneRenderRD::FogShaderData::set_code(const String &p_code) { actions.uniforms = &uniforms; - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); Error err = scene_singleton->volumetric_fog.compiler.compile(RS::SHADER_FOG, code, &actions, path, gen_code); ERR_FAIL_COND_MSG(err != OK, "Fog shader compilation failed."); @@ -3966,7 +3966,7 @@ Variant RendererSceneRenderRD::FogShaderData::get_default_parameter(const String } RS::ShaderNativeSourceCode RendererSceneRenderRD::FogShaderData::get_native_source_code() const { - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); return scene_singleton->volumetric_fog.shader.version_get_native_source_code(version); } @@ -3976,7 +3976,7 @@ RendererSceneRenderRD::FogShaderData::FogShaderData() { } RendererSceneRenderRD::FogShaderData::~FogShaderData() { - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); ERR_FAIL_COND(!scene_singleton); //pipeline variants will clear themselves if shader is gone if (version.is_valid()) { @@ -3988,7 +3988,7 @@ RendererSceneRenderRD::FogShaderData::~FogShaderData() { // Fog material bool RendererSceneRenderRD::FogMaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) { - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); uniform_set_updated = true; @@ -4276,7 +4276,7 @@ void RendererSceneRenderRD::_update_volumetric_fog(RID p_render_buffers, RID p_e FogMaterialData *material = nullptr; if (fog_material.is_valid()) { - material = (FogMaterialData *)material_storage->material_get_data(fog_material, RendererRD::SHADER_TYPE_FOG); + material = static_cast<FogMaterialData *>(material_storage->material_get_data(fog_material, RendererRD::SHADER_TYPE_FOG)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -4284,7 +4284,7 @@ void RendererSceneRenderRD::_update_volumetric_fog(RID p_render_buffers, RID p_e if (!material) { fog_material = volumetric_fog.default_material; - material = (FogMaterialData *)material_storage->material_get_data(fog_material, RendererRD::SHADER_TYPE_FOG); + material = static_cast<FogMaterialData *>(material_storage->material_get_data(fog_material, RendererRD::SHADER_TYPE_FOG)); } ERR_FAIL_COND(!material); @@ -4641,7 +4641,7 @@ void RendererSceneRenderRD::_update_volumetric_fog(RID p_render_buffers, RID p_e params.fog_frustum_end = fog_end; - Color ambient_color = env->ambient_light.to_linear(); + Color ambient_color = env->ambient_light.srgb_to_linear(); params.ambient_color[0] = ambient_color.r; params.ambient_color[1] = ambient_color.g; params.ambient_color[2] = ambient_color.b; @@ -4653,13 +4653,13 @@ void RendererSceneRenderRD::_update_volumetric_fog(RID p_render_buffers, RID p_e params.directional_light_count = p_directional_light_count; - Color emission = env->volumetric_fog_emission.to_linear(); + Color emission = env->volumetric_fog_emission.srgb_to_linear(); params.base_emission[0] = emission.r * env->volumetric_fog_emission_energy; params.base_emission[1] = emission.g * env->volumetric_fog_emission_energy; params.base_emission[2] = emission.b * env->volumetric_fog_emission_energy; params.base_density = env->volumetric_fog_density; - Color base_scattering = env->volumetric_fog_scattering.to_linear(); + Color base_scattering = env->volumetric_fog_scattering.srgb_to_linear(); params.base_scattering[0] = base_scattering.r; params.base_scattering[1] = base_scattering.g; params.base_scattering[2] = base_scattering.b; @@ -5501,7 +5501,7 @@ TypedArray<Image> RendererSceneRenderRD::bake_render_uv2(RID p_base, const Vecto GeometryInstance *gi = geometry_instance_create(p_base); - uint32_t sc = RSG::storage->mesh_get_surface_count(p_base); + uint32_t sc = RSG::mesh_storage->mesh_get_surface_count(p_base); Vector<RID> materials; materials.resize(sc); @@ -5732,7 +5732,7 @@ void fog() { material_storage->material_initialize(volumetric_fog.default_material); material_storage->material_set_shader(volumetric_fog.default_material, volumetric_fog.default_shader); - FogMaterialData *md = (FogMaterialData *)material_storage->material_get_data(volumetric_fog.default_material, RendererRD::SHADER_TYPE_FOG); + FogMaterialData *md = static_cast<FogMaterialData *>(material_storage->material_get_data(volumetric_fog.default_material, RendererRD::SHADER_TYPE_FOG)); volumetric_fog.default_shader_rd = volumetric_fog.shader.version_get_shader(md->shader_data->version, 0); Vector<RD::Uniform> uniforms; diff --git a/servers/rendering/renderer_rd/renderer_scene_render_rd.h b/servers/rendering/renderer_rd/renderer_scene_render_rd.h index 77c0437e83..b2c8daffb1 100644 --- a/servers/rendering/renderer_rd/renderer_scene_render_rd.h +++ b/servers/rendering/renderer_rd/renderer_scene_render_rd.h @@ -92,7 +92,7 @@ class RendererSceneRenderRD : public RendererSceneRender { friend RendererSceneGIRD; protected: - RendererStorageRD *storage; + RendererStorageRD *storage = nullptr; double time; double time_step = 0; @@ -314,10 +314,10 @@ private: float shadows_quality_radius = 1.0; float directional_shadow_quality_radius = 1.0; - float *directional_penumbra_shadow_kernel; - float *directional_soft_shadow_kernel; - float *penumbra_shadow_kernel; - float *soft_shadow_kernel; + float *directional_penumbra_shadow_kernel = nullptr; + float *directional_soft_shadow_kernel = nullptr; + float *penumbra_shadow_kernel = nullptr; + float *soft_shadow_kernel = nullptr; int directional_penumbra_shadow_samples = 0; int directional_soft_shadow_samples = 0; int penumbra_shadow_samples = 0; @@ -705,27 +705,27 @@ private: template <class T> struct InstanceSort { float depth; - T *instance; + T *instance = nullptr; bool operator<(const InstanceSort &p_sort) const { return depth < p_sort.depth; } }; - ReflectionData *reflections; + ReflectionData *reflections = nullptr; InstanceSort<ReflectionProbeInstance> *reflection_sort; uint32_t max_reflections; RID reflection_buffer; uint32_t max_reflection_probes_per_instance; uint32_t reflection_count = 0; - DecalData *decals; + DecalData *decals = nullptr; InstanceSort<DecalInstance> *decal_sort; uint32_t max_decals; RID decal_buffer; uint32_t decal_count; - LightData *omni_lights; - LightData *spot_lights; + LightData *omni_lights = nullptr; + LightData *spot_lights = nullptr; InstanceSort<LightInstance> *omni_light_sort; InstanceSort<LightInstance> *spot_light_sort; @@ -735,7 +735,7 @@ private: uint32_t omni_light_count = 0; uint32_t spot_light_count = 0; - DirectionalLightData *directional_lights; + DirectionalLightData *directional_lights = nullptr; uint32_t max_directional_lights; RID directional_light_buffer; @@ -938,7 +938,7 @@ private: }; struct FogMaterialData : public RendererRD::MaterialData { - FogShaderData *shader_data; + FogShaderData *shader_data = nullptr; RID uniform_set; bool uniform_set_updated; diff --git a/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp b/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp index 1c4ddcb5e1..44298711cd 100644 --- a/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_scene_sky_rd.cpp @@ -91,7 +91,7 @@ void RendererSceneSkyRD::SkyShaderData::set_code(const String &p_code) { actions.uniforms = &uniforms; // !BAS! Contemplate making `SkyShader sky` accessible from this struct or even part of this struct. - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); Error err = scene_singleton->sky.sky_shader.compiler.compile(RS::SHADER_SKY, code, &actions, path, gen_code); ERR_FAIL_COND_MSG(err != OK, "Shader compilation failed."); @@ -219,7 +219,7 @@ Variant RendererSceneSkyRD::SkyShaderData::get_default_parameter(const StringNam } RS::ShaderNativeSourceCode RendererSceneSkyRD::SkyShaderData::get_native_source_code() const { - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); return scene_singleton->sky.sky_shader.shader.version_get_native_source_code(version); } @@ -229,7 +229,7 @@ RendererSceneSkyRD::SkyShaderData::SkyShaderData() { } RendererSceneSkyRD::SkyShaderData::~SkyShaderData() { - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); ERR_FAIL_COND(!scene_singleton); //pipeline variants will clear themselves if shader is gone if (version.is_valid()) { @@ -241,7 +241,7 @@ RendererSceneSkyRD::SkyShaderData::~SkyShaderData() { // Sky material bool RendererSceneSkyRD::SkyMaterialData::update_parameters(const Map<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) { - RendererSceneRenderRD *scene_singleton = (RendererSceneRenderRD *)RendererSceneRenderRD::singleton; + RendererSceneRenderRD *scene_singleton = static_cast<RendererSceneRenderRD *>(RendererSceneRenderRD::singleton); uniform_set_updated = true; @@ -916,7 +916,7 @@ void sky() { material_storage->material_set_shader(sky_shader.default_material, sky_shader.default_shader); - SkyMaterialData *md = (SkyMaterialData *)material_storage->material_get_data(sky_shader.default_material, RendererRD::SHADER_TYPE_SKY); + SkyMaterialData *md = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_shader.default_material, RendererRD::SHADER_TYPE_SKY)); sky_shader.default_shader_rd = sky_shader.shader.version_get_shader(md->shader_data->version, SKY_VERSION_BACKGROUND); sky_scene_state.uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(SkySceneState::UBO)); @@ -1059,7 +1059,7 @@ RendererSceneSkyRD::~RendererSceneSkyRD() { // cleanup anything created in init... RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton(); - SkyMaterialData *md = (SkyMaterialData *)material_storage->material_get_data(sky_shader.default_material, RendererRD::SHADER_TYPE_SKY); + SkyMaterialData *md = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_shader.default_material, RendererRD::SHADER_TYPE_SKY)); sky_shader.shader.version_free(md->shader_data->version); RD::get_singleton()->free(sky_scene_state.directional_light_buffer); RD::get_singleton()->free(sky_scene_state.uniform_buffer); @@ -1100,7 +1100,7 @@ void RendererSceneSkyRD::setup(RendererSceneEnvironmentRD *p_env, RID p_render_b sky_material = sky_get_material(p_env->sky); if (sky_material.is_valid()) { - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -1108,7 +1108,7 @@ void RendererSceneSkyRD::setup(RendererSceneEnvironmentRD *p_env, RID p_render_b if (!material) { sky_material = sky_shader.default_material; - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); } ERR_FAIL_COND(!material); @@ -1194,7 +1194,7 @@ void RendererSceneSkyRD::setup(RendererSceneEnvironmentRD *p_env, RID p_render_b float sign = storage->light_is_negative(base) ? -1 : 1; sky_light_data.energy = sign * storage->light_get_param(base, RS::LIGHT_PARAM_ENERGY); - Color linear_col = storage->light_get_color(base).to_linear(); + Color linear_col = storage->light_get_color(base).srgb_to_linear(); sky_light_data.color[0] = linear_col.r; sky_light_data.color[1] = linear_col.g; sky_light_data.color[2] = linear_col.b; @@ -1286,7 +1286,7 @@ void RendererSceneSkyRD::setup(RendererSceneEnvironmentRD *p_env, RID p_render_b sky_scene_state.ubo.fog_enabled = p_env->fog_enabled; sky_scene_state.ubo.fog_density = p_env->fog_density; sky_scene_state.ubo.fog_aerial_perspective = p_env->fog_aerial_perspective; - Color fog_color = p_env->fog_light_color.to_linear(); + Color fog_color = p_env->fog_light_color.srgb_to_linear(); float fog_energy = p_env->fog_light_energy; sky_scene_state.ubo.fog_light_color[0] = fog_color.r * fog_energy; sky_scene_state.ubo.fog_light_color[1] = fog_color.g * fog_energy; @@ -1308,7 +1308,7 @@ void RendererSceneSkyRD::update(RendererSceneEnvironmentRD *p_env, const CameraM SkyMaterialData *material = nullptr; if (sky_material.is_valid()) { - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -1316,7 +1316,7 @@ void RendererSceneSkyRD::update(RendererSceneEnvironmentRD *p_env, const CameraM if (!material) { sky_material = sky_shader.default_material; - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); } ERR_FAIL_COND(!material); @@ -1484,7 +1484,7 @@ void RendererSceneSkyRD::draw(RendererSceneEnvironmentRD *p_env, bool p_can_cont sky_material = sky_get_material(p_env->sky); if (sky_material.is_valid()) { - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -1492,13 +1492,13 @@ void RendererSceneSkyRD::draw(RendererSceneEnvironmentRD *p_env, bool p_can_cont if (!material) { sky_material = sky_shader.default_material; - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); } } if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) { sky_material = sky_scene_state.fog_material; - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); } ERR_FAIL_COND(!material); @@ -1588,7 +1588,7 @@ void RendererSceneSkyRD::update_res_buffers(RendererSceneEnvironmentRD *p_env, u sky_material = sky_get_material(p_env->sky); if (sky_material.is_valid()) { - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -1596,7 +1596,7 @@ void RendererSceneSkyRD::update_res_buffers(RendererSceneEnvironmentRD *p_env, u if (!material) { sky_material = sky_shader.default_material; - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); } ERR_FAIL_COND(!material); @@ -1676,7 +1676,7 @@ void RendererSceneSkyRD::draw(RD::DrawListID p_draw_list, RendererSceneEnvironme sky_material = sky_get_material(p_env->sky); if (sky_material.is_valid()) { - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); if (!material || !material->shader_data->valid) { material = nullptr; } @@ -1684,13 +1684,13 @@ void RendererSceneSkyRD::draw(RD::DrawListID p_draw_list, RendererSceneEnvironme if (!material) { sky_material = sky_shader.default_material; - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); } } if (background == RS::ENV_BG_CLEAR_COLOR || background == RS::ENV_BG_COLOR) { sky_material = sky_scene_state.fog_material; - material = (SkyMaterialData *)material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY); + material = static_cast<SkyMaterialData *>(material_storage->material_get_data(sky_material, RendererRD::SHADER_TYPE_SKY)); } ERR_FAIL_COND(!material); diff --git a/servers/rendering/renderer_rd/renderer_scene_sky_rd.h b/servers/rendering/renderer_rd/renderer_scene_sky_rd.h index 7a3e545add..010e2178a9 100644 --- a/servers/rendering/renderer_rd/renderer_scene_sky_rd.h +++ b/servers/rendering/renderer_rd/renderer_scene_sky_rd.h @@ -63,7 +63,7 @@ public: }; private: - RendererStorageRD *storage; + RendererStorageRD *storage = nullptr; RD::DataFormat texture_format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT; RID index_buffer; @@ -162,8 +162,8 @@ public: UBO ubo; - SkyDirectionalLightData *directional_lights; - SkyDirectionalLightData *last_frame_directional_lights; + SkyDirectionalLightData *directional_lights = nullptr; + SkyDirectionalLightData *last_frame_directional_lights = nullptr; uint32_t max_directional_lights; uint32_t last_frame_directional_light_count; RID directional_light_buffer; @@ -228,7 +228,7 @@ public: } sky_shader; struct SkyMaterialData : public RendererRD::MaterialData { - SkyShaderData *shader_data; + SkyShaderData *shader_data = nullptr; RID uniform_set; bool uniform_set_updated; @@ -262,7 +262,7 @@ public: Sky *dirty_list = nullptr; //State to track when radiance cubemap needs updating - SkyMaterialData *prev_material; + SkyMaterialData *prev_material = nullptr; Vector3 prev_position; float prev_time; diff --git a/servers/rendering/renderer_rd/renderer_storage_rd.cpp b/servers/rendering/renderer_rd/renderer_storage_rd.cpp index c5df3a9f4e..72f98a4690 100644 --- a/servers/rendering/renderer_rd/renderer_storage_rd.cpp +++ b/servers/rendering/renderer_rd/renderer_storage_rd.cpp @@ -35,6 +35,10 @@ #include "core/io/resource_loader.h" #include "core/math/math_defs.h" #include "renderer_compositor_rd.h" +#include "servers/rendering/renderer_rd/storage_rd/canvas_texture_storage.h" +#include "servers/rendering/renderer_rd/storage_rd/decal_atlas_storage.h" +#include "servers/rendering/renderer_rd/storage_rd/mesh_storage.h" +#include "servers/rendering/renderer_rd/storage_rd/texture_storage.h" #include "servers/rendering/rendering_server_globals.h" #include "servers/rendering/shader_language.h" @@ -134,1489 +138,6 @@ void RendererStorageRD::sampler_rd_configure_custom(float p_mipmap_bias) { } } -/* MESH API */ - -RID RendererStorageRD::mesh_allocate() { - return mesh_owner.allocate_rid(); -} -void RendererStorageRD::mesh_initialize(RID p_rid) { - mesh_owner.initialize_rid(p_rid, Mesh()); -} - -void RendererStorageRD::mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) { - ERR_FAIL_COND(p_blend_shape_count < 0); - - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - - ERR_FAIL_COND(mesh->surface_count > 0); //surfaces already exist - - mesh->blend_shape_count = p_blend_shape_count; -} - -/// Returns stride -void RendererStorageRD::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - - ERR_FAIL_COND(mesh->surface_count == RS::MAX_MESH_SURFACES); - -#ifdef DEBUG_ENABLED - //do a validation, to catch errors first - { - uint32_t stride = 0; - uint32_t attrib_stride = 0; - uint32_t skin_stride = 0; - - for (int i = 0; i < RS::ARRAY_WEIGHTS; i++) { - if ((p_surface.format & (1 << i))) { - switch (i) { - case RS::ARRAY_VERTEX: { - if (p_surface.format & RS::ARRAY_FLAG_USE_2D_VERTICES) { - stride += sizeof(float) * 2; - } else { - stride += sizeof(float) * 3; - } - - } break; - case RS::ARRAY_NORMAL: { - stride += sizeof(int32_t); - - } break; - case RS::ARRAY_TANGENT: { - stride += sizeof(int32_t); - - } break; - case RS::ARRAY_COLOR: { - attrib_stride += sizeof(uint32_t); - } break; - case RS::ARRAY_TEX_UV: { - attrib_stride += sizeof(float) * 2; - - } break; - case RS::ARRAY_TEX_UV2: { - attrib_stride += sizeof(float) * 2; - - } break; - case RS::ARRAY_CUSTOM0: - case RS::ARRAY_CUSTOM1: - case RS::ARRAY_CUSTOM2: - case RS::ARRAY_CUSTOM3: { - int idx = i - RS::ARRAY_CUSTOM0; - uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT }; - uint32_t fmt = (p_surface.format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK; - uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 }; - attrib_stride += fmtsize[fmt]; - - } break; - case RS::ARRAY_WEIGHTS: - case RS::ARRAY_BONES: { - //uses a separate array - bool use_8 = p_surface.format & RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS; - skin_stride += sizeof(int16_t) * (use_8 ? 16 : 8); - } break; - } - } - } - - int expected_size = stride * p_surface.vertex_count; - ERR_FAIL_COND_MSG(expected_size != p_surface.vertex_data.size(), "Size of vertex data provided (" + itos(p_surface.vertex_data.size()) + ") does not match expected (" + itos(expected_size) + ")"); - - int bs_expected_size = expected_size * mesh->blend_shape_count; - - ERR_FAIL_COND_MSG(bs_expected_size != p_surface.blend_shape_data.size(), "Size of blend shape data provided (" + itos(p_surface.blend_shape_data.size()) + ") does not match expected (" + itos(bs_expected_size) + ")"); - - int expected_attrib_size = attrib_stride * p_surface.vertex_count; - ERR_FAIL_COND_MSG(expected_attrib_size != p_surface.attribute_data.size(), "Size of attribute data provided (" + itos(p_surface.attribute_data.size()) + ") does not match expected (" + itos(expected_attrib_size) + ")"); - - if ((p_surface.format & RS::ARRAY_FORMAT_WEIGHTS) && (p_surface.format & RS::ARRAY_FORMAT_BONES)) { - expected_size = skin_stride * p_surface.vertex_count; - ERR_FAIL_COND_MSG(expected_size != p_surface.skin_data.size(), "Size of skin data provided (" + itos(p_surface.skin_data.size()) + ") does not match expected (" + itos(expected_size) + ")"); - } - } - -#endif - - Mesh::Surface *s = memnew(Mesh::Surface); - - s->format = p_surface.format; - s->primitive = p_surface.primitive; - - bool use_as_storage = (p_surface.skin_data.size() || mesh->blend_shape_count > 0); - - s->vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.vertex_data.size(), p_surface.vertex_data, use_as_storage); - s->vertex_buffer_size = p_surface.vertex_data.size(); - - if (p_surface.attribute_data.size()) { - s->attribute_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.attribute_data.size(), p_surface.attribute_data); - } - if (p_surface.skin_data.size()) { - s->skin_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.skin_data.size(), p_surface.skin_data, use_as_storage); - s->skin_buffer_size = p_surface.skin_data.size(); - } - - s->vertex_count = p_surface.vertex_count; - - if (p_surface.format & RS::ARRAY_FORMAT_BONES) { - mesh->has_bone_weights = true; - } - - if (p_surface.index_count) { - bool is_index_16 = p_surface.vertex_count <= 65536; - - s->index_buffer = RD::get_singleton()->index_buffer_create(p_surface.index_count, is_index_16 ? RD::INDEX_BUFFER_FORMAT_UINT16 : RD::INDEX_BUFFER_FORMAT_UINT32, p_surface.index_data, false); - s->index_count = p_surface.index_count; - s->index_array = RD::get_singleton()->index_array_create(s->index_buffer, 0, s->index_count); - if (p_surface.lods.size()) { - s->lods = memnew_arr(Mesh::Surface::LOD, p_surface.lods.size()); - s->lod_count = p_surface.lods.size(); - - for (int i = 0; i < p_surface.lods.size(); i++) { - uint32_t indices = p_surface.lods[i].index_data.size() / (is_index_16 ? 2 : 4); - s->lods[i].index_buffer = RD::get_singleton()->index_buffer_create(indices, is_index_16 ? RD::INDEX_BUFFER_FORMAT_UINT16 : RD::INDEX_BUFFER_FORMAT_UINT32, p_surface.lods[i].index_data); - s->lods[i].index_array = RD::get_singleton()->index_array_create(s->lods[i].index_buffer, 0, indices); - s->lods[i].edge_length = p_surface.lods[i].edge_length; - s->lods[i].index_count = indices; - } - } - } - - s->aabb = p_surface.aabb; - s->bone_aabbs = p_surface.bone_aabbs; //only really useful for returning them. - - if (mesh->blend_shape_count > 0) { - s->blend_shape_buffer = RD::get_singleton()->storage_buffer_create(p_surface.blend_shape_data.size(), p_surface.blend_shape_data); - } - - if (use_as_storage) { - Vector<RD::Uniform> uniforms; - { - RD::Uniform u; - u.binding = 0; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.append_id(s->vertex_buffer); - uniforms.push_back(u); - } - { - RD::Uniform u; - u.binding = 1; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - if (s->skin_buffer.is_valid()) { - u.append_id(s->skin_buffer); - } else { - u.append_id(default_rd_storage_buffer); - } - uniforms.push_back(u); - } - { - RD::Uniform u; - u.binding = 2; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - if (s->blend_shape_buffer.is_valid()) { - u.append_id(s->blend_shape_buffer); - } else { - u.append_id(default_rd_storage_buffer); - } - uniforms.push_back(u); - } - - s->uniform_set = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_SURFACE); - } - - if (mesh->surface_count == 0) { - mesh->bone_aabbs = p_surface.bone_aabbs; - mesh->aabb = p_surface.aabb; - } else { - if (mesh->bone_aabbs.size() < p_surface.bone_aabbs.size()) { - // ArrayMesh::_surface_set_data only allocates bone_aabbs up to max_bone - // Each surface may affect different numbers of bones. - mesh->bone_aabbs.resize(p_surface.bone_aabbs.size()); - } - for (int i = 0; i < p_surface.bone_aabbs.size(); i++) { - mesh->bone_aabbs.write[i].merge_with(p_surface.bone_aabbs[i]); - } - mesh->aabb.merge_with(p_surface.aabb); - } - - s->material = p_surface.material; - - mesh->surfaces = (Mesh::Surface **)memrealloc(mesh->surfaces, sizeof(Mesh::Surface *) * (mesh->surface_count + 1)); - mesh->surfaces[mesh->surface_count] = s; - mesh->surface_count++; - - for (MeshInstance *mi : mesh->instances) { - _mesh_instance_add_surface(mi, mesh, mesh->surface_count - 1); - } - - mesh->dependency.changed_notify(DEPENDENCY_CHANGED_MESH); - - for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) { - Mesh *shadow_owner = E->get(); - shadow_owner->shadow_mesh = RID(); - shadow_owner->dependency.changed_notify(DEPENDENCY_CHANGED_MESH); - } - - mesh->material_cache.clear(); -} - -int RendererStorageRD::mesh_get_blend_shape_count(RID p_mesh) const { - const Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, -1); - return mesh->blend_shape_count; -} - -void RendererStorageRD::mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - ERR_FAIL_INDEX((int)p_mode, 2); - - mesh->blend_shape_mode = p_mode; -} - -RS::BlendShapeMode RendererStorageRD::mesh_get_blend_shape_mode(RID p_mesh) const { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, RS::BLEND_SHAPE_MODE_NORMALIZED); - return mesh->blend_shape_mode; -} - -void RendererStorageRD::mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); - ERR_FAIL_COND(p_data.size() == 0); - uint64_t data_size = p_data.size(); - const uint8_t *r = p_data.ptr(); - - RD::get_singleton()->buffer_update(mesh->surfaces[p_surface]->vertex_buffer, p_offset, data_size, r); -} - -void RendererStorageRD::mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); - ERR_FAIL_COND(p_data.size() == 0); - ERR_FAIL_COND(mesh->surfaces[p_surface]->attribute_buffer.is_null()); - uint64_t data_size = p_data.size(); - const uint8_t *r = p_data.ptr(); - - RD::get_singleton()->buffer_update(mesh->surfaces[p_surface]->attribute_buffer, p_offset, data_size, r); -} - -void RendererStorageRD::mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); - ERR_FAIL_COND(p_data.size() == 0); - ERR_FAIL_COND(mesh->surfaces[p_surface]->skin_buffer.is_null()); - uint64_t data_size = p_data.size(); - const uint8_t *r = p_data.ptr(); - - RD::get_singleton()->buffer_update(mesh->surfaces[p_surface]->skin_buffer, p_offset, data_size, r); -} - -void RendererStorageRD::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); - mesh->surfaces[p_surface]->material = p_material; - - mesh->dependency.changed_notify(DEPENDENCY_CHANGED_MATERIAL); - mesh->material_cache.clear(); -} - -RID RendererStorageRD::mesh_surface_get_material(RID p_mesh, int p_surface) const { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, RID()); - ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_surface, mesh->surface_count, RID()); - - return mesh->surfaces[p_surface]->material; -} - -RS::SurfaceData RendererStorageRD::mesh_get_surface(RID p_mesh, int p_surface) const { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, RS::SurfaceData()); - ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_surface, mesh->surface_count, RS::SurfaceData()); - - Mesh::Surface &s = *mesh->surfaces[p_surface]; - - RS::SurfaceData sd; - sd.format = s.format; - sd.vertex_data = RD::get_singleton()->buffer_get_data(s.vertex_buffer); - if (s.attribute_buffer.is_valid()) { - sd.attribute_data = RD::get_singleton()->buffer_get_data(s.attribute_buffer); - } - if (s.skin_buffer.is_valid()) { - sd.skin_data = RD::get_singleton()->buffer_get_data(s.skin_buffer); - } - sd.vertex_count = s.vertex_count; - sd.index_count = s.index_count; - sd.primitive = s.primitive; - - if (sd.index_count) { - sd.index_data = RD::get_singleton()->buffer_get_data(s.index_buffer); - } - sd.aabb = s.aabb; - for (uint32_t i = 0; i < s.lod_count; i++) { - RS::SurfaceData::LOD lod; - lod.edge_length = s.lods[i].edge_length; - lod.index_data = RD::get_singleton()->buffer_get_data(s.lods[i].index_buffer); - sd.lods.push_back(lod); - } - - sd.bone_aabbs = s.bone_aabbs; - - if (s.blend_shape_buffer.is_valid()) { - sd.blend_shape_data = RD::get_singleton()->buffer_get_data(s.blend_shape_buffer); - } - - return sd; -} - -int RendererStorageRD::mesh_get_surface_count(RID p_mesh) const { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, 0); - return mesh->surface_count; -} - -void RendererStorageRD::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - mesh->custom_aabb = p_aabb; -} - -AABB RendererStorageRD::mesh_get_custom_aabb(RID p_mesh) const { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, AABB()); - return mesh->custom_aabb; -} - -AABB RendererStorageRD::mesh_get_aabb(RID p_mesh, RID p_skeleton) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, AABB()); - - if (mesh->custom_aabb != AABB()) { - return mesh->custom_aabb; - } - - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - - if (!skeleton || skeleton->size == 0) { - return mesh->aabb; - } - - AABB aabb; - - for (uint32_t i = 0; i < mesh->surface_count; i++) { - AABB laabb; - if ((mesh->surfaces[i]->format & RS::ARRAY_FORMAT_BONES) && mesh->surfaces[i]->bone_aabbs.size()) { - int bs = mesh->surfaces[i]->bone_aabbs.size(); - const AABB *skbones = mesh->surfaces[i]->bone_aabbs.ptr(); - - int sbs = skeleton->size; - ERR_CONTINUE(bs > sbs); - const float *baseptr = skeleton->data.ptr(); - - bool first = true; - - if (skeleton->use_2d) { - for (int j = 0; j < bs; j++) { - if (skbones[0].size == Vector3()) { - continue; //bone is unused - } - - const float *dataptr = baseptr + j * 8; - - Transform3D mtx; - - mtx.basis.elements[0].x = dataptr[0]; - mtx.basis.elements[1].x = dataptr[1]; - mtx.origin.x = dataptr[3]; - - mtx.basis.elements[0].y = dataptr[4]; - mtx.basis.elements[1].y = dataptr[5]; - mtx.origin.y = dataptr[7]; - - AABB baabb = mtx.xform(skbones[j]); - - if (first) { - laabb = baabb; - first = false; - } else { - laabb.merge_with(baabb); - } - } - } else { - for (int j = 0; j < bs; j++) { - if (skbones[0].size == Vector3()) { - continue; //bone is unused - } - - const float *dataptr = baseptr + j * 12; - - Transform3D mtx; - - mtx.basis.elements[0][0] = dataptr[0]; - mtx.basis.elements[0][1] = dataptr[1]; - mtx.basis.elements[0][2] = dataptr[2]; - mtx.origin.x = dataptr[3]; - mtx.basis.elements[1][0] = dataptr[4]; - mtx.basis.elements[1][1] = dataptr[5]; - mtx.basis.elements[1][2] = dataptr[6]; - mtx.origin.y = dataptr[7]; - mtx.basis.elements[2][0] = dataptr[8]; - mtx.basis.elements[2][1] = dataptr[9]; - mtx.basis.elements[2][2] = dataptr[10]; - mtx.origin.z = dataptr[11]; - - AABB baabb = mtx.xform(skbones[j]); - if (first) { - laabb = baabb; - first = false; - } else { - laabb.merge_with(baabb); - } - } - } - - if (laabb.size == Vector3()) { - laabb = mesh->surfaces[i]->aabb; - } - } else { - laabb = mesh->surfaces[i]->aabb; - } - - if (i == 0) { - aabb = laabb; - } else { - aabb.merge_with(laabb); - } - } - - return aabb; -} - -void RendererStorageRD::mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - - Mesh *shadow_mesh = mesh_owner.get_or_null(mesh->shadow_mesh); - if (shadow_mesh) { - shadow_mesh->shadow_owners.erase(mesh); - } - mesh->shadow_mesh = p_shadow_mesh; - - shadow_mesh = mesh_owner.get_or_null(mesh->shadow_mesh); - - if (shadow_mesh) { - shadow_mesh->shadow_owners.insert(mesh); - } - - mesh->dependency.changed_notify(DEPENDENCY_CHANGED_MESH); -} - -void RendererStorageRD::mesh_clear(RID p_mesh) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND(!mesh); - for (uint32_t i = 0; i < mesh->surface_count; i++) { - Mesh::Surface &s = *mesh->surfaces[i]; - RD::get_singleton()->free(s.vertex_buffer); //clears arrays as dependency automatically, including all versions - if (s.attribute_buffer.is_valid()) { - RD::get_singleton()->free(s.attribute_buffer); - } - if (s.skin_buffer.is_valid()) { - RD::get_singleton()->free(s.skin_buffer); - } - if (s.versions) { - memfree(s.versions); //reallocs, so free with memfree. - } - - if (s.index_buffer.is_valid()) { - RD::get_singleton()->free(s.index_buffer); - } - - if (s.lod_count) { - for (uint32_t j = 0; j < s.lod_count; j++) { - RD::get_singleton()->free(s.lods[j].index_buffer); - } - memdelete_arr(s.lods); - } - - if (s.blend_shape_buffer.is_valid()) { - RD::get_singleton()->free(s.blend_shape_buffer); - } - - memdelete(mesh->surfaces[i]); - } - if (mesh->surfaces) { - memfree(mesh->surfaces); - } - - mesh->surfaces = nullptr; - mesh->surface_count = 0; - mesh->material_cache.clear(); - //clear instance data - for (MeshInstance *mi : mesh->instances) { - _mesh_instance_clear(mi); - } - mesh->has_bone_weights = false; - mesh->dependency.changed_notify(DEPENDENCY_CHANGED_MESH); - - for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) { - Mesh *shadow_owner = E->get(); - shadow_owner->shadow_mesh = RID(); - shadow_owner->dependency.changed_notify(DEPENDENCY_CHANGED_MESH); - } -} - -bool RendererStorageRD::mesh_needs_instance(RID p_mesh, bool p_has_skeleton) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, false); - - return mesh->blend_shape_count > 0 || (mesh->has_bone_weights && p_has_skeleton); -} - -/* MESH INSTANCE */ - -RID RendererStorageRD::mesh_instance_create(RID p_base) { - Mesh *mesh = mesh_owner.get_or_null(p_base); - ERR_FAIL_COND_V(!mesh, RID()); - - RID rid = mesh_instance_owner.make_rid(); - MeshInstance *mi = mesh_instance_owner.get_or_null(rid); - - mi->mesh = mesh; - - for (uint32_t i = 0; i < mesh->surface_count; i++) { - _mesh_instance_add_surface(mi, mesh, i); - } - - mi->I = mesh->instances.push_back(mi); - - mi->dirty = true; - - return rid; -} -void RendererStorageRD::mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) { - MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); - if (mi->skeleton == p_skeleton) { - return; - } - mi->skeleton = p_skeleton; - mi->skeleton_version = 0; - mi->dirty = true; -} - -void RendererStorageRD::mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) { - MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); - ERR_FAIL_COND(!mi); - ERR_FAIL_INDEX(p_shape, (int)mi->blend_weights.size()); - mi->blend_weights[p_shape] = p_weight; - mi->weights_dirty = true; - //will be eventually updated -} - -void RendererStorageRD::_mesh_instance_clear(MeshInstance *mi) { - for (uint32_t i = 0; i < mi->surfaces.size(); i++) { - if (mi->surfaces[i].versions) { - for (uint32_t j = 0; j < mi->surfaces[i].version_count; j++) { - RD::get_singleton()->free(mi->surfaces[i].versions[j].vertex_array); - } - memfree(mi->surfaces[i].versions); - } - if (mi->surfaces[i].vertex_buffer.is_valid()) { - RD::get_singleton()->free(mi->surfaces[i].vertex_buffer); - } - } - mi->surfaces.clear(); - - if (mi->blend_weights_buffer.is_valid()) { - RD::get_singleton()->free(mi->blend_weights_buffer); - } - mi->blend_weights.clear(); - mi->weights_dirty = false; - mi->skeleton_version = 0; -} - -void RendererStorageRD::_mesh_instance_add_surface(MeshInstance *mi, Mesh *mesh, uint32_t p_surface) { - if (mesh->blend_shape_count > 0 && mi->blend_weights_buffer.is_null()) { - mi->blend_weights.resize(mesh->blend_shape_count); - for (uint32_t i = 0; i < mi->blend_weights.size(); i++) { - mi->blend_weights[i] = 0; - } - mi->blend_weights_buffer = RD::get_singleton()->storage_buffer_create(sizeof(float) * mi->blend_weights.size(), mi->blend_weights.to_byte_array()); - mi->weights_dirty = true; - } - - MeshInstance::Surface s; - if (mesh->blend_shape_count > 0 || (mesh->surfaces[p_surface]->format & RS::ARRAY_FORMAT_BONES)) { - //surface warrants transform - s.vertex_buffer = RD::get_singleton()->vertex_buffer_create(mesh->surfaces[p_surface]->vertex_buffer_size, Vector<uint8_t>(), true); - - Vector<RD::Uniform> uniforms; - { - RD::Uniform u; - u.binding = 1; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.append_id(s.vertex_buffer); - uniforms.push_back(u); - } - { - RD::Uniform u; - u.binding = 2; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - if (mi->blend_weights_buffer.is_valid()) { - u.append_id(mi->blend_weights_buffer); - } else { - u.append_id(default_rd_storage_buffer); - } - uniforms.push_back(u); - } - s.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_INSTANCE); - } - - mi->surfaces.push_back(s); - mi->dirty = true; -} - -void RendererStorageRD::mesh_instance_check_for_update(RID p_mesh_instance) { - MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); - - bool needs_update = mi->dirty; - - if (mi->weights_dirty && !mi->weight_update_list.in_list()) { - dirty_mesh_instance_weights.add(&mi->weight_update_list); - needs_update = true; - } - - if (mi->array_update_list.in_list()) { - return; - } - - if (!needs_update && mi->skeleton.is_valid()) { - Skeleton *sk = skeleton_owner.get_or_null(mi->skeleton); - if (sk && sk->version != mi->skeleton_version) { - needs_update = true; - } - } - - if (needs_update) { - dirty_mesh_instance_arrays.add(&mi->array_update_list); - } -} - -void RendererStorageRD::update_mesh_instances() { - while (dirty_mesh_instance_weights.first()) { - MeshInstance *mi = dirty_mesh_instance_weights.first()->self(); - - if (mi->blend_weights_buffer.is_valid()) { - RD::get_singleton()->buffer_update(mi->blend_weights_buffer, 0, mi->blend_weights.size() * sizeof(float), mi->blend_weights.ptr()); - } - dirty_mesh_instance_weights.remove(&mi->weight_update_list); - mi->weights_dirty = false; - } - if (dirty_mesh_instance_arrays.first() == nullptr) { - return; //nothing to do - } - - //process skeletons and blend shapes - RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin(); - - while (dirty_mesh_instance_arrays.first()) { - MeshInstance *mi = dirty_mesh_instance_arrays.first()->self(); - - Skeleton *sk = skeleton_owner.get_or_null(mi->skeleton); - - for (uint32_t i = 0; i < mi->surfaces.size(); i++) { - if (mi->surfaces[i].uniform_set == RID() || mi->mesh->surfaces[i]->uniform_set == RID()) { - continue; - } - - bool array_is_2d = mi->mesh->surfaces[i]->format & RS::ARRAY_FLAG_USE_2D_VERTICES; - - RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, skeleton_shader.pipeline[array_is_2d ? SkeletonShader::SHADER_MODE_2D : SkeletonShader::SHADER_MODE_3D]); - - RD::get_singleton()->compute_list_bind_uniform_set(compute_list, mi->surfaces[i].uniform_set, SkeletonShader::UNIFORM_SET_INSTANCE); - RD::get_singleton()->compute_list_bind_uniform_set(compute_list, mi->mesh->surfaces[i]->uniform_set, SkeletonShader::UNIFORM_SET_SURFACE); - if (sk && sk->uniform_set_mi.is_valid()) { - RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sk->uniform_set_mi, SkeletonShader::UNIFORM_SET_SKELETON); - } else { - RD::get_singleton()->compute_list_bind_uniform_set(compute_list, skeleton_shader.default_skeleton_uniform_set, SkeletonShader::UNIFORM_SET_SKELETON); - } - - SkeletonShader::PushConstant push_constant; - - push_constant.has_normal = mi->mesh->surfaces[i]->format & RS::ARRAY_FORMAT_NORMAL; - push_constant.has_tangent = mi->mesh->surfaces[i]->format & RS::ARRAY_FORMAT_TANGENT; - push_constant.has_skeleton = sk != nullptr && sk->use_2d == array_is_2d && (mi->mesh->surfaces[i]->format & RS::ARRAY_FORMAT_BONES); - push_constant.has_blend_shape = mi->mesh->blend_shape_count > 0; - - push_constant.vertex_count = mi->mesh->surfaces[i]->vertex_count; - push_constant.vertex_stride = (mi->mesh->surfaces[i]->vertex_buffer_size / mi->mesh->surfaces[i]->vertex_count) / 4; - push_constant.skin_stride = (mi->mesh->surfaces[i]->skin_buffer_size / mi->mesh->surfaces[i]->vertex_count) / 4; - push_constant.skin_weight_offset = (mi->mesh->surfaces[i]->format & RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS) ? 4 : 2; - - push_constant.blend_shape_count = mi->mesh->blend_shape_count; - push_constant.normalized_blend_shapes = mi->mesh->blend_shape_mode == RS::BLEND_SHAPE_MODE_NORMALIZED; - push_constant.pad0 = 0; - push_constant.pad1 = 0; - - RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SkeletonShader::PushConstant)); - - //dispatch without barrier, so all is done at the same time - RD::get_singleton()->compute_list_dispatch_threads(compute_list, push_constant.vertex_count, 1, 1); - } - - mi->dirty = false; - if (sk) { - mi->skeleton_version = sk->version; - } - dirty_mesh_instance_arrays.remove(&mi->array_update_list); - } - - RD::get_singleton()->compute_list_end(); -} - -void RendererStorageRD::_mesh_surface_generate_version_for_input_mask(Mesh::Surface::Version &v, Mesh::Surface *s, uint32_t p_input_mask, MeshInstance::Surface *mis) { - Vector<RD::VertexAttribute> attributes; - Vector<RID> buffers; - - uint32_t stride = 0; - uint32_t attribute_stride = 0; - uint32_t skin_stride = 0; - - for (int i = 0; i < RS::ARRAY_INDEX; i++) { - RD::VertexAttribute vd; - RID buffer; - vd.location = i; - - if (!(s->format & (1 << i))) { - // Not supplied by surface, use default value - buffer = mesh_default_rd_buffers[i]; - vd.stride = 0; - switch (i) { - case RS::ARRAY_VERTEX: { - vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT; - - } break; - case RS::ARRAY_NORMAL: { - vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT; - } break; - case RS::ARRAY_TANGENT: { - vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; - } break; - case RS::ARRAY_COLOR: { - vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; - - } break; - case RS::ARRAY_TEX_UV: { - vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; - - } break; - case RS::ARRAY_TEX_UV2: { - vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; - } break; - case RS::ARRAY_CUSTOM0: - case RS::ARRAY_CUSTOM1: - case RS::ARRAY_CUSTOM2: - case RS::ARRAY_CUSTOM3: { - //assumed weights too - vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; - } break; - case RS::ARRAY_BONES: { - //assumed weights too - vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT; - } break; - case RS::ARRAY_WEIGHTS: { - //assumed weights too - vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; - } break; - } - } else { - //Supplied, use it - - vd.stride = 1; //mark that it needs a stride set (default uses 0) - - switch (i) { - case RS::ARRAY_VERTEX: { - vd.offset = stride; - - if (s->format & RS::ARRAY_FLAG_USE_2D_VERTICES) { - vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; - stride += sizeof(float) * 2; - } else { - vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT; - stride += sizeof(float) * 3; - } - - if (mis) { - buffer = mis->vertex_buffer; - } else { - buffer = s->vertex_buffer; - } - - } break; - case RS::ARRAY_NORMAL: { - vd.offset = stride; - - vd.format = RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32; - - stride += sizeof(uint32_t); - if (mis) { - buffer = mis->vertex_buffer; - } else { - buffer = s->vertex_buffer; - } - } break; - case RS::ARRAY_TANGENT: { - vd.offset = stride; - - vd.format = RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32; - stride += sizeof(uint32_t); - if (mis) { - buffer = mis->vertex_buffer; - } else { - buffer = s->vertex_buffer; - } - } break; - case RS::ARRAY_COLOR: { - vd.offset = attribute_stride; - - vd.format = RD::DATA_FORMAT_R8G8B8A8_UNORM; - attribute_stride += sizeof(int8_t) * 4; - buffer = s->attribute_buffer; - } break; - case RS::ARRAY_TEX_UV: { - vd.offset = attribute_stride; - - vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; - attribute_stride += sizeof(float) * 2; - buffer = s->attribute_buffer; - - } break; - case RS::ARRAY_TEX_UV2: { - vd.offset = attribute_stride; - - vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; - attribute_stride += sizeof(float) * 2; - buffer = s->attribute_buffer; - } break; - case RS::ARRAY_CUSTOM0: - case RS::ARRAY_CUSTOM1: - case RS::ARRAY_CUSTOM2: - case RS::ARRAY_CUSTOM3: { - vd.offset = attribute_stride; - - int idx = i - RS::ARRAY_CUSTOM0; - uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT }; - uint32_t fmt = (s->format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK; - uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 }; - RD::DataFormat fmtrd[RS::ARRAY_CUSTOM_MAX] = { RD::DATA_FORMAT_R8G8B8A8_UNORM, RD::DATA_FORMAT_R8G8B8A8_SNORM, RD::DATA_FORMAT_R16G16_SFLOAT, RD::DATA_FORMAT_R16G16B16A16_SFLOAT, RD::DATA_FORMAT_R32_SFLOAT, RD::DATA_FORMAT_R32G32_SFLOAT, RD::DATA_FORMAT_R32G32B32_SFLOAT, RD::DATA_FORMAT_R32G32B32A32_SFLOAT }; - vd.format = fmtrd[fmt]; - attribute_stride += fmtsize[fmt]; - buffer = s->attribute_buffer; - } break; - case RS::ARRAY_BONES: { - vd.offset = skin_stride; - - vd.format = RD::DATA_FORMAT_R16G16B16A16_UINT; - skin_stride += sizeof(int16_t) * 4; - buffer = s->skin_buffer; - } break; - case RS::ARRAY_WEIGHTS: { - vd.offset = skin_stride; - - vd.format = RD::DATA_FORMAT_R16G16B16A16_UNORM; - skin_stride += sizeof(int16_t) * 4; - buffer = s->skin_buffer; - } break; - } - } - - if (!(p_input_mask & (1 << i))) { - continue; // Shader does not need this, skip it (but computing stride was important anyway) - } - - attributes.push_back(vd); - buffers.push_back(buffer); - } - - //update final stride - for (int i = 0; i < attributes.size(); i++) { - if (attributes[i].stride == 0) { - continue; //default location - } - int loc = attributes[i].location; - - if (loc < RS::ARRAY_COLOR) { - attributes.write[i].stride = stride; - } else if (loc < RS::ARRAY_BONES) { - attributes.write[i].stride = attribute_stride; - } else { - attributes.write[i].stride = skin_stride; - } - } - - v.input_mask = p_input_mask; - v.vertex_format = RD::get_singleton()->vertex_format_create(attributes); - v.vertex_array = RD::get_singleton()->vertex_array_create(s->vertex_count, v.vertex_format, buffers); -} - -////////////////// MULTIMESH - -RID RendererStorageRD::multimesh_allocate() { - return multimesh_owner.allocate_rid(); -} -void RendererStorageRD::multimesh_initialize(RID p_rid) { - multimesh_owner.initialize_rid(p_rid, MultiMesh()); -} - -void RendererStorageRD::multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors, bool p_use_custom_data) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - - if (multimesh->instances == p_instances && multimesh->xform_format == p_transform_format && multimesh->uses_colors == p_use_colors && multimesh->uses_custom_data == p_use_custom_data) { - return; - } - - if (multimesh->buffer.is_valid()) { - RD::get_singleton()->free(multimesh->buffer); - multimesh->buffer = RID(); - multimesh->uniform_set_2d = RID(); //cleared by dependency - multimesh->uniform_set_3d = RID(); //cleared by dependency - } - - if (multimesh->data_cache_dirty_regions) { - memdelete_arr(multimesh->data_cache_dirty_regions); - multimesh->data_cache_dirty_regions = nullptr; - multimesh->data_cache_used_dirty_regions = 0; - } - - multimesh->instances = p_instances; - multimesh->xform_format = p_transform_format; - multimesh->uses_colors = p_use_colors; - multimesh->color_offset_cache = p_transform_format == RS::MULTIMESH_TRANSFORM_2D ? 8 : 12; - multimesh->uses_custom_data = p_use_custom_data; - multimesh->custom_data_offset_cache = multimesh->color_offset_cache + (p_use_colors ? 4 : 0); - multimesh->stride_cache = multimesh->custom_data_offset_cache + (p_use_custom_data ? 4 : 0); - multimesh->buffer_set = false; - - //print_line("allocate, elements: " + itos(p_instances) + " 2D: " + itos(p_transform_format == RS::MULTIMESH_TRANSFORM_2D) + " colors " + itos(multimesh->uses_colors) + " data " + itos(multimesh->uses_custom_data) + " stride " + itos(multimesh->stride_cache) + " total size " + itos(multimesh->stride_cache * multimesh->instances)); - multimesh->data_cache = Vector<float>(); - multimesh->aabb = AABB(); - multimesh->aabb_dirty = false; - multimesh->visible_instances = MIN(multimesh->visible_instances, multimesh->instances); - - if (multimesh->instances) { - multimesh->buffer = RD::get_singleton()->storage_buffer_create(multimesh->instances * multimesh->stride_cache * 4); - } - - multimesh->dependency.changed_notify(DEPENDENCY_CHANGED_MULTIMESH); -} - -int RendererStorageRD::multimesh_get_instance_count(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, 0); - return multimesh->instances; -} - -void RendererStorageRD::multimesh_set_mesh(RID p_multimesh, RID p_mesh) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - if (multimesh->mesh == p_mesh) { - return; - } - multimesh->mesh = p_mesh; - - if (multimesh->instances == 0) { - return; - } - - if (multimesh->data_cache.size()) { - //we have a data cache, just mark it dirt - _multimesh_mark_all_dirty(multimesh, false, true); - } else if (multimesh->instances) { - //need to re-create AABB unfortunately, calling this has a penalty - if (multimesh->buffer_set) { - Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer); - const uint8_t *r = buffer.ptr(); - const float *data = (const float *)r; - _multimesh_re_create_aabb(multimesh, data, multimesh->instances); - } - } - - multimesh->dependency.changed_notify(DEPENDENCY_CHANGED_MESH); -} - -#define MULTIMESH_DIRTY_REGION_SIZE 512 - -void RendererStorageRD::_multimesh_make_local(MultiMesh *multimesh) const { - if (multimesh->data_cache.size() > 0) { - return; //already local - } - ERR_FAIL_COND(multimesh->data_cache.size() > 0); - // this means that the user wants to load/save individual elements, - // for this, the data must reside on CPU, so just copy it there. - multimesh->data_cache.resize(multimesh->instances * multimesh->stride_cache); - { - float *w = multimesh->data_cache.ptrw(); - - if (multimesh->buffer_set) { - Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer); - { - const uint8_t *r = buffer.ptr(); - memcpy(w, r, buffer.size()); - } - } else { - memset(w, 0, (size_t)multimesh->instances * multimesh->stride_cache * sizeof(float)); - } - } - uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; - multimesh->data_cache_dirty_regions = memnew_arr(bool, data_cache_dirty_region_count); - for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { - multimesh->data_cache_dirty_regions[i] = false; - } - multimesh->data_cache_used_dirty_regions = 0; -} - -void RendererStorageRD::_multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb) { - uint32_t region_index = p_index / MULTIMESH_DIRTY_REGION_SIZE; -#ifdef DEBUG_ENABLED - uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; - ERR_FAIL_UNSIGNED_INDEX(region_index, data_cache_dirty_region_count); //bug -#endif - if (!multimesh->data_cache_dirty_regions[region_index]) { - multimesh->data_cache_dirty_regions[region_index] = true; - multimesh->data_cache_used_dirty_regions++; - } - - if (p_aabb) { - multimesh->aabb_dirty = true; - } - - if (!multimesh->dirty) { - multimesh->dirty_list = multimesh_dirty_list; - multimesh_dirty_list = multimesh; - multimesh->dirty = true; - } -} - -void RendererStorageRD::_multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb) { - if (p_data) { - uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; - - for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { - if (!multimesh->data_cache_dirty_regions[i]) { - multimesh->data_cache_dirty_regions[i] = true; - multimesh->data_cache_used_dirty_regions++; - } - } - } - - if (p_aabb) { - multimesh->aabb_dirty = true; - } - - if (!multimesh->dirty) { - multimesh->dirty_list = multimesh_dirty_list; - multimesh_dirty_list = multimesh; - multimesh->dirty = true; - } -} - -void RendererStorageRD::_multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances) { - ERR_FAIL_COND(multimesh->mesh.is_null()); - AABB aabb; - AABB mesh_aabb = mesh_get_aabb(multimesh->mesh); - for (int i = 0; i < p_instances; i++) { - const float *data = p_data + multimesh->stride_cache * i; - Transform3D t; - - if (multimesh->xform_format == RS::MULTIMESH_TRANSFORM_3D) { - t.basis.elements[0][0] = data[0]; - t.basis.elements[0][1] = data[1]; - t.basis.elements[0][2] = data[2]; - t.origin.x = data[3]; - t.basis.elements[1][0] = data[4]; - t.basis.elements[1][1] = data[5]; - t.basis.elements[1][2] = data[6]; - t.origin.y = data[7]; - t.basis.elements[2][0] = data[8]; - t.basis.elements[2][1] = data[9]; - t.basis.elements[2][2] = data[10]; - t.origin.z = data[11]; - - } else { - t.basis.elements[0].x = data[0]; - t.basis.elements[1].x = data[1]; - t.origin.x = data[3]; - - t.basis.elements[0].y = data[4]; - t.basis.elements[1].y = data[5]; - t.origin.y = data[7]; - } - - if (i == 0) { - aabb = t.xform(mesh_aabb); - } else { - aabb.merge_with(t.xform(mesh_aabb)); - } - } - - multimesh->aabb = aabb; -} - -void RendererStorageRD::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - ERR_FAIL_INDEX(p_index, multimesh->instances); - ERR_FAIL_COND(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_3D); - - _multimesh_make_local(multimesh); - - { - float *w = multimesh->data_cache.ptrw(); - - float *dataptr = w + p_index * multimesh->stride_cache; - - dataptr[0] = p_transform.basis.elements[0][0]; - dataptr[1] = p_transform.basis.elements[0][1]; - dataptr[2] = p_transform.basis.elements[0][2]; - dataptr[3] = p_transform.origin.x; - dataptr[4] = p_transform.basis.elements[1][0]; - dataptr[5] = p_transform.basis.elements[1][1]; - dataptr[6] = p_transform.basis.elements[1][2]; - dataptr[7] = p_transform.origin.y; - dataptr[8] = p_transform.basis.elements[2][0]; - dataptr[9] = p_transform.basis.elements[2][1]; - dataptr[10] = p_transform.basis.elements[2][2]; - dataptr[11] = p_transform.origin.z; - } - - _multimesh_mark_dirty(multimesh, p_index, true); -} - -void RendererStorageRD::multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - ERR_FAIL_INDEX(p_index, multimesh->instances); - ERR_FAIL_COND(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_2D); - - _multimesh_make_local(multimesh); - - { - float *w = multimesh->data_cache.ptrw(); - - float *dataptr = w + p_index * multimesh->stride_cache; - - dataptr[0] = p_transform.elements[0][0]; - dataptr[1] = p_transform.elements[1][0]; - dataptr[2] = 0; - dataptr[3] = p_transform.elements[2][0]; - dataptr[4] = p_transform.elements[0][1]; - dataptr[5] = p_transform.elements[1][1]; - dataptr[6] = 0; - dataptr[7] = p_transform.elements[2][1]; - } - - _multimesh_mark_dirty(multimesh, p_index, true); -} - -void RendererStorageRD::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - ERR_FAIL_INDEX(p_index, multimesh->instances); - ERR_FAIL_COND(!multimesh->uses_colors); - - _multimesh_make_local(multimesh); - - { - float *w = multimesh->data_cache.ptrw(); - - float *dataptr = w + p_index * multimesh->stride_cache + multimesh->color_offset_cache; - - dataptr[0] = p_color.r; - dataptr[1] = p_color.g; - dataptr[2] = p_color.b; - dataptr[3] = p_color.a; - } - - _multimesh_mark_dirty(multimesh, p_index, false); -} - -void RendererStorageRD::multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - ERR_FAIL_INDEX(p_index, multimesh->instances); - ERR_FAIL_COND(!multimesh->uses_custom_data); - - _multimesh_make_local(multimesh); - - { - float *w = multimesh->data_cache.ptrw(); - - float *dataptr = w + p_index * multimesh->stride_cache + multimesh->custom_data_offset_cache; - - dataptr[0] = p_color.r; - dataptr[1] = p_color.g; - dataptr[2] = p_color.b; - dataptr[3] = p_color.a; - } - - _multimesh_mark_dirty(multimesh, p_index, false); -} - -RID RendererStorageRD::multimesh_get_mesh(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, RID()); - - return multimesh->mesh; -} - -Transform3D RendererStorageRD::multimesh_instance_get_transform(RID p_multimesh, int p_index) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, Transform3D()); - ERR_FAIL_INDEX_V(p_index, multimesh->instances, Transform3D()); - ERR_FAIL_COND_V(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_3D, Transform3D()); - - _multimesh_make_local(multimesh); - - Transform3D t; - { - const float *r = multimesh->data_cache.ptr(); - - const float *dataptr = r + p_index * multimesh->stride_cache; - - t.basis.elements[0][0] = dataptr[0]; - t.basis.elements[0][1] = dataptr[1]; - t.basis.elements[0][2] = dataptr[2]; - t.origin.x = dataptr[3]; - t.basis.elements[1][0] = dataptr[4]; - t.basis.elements[1][1] = dataptr[5]; - t.basis.elements[1][2] = dataptr[6]; - t.origin.y = dataptr[7]; - t.basis.elements[2][0] = dataptr[8]; - t.basis.elements[2][1] = dataptr[9]; - t.basis.elements[2][2] = dataptr[10]; - t.origin.z = dataptr[11]; - } - - return t; -} - -Transform2D RendererStorageRD::multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, Transform2D()); - ERR_FAIL_INDEX_V(p_index, multimesh->instances, Transform2D()); - ERR_FAIL_COND_V(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_2D, Transform2D()); - - _multimesh_make_local(multimesh); - - Transform2D t; - { - const float *r = multimesh->data_cache.ptr(); - - const float *dataptr = r + p_index * multimesh->stride_cache; - - t.elements[0][0] = dataptr[0]; - t.elements[1][0] = dataptr[1]; - t.elements[2][0] = dataptr[3]; - t.elements[0][1] = dataptr[4]; - t.elements[1][1] = dataptr[5]; - t.elements[2][1] = dataptr[7]; - } - - return t; -} - -Color RendererStorageRD::multimesh_instance_get_color(RID p_multimesh, int p_index) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, Color()); - ERR_FAIL_INDEX_V(p_index, multimesh->instances, Color()); - ERR_FAIL_COND_V(!multimesh->uses_colors, Color()); - - _multimesh_make_local(multimesh); - - Color c; - { - const float *r = multimesh->data_cache.ptr(); - - const float *dataptr = r + p_index * multimesh->stride_cache + multimesh->color_offset_cache; - - c.r = dataptr[0]; - c.g = dataptr[1]; - c.b = dataptr[2]; - c.a = dataptr[3]; - } - - return c; -} - -Color RendererStorageRD::multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, Color()); - ERR_FAIL_INDEX_V(p_index, multimesh->instances, Color()); - ERR_FAIL_COND_V(!multimesh->uses_custom_data, Color()); - - _multimesh_make_local(multimesh); - - Color c; - { - const float *r = multimesh->data_cache.ptr(); - - const float *dataptr = r + p_index * multimesh->stride_cache + multimesh->custom_data_offset_cache; - - c.r = dataptr[0]; - c.g = dataptr[1]; - c.b = dataptr[2]; - c.a = dataptr[3]; - } - - return c; -} - -void RendererStorageRD::multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - ERR_FAIL_COND(p_buffer.size() != (multimesh->instances * (int)multimesh->stride_cache)); - - { - const float *r = p_buffer.ptr(); - RD::get_singleton()->buffer_update(multimesh->buffer, 0, p_buffer.size() * sizeof(float), r); - multimesh->buffer_set = true; - } - - if (multimesh->data_cache.size()) { - //if we have a data cache, just update it - multimesh->data_cache = p_buffer; - { - //clear dirty since nothing will be dirty anymore - uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; - for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { - multimesh->data_cache_dirty_regions[i] = false; - } - multimesh->data_cache_used_dirty_regions = 0; - } - - _multimesh_mark_all_dirty(multimesh, false, true); //update AABB - } else if (multimesh->mesh.is_valid()) { - //if we have a mesh set, we need to re-generate the AABB from the new data - const float *data = p_buffer.ptr(); - - _multimesh_re_create_aabb(multimesh, data, multimesh->instances); - multimesh->dependency.changed_notify(DEPENDENCY_CHANGED_AABB); - } -} - -Vector<float> RendererStorageRD::multimesh_get_buffer(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, Vector<float>()); - if (multimesh->buffer.is_null()) { - return Vector<float>(); - } else if (multimesh->data_cache.size()) { - return multimesh->data_cache; - } else { - //get from memory - - Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer); - Vector<float> ret; - ret.resize(multimesh->instances * multimesh->stride_cache); - { - float *w = ret.ptrw(); - const uint8_t *r = buffer.ptr(); - memcpy(w, r, buffer.size()); - } - - return ret; - } -} - -void RendererStorageRD::multimesh_set_visible_instances(RID p_multimesh, int p_visible) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND(!multimesh); - ERR_FAIL_COND(p_visible < -1 || p_visible > multimesh->instances); - if (multimesh->visible_instances == p_visible) { - return; - } - - if (multimesh->data_cache.size()) { - //there is a data cache.. - _multimesh_mark_all_dirty(multimesh, false, true); - } - - multimesh->visible_instances = p_visible; - - multimesh->dependency.changed_notify(DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES); -} - -int RendererStorageRD::multimesh_get_visible_instances(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, 0); - return multimesh->visible_instances; -} - -AABB RendererStorageRD::multimesh_get_aabb(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - ERR_FAIL_COND_V(!multimesh, AABB()); - if (multimesh->aabb_dirty) { - const_cast<RendererStorageRD *>(this)->_update_dirty_multimeshes(); - } - return multimesh->aabb; -} - -void RendererStorageRD::_update_dirty_multimeshes() { - while (multimesh_dirty_list) { - MultiMesh *multimesh = multimesh_dirty_list; - - if (multimesh->data_cache.size()) { //may have been cleared, so only process if it exists - const float *data = multimesh->data_cache.ptr(); - - uint32_t visible_instances = multimesh->visible_instances >= 0 ? multimesh->visible_instances : multimesh->instances; - - if (multimesh->data_cache_used_dirty_regions) { - uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; - uint32_t visible_region_count = visible_instances == 0 ? 0 : (visible_instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; - - uint32_t region_size = multimesh->stride_cache * MULTIMESH_DIRTY_REGION_SIZE * sizeof(float); - - if (multimesh->data_cache_used_dirty_regions > 32 || multimesh->data_cache_used_dirty_regions > visible_region_count / 2) { - //if there too many dirty regions, or represent the majority of regions, just copy all, else transfer cost piles up too much - RD::get_singleton()->buffer_update(multimesh->buffer, 0, MIN(visible_region_count * region_size, multimesh->instances * (uint32_t)multimesh->stride_cache * (uint32_t)sizeof(float)), data); - } else { - //not that many regions? update them all - for (uint32_t i = 0; i < visible_region_count; i++) { - if (multimesh->data_cache_dirty_regions[i]) { - uint32_t offset = i * region_size; - uint32_t size = multimesh->stride_cache * (uint32_t)multimesh->instances * (uint32_t)sizeof(float); - uint32_t region_start_index = multimesh->stride_cache * MULTIMESH_DIRTY_REGION_SIZE * i; - RD::get_singleton()->buffer_update(multimesh->buffer, offset, MIN(region_size, size - offset), &data[region_start_index]); - } - } - } - - for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { - multimesh->data_cache_dirty_regions[i] = false; - } - - multimesh->data_cache_used_dirty_regions = 0; - } - - if (multimesh->aabb_dirty) { - //aabb is dirty.. - _multimesh_re_create_aabb(multimesh, data, visible_instances); - multimesh->aabb_dirty = false; - multimesh->dependency.changed_notify(DEPENDENCY_CHANGED_AABB); - } - } - - multimesh_dirty_list = multimesh->dirty_list; - - multimesh->dirty_list = nullptr; - multimesh->dirty = false; - } - - multimesh_dirty_list = nullptr; -} - /* PARTICLES */ RID RendererStorageRD::particles_allocate() { @@ -1900,7 +421,7 @@ void RendererStorageRD::_particles_allocate_emission_buffer(Particles *particles particles->emission_buffer_data.resize(sizeof(ParticleEmissionBuffer::Data) * particles->amount + sizeof(uint32_t) * 4); memset(particles->emission_buffer_data.ptrw(), 0, particles->emission_buffer_data.size()); - particles->emission_buffer = (ParticleEmissionBuffer *)particles->emission_buffer_data.ptrw(); + particles->emission_buffer = reinterpret_cast<ParticleEmissionBuffer *>(particles->emission_buffer_data.ptrw()); particles->emission_buffer->particle_max = particles->amount; particles->emission_storage_buffer = RD::get_singleton()->storage_buffer_create(particles->emission_buffer_data.size(), particles->emission_buffer_data); @@ -2024,7 +545,7 @@ AABB RendererStorageRD::particles_get_current_aabb(RID p_particles) { float longest_axis_size = 0; for (int i = 0; i < particles->draw_passes.size(); i++) { if (particles->draw_passes[i].is_valid()) { - AABB maabb = mesh_get_aabb(particles->draw_passes[i], RID()); + AABB maabb = RendererRD::MeshStorage::get_singleton()->mesh_get_aabb(particles->draw_passes[i], RID()); longest_axis_size = MAX(maabb.get_longest_axis_size(), longest_axis_size); } } @@ -2113,7 +634,7 @@ void RendererStorageRD::_particles_process(Particles *p_particles, double p_delt if (p_particles->emission_storage_buffer.is_valid()) { u.append_id(p_particles->emission_storage_buffer); } else { - u.append_id(default_rd_storage_buffer); + u.append_id(RendererRD::MeshStorage::get_singleton()->get_default_rd_storage_buffer()); } uniforms.push_back(u); } @@ -2128,7 +649,7 @@ void RendererStorageRD::_particles_process(Particles *p_particles, double p_delt } u.append_id(sub_emitter->emission_storage_buffer); } else { - u.append_id(default_rd_storage_buffer); + u.append_id(RendererRD::MeshStorage::get_singleton()->get_default_rd_storage_buffer()); } uniforms.push_back(u); } @@ -2476,9 +997,9 @@ void RendererStorageRD::_particles_process(Particles *p_particles, double p_delt RD::get_singleton()->buffer_update(p_particles->frame_params_buffer, 0, sizeof(ParticlesFrameParams) * p_particles->trail_params.size(), p_particles->trail_params.ptr()); - ParticlesMaterialData *m = (ParticlesMaterialData *)material_storage->material_get_data(p_particles->process_material, RendererRD::SHADER_TYPE_PARTICLES); + ParticlesMaterialData *m = static_cast<ParticlesMaterialData *>(material_storage->material_get_data(p_particles->process_material, RendererRD::SHADER_TYPE_PARTICLES)); if (!m) { - m = (ParticlesMaterialData *)material_storage->material_get_data(particles_shader.default_material, RendererRD::SHADER_TYPE_PARTICLES); + m = static_cast<ParticlesMaterialData *>(material_storage->material_get_data(particles_shader.default_material, RendererRD::SHADER_TYPE_PARTICLES)); } ERR_FAIL_COND(!m); @@ -2771,7 +1292,7 @@ void RendererStorageRD::update_particles() { if (particles->trail_bind_pose_buffer.is_valid()) { u.append_id(particles->trail_bind_pose_buffer); } else { - u.append_id(default_rd_storage_buffer); + u.append_id(RendererRD::MeshStorage::get_singleton()->get_default_rd_storage_buffer()); } uniforms.push_back(u); } @@ -3407,195 +1928,6 @@ void RendererStorageRD::visibility_notifier_call(RID p_notifier, bool p_enter, b } } -/* SKELETON API */ - -RID RendererStorageRD::skeleton_allocate() { - return skeleton_owner.allocate_rid(); -} -void RendererStorageRD::skeleton_initialize(RID p_rid) { - skeleton_owner.initialize_rid(p_rid, Skeleton()); -} - -void RendererStorageRD::_skeleton_make_dirty(Skeleton *skeleton) { - if (!skeleton->dirty) { - skeleton->dirty = true; - skeleton->dirty_list = skeleton_dirty_list; - skeleton_dirty_list = skeleton; - } -} - -void RendererStorageRD::skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton) { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - ERR_FAIL_COND(!skeleton); - ERR_FAIL_COND(p_bones < 0); - - if (skeleton->size == p_bones && skeleton->use_2d == p_2d_skeleton) { - return; - } - - skeleton->size = p_bones; - skeleton->use_2d = p_2d_skeleton; - skeleton->uniform_set_3d = RID(); - - if (skeleton->buffer.is_valid()) { - RD::get_singleton()->free(skeleton->buffer); - skeleton->buffer = RID(); - skeleton->data.clear(); - skeleton->uniform_set_mi = RID(); - } - - if (skeleton->size) { - skeleton->data.resize(skeleton->size * (skeleton->use_2d ? 8 : 12)); - skeleton->buffer = RD::get_singleton()->storage_buffer_create(skeleton->data.size() * sizeof(float)); - memset(skeleton->data.ptrw(), 0, skeleton->data.size() * sizeof(float)); - - _skeleton_make_dirty(skeleton); - - { - Vector<RD::Uniform> uniforms; - { - RD::Uniform u; - u.binding = 0; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.append_id(skeleton->buffer); - uniforms.push_back(u); - } - skeleton->uniform_set_mi = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_SKELETON); - } - } - - skeleton->dependency.changed_notify(DEPENDENCY_CHANGED_SKELETON_DATA); -} - -int RendererStorageRD::skeleton_get_bone_count(RID p_skeleton) const { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - ERR_FAIL_COND_V(!skeleton, 0); - - return skeleton->size; -} - -void RendererStorageRD::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - - ERR_FAIL_COND(!skeleton); - ERR_FAIL_INDEX(p_bone, skeleton->size); - ERR_FAIL_COND(skeleton->use_2d); - - float *dataptr = skeleton->data.ptrw() + p_bone * 12; - - dataptr[0] = p_transform.basis.elements[0][0]; - dataptr[1] = p_transform.basis.elements[0][1]; - dataptr[2] = p_transform.basis.elements[0][2]; - dataptr[3] = p_transform.origin.x; - dataptr[4] = p_transform.basis.elements[1][0]; - dataptr[5] = p_transform.basis.elements[1][1]; - dataptr[6] = p_transform.basis.elements[1][2]; - dataptr[7] = p_transform.origin.y; - dataptr[8] = p_transform.basis.elements[2][0]; - dataptr[9] = p_transform.basis.elements[2][1]; - dataptr[10] = p_transform.basis.elements[2][2]; - dataptr[11] = p_transform.origin.z; - - _skeleton_make_dirty(skeleton); -} - -Transform3D RendererStorageRD::skeleton_bone_get_transform(RID p_skeleton, int p_bone) const { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - - ERR_FAIL_COND_V(!skeleton, Transform3D()); - ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform3D()); - ERR_FAIL_COND_V(skeleton->use_2d, Transform3D()); - - const float *dataptr = skeleton->data.ptr() + p_bone * 12; - - Transform3D t; - - t.basis.elements[0][0] = dataptr[0]; - t.basis.elements[0][1] = dataptr[1]; - t.basis.elements[0][2] = dataptr[2]; - t.origin.x = dataptr[3]; - t.basis.elements[1][0] = dataptr[4]; - t.basis.elements[1][1] = dataptr[5]; - t.basis.elements[1][2] = dataptr[6]; - t.origin.y = dataptr[7]; - t.basis.elements[2][0] = dataptr[8]; - t.basis.elements[2][1] = dataptr[9]; - t.basis.elements[2][2] = dataptr[10]; - t.origin.z = dataptr[11]; - - return t; -} - -void RendererStorageRD::skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - - ERR_FAIL_COND(!skeleton); - ERR_FAIL_INDEX(p_bone, skeleton->size); - ERR_FAIL_COND(!skeleton->use_2d); - - float *dataptr = skeleton->data.ptrw() + p_bone * 8; - - dataptr[0] = p_transform.elements[0][0]; - dataptr[1] = p_transform.elements[1][0]; - dataptr[2] = 0; - dataptr[3] = p_transform.elements[2][0]; - dataptr[4] = p_transform.elements[0][1]; - dataptr[5] = p_transform.elements[1][1]; - dataptr[6] = 0; - dataptr[7] = p_transform.elements[2][1]; - - _skeleton_make_dirty(skeleton); -} - -Transform2D RendererStorageRD::skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - - ERR_FAIL_COND_V(!skeleton, Transform2D()); - ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform2D()); - ERR_FAIL_COND_V(!skeleton->use_2d, Transform2D()); - - const float *dataptr = skeleton->data.ptr() + p_bone * 8; - - Transform2D t; - t.elements[0][0] = dataptr[0]; - t.elements[1][0] = dataptr[1]; - t.elements[2][0] = dataptr[3]; - t.elements[0][1] = dataptr[4]; - t.elements[1][1] = dataptr[5]; - t.elements[2][1] = dataptr[7]; - - return t; -} - -void RendererStorageRD::skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - - ERR_FAIL_COND(!skeleton->use_2d); - - skeleton->base_transform_2d = p_base_transform; -} - -void RendererStorageRD::_update_dirty_skeletons() { - while (skeleton_dirty_list) { - Skeleton *skeleton = skeleton_dirty_list; - - if (skeleton->size) { - RD::get_singleton()->buffer_update(skeleton->buffer, 0, skeleton->data.size() * sizeof(float), skeleton->data.ptr()); - } - - skeleton_dirty_list = skeleton->dirty_list; - - skeleton->dependency.changed_notify(DEPENDENCY_CHANGED_SKELETON_BONES); - - skeleton->version++; - - skeleton->dirty = false; - skeleton->dirty_list = nullptr; - } - - skeleton_dirty_list = nullptr; -} - /* LIGHT */ void RendererStorageRD::_light_initialize(RID p_light, RS::LightType p_type) { @@ -5311,11 +3643,11 @@ void RendererStorageRD::render_target_set_backbuffer_uniform_set(RID p_render_ta } void RendererStorageRD::base_update_dependency(RID p_base, DependencyTracker *p_instance) { - if (mesh_owner.owns(p_base)) { - Mesh *mesh = mesh_owner.get_or_null(p_base); + if (RendererRD::MeshStorage::get_singleton()->owns_mesh(p_base)) { + RendererRD::Mesh *mesh = RendererRD::MeshStorage::get_singleton()->get_mesh(p_base); p_instance->update_dependency(&mesh->dependency); - } else if (multimesh_owner.owns(p_base)) { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_base); + } else if (RendererRD::MeshStorage::get_singleton()->owns_multimesh(p_base)) { + RendererRD::MultiMesh *multimesh = RendererRD::MeshStorage::get_singleton()->get_multimesh(p_base); p_instance->update_dependency(&multimesh->dependency); if (multimesh->mesh.is_valid()) { base_update_dependency(multimesh->mesh, p_instance); @@ -5350,18 +3682,11 @@ void RendererStorageRD::base_update_dependency(RID p_base, DependencyTracker *p_ } } -void RendererStorageRD::skeleton_update_dependency(RID p_skeleton, DependencyTracker *p_instance) { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - ERR_FAIL_COND(!skeleton); - - p_instance->update_dependency(&skeleton->dependency); -} - RS::InstanceType RendererStorageRD::get_base_type(RID p_rid) const { - if (mesh_owner.owns(p_rid)) { + if (RendererRD::MeshStorage::get_singleton()->owns_mesh(p_rid)) { return RS::INSTANCE_MESH; } - if (multimesh_owner.owns(p_rid)) { + if (RendererRD::MeshStorage::get_singleton()->owns_multimesh(p_rid)) { return RS::INSTANCE_MULTIMESH; } if (reflection_probe_owner.owns(p_rid)) { @@ -5398,8 +3723,8 @@ RS::InstanceType RendererStorageRD::get_base_type(RID p_rid) const { void RendererStorageRD::update_dirty_resources() { RendererRD::MaterialStorage::get_singleton()->_update_global_variables(); //must do before materials, so it can queue them for update RendererRD::MaterialStorage::get_singleton()->_update_queued_materials(); - _update_dirty_multimeshes(); - _update_dirty_skeletons(); + RendererRD::MeshStorage::get_singleton()->_update_dirty_multimeshes(); + RendererRD::MeshStorage::get_singleton()->_update_dirty_skeletons(); RendererRD::DecalAtlasStorage::get_singleton()->update_decal_atlas(); } @@ -5432,42 +3757,14 @@ bool RendererStorageRD::free(RID p_rid) { RendererRD::MaterialStorage::get_singleton()->shader_free(p_rid); } else if (RendererRD::MaterialStorage::get_singleton()->owns_material(p_rid)) { RendererRD::MaterialStorage::get_singleton()->material_free(p_rid); - } else if (mesh_owner.owns(p_rid)) { - mesh_clear(p_rid); - mesh_set_shadow_mesh(p_rid, RID()); - Mesh *mesh = mesh_owner.get_or_null(p_rid); - mesh->dependency.deleted_notify(p_rid); - if (mesh->instances.size()) { - ERR_PRINT("deleting mesh with active instances"); - } - if (mesh->shadow_owners.size()) { - for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) { - Mesh *shadow_owner = E->get(); - shadow_owner->shadow_mesh = RID(); - shadow_owner->dependency.changed_notify(DEPENDENCY_CHANGED_MESH); - } - } - mesh_owner.free(p_rid); - } else if (mesh_instance_owner.owns(p_rid)) { - MeshInstance *mi = mesh_instance_owner.get_or_null(p_rid); - _mesh_instance_clear(mi); - mi->mesh->instances.erase(mi->I); - mi->I = nullptr; - - mesh_instance_owner.free(p_rid); - - } else if (multimesh_owner.owns(p_rid)) { - _update_dirty_multimeshes(); - multimesh_allocate_data(p_rid, 0, RS::MULTIMESH_TRANSFORM_2D); - MultiMesh *multimesh = multimesh_owner.get_or_null(p_rid); - multimesh->dependency.deleted_notify(p_rid); - multimesh_owner.free(p_rid); - } else if (skeleton_owner.owns(p_rid)) { - _update_dirty_skeletons(); - skeleton_allocate_data(p_rid, 0); - Skeleton *skeleton = skeleton_owner.get_or_null(p_rid); - skeleton->dependency.deleted_notify(p_rid); - skeleton_owner.free(p_rid); + } else if (RendererRD::MeshStorage::get_singleton()->owns_mesh(p_rid)) { + RendererRD::MeshStorage::get_singleton()->mesh_free(p_rid); + } else if (RendererRD::MeshStorage::get_singleton()->owns_mesh_instance(p_rid)) { + RendererRD::MeshStorage::get_singleton()->mesh_instance_free(p_rid); + } else if (RendererRD::MeshStorage::get_singleton()->owns_multimesh(p_rid)) { + RendererRD::MeshStorage::get_singleton()->multimesh_free(p_rid); + } else if (RendererRD::MeshStorage::get_singleton()->owns_skeleton(p_rid)) { + RendererRD::MeshStorage::get_singleton()->skeleton_free(p_rid); } else if (reflection_probe_owner.owns(p_rid)) { ReflectionProbe *reflection_probe = reflection_probe_owner.get_or_null(p_rid); reflection_probe->dependency.deleted_notify(p_rid); @@ -5696,120 +3993,6 @@ RendererStorageRD::RendererStorageRD() { //custom sampler sampler_rd_configure_custom(0.0f); - //default rd buffers - { - Vector<uint8_t> buffer; - { - buffer.resize(sizeof(float) * 3); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 0.0; - fptr[1] = 0.0; - fptr[2] = 0.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_VERTEX] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - - { //normal - buffer.resize(sizeof(float) * 3); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 1.0; - fptr[1] = 0.0; - fptr[2] = 0.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_NORMAL] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - - { //tangent - buffer.resize(sizeof(float) * 4); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 1.0; - fptr[1] = 0.0; - fptr[2] = 0.0; - fptr[3] = 0.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_TANGENT] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - - { //color - buffer.resize(sizeof(float) * 4); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 1.0; - fptr[1] = 1.0; - fptr[2] = 1.0; - fptr[3] = 1.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_COLOR] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - - { //tex uv 1 - buffer.resize(sizeof(float) * 2); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 0.0; - fptr[1] = 0.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_TEX_UV] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - { //tex uv 2 - buffer.resize(sizeof(float) * 2); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 0.0; - fptr[1] = 0.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_TEX_UV2] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - - for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) { - buffer.resize(sizeof(float) * 4); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 0.0; - fptr[1] = 0.0; - fptr[2] = 0.0; - fptr[3] = 0.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_CUSTOM0 + i] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - - { //bones - buffer.resize(sizeof(uint32_t) * 4); - { - uint8_t *w = buffer.ptrw(); - uint32_t *fptr = (uint32_t *)w; - fptr[0] = 0; - fptr[1] = 0; - fptr[2] = 0; - fptr[3] = 0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_BONES] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - - { //weights - buffer.resize(sizeof(float) * 4); - { - uint8_t *w = buffer.ptrw(); - float *fptr = (float *)w; - fptr[0] = 0.0; - fptr[1] = 0.0; - fptr[2] = 0.0; - fptr[3] = 0.0; - } - mesh_default_rd_buffers[DEFAULT_RD_BUFFER_WEIGHTS] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); - } - } - using_lightmap_array = true; // high end if (using_lightmap_array) { uint64_t textures_per_stage = RD::get_singleton()->limit_get(RD::LIMIT_MAX_TEXTURES_PER_SHADER_STAGE); @@ -5915,7 +4098,7 @@ void process() { material_storage->material_initialize(particles_shader.default_material); material_storage->material_set_shader(particles_shader.default_material, particles_shader.default_shader); - ParticlesMaterialData *md = (ParticlesMaterialData *)material_storage->material_get_data(particles_shader.default_material, RendererRD::SHADER_TYPE_PARTICLES); + ParticlesMaterialData *md = static_cast<ParticlesMaterialData *>(material_storage->material_get_data(particles_shader.default_material, RendererRD::SHADER_TYPE_PARTICLES)); particles_shader.default_shader_rd = particles_shader.shader.version_get_shader(md->shader_data->version, 0); Vector<RD::Uniform> uniforms; @@ -5952,8 +4135,6 @@ void process() { particles_shader.base_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, particles_shader.default_shader_rd, 0); } - default_rd_storage_buffer = RD::get_singleton()->storage_buffer_create(sizeof(uint32_t) * 4); - { Vector<String> copy_modes; for (int i = 0; i <= ParticlesShader::MAX_USERDATAS; i++) { @@ -5996,30 +4177,6 @@ void process() { rt_sdf.pipelines[i] = RD::get_singleton()->compute_pipeline_create(rt_sdf.shader.version_get_shader(rt_sdf.shader_version, i)); } } - { - Vector<String> skeleton_modes; - skeleton_modes.push_back("\n#define MODE_2D\n"); - skeleton_modes.push_back(""); - - skeleton_shader.shader.initialize(skeleton_modes); - skeleton_shader.version = skeleton_shader.shader.version_create(); - for (int i = 0; i < SkeletonShader::SHADER_MODE_MAX; i++) { - skeleton_shader.version_shader[i] = skeleton_shader.shader.version_get_shader(skeleton_shader.version, i); - skeleton_shader.pipeline[i] = RD::get_singleton()->compute_pipeline_create(skeleton_shader.version_shader[i]); - } - - { - Vector<RD::Uniform> uniforms; - { - RD::Uniform u; - u.binding = 0; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.append_id(default_rd_storage_buffer); - uniforms.push_back(u); - } - skeleton_shader.default_skeleton_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_SKELETON); - } - } } RendererStorageRD::~RendererStorageRD() { @@ -6041,21 +4198,12 @@ RendererStorageRD::~RendererStorageRD() { } } - //def buffers - for (int i = 0; i < DEFAULT_RD_BUFFER_MAX; i++) { - RD::get_singleton()->free(mesh_default_rd_buffers[i]); - } - particles_shader.copy_shader.version_free(particles_shader.copy_shader_version); rt_sdf.shader.version_free(rt_sdf.shader_version); - skeleton_shader.shader.version_free(skeleton_shader.version); - material_storage->material_free(particles_shader.default_material); material_storage->shader_free(particles_shader.default_shader); - RD::get_singleton()->free(default_rd_storage_buffer); - if (effects) { memdelete(effects); effects = nullptr; diff --git a/servers/rendering/renderer_rd/renderer_storage_rd.h b/servers/rendering/renderer_rd/renderer_storage_rd.h index 42d4141f9c..4c45dd4295 100644 --- a/servers/rendering/renderer_rd/renderer_storage_rd.h +++ b/servers/rendering/renderer_rd/renderer_storage_rd.h @@ -39,12 +39,8 @@ #include "servers/rendering/renderer_rd/shaders/canvas_sdf.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/particles.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/particles_copy.glsl.gen.h" -#include "servers/rendering/renderer_rd/shaders/skeleton.glsl.gen.h" #include "servers/rendering/renderer_rd/shaders/voxel_gi_sdf.glsl.gen.h" -#include "servers/rendering/renderer_rd/storage_rd/canvas_texture_storage.h" -#include "servers/rendering/renderer_rd/storage_rd/decal_atlas_storage.h" #include "servers/rendering/renderer_rd/storage_rd/material_storage.h" -#include "servers/rendering/renderer_rd/storage_rd/texture_storage.h" #include "servers/rendering/renderer_scene_render.h" #include "servers/rendering/rendering_device.h" #include "servers/rendering/shader_compiler.h" @@ -129,232 +125,11 @@ public: } } - enum DefaultRDBuffer { - DEFAULT_RD_BUFFER_VERTEX, - DEFAULT_RD_BUFFER_NORMAL, - DEFAULT_RD_BUFFER_TANGENT, - DEFAULT_RD_BUFFER_COLOR, - DEFAULT_RD_BUFFER_TEX_UV, - DEFAULT_RD_BUFFER_TEX_UV2, - DEFAULT_RD_BUFFER_CUSTOM0, - DEFAULT_RD_BUFFER_CUSTOM1, - DEFAULT_RD_BUFFER_CUSTOM2, - DEFAULT_RD_BUFFER_CUSTOM3, - DEFAULT_RD_BUFFER_BONES, - DEFAULT_RD_BUFFER_WEIGHTS, - DEFAULT_RD_BUFFER_MAX, - }; - private: /* TEXTURE API */ RID default_rd_samplers[RS::CANVAS_ITEM_TEXTURE_FILTER_MAX][RS::CANVAS_ITEM_TEXTURE_REPEAT_MAX]; RID custom_rd_samplers[RS::CANVAS_ITEM_TEXTURE_FILTER_MAX][RS::CANVAS_ITEM_TEXTURE_REPEAT_MAX]; - RID default_rd_storage_buffer; - - /* Mesh */ - - struct MeshInstance; - - struct Mesh { - struct Surface { - RS::PrimitiveType primitive = RS::PRIMITIVE_POINTS; - uint32_t format = 0; - - RID vertex_buffer; - RID attribute_buffer; - RID skin_buffer; - uint32_t vertex_count = 0; - uint32_t vertex_buffer_size = 0; - uint32_t skin_buffer_size = 0; - - // A different pipeline needs to be allocated - // depending on the inputs available in the - // material. - // There are never that many geometry/material - // combinations, so a simple array is the most - // cache-efficient structure. - - struct Version { - uint32_t input_mask = 0; - RD::VertexFormatID vertex_format = 0; - RID vertex_array; - }; - - SpinLock version_lock; //needed to access versions - Version *versions = nullptr; //allocated on demand - uint32_t version_count = 0; - - RID index_buffer; - RID index_array; - uint32_t index_count = 0; - - struct LOD { - float edge_length = 0.0; - uint32_t index_count = 0; - RID index_buffer; - RID index_array; - }; - - LOD *lods = nullptr; - uint32_t lod_count = 0; - - AABB aabb; - - Vector<AABB> bone_aabbs; - - RID blend_shape_buffer; - - RID material; - - uint32_t render_index = 0; - uint64_t render_pass = 0; - - uint32_t multimesh_render_index = 0; - uint64_t multimesh_render_pass = 0; - - uint32_t particles_render_index = 0; - uint64_t particles_render_pass = 0; - - RID uniform_set; - }; - - uint32_t blend_shape_count = 0; - RS::BlendShapeMode blend_shape_mode = RS::BLEND_SHAPE_MODE_NORMALIZED; - - Surface **surfaces = nullptr; - uint32_t surface_count = 0; - - Vector<AABB> bone_aabbs; - - bool has_bone_weights = false; - - AABB aabb; - AABB custom_aabb; - - Vector<RID> material_cache; - - List<MeshInstance *> instances; - - RID shadow_mesh; - Set<Mesh *> shadow_owners; - - Dependency dependency; - }; - - mutable RID_Owner<Mesh, true> mesh_owner; - - struct MeshInstance { - Mesh *mesh; - RID skeleton; - struct Surface { - RID vertex_buffer; - RID uniform_set; - - Mesh::Surface::Version *versions = nullptr; //allocated on demand - uint32_t version_count = 0; - }; - LocalVector<Surface> surfaces; - LocalVector<float> blend_weights; - - RID blend_weights_buffer; - List<MeshInstance *>::Element *I = nullptr; //used to erase itself - uint64_t skeleton_version = 0; - bool dirty = false; - bool weights_dirty = false; - SelfList<MeshInstance> weight_update_list; - SelfList<MeshInstance> array_update_list; - MeshInstance() : - weight_update_list(this), array_update_list(this) {} - }; - - void _mesh_instance_clear(MeshInstance *mi); - void _mesh_instance_add_surface(MeshInstance *mi, Mesh *mesh, uint32_t p_surface); - - mutable RID_Owner<MeshInstance> mesh_instance_owner; - - SelfList<MeshInstance>::List dirty_mesh_instance_weights; - SelfList<MeshInstance>::List dirty_mesh_instance_arrays; - - struct SkeletonShader { - struct PushConstant { - uint32_t has_normal; - uint32_t has_tangent; - uint32_t has_skeleton; - uint32_t has_blend_shape; - - uint32_t vertex_count; - uint32_t vertex_stride; - uint32_t skin_stride; - uint32_t skin_weight_offset; - - uint32_t blend_shape_count; - uint32_t normalized_blend_shapes; - uint32_t pad0; - uint32_t pad1; - }; - - enum { - UNIFORM_SET_INSTANCE = 0, - UNIFORM_SET_SURFACE = 1, - UNIFORM_SET_SKELETON = 2, - }; - enum { - SHADER_MODE_2D, - SHADER_MODE_3D, - SHADER_MODE_MAX - }; - - SkeletonShaderRD shader; - RID version; - RID version_shader[SHADER_MODE_MAX]; - RID pipeline[SHADER_MODE_MAX]; - - RID default_skeleton_uniform_set; - } skeleton_shader; - - void _mesh_surface_generate_version_for_input_mask(Mesh::Surface::Version &v, Mesh::Surface *s, uint32_t p_input_mask, MeshInstance::Surface *mis = nullptr); - - RID mesh_default_rd_buffers[DEFAULT_RD_BUFFER_MAX]; - - /* MultiMesh */ - struct MultiMesh { - RID mesh; - int instances = 0; - RS::MultimeshTransformFormat xform_format = RS::MULTIMESH_TRANSFORM_3D; - bool uses_colors = false; - bool uses_custom_data = false; - int visible_instances = -1; - AABB aabb; - bool aabb_dirty = false; - bool buffer_set = false; - uint32_t stride_cache = 0; - uint32_t color_offset_cache = 0; - uint32_t custom_data_offset_cache = 0; - - Vector<float> data_cache; //used if individual setting is used - bool *data_cache_dirty_regions = nullptr; - uint32_t data_cache_used_dirty_regions = 0; - - RID buffer; //storage buffer - RID uniform_set_3d; - RID uniform_set_2d; - - bool dirty = false; - MultiMesh *dirty_list = nullptr; - - Dependency dependency; - }; - - mutable RID_Owner<MultiMesh, true> multimesh_owner; - - MultiMesh *multimesh_dirty_list = nullptr; - - _FORCE_INLINE_ void _multimesh_make_local(MultiMesh *multimesh) const; - _FORCE_INLINE_ void _multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb); - _FORCE_INLINE_ void _multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb); - _FORCE_INLINE_ void _multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances); - void _update_dirty_multimeshes(); /* PARTICLES */ @@ -732,34 +507,6 @@ private: mutable RID_Owner<VisibilityNotifier> visibility_notifier_owner; - /* Skeleton */ - - struct Skeleton { - bool use_2d = false; - int size = 0; - Vector<float> data; - RID buffer; - - bool dirty = false; - Skeleton *dirty_list = nullptr; - Transform2D base_transform_2d; - - RID uniform_set_3d; - RID uniform_set_mi; - - uint64_t version = 1; - - Dependency dependency; - }; - - mutable RID_Owner<Skeleton, true> skeleton_owner; - - _FORCE_INLINE_ void _skeleton_make_dirty(Skeleton *skeleton); - - Skeleton *skeleton_dirty_list = nullptr; - - void _update_dirty_skeletons(); - /* LIGHT */ struct Light { @@ -975,360 +722,6 @@ public: void sampler_rd_set_default(float p_mipmap_bias); - /* MESH API */ - - RID mesh_allocate(); - void mesh_initialize(RID p_mesh); - - virtual void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count); - - /// Return stride - virtual void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface); - - virtual int mesh_get_blend_shape_count(RID p_mesh) const; - - virtual void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode); - virtual RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const; - - virtual void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data); - virtual void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data); - virtual void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data); - - virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material); - virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const; - - virtual RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const; - - virtual int mesh_get_surface_count(RID p_mesh) const; - - virtual void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb); - virtual AABB mesh_get_custom_aabb(RID p_mesh) const; - - virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()); - virtual void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh); - - virtual void mesh_clear(RID p_mesh); - - virtual bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton); - - /* MESH INSTANCE */ - - virtual RID mesh_instance_create(RID p_base); - virtual void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton); - virtual void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight); - virtual void mesh_instance_check_for_update(RID p_mesh_instance); - virtual void update_mesh_instances(); - - _FORCE_INLINE_ const RID *mesh_get_surface_count_and_materials(RID p_mesh, uint32_t &r_surface_count) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, nullptr); - r_surface_count = mesh->surface_count; - if (r_surface_count == 0) { - return nullptr; - } - if (mesh->material_cache.is_empty()) { - mesh->material_cache.resize(mesh->surface_count); - for (uint32_t i = 0; i < r_surface_count; i++) { - mesh->material_cache.write[i] = mesh->surfaces[i]->material; - } - } - - return mesh->material_cache.ptr(); - } - - _FORCE_INLINE_ void *mesh_get_surface(RID p_mesh, uint32_t p_surface_index) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, nullptr); - ERR_FAIL_UNSIGNED_INDEX_V(p_surface_index, mesh->surface_count, nullptr); - - return mesh->surfaces[p_surface_index]; - } - - _FORCE_INLINE_ RID mesh_get_shadow_mesh(RID p_mesh) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - ERR_FAIL_COND_V(!mesh, RID()); - - return mesh->shadow_mesh; - } - - _FORCE_INLINE_ RS::PrimitiveType mesh_surface_get_primitive(void *p_surface) { - Mesh::Surface *surface = reinterpret_cast<Mesh::Surface *>(p_surface); - return surface->primitive; - } - - _FORCE_INLINE_ bool mesh_surface_has_lod(void *p_surface) const { - Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); - return s->lod_count > 0; - } - - _FORCE_INLINE_ uint32_t mesh_surface_get_vertices_drawn_count(void *p_surface) const { - Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); - return s->index_count ? s->index_count : s->vertex_count; - } - - _FORCE_INLINE_ uint32_t mesh_surface_get_lod(void *p_surface, float p_model_scale, float p_distance_threshold, float p_mesh_lod_threshold, uint32_t *r_index_count = nullptr) const { - Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); - - int32_t current_lod = -1; - if (r_index_count) { - *r_index_count = s->index_count; - } - for (uint32_t i = 0; i < s->lod_count; i++) { - float screen_size = s->lods[i].edge_length * p_model_scale / p_distance_threshold; - if (screen_size > p_mesh_lod_threshold) { - break; - } - current_lod = i; - } - if (current_lod == -1) { - return 0; - } else { - if (r_index_count) { - *r_index_count = s->lods[current_lod].index_count; - } - return current_lod + 1; - } - } - - _FORCE_INLINE_ RID mesh_surface_get_index_array(void *p_surface, uint32_t p_lod) const { - Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); - - if (p_lod == 0) { - return s->index_array; - } else { - return s->lods[p_lod - 1].index_array; - } - } - - _FORCE_INLINE_ void mesh_surface_get_vertex_arrays_and_format(void *p_surface, uint32_t p_input_mask, RID &r_vertex_array_rd, RD::VertexFormatID &r_vertex_format) { - Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); - - s->version_lock.lock(); - - //there will never be more than, at much, 3 or 4 versions, so iterating is the fastest way - - for (uint32_t i = 0; i < s->version_count; i++) { - if (s->versions[i].input_mask != p_input_mask) { - continue; - } - //we have this version, hooray - r_vertex_format = s->versions[i].vertex_format; - r_vertex_array_rd = s->versions[i].vertex_array; - s->version_lock.unlock(); - return; - } - - uint32_t version = s->version_count; - s->version_count++; - s->versions = (Mesh::Surface::Version *)memrealloc(s->versions, sizeof(Mesh::Surface::Version) * s->version_count); - - _mesh_surface_generate_version_for_input_mask(s->versions[version], s, p_input_mask); - - r_vertex_format = s->versions[version].vertex_format; - r_vertex_array_rd = s->versions[version].vertex_array; - - s->version_lock.unlock(); - } - - _FORCE_INLINE_ void mesh_instance_surface_get_vertex_arrays_and_format(RID p_mesh_instance, uint32_t p_surface_index, uint32_t p_input_mask, RID &r_vertex_array_rd, RD::VertexFormatID &r_vertex_format) { - MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); - ERR_FAIL_COND(!mi); - Mesh *mesh = mi->mesh; - ERR_FAIL_UNSIGNED_INDEX(p_surface_index, mesh->surface_count); - - MeshInstance::Surface *mis = &mi->surfaces[p_surface_index]; - Mesh::Surface *s = mesh->surfaces[p_surface_index]; - - s->version_lock.lock(); - - //there will never be more than, at much, 3 or 4 versions, so iterating is the fastest way - - for (uint32_t i = 0; i < mis->version_count; i++) { - if (mis->versions[i].input_mask != p_input_mask) { - continue; - } - //we have this version, hooray - r_vertex_format = mis->versions[i].vertex_format; - r_vertex_array_rd = mis->versions[i].vertex_array; - s->version_lock.unlock(); - return; - } - - uint32_t version = mis->version_count; - mis->version_count++; - mis->versions = (Mesh::Surface::Version *)memrealloc(mis->versions, sizeof(Mesh::Surface::Version) * mis->version_count); - - _mesh_surface_generate_version_for_input_mask(mis->versions[version], s, p_input_mask, mis); - - r_vertex_format = mis->versions[version].vertex_format; - r_vertex_array_rd = mis->versions[version].vertex_array; - - s->version_lock.unlock(); - } - - _FORCE_INLINE_ RID mesh_get_default_rd_buffer(DefaultRDBuffer p_buffer) { - ERR_FAIL_INDEX_V(p_buffer, DEFAULT_RD_BUFFER_MAX, RID()); - return mesh_default_rd_buffers[p_buffer]; - } - - _FORCE_INLINE_ uint32_t mesh_surface_get_render_pass_index(RID p_mesh, uint32_t p_surface_index, uint64_t p_render_pass, uint32_t *r_index) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - Mesh::Surface *s = mesh->surfaces[p_surface_index]; - - if (s->render_pass != p_render_pass) { - (*r_index)++; - s->render_pass = p_render_pass; - s->render_index = *r_index; - } - - return s->render_index; - } - - _FORCE_INLINE_ uint32_t mesh_surface_get_multimesh_render_pass_index(RID p_mesh, uint32_t p_surface_index, uint64_t p_render_pass, uint32_t *r_index) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - Mesh::Surface *s = mesh->surfaces[p_surface_index]; - - if (s->multimesh_render_pass != p_render_pass) { - (*r_index)++; - s->multimesh_render_pass = p_render_pass; - s->multimesh_render_index = *r_index; - } - - return s->multimesh_render_index; - } - - _FORCE_INLINE_ uint32_t mesh_surface_get_particles_render_pass_index(RID p_mesh, uint32_t p_surface_index, uint64_t p_render_pass, uint32_t *r_index) { - Mesh *mesh = mesh_owner.get_or_null(p_mesh); - Mesh::Surface *s = mesh->surfaces[p_surface_index]; - - if (s->particles_render_pass != p_render_pass) { - (*r_index)++; - s->particles_render_pass = p_render_pass; - s->particles_render_index = *r_index; - } - - return s->particles_render_index; - } - - /* MULTIMESH API */ - - RID multimesh_allocate(); - void multimesh_initialize(RID p_multimesh); - - void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false); - int multimesh_get_instance_count(RID p_multimesh) const; - - void multimesh_set_mesh(RID p_multimesh, RID p_mesh); - void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform); - void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform); - void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color); - void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color); - - RID multimesh_get_mesh(RID p_multimesh) const; - - Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const; - Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const; - Color multimesh_instance_get_color(RID p_multimesh, int p_index) const; - Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const; - - void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer); - Vector<float> multimesh_get_buffer(RID p_multimesh) const; - - void multimesh_set_visible_instances(RID p_multimesh, int p_visible); - int multimesh_get_visible_instances(RID p_multimesh) const; - - AABB multimesh_get_aabb(RID p_multimesh) const; - - _FORCE_INLINE_ RS::MultimeshTransformFormat multimesh_get_transform_format(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - return multimesh->xform_format; - } - - _FORCE_INLINE_ bool multimesh_uses_colors(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - return multimesh->uses_colors; - } - - _FORCE_INLINE_ bool multimesh_uses_custom_data(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - return multimesh->uses_custom_data; - } - - _FORCE_INLINE_ uint32_t multimesh_get_instances_to_draw(RID p_multimesh) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - if (multimesh->visible_instances >= 0) { - return multimesh->visible_instances; - } - return multimesh->instances; - } - - _FORCE_INLINE_ RID multimesh_get_3d_uniform_set(RID p_multimesh, RID p_shader, uint32_t p_set) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - if (!multimesh->uniform_set_3d.is_valid()) { - Vector<RD::Uniform> uniforms; - RD::Uniform u; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.binding = 0; - u.append_id(multimesh->buffer); - uniforms.push_back(u); - multimesh->uniform_set_3d = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set); - } - - return multimesh->uniform_set_3d; - } - - _FORCE_INLINE_ RID multimesh_get_2d_uniform_set(RID p_multimesh, RID p_shader, uint32_t p_set) const { - MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); - if (!multimesh->uniform_set_2d.is_valid()) { - Vector<RD::Uniform> uniforms; - RD::Uniform u; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.binding = 0; - u.append_id(multimesh->buffer); - uniforms.push_back(u); - multimesh->uniform_set_2d = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set); - } - - return multimesh->uniform_set_2d; - } - - /* SKELETON API */ - - RID skeleton_allocate(); - void skeleton_initialize(RID p_skeleton); - - void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false); - void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform); - void skeleton_set_world_transform(RID p_skeleton, bool p_enable, const Transform3D &p_world_transform); - int skeleton_get_bone_count(RID p_skeleton) const; - void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform); - Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const; - void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform); - Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const; - - _FORCE_INLINE_ bool skeleton_is_valid(RID p_skeleton) { - return skeleton_owner.get_or_null(p_skeleton) != nullptr; - } - - _FORCE_INLINE_ RID skeleton_get_3d_uniform_set(RID p_skeleton, RID p_shader, uint32_t p_set) const { - Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); - ERR_FAIL_COND_V(!skeleton, RID()); - ERR_FAIL_COND_V(skeleton->size == 0, RID()); - if (skeleton->use_2d) { - return RID(); - } - if (!skeleton->uniform_set_3d.is_valid()) { - Vector<RD::Uniform> uniforms; - RD::Uniform u; - u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; - u.binding = 0; - u.append_id(skeleton->buffer); - uniforms.push_back(u); - skeleton->uniform_set_3d = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set); - } - - return skeleton->uniform_set_3d; - } /* Light API */ void _light_initialize(RID p_rid, RS::LightType p_type); @@ -1498,7 +891,6 @@ public: float reflection_probe_get_ambient_color_energy(RID p_probe) const; void base_update_dependency(RID p_base, DependencyTracker *p_instance); - void skeleton_update_dependency(RID p_skeleton, DependencyTracker *p_instance); /* VOXEL GI API */ @@ -1829,8 +1221,6 @@ public: virtual uint64_t get_captured_timestamp_cpu_time(uint32_t p_index) const; virtual String get_captured_timestamp_name(uint32_t p_index) const; - RID get_default_rd_storage_buffer() { return default_rd_storage_buffer; } - static RendererStorageRD *base_singleton; void init_effects(bool p_prefer_raster_effects); diff --git a/servers/rendering/renderer_rd/shader_rd.cpp b/servers/rendering/renderer_rd/shader_rd.cpp index 73766d14d8..fdfecf2d2c 100644 --- a/servers/rendering/renderer_rd/shader_rd.cpp +++ b/servers/rendering/renderer_rd/shader_rd.cpp @@ -382,8 +382,8 @@ bool ShaderRD::_load_from_cache(Version *p_version) { String sha1 = _version_get_sha1(p_version); String path = shader_cache_dir.plus_file(name).plus_file(base_sha256).plus_file(sha1) + ".cache"; - FileAccessRef f = FileAccess::open(path, FileAccess::READ); - if (!f) { + Ref<FileAccess> f = FileAccess::open(path, FileAccess::READ); + if (f.is_null()) { return false; } @@ -445,8 +445,8 @@ void ShaderRD::_save_to_cache(Version *p_version) { String sha1 = _version_get_sha1(p_version); String path = shader_cache_dir.plus_file(name).plus_file(base_sha256).plus_file(sha1) + ".cache"; - FileAccessRef f = FileAccess::open(path, FileAccess::WRITE); - ERR_FAIL_COND(!f); + Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE); + ERR_FAIL_COND(f.is_null()); f->store_buffer((const uint8_t *)shader_file_header, 4); f->store_32(cache_file_version); //file version uint32_t variant_count = variant_defines.size(); @@ -456,8 +456,6 @@ void ShaderRD::_save_to_cache(Version *p_version) { f->store_32(p_version->variant_data[i].size()); //stage count f->store_buffer(p_version->variant_data[i].ptr(), p_version->variant_data[i].size()); } - - f->close(); } void ShaderRD::_compile_version(Version *p_version) { @@ -652,8 +650,8 @@ void ShaderRD::initialize(const Vector<String> &p_variant_defines, const String base_sha256 = hash_build.as_string().sha256_text(); - DirAccessRef d = DirAccess::open(shader_cache_dir); - ERR_FAIL_COND(!d); + Ref<DirAccess> d = DirAccess::open(shader_cache_dir); + ERR_FAIL_COND(d.is_null()); if (d->change_dir(name) != OK) { Error err = d->make_dir(name); ERR_FAIL_COND(err != OK); diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl index abe1a09b06..58b4ded9f4 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward_clustered.glsl @@ -1479,62 +1479,78 @@ void main() { } else { //no soft shadows vec4 pssm_coord; + float blur_factor; + if (depth_z < directional_lights.data[i].shadow_split_offsets.x) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 0) pssm_coord = (directional_lights.data[i].shadow_matrix1 * v); + blur_factor = 1.0; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 1) pssm_coord = (directional_lights.data[i].shadow_matrix2 * v); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.y; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 2) pssm_coord = (directional_lights.data[i].shadow_matrix3 * v); - + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.z; } else { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 3) pssm_coord = (directional_lights.data[i].shadow_matrix4 * v); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.w; } pssm_coord /= pssm_coord.w; - shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord); + shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale * blur_factor, pssm_coord); if (directional_lights.data[i].blend_splits) { float pssm_blend; + float blur_factor2; if (depth_z < directional_lights.data[i].shadow_split_offsets.x) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 1) pssm_coord = (directional_lights.data[i].shadow_matrix2 * v); pssm_blend = smoothstep(0.0, directional_lights.data[i].shadow_split_offsets.x, depth_z); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor2 = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.y; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 2) pssm_coord = (directional_lights.data[i].shadow_matrix3 * v); pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.x, directional_lights.data[i].shadow_split_offsets.y, depth_z); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor2 = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.z; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 3) pssm_coord = (directional_lights.data[i].shadow_matrix4 * v); pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.y, directional_lights.data[i].shadow_split_offsets.z, depth_z); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor2 = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.w; } else { pssm_blend = 0.0; //if no blend, same coord will be used (divide by z will result in same value, and already cached) + blur_factor2 = 1.0; } pssm_coord /= pssm_coord.w; - float shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord); + float shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale * blur_factor2, pssm_coord); shadow = mix(shadow, shadow2, pssm_blend); } } diff --git a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl index 6911cab27b..b6ba244665 100644 --- a/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl +++ b/servers/rendering/renderer_rd/shaders/scene_forward_mobile.glsl @@ -1282,6 +1282,7 @@ void main() { float depth_z = -vertex.z; vec4 pssm_coord; + float blur_factor; vec3 light_dir = directional_lights.data[i].direction; vec3 base_normal_bias = normalize(normal_interp) * (1.0 - max(0.0, dot(light_dir, -normalize(normal_interp)))); @@ -1297,56 +1298,71 @@ void main() { BIAS_FUNC(v, 0) pssm_coord = (directional_lights.data[i].shadow_matrix1 * v); + blur_factor = 1.0; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 1) pssm_coord = (directional_lights.data[i].shadow_matrix2 * v); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.y; + ; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 2) pssm_coord = (directional_lights.data[i].shadow_matrix3 * v); - + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.z; } else { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 3) pssm_coord = (directional_lights.data[i].shadow_matrix4 * v); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.w; } pssm_coord /= pssm_coord.w; - shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord); + shadow = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale * blur_factor, pssm_coord); if (directional_lights.data[i].blend_splits) { float pssm_blend; + float blur_factor2; if (depth_z < directional_lights.data[i].shadow_split_offsets.x) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 1) pssm_coord = (directional_lights.data[i].shadow_matrix2 * v); pssm_blend = smoothstep(0.0, directional_lights.data[i].shadow_split_offsets.x, depth_z); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor2 = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.y; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.y) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 2) pssm_coord = (directional_lights.data[i].shadow_matrix3 * v); pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.x, directional_lights.data[i].shadow_split_offsets.y, depth_z); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor2 = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.z; } else if (depth_z < directional_lights.data[i].shadow_split_offsets.z) { vec4 v = vec4(vertex, 1.0); BIAS_FUNC(v, 3) pssm_coord = (directional_lights.data[i].shadow_matrix4 * v); pssm_blend = smoothstep(directional_lights.data[i].shadow_split_offsets.y, directional_lights.data[i].shadow_split_offsets.z, depth_z); + // Adjust shadow blur with reference to the first split to reduce discrepancy between shadow splits. + blur_factor2 = directional_lights.data[i].shadow_split_offsets.x / directional_lights.data[i].shadow_split_offsets.w; } else { pssm_blend = 0.0; //if no blend, same coord will be used (divide by z will result in same value, and already cached) + blur_factor2 = 1.0; } pssm_coord /= pssm_coord.w; - float shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale, pssm_coord); + float shadow2 = sample_directional_pcf_shadow(directional_shadow_atlas, scene_data.directional_shadow_pixel_size * directional_lights.data[i].soft_shadow_scale * blur_factor2, pssm_coord); shadow = mix(shadow, shadow2, pssm_blend); } diff --git a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp index 9e3d124bbb..2a2c5f350a 100644 --- a/servers/rendering/renderer_rd/storage_rd/material_storage.cpp +++ b/servers/rendering/renderer_rd/storage_rd/material_storage.cpp @@ -422,7 +422,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy if (i < s) { Color color = a[i]; if (p_linear_color) { - color = color.to_linear(); + color = color.srgb_to_linear(); } gui[j] = color.r; gui[j + 1] = color.g; @@ -459,7 +459,7 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy Color v = value; if (p_linear_color) { - v = v.to_linear(); + v = v.srgb_to_linear(); } gui[0] = v.r; @@ -1498,7 +1498,7 @@ void MaterialStorage::_global_variable_store_in_buffer(int32_t p_index, RS::Glob bv.w = v.a; GlobalVariables::Value &bv_linear = global_variables.buffer_values[p_index + 1]; - v = v.to_linear(); + v = v.srgb_to_linear(); bv_linear.x = v.r; bv_linear.y = v.g; bv_linear.z = v.b; diff --git a/servers/rendering/renderer_rd/storage_rd/material_storage.h b/servers/rendering/renderer_rd/storage_rd/material_storage.h index 69b7b702b0..270d9f0982 100644 --- a/servers/rendering/renderer_rd/storage_rd/material_storage.h +++ b/servers/rendering/renderer_rd/storage_rd/material_storage.h @@ -73,7 +73,7 @@ typedef ShaderData *(*ShaderDataRequestFunction)(); struct Material; struct Shader { - ShaderData *data; + ShaderData *data = nullptr; String code; ShaderType type; Map<StringName, Map<int, RID>> default_texture_parameter; @@ -177,9 +177,9 @@ struct GlobalVariables { List<RID> materials_using_texture; RID buffer; - Value *buffer_values; - ValueUsage *buffer_usage; - bool *buffer_dirty_regions; + Value *buffer_values = nullptr; + ValueUsage *buffer_usage = nullptr; + bool *buffer_dirty_regions = nullptr; uint32_t buffer_dirty_region_count = 0; uint32_t buffer_size; diff --git a/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp b/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp new file mode 100644 index 0000000000..8c60264ce3 --- /dev/null +++ b/servers/rendering/renderer_rd/storage_rd/mesh_storage.cpp @@ -0,0 +1,1921 @@ +/*************************************************************************/ +/* mesh_storage.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "mesh_storage.h" + +using namespace RendererRD; + +MeshStorage *MeshStorage::singleton = nullptr; + +MeshStorage *MeshStorage::get_singleton() { + return singleton; +} + +MeshStorage::MeshStorage() { + singleton = this; + + default_rd_storage_buffer = RD::get_singleton()->storage_buffer_create(sizeof(uint32_t) * 4); + + //default rd buffers + { + Vector<uint8_t> buffer; + { + buffer.resize(sizeof(float) * 3); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 0.0; + fptr[1] = 0.0; + fptr[2] = 0.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_VERTEX] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + + { //normal + buffer.resize(sizeof(float) * 3); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 1.0; + fptr[1] = 0.0; + fptr[2] = 0.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_NORMAL] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + + { //tangent + buffer.resize(sizeof(float) * 4); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 1.0; + fptr[1] = 0.0; + fptr[2] = 0.0; + fptr[3] = 0.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_TANGENT] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + + { //color + buffer.resize(sizeof(float) * 4); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 1.0; + fptr[1] = 1.0; + fptr[2] = 1.0; + fptr[3] = 1.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_COLOR] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + + { //tex uv 1 + buffer.resize(sizeof(float) * 2); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 0.0; + fptr[1] = 0.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_TEX_UV] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + { //tex uv 2 + buffer.resize(sizeof(float) * 2); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 0.0; + fptr[1] = 0.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_TEX_UV2] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + + for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) { + buffer.resize(sizeof(float) * 4); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 0.0; + fptr[1] = 0.0; + fptr[2] = 0.0; + fptr[3] = 0.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_CUSTOM0 + i] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + + { //bones + buffer.resize(sizeof(uint32_t) * 4); + { + uint8_t *w = buffer.ptrw(); + uint32_t *fptr = (uint32_t *)w; + fptr[0] = 0; + fptr[1] = 0; + fptr[2] = 0; + fptr[3] = 0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_BONES] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + + { //weights + buffer.resize(sizeof(float) * 4); + { + uint8_t *w = buffer.ptrw(); + float *fptr = (float *)w; + fptr[0] = 0.0; + fptr[1] = 0.0; + fptr[2] = 0.0; + fptr[3] = 0.0; + } + mesh_default_rd_buffers[DEFAULT_RD_BUFFER_WEIGHTS] = RD::get_singleton()->vertex_buffer_create(buffer.size(), buffer); + } + } + + { + Vector<String> skeleton_modes; + skeleton_modes.push_back("\n#define MODE_2D\n"); + skeleton_modes.push_back(""); + + skeleton_shader.shader.initialize(skeleton_modes); + skeleton_shader.version = skeleton_shader.shader.version_create(); + for (int i = 0; i < SkeletonShader::SHADER_MODE_MAX; i++) { + skeleton_shader.version_shader[i] = skeleton_shader.shader.version_get_shader(skeleton_shader.version, i); + skeleton_shader.pipeline[i] = RD::get_singleton()->compute_pipeline_create(skeleton_shader.version_shader[i]); + } + + { + Vector<RD::Uniform> uniforms; + { + RD::Uniform u; + u.binding = 0; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + u.append_id(default_rd_storage_buffer); + uniforms.push_back(u); + } + skeleton_shader.default_skeleton_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_SKELETON); + } + } +} + +MeshStorage::~MeshStorage() { + //def buffers + for (int i = 0; i < DEFAULT_RD_BUFFER_MAX; i++) { + RD::get_singleton()->free(mesh_default_rd_buffers[i]); + } + + skeleton_shader.shader.version_free(skeleton_shader.version); + + RD::get_singleton()->free(default_rd_storage_buffer); + + singleton = nullptr; +} + +/* MESH API */ + +RID MeshStorage::mesh_allocate() { + return mesh_owner.allocate_rid(); +} + +void MeshStorage::mesh_initialize(RID p_rid) { + mesh_owner.initialize_rid(p_rid, Mesh()); +} + +void MeshStorage::mesh_free(RID p_rid) { + mesh_clear(p_rid); + mesh_set_shadow_mesh(p_rid, RID()); + Mesh *mesh = mesh_owner.get_or_null(p_rid); + mesh->dependency.deleted_notify(p_rid); + if (mesh->instances.size()) { + ERR_PRINT("deleting mesh with active instances"); + } + if (mesh->shadow_owners.size()) { + for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) { + Mesh *shadow_owner = E->get(); + shadow_owner->shadow_mesh = RID(); + shadow_owner->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH); + } + } + mesh_owner.free(p_rid); +} + +void MeshStorage::mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) { + ERR_FAIL_COND(p_blend_shape_count < 0); + + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + + ERR_FAIL_COND(mesh->surface_count > 0); //surfaces already exist + + mesh->blend_shape_count = p_blend_shape_count; +} + +/// Returns stride +void MeshStorage::mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + + ERR_FAIL_COND(mesh->surface_count == RS::MAX_MESH_SURFACES); + +#ifdef DEBUG_ENABLED + //do a validation, to catch errors first + { + uint32_t stride = 0; + uint32_t attrib_stride = 0; + uint32_t skin_stride = 0; + + for (int i = 0; i < RS::ARRAY_WEIGHTS; i++) { + if ((p_surface.format & (1 << i))) { + switch (i) { + case RS::ARRAY_VERTEX: { + if (p_surface.format & RS::ARRAY_FLAG_USE_2D_VERTICES) { + stride += sizeof(float) * 2; + } else { + stride += sizeof(float) * 3; + } + + } break; + case RS::ARRAY_NORMAL: { + stride += sizeof(int32_t); + + } break; + case RS::ARRAY_TANGENT: { + stride += sizeof(int32_t); + + } break; + case RS::ARRAY_COLOR: { + attrib_stride += sizeof(uint32_t); + } break; + case RS::ARRAY_TEX_UV: { + attrib_stride += sizeof(float) * 2; + + } break; + case RS::ARRAY_TEX_UV2: { + attrib_stride += sizeof(float) * 2; + + } break; + case RS::ARRAY_CUSTOM0: + case RS::ARRAY_CUSTOM1: + case RS::ARRAY_CUSTOM2: + case RS::ARRAY_CUSTOM3: { + int idx = i - RS::ARRAY_CUSTOM0; + uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT }; + uint32_t fmt = (p_surface.format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK; + uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 }; + attrib_stride += fmtsize[fmt]; + + } break; + case RS::ARRAY_WEIGHTS: + case RS::ARRAY_BONES: { + //uses a separate array + bool use_8 = p_surface.format & RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS; + skin_stride += sizeof(int16_t) * (use_8 ? 16 : 8); + } break; + } + } + } + + int expected_size = stride * p_surface.vertex_count; + ERR_FAIL_COND_MSG(expected_size != p_surface.vertex_data.size(), "Size of vertex data provided (" + itos(p_surface.vertex_data.size()) + ") does not match expected (" + itos(expected_size) + ")"); + + int bs_expected_size = expected_size * mesh->blend_shape_count; + + ERR_FAIL_COND_MSG(bs_expected_size != p_surface.blend_shape_data.size(), "Size of blend shape data provided (" + itos(p_surface.blend_shape_data.size()) + ") does not match expected (" + itos(bs_expected_size) + ")"); + + int expected_attrib_size = attrib_stride * p_surface.vertex_count; + ERR_FAIL_COND_MSG(expected_attrib_size != p_surface.attribute_data.size(), "Size of attribute data provided (" + itos(p_surface.attribute_data.size()) + ") does not match expected (" + itos(expected_attrib_size) + ")"); + + if ((p_surface.format & RS::ARRAY_FORMAT_WEIGHTS) && (p_surface.format & RS::ARRAY_FORMAT_BONES)) { + expected_size = skin_stride * p_surface.vertex_count; + ERR_FAIL_COND_MSG(expected_size != p_surface.skin_data.size(), "Size of skin data provided (" + itos(p_surface.skin_data.size()) + ") does not match expected (" + itos(expected_size) + ")"); + } + } + +#endif + + Mesh::Surface *s = memnew(Mesh::Surface); + + s->format = p_surface.format; + s->primitive = p_surface.primitive; + + bool use_as_storage = (p_surface.skin_data.size() || mesh->blend_shape_count > 0); + + s->vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.vertex_data.size(), p_surface.vertex_data, use_as_storage); + s->vertex_buffer_size = p_surface.vertex_data.size(); + + if (p_surface.attribute_data.size()) { + s->attribute_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.attribute_data.size(), p_surface.attribute_data); + } + if (p_surface.skin_data.size()) { + s->skin_buffer = RD::get_singleton()->vertex_buffer_create(p_surface.skin_data.size(), p_surface.skin_data, use_as_storage); + s->skin_buffer_size = p_surface.skin_data.size(); + } + + s->vertex_count = p_surface.vertex_count; + + if (p_surface.format & RS::ARRAY_FORMAT_BONES) { + mesh->has_bone_weights = true; + } + + if (p_surface.index_count) { + bool is_index_16 = p_surface.vertex_count <= 65536; + + s->index_buffer = RD::get_singleton()->index_buffer_create(p_surface.index_count, is_index_16 ? RD::INDEX_BUFFER_FORMAT_UINT16 : RD::INDEX_BUFFER_FORMAT_UINT32, p_surface.index_data, false); + s->index_count = p_surface.index_count; + s->index_array = RD::get_singleton()->index_array_create(s->index_buffer, 0, s->index_count); + if (p_surface.lods.size()) { + s->lods = memnew_arr(Mesh::Surface::LOD, p_surface.lods.size()); + s->lod_count = p_surface.lods.size(); + + for (int i = 0; i < p_surface.lods.size(); i++) { + uint32_t indices = p_surface.lods[i].index_data.size() / (is_index_16 ? 2 : 4); + s->lods[i].index_buffer = RD::get_singleton()->index_buffer_create(indices, is_index_16 ? RD::INDEX_BUFFER_FORMAT_UINT16 : RD::INDEX_BUFFER_FORMAT_UINT32, p_surface.lods[i].index_data); + s->lods[i].index_array = RD::get_singleton()->index_array_create(s->lods[i].index_buffer, 0, indices); + s->lods[i].edge_length = p_surface.lods[i].edge_length; + s->lods[i].index_count = indices; + } + } + } + + s->aabb = p_surface.aabb; + s->bone_aabbs = p_surface.bone_aabbs; //only really useful for returning them. + + if (mesh->blend_shape_count > 0) { + s->blend_shape_buffer = RD::get_singleton()->storage_buffer_create(p_surface.blend_shape_data.size(), p_surface.blend_shape_data); + } + + if (use_as_storage) { + Vector<RD::Uniform> uniforms; + { + RD::Uniform u; + u.binding = 0; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + u.append_id(s->vertex_buffer); + uniforms.push_back(u); + } + { + RD::Uniform u; + u.binding = 1; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + if (s->skin_buffer.is_valid()) { + u.append_id(s->skin_buffer); + } else { + u.append_id(default_rd_storage_buffer); + } + uniforms.push_back(u); + } + { + RD::Uniform u; + u.binding = 2; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + if (s->blend_shape_buffer.is_valid()) { + u.append_id(s->blend_shape_buffer); + } else { + u.append_id(default_rd_storage_buffer); + } + uniforms.push_back(u); + } + + s->uniform_set = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_SURFACE); + } + + if (mesh->surface_count == 0) { + mesh->bone_aabbs = p_surface.bone_aabbs; + mesh->aabb = p_surface.aabb; + } else { + if (mesh->bone_aabbs.size() < p_surface.bone_aabbs.size()) { + // ArrayMesh::_surface_set_data only allocates bone_aabbs up to max_bone + // Each surface may affect different numbers of bones. + mesh->bone_aabbs.resize(p_surface.bone_aabbs.size()); + } + for (int i = 0; i < p_surface.bone_aabbs.size(); i++) { + mesh->bone_aabbs.write[i].merge_with(p_surface.bone_aabbs[i]); + } + mesh->aabb.merge_with(p_surface.aabb); + } + + s->material = p_surface.material; + + mesh->surfaces = (Mesh::Surface **)memrealloc(mesh->surfaces, sizeof(Mesh::Surface *) * (mesh->surface_count + 1)); + mesh->surfaces[mesh->surface_count] = s; + mesh->surface_count++; + + for (MeshInstance *mi : mesh->instances) { + _mesh_instance_add_surface(mi, mesh, mesh->surface_count - 1); + } + + mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH); + + for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) { + Mesh *shadow_owner = E->get(); + shadow_owner->shadow_mesh = RID(); + shadow_owner->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH); + } + + mesh->material_cache.clear(); +} + +int MeshStorage::mesh_get_blend_shape_count(RID p_mesh) const { + const Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, -1); + return mesh->blend_shape_count; +} + +void MeshStorage::mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + ERR_FAIL_INDEX((int)p_mode, 2); + + mesh->blend_shape_mode = p_mode; +} + +RS::BlendShapeMode MeshStorage::mesh_get_blend_shape_mode(RID p_mesh) const { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, RS::BLEND_SHAPE_MODE_NORMALIZED); + return mesh->blend_shape_mode; +} + +void MeshStorage::mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); + ERR_FAIL_COND(p_data.size() == 0); + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + + RD::get_singleton()->buffer_update(mesh->surfaces[p_surface]->vertex_buffer, p_offset, data_size, r); +} + +void MeshStorage::mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); + ERR_FAIL_COND(p_data.size() == 0); + ERR_FAIL_COND(mesh->surfaces[p_surface]->attribute_buffer.is_null()); + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + + RD::get_singleton()->buffer_update(mesh->surfaces[p_surface]->attribute_buffer, p_offset, data_size, r); +} + +void MeshStorage::mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); + ERR_FAIL_COND(p_data.size() == 0); + ERR_FAIL_COND(mesh->surfaces[p_surface]->skin_buffer.is_null()); + uint64_t data_size = p_data.size(); + const uint8_t *r = p_data.ptr(); + + RD::get_singleton()->buffer_update(mesh->surfaces[p_surface]->skin_buffer, p_offset, data_size, r); +} + +void MeshStorage::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + ERR_FAIL_UNSIGNED_INDEX((uint32_t)p_surface, mesh->surface_count); + mesh->surfaces[p_surface]->material = p_material; + + mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MATERIAL); + mesh->material_cache.clear(); +} + +RID MeshStorage::mesh_surface_get_material(RID p_mesh, int p_surface) const { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, RID()); + ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_surface, mesh->surface_count, RID()); + + return mesh->surfaces[p_surface]->material; +} + +RS::SurfaceData MeshStorage::mesh_get_surface(RID p_mesh, int p_surface) const { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, RS::SurfaceData()); + ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_surface, mesh->surface_count, RS::SurfaceData()); + + Mesh::Surface &s = *mesh->surfaces[p_surface]; + + RS::SurfaceData sd; + sd.format = s.format; + sd.vertex_data = RD::get_singleton()->buffer_get_data(s.vertex_buffer); + if (s.attribute_buffer.is_valid()) { + sd.attribute_data = RD::get_singleton()->buffer_get_data(s.attribute_buffer); + } + if (s.skin_buffer.is_valid()) { + sd.skin_data = RD::get_singleton()->buffer_get_data(s.skin_buffer); + } + sd.vertex_count = s.vertex_count; + sd.index_count = s.index_count; + sd.primitive = s.primitive; + + if (sd.index_count) { + sd.index_data = RD::get_singleton()->buffer_get_data(s.index_buffer); + } + sd.aabb = s.aabb; + for (uint32_t i = 0; i < s.lod_count; i++) { + RS::SurfaceData::LOD lod; + lod.edge_length = s.lods[i].edge_length; + lod.index_data = RD::get_singleton()->buffer_get_data(s.lods[i].index_buffer); + sd.lods.push_back(lod); + } + + sd.bone_aabbs = s.bone_aabbs; + + if (s.blend_shape_buffer.is_valid()) { + sd.blend_shape_data = RD::get_singleton()->buffer_get_data(s.blend_shape_buffer); + } + + return sd; +} + +int MeshStorage::mesh_get_surface_count(RID p_mesh) const { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, 0); + return mesh->surface_count; +} + +void MeshStorage::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + mesh->custom_aabb = p_aabb; +} + +AABB MeshStorage::mesh_get_custom_aabb(RID p_mesh) const { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, AABB()); + return mesh->custom_aabb; +} + +AABB MeshStorage::mesh_get_aabb(RID p_mesh, RID p_skeleton) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, AABB()); + + if (mesh->custom_aabb != AABB()) { + return mesh->custom_aabb; + } + + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + + if (!skeleton || skeleton->size == 0) { + return mesh->aabb; + } + + AABB aabb; + + for (uint32_t i = 0; i < mesh->surface_count; i++) { + AABB laabb; + if ((mesh->surfaces[i]->format & RS::ARRAY_FORMAT_BONES) && mesh->surfaces[i]->bone_aabbs.size()) { + int bs = mesh->surfaces[i]->bone_aabbs.size(); + const AABB *skbones = mesh->surfaces[i]->bone_aabbs.ptr(); + + int sbs = skeleton->size; + ERR_CONTINUE(bs > sbs); + const float *baseptr = skeleton->data.ptr(); + + bool first = true; + + if (skeleton->use_2d) { + for (int j = 0; j < bs; j++) { + if (skbones[0].size == Vector3()) { + continue; //bone is unused + } + + const float *dataptr = baseptr + j * 8; + + Transform3D mtx; + + mtx.basis.elements[0].x = dataptr[0]; + mtx.basis.elements[1].x = dataptr[1]; + mtx.origin.x = dataptr[3]; + + mtx.basis.elements[0].y = dataptr[4]; + mtx.basis.elements[1].y = dataptr[5]; + mtx.origin.y = dataptr[7]; + + AABB baabb = mtx.xform(skbones[j]); + + if (first) { + laabb = baabb; + first = false; + } else { + laabb.merge_with(baabb); + } + } + } else { + for (int j = 0; j < bs; j++) { + if (skbones[0].size == Vector3()) { + continue; //bone is unused + } + + const float *dataptr = baseptr + j * 12; + + Transform3D mtx; + + mtx.basis.elements[0][0] = dataptr[0]; + mtx.basis.elements[0][1] = dataptr[1]; + mtx.basis.elements[0][2] = dataptr[2]; + mtx.origin.x = dataptr[3]; + mtx.basis.elements[1][0] = dataptr[4]; + mtx.basis.elements[1][1] = dataptr[5]; + mtx.basis.elements[1][2] = dataptr[6]; + mtx.origin.y = dataptr[7]; + mtx.basis.elements[2][0] = dataptr[8]; + mtx.basis.elements[2][1] = dataptr[9]; + mtx.basis.elements[2][2] = dataptr[10]; + mtx.origin.z = dataptr[11]; + + AABB baabb = mtx.xform(skbones[j]); + if (first) { + laabb = baabb; + first = false; + } else { + laabb.merge_with(baabb); + } + } + } + + if (laabb.size == Vector3()) { + laabb = mesh->surfaces[i]->aabb; + } + } else { + laabb = mesh->surfaces[i]->aabb; + } + + if (i == 0) { + aabb = laabb; + } else { + aabb.merge_with(laabb); + } + } + + return aabb; +} + +void MeshStorage::mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + + Mesh *shadow_mesh = mesh_owner.get_or_null(mesh->shadow_mesh); + if (shadow_mesh) { + shadow_mesh->shadow_owners.erase(mesh); + } + mesh->shadow_mesh = p_shadow_mesh; + + shadow_mesh = mesh_owner.get_or_null(mesh->shadow_mesh); + + if (shadow_mesh) { + shadow_mesh->shadow_owners.insert(mesh); + } + + mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH); +} + +void MeshStorage::mesh_clear(RID p_mesh) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND(!mesh); + for (uint32_t i = 0; i < mesh->surface_count; i++) { + Mesh::Surface &s = *mesh->surfaces[i]; + RD::get_singleton()->free(s.vertex_buffer); //clears arrays as dependency automatically, including all versions + if (s.attribute_buffer.is_valid()) { + RD::get_singleton()->free(s.attribute_buffer); + } + if (s.skin_buffer.is_valid()) { + RD::get_singleton()->free(s.skin_buffer); + } + if (s.versions) { + memfree(s.versions); //reallocs, so free with memfree. + } + + if (s.index_buffer.is_valid()) { + RD::get_singleton()->free(s.index_buffer); + } + + if (s.lod_count) { + for (uint32_t j = 0; j < s.lod_count; j++) { + RD::get_singleton()->free(s.lods[j].index_buffer); + } + memdelete_arr(s.lods); + } + + if (s.blend_shape_buffer.is_valid()) { + RD::get_singleton()->free(s.blend_shape_buffer); + } + + memdelete(mesh->surfaces[i]); + } + if (mesh->surfaces) { + memfree(mesh->surfaces); + } + + mesh->surfaces = nullptr; + mesh->surface_count = 0; + mesh->material_cache.clear(); + //clear instance data + for (MeshInstance *mi : mesh->instances) { + _mesh_instance_clear(mi); + } + mesh->has_bone_weights = false; + mesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH); + + for (Set<Mesh *>::Element *E = mesh->shadow_owners.front(); E; E = E->next()) { + Mesh *shadow_owner = E->get(); + shadow_owner->shadow_mesh = RID(); + shadow_owner->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH); + } +} + +bool MeshStorage::mesh_needs_instance(RID p_mesh, bool p_has_skeleton) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, false); + + return mesh->blend_shape_count > 0 || (mesh->has_bone_weights && p_has_skeleton); +} + +/* MESH INSTANCE */ + +RID MeshStorage::mesh_instance_create(RID p_base) { + Mesh *mesh = mesh_owner.get_or_null(p_base); + ERR_FAIL_COND_V(!mesh, RID()); + + RID rid = mesh_instance_owner.make_rid(); + MeshInstance *mi = mesh_instance_owner.get_or_null(rid); + + mi->mesh = mesh; + + for (uint32_t i = 0; i < mesh->surface_count; i++) { + _mesh_instance_add_surface(mi, mesh, i); + } + + mi->I = mesh->instances.push_back(mi); + + mi->dirty = true; + + return rid; +} + +void MeshStorage::mesh_instance_free(RID p_rid) { + MeshInstance *mi = mesh_instance_owner.get_or_null(p_rid); + _mesh_instance_clear(mi); + mi->mesh->instances.erase(mi->I); + mi->I = nullptr; + + mesh_instance_owner.free(p_rid); +} + +void MeshStorage::mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) { + MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); + if (mi->skeleton == p_skeleton) { + return; + } + mi->skeleton = p_skeleton; + mi->skeleton_version = 0; + mi->dirty = true; +} + +void MeshStorage::mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) { + MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); + ERR_FAIL_COND(!mi); + ERR_FAIL_INDEX(p_shape, (int)mi->blend_weights.size()); + mi->blend_weights[p_shape] = p_weight; + mi->weights_dirty = true; + //will be eventually updated +} + +void MeshStorage::_mesh_instance_clear(MeshInstance *mi) { + for (uint32_t i = 0; i < mi->surfaces.size(); i++) { + if (mi->surfaces[i].versions) { + for (uint32_t j = 0; j < mi->surfaces[i].version_count; j++) { + RD::get_singleton()->free(mi->surfaces[i].versions[j].vertex_array); + } + memfree(mi->surfaces[i].versions); + } + if (mi->surfaces[i].vertex_buffer.is_valid()) { + RD::get_singleton()->free(mi->surfaces[i].vertex_buffer); + } + } + mi->surfaces.clear(); + + if (mi->blend_weights_buffer.is_valid()) { + RD::get_singleton()->free(mi->blend_weights_buffer); + } + mi->blend_weights.clear(); + mi->weights_dirty = false; + mi->skeleton_version = 0; +} + +void MeshStorage::_mesh_instance_add_surface(MeshInstance *mi, Mesh *mesh, uint32_t p_surface) { + if (mesh->blend_shape_count > 0 && mi->blend_weights_buffer.is_null()) { + mi->blend_weights.resize(mesh->blend_shape_count); + for (uint32_t i = 0; i < mi->blend_weights.size(); i++) { + mi->blend_weights[i] = 0; + } + mi->blend_weights_buffer = RD::get_singleton()->storage_buffer_create(sizeof(float) * mi->blend_weights.size(), mi->blend_weights.to_byte_array()); + mi->weights_dirty = true; + } + + MeshInstance::Surface s; + if (mesh->blend_shape_count > 0 || (mesh->surfaces[p_surface]->format & RS::ARRAY_FORMAT_BONES)) { + //surface warrants transform + s.vertex_buffer = RD::get_singleton()->vertex_buffer_create(mesh->surfaces[p_surface]->vertex_buffer_size, Vector<uint8_t>(), true); + + Vector<RD::Uniform> uniforms; + { + RD::Uniform u; + u.binding = 1; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + u.append_id(s.vertex_buffer); + uniforms.push_back(u); + } + { + RD::Uniform u; + u.binding = 2; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + if (mi->blend_weights_buffer.is_valid()) { + u.append_id(mi->blend_weights_buffer); + } else { + u.append_id(default_rd_storage_buffer); + } + uniforms.push_back(u); + } + s.uniform_set = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_INSTANCE); + } + + mi->surfaces.push_back(s); + mi->dirty = true; +} + +void MeshStorage::mesh_instance_check_for_update(RID p_mesh_instance) { + MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); + + bool needs_update = mi->dirty; + + if (mi->weights_dirty && !mi->weight_update_list.in_list()) { + dirty_mesh_instance_weights.add(&mi->weight_update_list); + needs_update = true; + } + + if (mi->array_update_list.in_list()) { + return; + } + + if (!needs_update && mi->skeleton.is_valid()) { + Skeleton *sk = skeleton_owner.get_or_null(mi->skeleton); + if (sk && sk->version != mi->skeleton_version) { + needs_update = true; + } + } + + if (needs_update) { + dirty_mesh_instance_arrays.add(&mi->array_update_list); + } +} + +void MeshStorage::update_mesh_instances() { + while (dirty_mesh_instance_weights.first()) { + MeshInstance *mi = dirty_mesh_instance_weights.first()->self(); + + if (mi->blend_weights_buffer.is_valid()) { + RD::get_singleton()->buffer_update(mi->blend_weights_buffer, 0, mi->blend_weights.size() * sizeof(float), mi->blend_weights.ptr()); + } + dirty_mesh_instance_weights.remove(&mi->weight_update_list); + mi->weights_dirty = false; + } + if (dirty_mesh_instance_arrays.first() == nullptr) { + return; //nothing to do + } + + //process skeletons and blend shapes + RD::ComputeListID compute_list = RD::get_singleton()->compute_list_begin(); + + while (dirty_mesh_instance_arrays.first()) { + MeshInstance *mi = dirty_mesh_instance_arrays.first()->self(); + + Skeleton *sk = skeleton_owner.get_or_null(mi->skeleton); + + for (uint32_t i = 0; i < mi->surfaces.size(); i++) { + if (mi->surfaces[i].uniform_set == RID() || mi->mesh->surfaces[i]->uniform_set == RID()) { + continue; + } + + bool array_is_2d = mi->mesh->surfaces[i]->format & RS::ARRAY_FLAG_USE_2D_VERTICES; + + RD::get_singleton()->compute_list_bind_compute_pipeline(compute_list, skeleton_shader.pipeline[array_is_2d ? SkeletonShader::SHADER_MODE_2D : SkeletonShader::SHADER_MODE_3D]); + + RD::get_singleton()->compute_list_bind_uniform_set(compute_list, mi->surfaces[i].uniform_set, SkeletonShader::UNIFORM_SET_INSTANCE); + RD::get_singleton()->compute_list_bind_uniform_set(compute_list, mi->mesh->surfaces[i]->uniform_set, SkeletonShader::UNIFORM_SET_SURFACE); + if (sk && sk->uniform_set_mi.is_valid()) { + RD::get_singleton()->compute_list_bind_uniform_set(compute_list, sk->uniform_set_mi, SkeletonShader::UNIFORM_SET_SKELETON); + } else { + RD::get_singleton()->compute_list_bind_uniform_set(compute_list, skeleton_shader.default_skeleton_uniform_set, SkeletonShader::UNIFORM_SET_SKELETON); + } + + SkeletonShader::PushConstant push_constant; + + push_constant.has_normal = mi->mesh->surfaces[i]->format & RS::ARRAY_FORMAT_NORMAL; + push_constant.has_tangent = mi->mesh->surfaces[i]->format & RS::ARRAY_FORMAT_TANGENT; + push_constant.has_skeleton = sk != nullptr && sk->use_2d == array_is_2d && (mi->mesh->surfaces[i]->format & RS::ARRAY_FORMAT_BONES); + push_constant.has_blend_shape = mi->mesh->blend_shape_count > 0; + + push_constant.vertex_count = mi->mesh->surfaces[i]->vertex_count; + push_constant.vertex_stride = (mi->mesh->surfaces[i]->vertex_buffer_size / mi->mesh->surfaces[i]->vertex_count) / 4; + push_constant.skin_stride = (mi->mesh->surfaces[i]->skin_buffer_size / mi->mesh->surfaces[i]->vertex_count) / 4; + push_constant.skin_weight_offset = (mi->mesh->surfaces[i]->format & RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS) ? 4 : 2; + + push_constant.blend_shape_count = mi->mesh->blend_shape_count; + push_constant.normalized_blend_shapes = mi->mesh->blend_shape_mode == RS::BLEND_SHAPE_MODE_NORMALIZED; + push_constant.pad0 = 0; + push_constant.pad1 = 0; + + RD::get_singleton()->compute_list_set_push_constant(compute_list, &push_constant, sizeof(SkeletonShader::PushConstant)); + + //dispatch without barrier, so all is done at the same time + RD::get_singleton()->compute_list_dispatch_threads(compute_list, push_constant.vertex_count, 1, 1); + } + + mi->dirty = false; + if (sk) { + mi->skeleton_version = sk->version; + } + dirty_mesh_instance_arrays.remove(&mi->array_update_list); + } + + RD::get_singleton()->compute_list_end(); +} + +void MeshStorage::_mesh_surface_generate_version_for_input_mask(Mesh::Surface::Version &v, Mesh::Surface *s, uint32_t p_input_mask, MeshInstance::Surface *mis) { + Vector<RD::VertexAttribute> attributes; + Vector<RID> buffers; + + uint32_t stride = 0; + uint32_t attribute_stride = 0; + uint32_t skin_stride = 0; + + for (int i = 0; i < RS::ARRAY_INDEX; i++) { + RD::VertexAttribute vd; + RID buffer; + vd.location = i; + + if (!(s->format & (1 << i))) { + // Not supplied by surface, use default value + buffer = mesh_default_rd_buffers[i]; + vd.stride = 0; + switch (i) { + case RS::ARRAY_VERTEX: { + vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT; + + } break; + case RS::ARRAY_NORMAL: { + vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT; + } break; + case RS::ARRAY_TANGENT: { + vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; + } break; + case RS::ARRAY_COLOR: { + vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; + + } break; + case RS::ARRAY_TEX_UV: { + vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; + + } break; + case RS::ARRAY_TEX_UV2: { + vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; + } break; + case RS::ARRAY_CUSTOM0: + case RS::ARRAY_CUSTOM1: + case RS::ARRAY_CUSTOM2: + case RS::ARRAY_CUSTOM3: { + //assumed weights too + vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; + } break; + case RS::ARRAY_BONES: { + //assumed weights too + vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT; + } break; + case RS::ARRAY_WEIGHTS: { + //assumed weights too + vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT; + } break; + } + } else { + //Supplied, use it + + vd.stride = 1; //mark that it needs a stride set (default uses 0) + + switch (i) { + case RS::ARRAY_VERTEX: { + vd.offset = stride; + + if (s->format & RS::ARRAY_FLAG_USE_2D_VERTICES) { + vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; + stride += sizeof(float) * 2; + } else { + vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT; + stride += sizeof(float) * 3; + } + + if (mis) { + buffer = mis->vertex_buffer; + } else { + buffer = s->vertex_buffer; + } + + } break; + case RS::ARRAY_NORMAL: { + vd.offset = stride; + + vd.format = RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32; + + stride += sizeof(uint32_t); + if (mis) { + buffer = mis->vertex_buffer; + } else { + buffer = s->vertex_buffer; + } + } break; + case RS::ARRAY_TANGENT: { + vd.offset = stride; + + vd.format = RD::DATA_FORMAT_A2B10G10R10_UNORM_PACK32; + stride += sizeof(uint32_t); + if (mis) { + buffer = mis->vertex_buffer; + } else { + buffer = s->vertex_buffer; + } + } break; + case RS::ARRAY_COLOR: { + vd.offset = attribute_stride; + + vd.format = RD::DATA_FORMAT_R8G8B8A8_UNORM; + attribute_stride += sizeof(int8_t) * 4; + buffer = s->attribute_buffer; + } break; + case RS::ARRAY_TEX_UV: { + vd.offset = attribute_stride; + + vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; + attribute_stride += sizeof(float) * 2; + buffer = s->attribute_buffer; + + } break; + case RS::ARRAY_TEX_UV2: { + vd.offset = attribute_stride; + + vd.format = RD::DATA_FORMAT_R32G32_SFLOAT; + attribute_stride += sizeof(float) * 2; + buffer = s->attribute_buffer; + } break; + case RS::ARRAY_CUSTOM0: + case RS::ARRAY_CUSTOM1: + case RS::ARRAY_CUSTOM2: + case RS::ARRAY_CUSTOM3: { + vd.offset = attribute_stride; + + int idx = i - RS::ARRAY_CUSTOM0; + uint32_t fmt_shift[RS::ARRAY_CUSTOM_COUNT] = { RS::ARRAY_FORMAT_CUSTOM0_SHIFT, RS::ARRAY_FORMAT_CUSTOM1_SHIFT, RS::ARRAY_FORMAT_CUSTOM2_SHIFT, RS::ARRAY_FORMAT_CUSTOM3_SHIFT }; + uint32_t fmt = (s->format >> fmt_shift[idx]) & RS::ARRAY_FORMAT_CUSTOM_MASK; + uint32_t fmtsize[RS::ARRAY_CUSTOM_MAX] = { 4, 4, 4, 8, 4, 8, 12, 16 }; + RD::DataFormat fmtrd[RS::ARRAY_CUSTOM_MAX] = { RD::DATA_FORMAT_R8G8B8A8_UNORM, RD::DATA_FORMAT_R8G8B8A8_SNORM, RD::DATA_FORMAT_R16G16_SFLOAT, RD::DATA_FORMAT_R16G16B16A16_SFLOAT, RD::DATA_FORMAT_R32_SFLOAT, RD::DATA_FORMAT_R32G32_SFLOAT, RD::DATA_FORMAT_R32G32B32_SFLOAT, RD::DATA_FORMAT_R32G32B32A32_SFLOAT }; + vd.format = fmtrd[fmt]; + attribute_stride += fmtsize[fmt]; + buffer = s->attribute_buffer; + } break; + case RS::ARRAY_BONES: { + vd.offset = skin_stride; + + vd.format = RD::DATA_FORMAT_R16G16B16A16_UINT; + skin_stride += sizeof(int16_t) * 4; + buffer = s->skin_buffer; + } break; + case RS::ARRAY_WEIGHTS: { + vd.offset = skin_stride; + + vd.format = RD::DATA_FORMAT_R16G16B16A16_UNORM; + skin_stride += sizeof(int16_t) * 4; + buffer = s->skin_buffer; + } break; + } + } + + if (!(p_input_mask & (1 << i))) { + continue; // Shader does not need this, skip it (but computing stride was important anyway) + } + + attributes.push_back(vd); + buffers.push_back(buffer); + } + + //update final stride + for (int i = 0; i < attributes.size(); i++) { + if (attributes[i].stride == 0) { + continue; //default location + } + int loc = attributes[i].location; + + if (loc < RS::ARRAY_COLOR) { + attributes.write[i].stride = stride; + } else if (loc < RS::ARRAY_BONES) { + attributes.write[i].stride = attribute_stride; + } else { + attributes.write[i].stride = skin_stride; + } + } + + v.input_mask = p_input_mask; + v.vertex_format = RD::get_singleton()->vertex_format_create(attributes); + v.vertex_array = RD::get_singleton()->vertex_array_create(s->vertex_count, v.vertex_format, buffers); +} + +////////////////// MULTIMESH + +RID MeshStorage::multimesh_allocate() { + return multimesh_owner.allocate_rid(); +} +void MeshStorage::multimesh_initialize(RID p_rid) { + multimesh_owner.initialize_rid(p_rid, MultiMesh()); +} + +void MeshStorage::multimesh_free(RID p_rid) { + _update_dirty_multimeshes(); + multimesh_allocate_data(p_rid, 0, RS::MULTIMESH_TRANSFORM_2D); + MultiMesh *multimesh = multimesh_owner.get_or_null(p_rid); + multimesh->dependency.deleted_notify(p_rid); + multimesh_owner.free(p_rid); +} + +void MeshStorage::multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors, bool p_use_custom_data) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + + if (multimesh->instances == p_instances && multimesh->xform_format == p_transform_format && multimesh->uses_colors == p_use_colors && multimesh->uses_custom_data == p_use_custom_data) { + return; + } + + if (multimesh->buffer.is_valid()) { + RD::get_singleton()->free(multimesh->buffer); + multimesh->buffer = RID(); + multimesh->uniform_set_2d = RID(); //cleared by dependency + multimesh->uniform_set_3d = RID(); //cleared by dependency + } + + if (multimesh->data_cache_dirty_regions) { + memdelete_arr(multimesh->data_cache_dirty_regions); + multimesh->data_cache_dirty_regions = nullptr; + multimesh->data_cache_used_dirty_regions = 0; + } + + multimesh->instances = p_instances; + multimesh->xform_format = p_transform_format; + multimesh->uses_colors = p_use_colors; + multimesh->color_offset_cache = p_transform_format == RS::MULTIMESH_TRANSFORM_2D ? 8 : 12; + multimesh->uses_custom_data = p_use_custom_data; + multimesh->custom_data_offset_cache = multimesh->color_offset_cache + (p_use_colors ? 4 : 0); + multimesh->stride_cache = multimesh->custom_data_offset_cache + (p_use_custom_data ? 4 : 0); + multimesh->buffer_set = false; + + //print_line("allocate, elements: " + itos(p_instances) + " 2D: " + itos(p_transform_format == RS::MULTIMESH_TRANSFORM_2D) + " colors " + itos(multimesh->uses_colors) + " data " + itos(multimesh->uses_custom_data) + " stride " + itos(multimesh->stride_cache) + " total size " + itos(multimesh->stride_cache * multimesh->instances)); + multimesh->data_cache = Vector<float>(); + multimesh->aabb = AABB(); + multimesh->aabb_dirty = false; + multimesh->visible_instances = MIN(multimesh->visible_instances, multimesh->instances); + + if (multimesh->instances) { + multimesh->buffer = RD::get_singleton()->storage_buffer_create(multimesh->instances * multimesh->stride_cache * 4); + } + + multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MULTIMESH); +} + +int MeshStorage::multimesh_get_instance_count(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, 0); + return multimesh->instances; +} + +void MeshStorage::multimesh_set_mesh(RID p_multimesh, RID p_mesh) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + if (multimesh->mesh == p_mesh) { + return; + } + multimesh->mesh = p_mesh; + + if (multimesh->instances == 0) { + return; + } + + if (multimesh->data_cache.size()) { + //we have a data cache, just mark it dirt + _multimesh_mark_all_dirty(multimesh, false, true); + } else if (multimesh->instances) { + //need to re-create AABB unfortunately, calling this has a penalty + if (multimesh->buffer_set) { + Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer); + const uint8_t *r = buffer.ptr(); + const float *data = (const float *)r; + _multimesh_re_create_aabb(multimesh, data, multimesh->instances); + } + } + + multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MESH); +} + +#define MULTIMESH_DIRTY_REGION_SIZE 512 + +void MeshStorage::_multimesh_make_local(MultiMesh *multimesh) const { + if (multimesh->data_cache.size() > 0) { + return; //already local + } + ERR_FAIL_COND(multimesh->data_cache.size() > 0); + // this means that the user wants to load/save individual elements, + // for this, the data must reside on CPU, so just copy it there. + multimesh->data_cache.resize(multimesh->instances * multimesh->stride_cache); + { + float *w = multimesh->data_cache.ptrw(); + + if (multimesh->buffer_set) { + Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer); + { + const uint8_t *r = buffer.ptr(); + memcpy(w, r, buffer.size()); + } + } else { + memset(w, 0, (size_t)multimesh->instances * multimesh->stride_cache * sizeof(float)); + } + } + uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; + multimesh->data_cache_dirty_regions = memnew_arr(bool, data_cache_dirty_region_count); + for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { + multimesh->data_cache_dirty_regions[i] = false; + } + multimesh->data_cache_used_dirty_regions = 0; +} + +void MeshStorage::_multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb) { + uint32_t region_index = p_index / MULTIMESH_DIRTY_REGION_SIZE; +#ifdef DEBUG_ENABLED + uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; + ERR_FAIL_UNSIGNED_INDEX(region_index, data_cache_dirty_region_count); //bug +#endif + if (!multimesh->data_cache_dirty_regions[region_index]) { + multimesh->data_cache_dirty_regions[region_index] = true; + multimesh->data_cache_used_dirty_regions++; + } + + if (p_aabb) { + multimesh->aabb_dirty = true; + } + + if (!multimesh->dirty) { + multimesh->dirty_list = multimesh_dirty_list; + multimesh_dirty_list = multimesh; + multimesh->dirty = true; + } +} + +void MeshStorage::_multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb) { + if (p_data) { + uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; + + for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { + if (!multimesh->data_cache_dirty_regions[i]) { + multimesh->data_cache_dirty_regions[i] = true; + multimesh->data_cache_used_dirty_regions++; + } + } + } + + if (p_aabb) { + multimesh->aabb_dirty = true; + } + + if (!multimesh->dirty) { + multimesh->dirty_list = multimesh_dirty_list; + multimesh_dirty_list = multimesh; + multimesh->dirty = true; + } +} + +void MeshStorage::_multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances) { + ERR_FAIL_COND(multimesh->mesh.is_null()); + AABB aabb; + AABB mesh_aabb = mesh_get_aabb(multimesh->mesh); + for (int i = 0; i < p_instances; i++) { + const float *data = p_data + multimesh->stride_cache * i; + Transform3D t; + + if (multimesh->xform_format == RS::MULTIMESH_TRANSFORM_3D) { + t.basis.elements[0][0] = data[0]; + t.basis.elements[0][1] = data[1]; + t.basis.elements[0][2] = data[2]; + t.origin.x = data[3]; + t.basis.elements[1][0] = data[4]; + t.basis.elements[1][1] = data[5]; + t.basis.elements[1][2] = data[6]; + t.origin.y = data[7]; + t.basis.elements[2][0] = data[8]; + t.basis.elements[2][1] = data[9]; + t.basis.elements[2][2] = data[10]; + t.origin.z = data[11]; + + } else { + t.basis.elements[0].x = data[0]; + t.basis.elements[1].x = data[1]; + t.origin.x = data[3]; + + t.basis.elements[0].y = data[4]; + t.basis.elements[1].y = data[5]; + t.origin.y = data[7]; + } + + if (i == 0) { + aabb = t.xform(mesh_aabb); + } else { + aabb.merge_with(t.xform(mesh_aabb)); + } + } + + multimesh->aabb = aabb; +} + +void MeshStorage::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + ERR_FAIL_INDEX(p_index, multimesh->instances); + ERR_FAIL_COND(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_3D); + + _multimesh_make_local(multimesh); + + { + float *w = multimesh->data_cache.ptrw(); + + float *dataptr = w + p_index * multimesh->stride_cache; + + dataptr[0] = p_transform.basis.elements[0][0]; + dataptr[1] = p_transform.basis.elements[0][1]; + dataptr[2] = p_transform.basis.elements[0][2]; + dataptr[3] = p_transform.origin.x; + dataptr[4] = p_transform.basis.elements[1][0]; + dataptr[5] = p_transform.basis.elements[1][1]; + dataptr[6] = p_transform.basis.elements[1][2]; + dataptr[7] = p_transform.origin.y; + dataptr[8] = p_transform.basis.elements[2][0]; + dataptr[9] = p_transform.basis.elements[2][1]; + dataptr[10] = p_transform.basis.elements[2][2]; + dataptr[11] = p_transform.origin.z; + } + + _multimesh_mark_dirty(multimesh, p_index, true); +} + +void MeshStorage::multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + ERR_FAIL_INDEX(p_index, multimesh->instances); + ERR_FAIL_COND(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_2D); + + _multimesh_make_local(multimesh); + + { + float *w = multimesh->data_cache.ptrw(); + + float *dataptr = w + p_index * multimesh->stride_cache; + + dataptr[0] = p_transform.elements[0][0]; + dataptr[1] = p_transform.elements[1][0]; + dataptr[2] = 0; + dataptr[3] = p_transform.elements[2][0]; + dataptr[4] = p_transform.elements[0][1]; + dataptr[5] = p_transform.elements[1][1]; + dataptr[6] = 0; + dataptr[7] = p_transform.elements[2][1]; + } + + _multimesh_mark_dirty(multimesh, p_index, true); +} + +void MeshStorage::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + ERR_FAIL_INDEX(p_index, multimesh->instances); + ERR_FAIL_COND(!multimesh->uses_colors); + + _multimesh_make_local(multimesh); + + { + float *w = multimesh->data_cache.ptrw(); + + float *dataptr = w + p_index * multimesh->stride_cache + multimesh->color_offset_cache; + + dataptr[0] = p_color.r; + dataptr[1] = p_color.g; + dataptr[2] = p_color.b; + dataptr[3] = p_color.a; + } + + _multimesh_mark_dirty(multimesh, p_index, false); +} + +void MeshStorage::multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + ERR_FAIL_INDEX(p_index, multimesh->instances); + ERR_FAIL_COND(!multimesh->uses_custom_data); + + _multimesh_make_local(multimesh); + + { + float *w = multimesh->data_cache.ptrw(); + + float *dataptr = w + p_index * multimesh->stride_cache + multimesh->custom_data_offset_cache; + + dataptr[0] = p_color.r; + dataptr[1] = p_color.g; + dataptr[2] = p_color.b; + dataptr[3] = p_color.a; + } + + _multimesh_mark_dirty(multimesh, p_index, false); +} + +RID MeshStorage::multimesh_get_mesh(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, RID()); + + return multimesh->mesh; +} + +Transform3D MeshStorage::multimesh_instance_get_transform(RID p_multimesh, int p_index) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, Transform3D()); + ERR_FAIL_INDEX_V(p_index, multimesh->instances, Transform3D()); + ERR_FAIL_COND_V(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_3D, Transform3D()); + + _multimesh_make_local(multimesh); + + Transform3D t; + { + const float *r = multimesh->data_cache.ptr(); + + const float *dataptr = r + p_index * multimesh->stride_cache; + + t.basis.elements[0][0] = dataptr[0]; + t.basis.elements[0][1] = dataptr[1]; + t.basis.elements[0][2] = dataptr[2]; + t.origin.x = dataptr[3]; + t.basis.elements[1][0] = dataptr[4]; + t.basis.elements[1][1] = dataptr[5]; + t.basis.elements[1][2] = dataptr[6]; + t.origin.y = dataptr[7]; + t.basis.elements[2][0] = dataptr[8]; + t.basis.elements[2][1] = dataptr[9]; + t.basis.elements[2][2] = dataptr[10]; + t.origin.z = dataptr[11]; + } + + return t; +} + +Transform2D MeshStorage::multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, Transform2D()); + ERR_FAIL_INDEX_V(p_index, multimesh->instances, Transform2D()); + ERR_FAIL_COND_V(multimesh->xform_format != RS::MULTIMESH_TRANSFORM_2D, Transform2D()); + + _multimesh_make_local(multimesh); + + Transform2D t; + { + const float *r = multimesh->data_cache.ptr(); + + const float *dataptr = r + p_index * multimesh->stride_cache; + + t.elements[0][0] = dataptr[0]; + t.elements[1][0] = dataptr[1]; + t.elements[2][0] = dataptr[3]; + t.elements[0][1] = dataptr[4]; + t.elements[1][1] = dataptr[5]; + t.elements[2][1] = dataptr[7]; + } + + return t; +} + +Color MeshStorage::multimesh_instance_get_color(RID p_multimesh, int p_index) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, Color()); + ERR_FAIL_INDEX_V(p_index, multimesh->instances, Color()); + ERR_FAIL_COND_V(!multimesh->uses_colors, Color()); + + _multimesh_make_local(multimesh); + + Color c; + { + const float *r = multimesh->data_cache.ptr(); + + const float *dataptr = r + p_index * multimesh->stride_cache + multimesh->color_offset_cache; + + c.r = dataptr[0]; + c.g = dataptr[1]; + c.b = dataptr[2]; + c.a = dataptr[3]; + } + + return c; +} + +Color MeshStorage::multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, Color()); + ERR_FAIL_INDEX_V(p_index, multimesh->instances, Color()); + ERR_FAIL_COND_V(!multimesh->uses_custom_data, Color()); + + _multimesh_make_local(multimesh); + + Color c; + { + const float *r = multimesh->data_cache.ptr(); + + const float *dataptr = r + p_index * multimesh->stride_cache + multimesh->custom_data_offset_cache; + + c.r = dataptr[0]; + c.g = dataptr[1]; + c.b = dataptr[2]; + c.a = dataptr[3]; + } + + return c; +} + +void MeshStorage::multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + ERR_FAIL_COND(p_buffer.size() != (multimesh->instances * (int)multimesh->stride_cache)); + + { + const float *r = p_buffer.ptr(); + RD::get_singleton()->buffer_update(multimesh->buffer, 0, p_buffer.size() * sizeof(float), r); + multimesh->buffer_set = true; + } + + if (multimesh->data_cache.size()) { + //if we have a data cache, just update it + multimesh->data_cache = p_buffer; + { + //clear dirty since nothing will be dirty anymore + uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; + for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { + multimesh->data_cache_dirty_regions[i] = false; + } + multimesh->data_cache_used_dirty_regions = 0; + } + + _multimesh_mark_all_dirty(multimesh, false, true); //update AABB + } else if (multimesh->mesh.is_valid()) { + //if we have a mesh set, we need to re-generate the AABB from the new data + const float *data = p_buffer.ptr(); + + _multimesh_re_create_aabb(multimesh, data, multimesh->instances); + multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_AABB); + } +} + +Vector<float> MeshStorage::multimesh_get_buffer(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, Vector<float>()); + if (multimesh->buffer.is_null()) { + return Vector<float>(); + } else if (multimesh->data_cache.size()) { + return multimesh->data_cache; + } else { + //get from memory + + Vector<uint8_t> buffer = RD::get_singleton()->buffer_get_data(multimesh->buffer); + Vector<float> ret; + ret.resize(multimesh->instances * multimesh->stride_cache); + { + float *w = ret.ptrw(); + const uint8_t *r = buffer.ptr(); + memcpy(w, r, buffer.size()); + } + + return ret; + } +} + +void MeshStorage::multimesh_set_visible_instances(RID p_multimesh, int p_visible) { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND(!multimesh); + ERR_FAIL_COND(p_visible < -1 || p_visible > multimesh->instances); + if (multimesh->visible_instances == p_visible) { + return; + } + + if (multimesh->data_cache.size()) { + //there is a data cache.. + _multimesh_mark_all_dirty(multimesh, false, true); + } + + multimesh->visible_instances = p_visible; + + multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_MULTIMESH_VISIBLE_INSTANCES); +} + +int MeshStorage::multimesh_get_visible_instances(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, 0); + return multimesh->visible_instances; +} + +AABB MeshStorage::multimesh_get_aabb(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + ERR_FAIL_COND_V(!multimesh, AABB()); + if (multimesh->aabb_dirty) { + const_cast<MeshStorage *>(this)->_update_dirty_multimeshes(); + } + return multimesh->aabb; +} + +void MeshStorage::_update_dirty_multimeshes() { + while (multimesh_dirty_list) { + MultiMesh *multimesh = multimesh_dirty_list; + + if (multimesh->data_cache.size()) { //may have been cleared, so only process if it exists + const float *data = multimesh->data_cache.ptr(); + + uint32_t visible_instances = multimesh->visible_instances >= 0 ? multimesh->visible_instances : multimesh->instances; + + if (multimesh->data_cache_used_dirty_regions) { + uint32_t data_cache_dirty_region_count = (multimesh->instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; + uint32_t visible_region_count = visible_instances == 0 ? 0 : (visible_instances - 1) / MULTIMESH_DIRTY_REGION_SIZE + 1; + + uint32_t region_size = multimesh->stride_cache * MULTIMESH_DIRTY_REGION_SIZE * sizeof(float); + + if (multimesh->data_cache_used_dirty_regions > 32 || multimesh->data_cache_used_dirty_regions > visible_region_count / 2) { + //if there too many dirty regions, or represent the majority of regions, just copy all, else transfer cost piles up too much + RD::get_singleton()->buffer_update(multimesh->buffer, 0, MIN(visible_region_count * region_size, multimesh->instances * (uint32_t)multimesh->stride_cache * (uint32_t)sizeof(float)), data); + } else { + //not that many regions? update them all + for (uint32_t i = 0; i < visible_region_count; i++) { + if (multimesh->data_cache_dirty_regions[i]) { + uint32_t offset = i * region_size; + uint32_t size = multimesh->stride_cache * (uint32_t)multimesh->instances * (uint32_t)sizeof(float); + uint32_t region_start_index = multimesh->stride_cache * MULTIMESH_DIRTY_REGION_SIZE * i; + RD::get_singleton()->buffer_update(multimesh->buffer, offset, MIN(region_size, size - offset), &data[region_start_index]); + } + } + } + + for (uint32_t i = 0; i < data_cache_dirty_region_count; i++) { + multimesh->data_cache_dirty_regions[i] = false; + } + + multimesh->data_cache_used_dirty_regions = 0; + } + + if (multimesh->aabb_dirty) { + //aabb is dirty.. + _multimesh_re_create_aabb(multimesh, data, visible_instances); + multimesh->aabb_dirty = false; + multimesh->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_AABB); + } + } + + multimesh_dirty_list = multimesh->dirty_list; + + multimesh->dirty_list = nullptr; + multimesh->dirty = false; + } + + multimesh_dirty_list = nullptr; +} + +/* SKELETON API */ + +RID MeshStorage::skeleton_allocate() { + return skeleton_owner.allocate_rid(); +} +void MeshStorage::skeleton_initialize(RID p_rid) { + skeleton_owner.initialize_rid(p_rid, Skeleton()); +} + +void MeshStorage::skeleton_free(RID p_rid) { + _update_dirty_skeletons(); + skeleton_allocate_data(p_rid, 0); + Skeleton *skeleton = skeleton_owner.get_or_null(p_rid); + skeleton->dependency.deleted_notify(p_rid); + skeleton_owner.free(p_rid); +} + +void MeshStorage::_skeleton_make_dirty(Skeleton *skeleton) { + if (!skeleton->dirty) { + skeleton->dirty = true; + skeleton->dirty_list = skeleton_dirty_list; + skeleton_dirty_list = skeleton; + } +} + +void MeshStorage::skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton) { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + ERR_FAIL_COND(!skeleton); + ERR_FAIL_COND(p_bones < 0); + + if (skeleton->size == p_bones && skeleton->use_2d == p_2d_skeleton) { + return; + } + + skeleton->size = p_bones; + skeleton->use_2d = p_2d_skeleton; + skeleton->uniform_set_3d = RID(); + + if (skeleton->buffer.is_valid()) { + RD::get_singleton()->free(skeleton->buffer); + skeleton->buffer = RID(); + skeleton->data.clear(); + skeleton->uniform_set_mi = RID(); + } + + if (skeleton->size) { + skeleton->data.resize(skeleton->size * (skeleton->use_2d ? 8 : 12)); + skeleton->buffer = RD::get_singleton()->storage_buffer_create(skeleton->data.size() * sizeof(float)); + memset(skeleton->data.ptrw(), 0, skeleton->data.size() * sizeof(float)); + + _skeleton_make_dirty(skeleton); + + { + Vector<RD::Uniform> uniforms; + { + RD::Uniform u; + u.binding = 0; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + u.append_id(skeleton->buffer); + uniforms.push_back(u); + } + skeleton->uniform_set_mi = RD::get_singleton()->uniform_set_create(uniforms, skeleton_shader.version_shader[0], SkeletonShader::UNIFORM_SET_SKELETON); + } + } + + skeleton->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_SKELETON_DATA); +} + +int MeshStorage::skeleton_get_bone_count(RID p_skeleton) const { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + ERR_FAIL_COND_V(!skeleton, 0); + + return skeleton->size; +} + +void MeshStorage::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + + ERR_FAIL_COND(!skeleton); + ERR_FAIL_INDEX(p_bone, skeleton->size); + ERR_FAIL_COND(skeleton->use_2d); + + float *dataptr = skeleton->data.ptrw() + p_bone * 12; + + dataptr[0] = p_transform.basis.elements[0][0]; + dataptr[1] = p_transform.basis.elements[0][1]; + dataptr[2] = p_transform.basis.elements[0][2]; + dataptr[3] = p_transform.origin.x; + dataptr[4] = p_transform.basis.elements[1][0]; + dataptr[5] = p_transform.basis.elements[1][1]; + dataptr[6] = p_transform.basis.elements[1][2]; + dataptr[7] = p_transform.origin.y; + dataptr[8] = p_transform.basis.elements[2][0]; + dataptr[9] = p_transform.basis.elements[2][1]; + dataptr[10] = p_transform.basis.elements[2][2]; + dataptr[11] = p_transform.origin.z; + + _skeleton_make_dirty(skeleton); +} + +Transform3D MeshStorage::skeleton_bone_get_transform(RID p_skeleton, int p_bone) const { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + + ERR_FAIL_COND_V(!skeleton, Transform3D()); + ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform3D()); + ERR_FAIL_COND_V(skeleton->use_2d, Transform3D()); + + const float *dataptr = skeleton->data.ptr() + p_bone * 12; + + Transform3D t; + + t.basis.elements[0][0] = dataptr[0]; + t.basis.elements[0][1] = dataptr[1]; + t.basis.elements[0][2] = dataptr[2]; + t.origin.x = dataptr[3]; + t.basis.elements[1][0] = dataptr[4]; + t.basis.elements[1][1] = dataptr[5]; + t.basis.elements[1][2] = dataptr[6]; + t.origin.y = dataptr[7]; + t.basis.elements[2][0] = dataptr[8]; + t.basis.elements[2][1] = dataptr[9]; + t.basis.elements[2][2] = dataptr[10]; + t.origin.z = dataptr[11]; + + return t; +} + +void MeshStorage::skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + + ERR_FAIL_COND(!skeleton); + ERR_FAIL_INDEX(p_bone, skeleton->size); + ERR_FAIL_COND(!skeleton->use_2d); + + float *dataptr = skeleton->data.ptrw() + p_bone * 8; + + dataptr[0] = p_transform.elements[0][0]; + dataptr[1] = p_transform.elements[1][0]; + dataptr[2] = 0; + dataptr[3] = p_transform.elements[2][0]; + dataptr[4] = p_transform.elements[0][1]; + dataptr[5] = p_transform.elements[1][1]; + dataptr[6] = 0; + dataptr[7] = p_transform.elements[2][1]; + + _skeleton_make_dirty(skeleton); +} + +Transform2D MeshStorage::skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + + ERR_FAIL_COND_V(!skeleton, Transform2D()); + ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform2D()); + ERR_FAIL_COND_V(!skeleton->use_2d, Transform2D()); + + const float *dataptr = skeleton->data.ptr() + p_bone * 8; + + Transform2D t; + t.elements[0][0] = dataptr[0]; + t.elements[1][0] = dataptr[1]; + t.elements[2][0] = dataptr[3]; + t.elements[0][1] = dataptr[4]; + t.elements[1][1] = dataptr[5]; + t.elements[2][1] = dataptr[7]; + + return t; +} + +void MeshStorage::skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + + ERR_FAIL_COND(!skeleton->use_2d); + + skeleton->base_transform_2d = p_base_transform; +} + +void MeshStorage::_update_dirty_skeletons() { + while (skeleton_dirty_list) { + Skeleton *skeleton = skeleton_dirty_list; + + if (skeleton->size) { + RD::get_singleton()->buffer_update(skeleton->buffer, 0, skeleton->data.size() * sizeof(float), skeleton->data.ptr()); + } + + skeleton_dirty_list = skeleton->dirty_list; + + skeleton->dependency.changed_notify(RendererStorage::DEPENDENCY_CHANGED_SKELETON_BONES); + + skeleton->version++; + + skeleton->dirty = false; + skeleton->dirty_list = nullptr; + } + + skeleton_dirty_list = nullptr; +} + +void MeshStorage::skeleton_update_dependency(RID p_skeleton, RendererStorage::DependencyTracker *p_instance) { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + ERR_FAIL_COND(!skeleton); + + p_instance->update_dependency(&skeleton->dependency); +} diff --git a/servers/rendering/renderer_rd/storage_rd/mesh_storage.h b/servers/rendering/renderer_rd/storage_rd/mesh_storage.h new file mode 100644 index 0000000000..e8da8ad563 --- /dev/null +++ b/servers/rendering/renderer_rd/storage_rd/mesh_storage.h @@ -0,0 +1,694 @@ +/*************************************************************************/ +/* mesh_storage.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef MESH_STORAGE_RD_H +#define MESH_STORAGE_RD_H + +#include "core/templates/local_vector.h" +#include "core/templates/rid_owner.h" +#include "core/templates/self_list.h" +#include "servers/rendering/renderer_rd/shaders/skeleton.glsl.gen.h" +#include "servers/rendering/renderer_storage.h" +#include "servers/rendering/storage/mesh_storage.h" + +namespace RendererRD { + +/* Mesh */ + +enum DefaultRDBuffer { + DEFAULT_RD_BUFFER_VERTEX, + DEFAULT_RD_BUFFER_NORMAL, + DEFAULT_RD_BUFFER_TANGENT, + DEFAULT_RD_BUFFER_COLOR, + DEFAULT_RD_BUFFER_TEX_UV, + DEFAULT_RD_BUFFER_TEX_UV2, + DEFAULT_RD_BUFFER_CUSTOM0, + DEFAULT_RD_BUFFER_CUSTOM1, + DEFAULT_RD_BUFFER_CUSTOM2, + DEFAULT_RD_BUFFER_CUSTOM3, + DEFAULT_RD_BUFFER_BONES, + DEFAULT_RD_BUFFER_WEIGHTS, + DEFAULT_RD_BUFFER_MAX, +}; + +struct MeshInstance; + +struct Mesh { + struct Surface { + RS::PrimitiveType primitive = RS::PRIMITIVE_POINTS; + uint32_t format = 0; + + RID vertex_buffer; + RID attribute_buffer; + RID skin_buffer; + uint32_t vertex_count = 0; + uint32_t vertex_buffer_size = 0; + uint32_t skin_buffer_size = 0; + + // A different pipeline needs to be allocated + // depending on the inputs available in the + // material. + // There are never that many geometry/material + // combinations, so a simple array is the most + // cache-efficient structure. + + struct Version { + uint32_t input_mask = 0; + RD::VertexFormatID vertex_format = 0; + RID vertex_array; + }; + + SpinLock version_lock; //needed to access versions + Version *versions = nullptr; //allocated on demand + uint32_t version_count = 0; + + RID index_buffer; + RID index_array; + uint32_t index_count = 0; + + struct LOD { + float edge_length = 0.0; + uint32_t index_count = 0; + RID index_buffer; + RID index_array; + }; + + LOD *lods = nullptr; + uint32_t lod_count = 0; + + AABB aabb; + + Vector<AABB> bone_aabbs; + + RID blend_shape_buffer; + + RID material; + + uint32_t render_index = 0; + uint64_t render_pass = 0; + + uint32_t multimesh_render_index = 0; + uint64_t multimesh_render_pass = 0; + + uint32_t particles_render_index = 0; + uint64_t particles_render_pass = 0; + + RID uniform_set; + }; + + uint32_t blend_shape_count = 0; + RS::BlendShapeMode blend_shape_mode = RS::BLEND_SHAPE_MODE_NORMALIZED; + + Surface **surfaces = nullptr; + uint32_t surface_count = 0; + + Vector<AABB> bone_aabbs; + + bool has_bone_weights = false; + + AABB aabb; + AABB custom_aabb; + + Vector<RID> material_cache; + + List<MeshInstance *> instances; + + RID shadow_mesh; + Set<Mesh *> shadow_owners; + + RendererStorage::Dependency dependency; +}; + +/* Mesh Instance */ + +struct MeshInstance { + Mesh *mesh = nullptr; + RID skeleton; + struct Surface { + RID vertex_buffer; + RID uniform_set; + + Mesh::Surface::Version *versions = nullptr; //allocated on demand + uint32_t version_count = 0; + }; + LocalVector<Surface> surfaces; + LocalVector<float> blend_weights; + + RID blend_weights_buffer; + List<MeshInstance *>::Element *I = nullptr; //used to erase itself + uint64_t skeleton_version = 0; + bool dirty = false; + bool weights_dirty = false; + SelfList<MeshInstance> weight_update_list; + SelfList<MeshInstance> array_update_list; + MeshInstance() : + weight_update_list(this), array_update_list(this) {} +}; + +/* MultiMesh */ + +struct MultiMesh { + RID mesh; + int instances = 0; + RS::MultimeshTransformFormat xform_format = RS::MULTIMESH_TRANSFORM_3D; + bool uses_colors = false; + bool uses_custom_data = false; + int visible_instances = -1; + AABB aabb; + bool aabb_dirty = false; + bool buffer_set = false; + uint32_t stride_cache = 0; + uint32_t color_offset_cache = 0; + uint32_t custom_data_offset_cache = 0; + + Vector<float> data_cache; //used if individual setting is used + bool *data_cache_dirty_regions = nullptr; + uint32_t data_cache_used_dirty_regions = 0; + + RID buffer; //storage buffer + RID uniform_set_3d; + RID uniform_set_2d; + + bool dirty = false; + MultiMesh *dirty_list = nullptr; + + RendererStorage::Dependency dependency; +}; + +/* Skeleton */ + +struct SkeletonShader { + struct PushConstant { + uint32_t has_normal; + uint32_t has_tangent; + uint32_t has_skeleton; + uint32_t has_blend_shape; + + uint32_t vertex_count; + uint32_t vertex_stride; + uint32_t skin_stride; + uint32_t skin_weight_offset; + + uint32_t blend_shape_count; + uint32_t normalized_blend_shapes; + uint32_t pad0; + uint32_t pad1; + }; + + enum { + UNIFORM_SET_INSTANCE = 0, + UNIFORM_SET_SURFACE = 1, + UNIFORM_SET_SKELETON = 2, + }; + enum { + SHADER_MODE_2D, + SHADER_MODE_3D, + SHADER_MODE_MAX + }; + + SkeletonShaderRD shader; + RID version; + RID version_shader[SHADER_MODE_MAX]; + RID pipeline[SHADER_MODE_MAX]; + + RID default_skeleton_uniform_set; +}; + +struct Skeleton { + bool use_2d = false; + int size = 0; + Vector<float> data; + RID buffer; + + bool dirty = false; + Skeleton *dirty_list = nullptr; + Transform2D base_transform_2d; + + RID uniform_set_3d; + RID uniform_set_mi; + + uint64_t version = 1; + + RendererStorage::Dependency dependency; +}; + +class MeshStorage : public RendererMeshStorage { +private: + static MeshStorage *singleton; + + RID mesh_default_rd_buffers[DEFAULT_RD_BUFFER_MAX]; + RID default_rd_storage_buffer; + + /* Mesh */ + + mutable RID_Owner<Mesh, true> mesh_owner; + + void _mesh_surface_generate_version_for_input_mask(Mesh::Surface::Version &v, Mesh::Surface *s, uint32_t p_input_mask, MeshInstance::Surface *mis = nullptr); + + /* Mesh Instance API */ + + void _mesh_instance_clear(MeshInstance *mi); + void _mesh_instance_add_surface(MeshInstance *mi, Mesh *mesh, uint32_t p_surface); + + mutable RID_Owner<MeshInstance> mesh_instance_owner; + + SelfList<MeshInstance>::List dirty_mesh_instance_weights; + SelfList<MeshInstance>::List dirty_mesh_instance_arrays; + + /* MultiMesh */ + + mutable RID_Owner<MultiMesh, true> multimesh_owner; + + MultiMesh *multimesh_dirty_list = nullptr; + + _FORCE_INLINE_ void _multimesh_make_local(MultiMesh *multimesh) const; + _FORCE_INLINE_ void _multimesh_mark_dirty(MultiMesh *multimesh, int p_index, bool p_aabb); + _FORCE_INLINE_ void _multimesh_mark_all_dirty(MultiMesh *multimesh, bool p_data, bool p_aabb); + _FORCE_INLINE_ void _multimesh_re_create_aabb(MultiMesh *multimesh, const float *p_data, int p_instances); + + /* Skeleton */ + + SkeletonShader skeleton_shader; + + mutable RID_Owner<Skeleton, true> skeleton_owner; + + _FORCE_INLINE_ void _skeleton_make_dirty(Skeleton *skeleton); + + Skeleton *skeleton_dirty_list = nullptr; + +public: + static MeshStorage *get_singleton(); + + MeshStorage(); + virtual ~MeshStorage(); + + RID get_default_rd_storage_buffer() { return default_rd_storage_buffer; } + + /* MESH API */ + + Mesh *get_mesh(RID p_rid) { return mesh_owner.get_or_null(p_rid); }; + bool owns_mesh(RID p_rid) { return mesh_owner.owns(p_rid); }; + + virtual RID mesh_allocate() override; + virtual void mesh_initialize(RID p_mesh) override; + virtual void mesh_free(RID p_rid) override; + + virtual void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) override; + + /// Return stride + virtual void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) override; + + virtual int mesh_get_blend_shape_count(RID p_mesh) const override; + + virtual void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) override; + virtual RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const override; + + virtual void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; + virtual void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; + virtual void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) override; + + virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) override; + virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const override; + + virtual RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const override; + + virtual int mesh_get_surface_count(RID p_mesh) const override; + + virtual void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) override; + virtual AABB mesh_get_custom_aabb(RID p_mesh) const override; + + virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) override; + virtual void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) override; + + virtual void mesh_clear(RID p_mesh) override; + + virtual bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) override; + + _FORCE_INLINE_ const RID *mesh_get_surface_count_and_materials(RID p_mesh, uint32_t &r_surface_count) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, nullptr); + r_surface_count = mesh->surface_count; + if (r_surface_count == 0) { + return nullptr; + } + if (mesh->material_cache.is_empty()) { + mesh->material_cache.resize(mesh->surface_count); + for (uint32_t i = 0; i < r_surface_count; i++) { + mesh->material_cache.write[i] = mesh->surfaces[i]->material; + } + } + + return mesh->material_cache.ptr(); + } + + _FORCE_INLINE_ void *mesh_get_surface(RID p_mesh, uint32_t p_surface_index) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, nullptr); + ERR_FAIL_UNSIGNED_INDEX_V(p_surface_index, mesh->surface_count, nullptr); + + return mesh->surfaces[p_surface_index]; + } + + _FORCE_INLINE_ RID mesh_get_shadow_mesh(RID p_mesh) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + ERR_FAIL_COND_V(!mesh, RID()); + + return mesh->shadow_mesh; + } + + _FORCE_INLINE_ RS::PrimitiveType mesh_surface_get_primitive(void *p_surface) { + Mesh::Surface *surface = reinterpret_cast<Mesh::Surface *>(p_surface); + return surface->primitive; + } + + _FORCE_INLINE_ bool mesh_surface_has_lod(void *p_surface) const { + Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); + return s->lod_count > 0; + } + + _FORCE_INLINE_ uint32_t mesh_surface_get_vertices_drawn_count(void *p_surface) const { + Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); + return s->index_count ? s->index_count : s->vertex_count; + } + + _FORCE_INLINE_ uint32_t mesh_surface_get_lod(void *p_surface, float p_model_scale, float p_distance_threshold, float p_mesh_lod_threshold, uint32_t *r_index_count = nullptr) const { + Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); + + int32_t current_lod = -1; + if (r_index_count) { + *r_index_count = s->index_count; + } + for (uint32_t i = 0; i < s->lod_count; i++) { + float screen_size = s->lods[i].edge_length * p_model_scale / p_distance_threshold; + if (screen_size > p_mesh_lod_threshold) { + break; + } + current_lod = i; + } + if (current_lod == -1) { + return 0; + } else { + if (r_index_count) { + *r_index_count = s->lods[current_lod].index_count; + } + return current_lod + 1; + } + } + + _FORCE_INLINE_ RID mesh_surface_get_index_array(void *p_surface, uint32_t p_lod) const { + Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); + + if (p_lod == 0) { + return s->index_array; + } else { + return s->lods[p_lod - 1].index_array; + } + } + + _FORCE_INLINE_ void mesh_surface_get_vertex_arrays_and_format(void *p_surface, uint32_t p_input_mask, RID &r_vertex_array_rd, RD::VertexFormatID &r_vertex_format) { + Mesh::Surface *s = reinterpret_cast<Mesh::Surface *>(p_surface); + + s->version_lock.lock(); + + //there will never be more than, at much, 3 or 4 versions, so iterating is the fastest way + + for (uint32_t i = 0; i < s->version_count; i++) { + if (s->versions[i].input_mask != p_input_mask) { + continue; + } + //we have this version, hooray + r_vertex_format = s->versions[i].vertex_format; + r_vertex_array_rd = s->versions[i].vertex_array; + s->version_lock.unlock(); + return; + } + + uint32_t version = s->version_count; + s->version_count++; + s->versions = (Mesh::Surface::Version *)memrealloc(s->versions, sizeof(Mesh::Surface::Version) * s->version_count); + + _mesh_surface_generate_version_for_input_mask(s->versions[version], s, p_input_mask); + + r_vertex_format = s->versions[version].vertex_format; + r_vertex_array_rd = s->versions[version].vertex_array; + + s->version_lock.unlock(); + } + + _FORCE_INLINE_ void mesh_instance_surface_get_vertex_arrays_and_format(RID p_mesh_instance, uint32_t p_surface_index, uint32_t p_input_mask, RID &r_vertex_array_rd, RD::VertexFormatID &r_vertex_format) { + MeshInstance *mi = mesh_instance_owner.get_or_null(p_mesh_instance); + ERR_FAIL_COND(!mi); + Mesh *mesh = mi->mesh; + ERR_FAIL_UNSIGNED_INDEX(p_surface_index, mesh->surface_count); + + MeshInstance::Surface *mis = &mi->surfaces[p_surface_index]; + Mesh::Surface *s = mesh->surfaces[p_surface_index]; + + s->version_lock.lock(); + + //there will never be more than, at much, 3 or 4 versions, so iterating is the fastest way + + for (uint32_t i = 0; i < mis->version_count; i++) { + if (mis->versions[i].input_mask != p_input_mask) { + continue; + } + //we have this version, hooray + r_vertex_format = mis->versions[i].vertex_format; + r_vertex_array_rd = mis->versions[i].vertex_array; + s->version_lock.unlock(); + return; + } + + uint32_t version = mis->version_count; + mis->version_count++; + mis->versions = (Mesh::Surface::Version *)memrealloc(mis->versions, sizeof(Mesh::Surface::Version) * mis->version_count); + + _mesh_surface_generate_version_for_input_mask(mis->versions[version], s, p_input_mask, mis); + + r_vertex_format = mis->versions[version].vertex_format; + r_vertex_array_rd = mis->versions[version].vertex_array; + + s->version_lock.unlock(); + } + + _FORCE_INLINE_ RID mesh_get_default_rd_buffer(DefaultRDBuffer p_buffer) { + ERR_FAIL_INDEX_V(p_buffer, DEFAULT_RD_BUFFER_MAX, RID()); + return mesh_default_rd_buffers[p_buffer]; + } + + _FORCE_INLINE_ uint32_t mesh_surface_get_render_pass_index(RID p_mesh, uint32_t p_surface_index, uint64_t p_render_pass, uint32_t *r_index) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + Mesh::Surface *s = mesh->surfaces[p_surface_index]; + + if (s->render_pass != p_render_pass) { + (*r_index)++; + s->render_pass = p_render_pass; + s->render_index = *r_index; + } + + return s->render_index; + } + + _FORCE_INLINE_ uint32_t mesh_surface_get_multimesh_render_pass_index(RID p_mesh, uint32_t p_surface_index, uint64_t p_render_pass, uint32_t *r_index) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + Mesh::Surface *s = mesh->surfaces[p_surface_index]; + + if (s->multimesh_render_pass != p_render_pass) { + (*r_index)++; + s->multimesh_render_pass = p_render_pass; + s->multimesh_render_index = *r_index; + } + + return s->multimesh_render_index; + } + + _FORCE_INLINE_ uint32_t mesh_surface_get_particles_render_pass_index(RID p_mesh, uint32_t p_surface_index, uint64_t p_render_pass, uint32_t *r_index) { + Mesh *mesh = mesh_owner.get_or_null(p_mesh); + Mesh::Surface *s = mesh->surfaces[p_surface_index]; + + if (s->particles_render_pass != p_render_pass) { + (*r_index)++; + s->particles_render_pass = p_render_pass; + s->particles_render_index = *r_index; + } + + return s->particles_render_index; + } + + /* MESH INSTANCE API */ + + MeshInstance *get_mesh_instance(RID p_rid) { return mesh_instance_owner.get_or_null(p_rid); }; + bool owns_mesh_instance(RID p_rid) { return mesh_instance_owner.owns(p_rid); }; + + virtual RID mesh_instance_create(RID p_base) override; + virtual void mesh_instance_free(RID p_rid) override; + virtual void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) override; + virtual void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) override; + virtual void mesh_instance_check_for_update(RID p_mesh_instance) override; + virtual void update_mesh_instances() override; + + /* MULTIMESH API */ + + MultiMesh *get_multimesh(RID p_rid) { return multimesh_owner.get_or_null(p_rid); }; + bool owns_multimesh(RID p_rid) { return multimesh_owner.owns(p_rid); }; + + virtual RID multimesh_allocate() override; + virtual void multimesh_initialize(RID p_multimesh) override; + virtual void multimesh_free(RID p_rid) override; + + virtual void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) override; + virtual int multimesh_get_instance_count(RID p_multimesh) const override; + + virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) override; + virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) override; + virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) override; + virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) override; + virtual void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) override; + + virtual RID multimesh_get_mesh(RID p_multimesh) const override; + + virtual Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const override; + virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const override; + virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const override; + virtual Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const override; + + virtual void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) override; + virtual Vector<float> multimesh_get_buffer(RID p_multimesh) const override; + + virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) override; + virtual int multimesh_get_visible_instances(RID p_multimesh) const override; + + virtual AABB multimesh_get_aabb(RID p_multimesh) const override; + + void _update_dirty_multimeshes(); + + _FORCE_INLINE_ RS::MultimeshTransformFormat multimesh_get_transform_format(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + return multimesh->xform_format; + } + + _FORCE_INLINE_ bool multimesh_uses_colors(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + return multimesh->uses_colors; + } + + _FORCE_INLINE_ bool multimesh_uses_custom_data(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + return multimesh->uses_custom_data; + } + + _FORCE_INLINE_ uint32_t multimesh_get_instances_to_draw(RID p_multimesh) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + if (multimesh->visible_instances >= 0) { + return multimesh->visible_instances; + } + return multimesh->instances; + } + + _FORCE_INLINE_ RID multimesh_get_3d_uniform_set(RID p_multimesh, RID p_shader, uint32_t p_set) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + if (!multimesh->uniform_set_3d.is_valid()) { + Vector<RD::Uniform> uniforms; + RD::Uniform u; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + u.binding = 0; + u.append_id(multimesh->buffer); + uniforms.push_back(u); + multimesh->uniform_set_3d = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set); + } + + return multimesh->uniform_set_3d; + } + + _FORCE_INLINE_ RID multimesh_get_2d_uniform_set(RID p_multimesh, RID p_shader, uint32_t p_set) const { + MultiMesh *multimesh = multimesh_owner.get_or_null(p_multimesh); + if (!multimesh->uniform_set_2d.is_valid()) { + Vector<RD::Uniform> uniforms; + RD::Uniform u; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + u.binding = 0; + u.append_id(multimesh->buffer); + uniforms.push_back(u); + multimesh->uniform_set_2d = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set); + } + + return multimesh->uniform_set_2d; + } + + /* SKELETON API */ + + Skeleton *get_skeleton(RID p_rid) { return skeleton_owner.get_or_null(p_rid); }; + bool owns_skeleton(RID p_rid) { return skeleton_owner.owns(p_rid); }; + + virtual RID skeleton_allocate() override; + virtual void skeleton_initialize(RID p_skeleton) override; + virtual void skeleton_free(RID p_rid) override; + + virtual void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) override; + virtual void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) override; + void skeleton_set_world_transform(RID p_skeleton, bool p_enable, const Transform3D &p_world_transform); + virtual int skeleton_get_bone_count(RID p_skeleton) const override; + virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) override; + virtual Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const override; + virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) override; + virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const override; + + virtual void skeleton_update_dependency(RID p_skeleton, RendererStorage::DependencyTracker *p_instance) override; + + void _update_dirty_skeletons(); + + _FORCE_INLINE_ bool skeleton_is_valid(RID p_skeleton) { + return skeleton_owner.get_or_null(p_skeleton) != nullptr; + } + + _FORCE_INLINE_ RID skeleton_get_3d_uniform_set(RID p_skeleton, RID p_shader, uint32_t p_set) const { + Skeleton *skeleton = skeleton_owner.get_or_null(p_skeleton); + ERR_FAIL_COND_V(!skeleton, RID()); + ERR_FAIL_COND_V(skeleton->size == 0, RID()); + if (skeleton->use_2d) { + return RID(); + } + if (!skeleton->uniform_set_3d.is_valid()) { + Vector<RD::Uniform> uniforms; + RD::Uniform u; + u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER; + u.binding = 0; + u.append_id(skeleton->buffer); + uniforms.push_back(u); + skeleton->uniform_set_3d = RD::get_singleton()->uniform_set_create(uniforms, p_shader, p_set); + } + + return skeleton->uniform_set_3d; + } +}; + +} // namespace RendererRD + +#endif // !MESH_STORAGE_RD_H diff --git a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp index a3ca7d3720..3379e1cb17 100644 --- a/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp +++ b/servers/rendering/renderer_rd/storage_rd/texture_storage.cpp @@ -124,6 +124,26 @@ TextureStorage::TextureStorage() { default_rd_textures[DEFAULT_RD_TEXTURE_ANISO] = RD::get_singleton()->texture_create(tformat, RD::TextureView(), vpv); } + { + RD::TextureFormat tf; + tf.format = RD::DATA_FORMAT_D16_UNORM; + tf.width = 4; + tf.height = 4; + tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT | RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; + tf.texture_type = RD::TEXTURE_TYPE_2D; + + Vector<uint8_t> sv; + sv.resize(16 * 2); + uint16_t *ptr = (uint16_t *)sv.ptrw(); + for (int i = 0; i < 16; i++) { + ptr[i] = Math::make_half_float(1.0f); + } + + Vector<Vector<uint8_t>> vpv; + vpv.push_back(sv); + default_rd_textures[DEFAULT_RD_TEXTURE_DEPTH] = RD::get_singleton()->texture_create(tf, RD::TextureView(), vpv); + } + for (int i = 0; i < 16; i++) { pv.set(i * 4 + 0, 0); pv.set(i * 4 + 1, 0); diff --git a/servers/rendering/renderer_rd/storage_rd/texture_storage.h b/servers/rendering/renderer_rd/storage_rd/texture_storage.h index 5d8d165a08..edff10b944 100644 --- a/servers/rendering/renderer_rd/storage_rd/texture_storage.h +++ b/servers/rendering/renderer_rd/storage_rd/texture_storage.h @@ -42,6 +42,7 @@ enum DefaultRDTexture { DEFAULT_RD_TEXTURE_BLACK, DEFAULT_RD_TEXTURE_NORMAL, DEFAULT_RD_TEXTURE_ANISO, + DEFAULT_RD_TEXTURE_DEPTH, DEFAULT_RD_TEXTURE_MULTIMESH_BUFFER, DEFAULT_RD_TEXTURE_CUBEMAP_BLACK, DEFAULT_RD_TEXTURE_CUBEMAP_ARRAY_BLACK, diff --git a/servers/rendering/renderer_scene_cull.cpp b/servers/rendering/renderer_scene_cull.cpp index d70e4ffa0c..1304c811f7 100644 --- a/servers/rendering/renderer_scene_cull.cpp +++ b/servers/rendering/renderer_scene_cull.cpp @@ -464,10 +464,10 @@ void RendererSceneCull::instance_initialize(RID p_rid) { } void RendererSceneCull::_instance_update_mesh_instance(Instance *p_instance) { - bool needs_instance = RSG::storage->mesh_needs_instance(p_instance->base, p_instance->skeleton.is_valid()); + bool needs_instance = RSG::mesh_storage->mesh_needs_instance(p_instance->base, p_instance->skeleton.is_valid()); if (needs_instance != p_instance->mesh_instance.is_valid()) { if (needs_instance) { - p_instance->mesh_instance = RSG::storage->mesh_instance_create(p_instance->base); + p_instance->mesh_instance = RSG::mesh_storage->mesh_instance_create(p_instance->base); } else { RSG::storage->free(p_instance->mesh_instance); @@ -488,7 +488,7 @@ void RendererSceneCull::_instance_update_mesh_instance(Instance *p_instance) { } if (p_instance->mesh_instance.is_valid()) { - RSG::storage->mesh_instance_set_skeleton(p_instance->mesh_instance, p_instance->skeleton); + RSG::mesh_storage->mesh_instance_set_skeleton(p_instance->mesh_instance, p_instance->skeleton); } } @@ -890,7 +890,7 @@ void RendererSceneCull::instance_set_blend_shape_weight(RID p_instance, int p_sh } if (instance->mesh_instance.is_valid()) { - RSG::storage->mesh_instance_set_blend_shape_weight(instance->mesh_instance, p_shape, p_weight); + RSG::mesh_storage->mesh_instance_set_blend_shape_weight(instance->mesh_instance, p_shape, p_weight); } } @@ -900,7 +900,7 @@ void RendererSceneCull::instance_set_surface_override_material(RID p_instance, i if (instance->base_type == RS::INSTANCE_MESH) { //may not have been updated yet, may also have not been set yet. When updated will be correcte, worst case - instance->materials.resize(MAX(p_surface + 1, RSG::storage->mesh_get_surface_count(instance->base))); + instance->materials.resize(MAX(p_surface + 1, RSG::mesh_storage->mesh_get_surface_count(instance->base))); } ERR_FAIL_INDEX(p_surface, instance->materials.size()); @@ -997,7 +997,7 @@ void RendererSceneCull::instance_attach_skeleton(RID p_instance, RID p_skeleton) if (p_skeleton.is_valid()) { //update the dependency now, so if cleared, we remove it - RSG::storage->skeleton_update_dependency(p_skeleton, &instance->dependency_tracker); + RSG::mesh_storage->skeleton_update_dependency(p_skeleton, &instance->dependency_tracker); } _instance_queue_update(instance, true, true); @@ -1847,7 +1847,7 @@ void RendererSceneCull::_update_instance_aabb(Instance *p_instance) { if (p_instance->custom_aabb) { new_aabb = *p_instance->custom_aabb; } else { - new_aabb = RSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton); + new_aabb = RSG::mesh_storage->mesh_get_aabb(p_instance->base, p_instance->skeleton); } } break; @@ -1856,7 +1856,7 @@ void RendererSceneCull::_update_instance_aabb(Instance *p_instance) { if (p_instance->custom_aabb) { new_aabb = *p_instance->custom_aabb; } else { - new_aabb = RSG::storage->multimesh_get_aabb(p_instance->base); + new_aabb = RSG::mesh_storage->multimesh_get_aabb(p_instance->base); } } break; @@ -2271,14 +2271,14 @@ bool RendererSceneCull::_light_instance_update_shadow(Instance *p_instance, cons } if (instance->mesh_instance.is_valid()) { - RSG::storage->mesh_instance_check_for_update(instance->mesh_instance); + RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance); } } shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance); } - RSG::storage->update_mesh_instances(); + RSG::mesh_storage->update_mesh_instances(); scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), light_transform, radius, 0, i, 0); shadow_data.light = light->instance; @@ -2348,14 +2348,14 @@ bool RendererSceneCull::_light_instance_update_shadow(Instance *p_instance, cons animated_material_found = true; } if (instance->mesh_instance.is_valid()) { - RSG::storage->mesh_instance_check_for_update(instance->mesh_instance); + RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance); } } shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance); } - RSG::storage->update_mesh_instances(); + RSG::mesh_storage->update_mesh_instances(); scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i, 0); shadow_data.light = light->instance; @@ -2412,13 +2412,13 @@ bool RendererSceneCull::_light_instance_update_shadow(Instance *p_instance, cons } if (instance->mesh_instance.is_valid()) { - RSG::storage->mesh_instance_check_for_update(instance->mesh_instance); + RSG::mesh_storage->mesh_instance_check_for_update(instance->mesh_instance); } } shadow_data.instances.push_back(static_cast<InstanceGeometryData *>(instance->base_data)->geometry_instance); } - RSG::storage->update_mesh_instances(); + RSG::mesh_storage->update_mesh_instances(); scene_render->light_instance_set_shadow_transform(light->instance, cm, light_transform, radius, 0, 0, 0); shadow_data.light = light->instance; @@ -3037,9 +3037,9 @@ void RendererSceneCull::_render_scene(const RendererSceneRender::CameraData *p_c if (scene_cull_result.mesh_instances.size()) { for (uint64_t i = 0; i < scene_cull_result.mesh_instances.size(); i++) { - RSG::storage->mesh_instance_check_for_update(scene_cull_result.mesh_instances[i]); + RSG::mesh_storage->mesh_instance_check_for_update(scene_cull_result.mesh_instances[i]); } - RSG::storage->update_mesh_instances(); + RSG::mesh_storage->update_mesh_instances(); } } @@ -3677,7 +3677,7 @@ void RendererSceneCull::_update_dirty_instance(Instance *p_instance) { if (p_instance->base_type == RS::INSTANCE_MESH) { //remove materials no longer used and un-own them - int new_mat_count = RSG::storage->mesh_get_surface_count(p_instance->base); + int new_mat_count = RSG::mesh_storage->mesh_get_surface_count(p_instance->base); p_instance->materials.resize(new_mat_count); _instance_update_mesh_instance(p_instance); @@ -3717,7 +3717,7 @@ void RendererSceneCull::_update_dirty_instance(Instance *p_instance) { bool cast_shadows = false; for (int i = 0; i < p_instance->materials.size(); i++) { - RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::storage->mesh_surface_get_material(mesh, i); + RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : RSG::mesh_storage->mesh_surface_get_material(mesh, i); if (!mat.is_valid()) { cast_shadows = true; @@ -3742,13 +3742,13 @@ void RendererSceneCull::_update_dirty_instance(Instance *p_instance) { } } else if (p_instance->base_type == RS::INSTANCE_MULTIMESH) { - RID mesh = RSG::storage->multimesh_get_mesh(p_instance->base); + RID mesh = RSG::mesh_storage->multimesh_get_mesh(p_instance->base); if (mesh.is_valid()) { bool cast_shadows = false; - int sc = RSG::storage->mesh_get_surface_count(mesh); + int sc = RSG::mesh_storage->mesh_get_surface_count(mesh); for (int i = 0; i < sc; i++) { - RID mat = RSG::storage->mesh_surface_get_material(mesh, i); + RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, i); if (!mat.is_valid()) { cast_shadows = true; @@ -3784,9 +3784,9 @@ void RendererSceneCull::_update_dirty_instance(Instance *p_instance) { continue; } - int sc = RSG::storage->mesh_get_surface_count(mesh); + int sc = RSG::mesh_storage->mesh_get_surface_count(mesh); for (int j = 0; j < sc; j++) { - RID mat = RSG::storage->mesh_surface_get_material(mesh, j); + RID mat = RSG::mesh_storage->mesh_surface_get_material(mesh, j); if (!mat.is_valid()) { cast_shadows = true; @@ -3851,7 +3851,7 @@ void RendererSceneCull::_update_dirty_instance(Instance *p_instance) { } if (p_instance->skeleton.is_valid()) { - RSG::storage->skeleton_update_dependency(p_instance->skeleton, &p_instance->dependency_tracker); + RSG::mesh_storage->skeleton_update_dependency(p_instance->skeleton, &p_instance->dependency_tracker); } p_instance->dependency_tracker.update_end(); diff --git a/servers/rendering/renderer_scene_cull.h b/servers/rendering/renderer_scene_cull.h index 2112118673..5f71250ced 100644 --- a/servers/rendering/renderer_scene_cull.h +++ b/servers/rendering/renderer_scene_cull.h @@ -47,7 +47,7 @@ class RendererSceneCull : public RendererScene { public: - RendererSceneRender *scene_render; + RendererSceneRender *scene_render = nullptr; enum { SDFGI_MAX_CASCADES = 8, @@ -115,7 +115,7 @@ public: /* VISIBILITY NOTIFIER API */ - RendererSceneOcclusionCull *dummy_occlusion_culling; + RendererSceneOcclusionCull *dummy_occlusion_culling = nullptr; /* SCENARIO API */ @@ -273,7 +273,7 @@ public: union { uint64_t instance_data_rid; RendererSceneRender::GeometryInstance *instance_geometry; - InstanceVisibilityNotifierData *visibility_notifier; + InstanceVisibilityNotifierData *visibility_notifier = nullptr; }; Instance *instance = nullptr; int32_t parent_array_index = -1; @@ -365,8 +365,8 @@ public: /* INSTANCING API */ struct InstancePair { - Instance *a; - Instance *b; + Instance *a = nullptr; + Instance *b = nullptr; SelfList<InstancePair> list_a; SelfList<InstancePair> list_b; InstancePair() : @@ -409,7 +409,7 @@ public: bool dynamic_gi : 2; //same above for dynamic objects bool redraw_if_visible : 4; - Instance *lightmap; + Instance *lightmap = nullptr; Rect2 lightmap_uv_scale; int lightmap_slice_index; uint32_t lightmap_cull_index; @@ -455,7 +455,7 @@ public: SelfList<Instance> update_item; - AABB *custom_aabb; // <Zylann> would using aabb directly with a bool be better? + AABB *custom_aabb = nullptr; // <Zylann> would using aabb directly with a bool be better? float extra_margin; ObjectID object_id; @@ -465,7 +465,7 @@ public: uint64_t version; // changes to this, and changes to base increase version - InstanceBaseData *base_data; + InstanceBaseData *base_data = nullptr; SelfList<InstancePair>::List pairs; uint64_t pair_check; @@ -597,7 +597,7 @@ public: }; struct InstanceReflectionProbeData : public InstanceBaseData { - Instance *owner; + Instance *owner = nullptr; Set<Instance *> geometries; @@ -613,7 +613,7 @@ public: }; struct InstanceDecalData : public InstanceBaseData { - Instance *owner; + Instance *owner = nullptr; RID instance; Set<Instance *> geometries; @@ -656,7 +656,7 @@ public: Set<Instance *> geometries; - Instance *baked_light; + Instance *baked_light = nullptr; RS::LightBakeMode bake_mode; uint32_t max_sdfgi_cascade = 2; @@ -671,7 +671,7 @@ public: }; struct InstanceVoxelGIData : public InstanceBaseData { - Instance *owner; + Instance *owner = nullptr; Set<Instance *> geometries; Set<Instance *> dynamic_geometries; @@ -1023,7 +1023,7 @@ public: struct VisibilityCullData { uint64_t viewport_mask; - Scenario *scenario; + Scenario *scenario = nullptr; Vector3 camera_position; uint32_t cull_offset; uint32_t cull_count; @@ -1035,12 +1035,12 @@ public: _FORCE_INLINE_ int _visibility_range_check(InstanceVisibilityData &r_vis_data, const Vector3 &p_camera_pos, uint64_t p_viewport_mask); struct CullData { - Cull *cull; - Scenario *scenario; + Cull *cull = nullptr; + Scenario *scenario = nullptr; RID shadow_atlas; Transform3D cam_transform; uint32_t visible_layers; - Instance *render_reflection_probe; + Instance *render_reflection_probe = nullptr; const RendererSceneOcclusionCull::HZBuffer *occlusion_buffer; const CameraMatrix *camera_matrix; uint64_t visibility_viewport_mask; diff --git a/servers/rendering/renderer_scene_render.h b/servers/rendering/renderer_scene_render.h index 5f9c4bb816..0b8734e68c 100644 --- a/servers/rendering/renderer_scene_render.h +++ b/servers/rendering/renderer_scene_render.h @@ -223,7 +223,7 @@ public: struct RenderSDFGIUpdateData { bool update_static = false; uint32_t static_cascade_count; - uint32_t *static_cascade_indices; + uint32_t *static_cascade_indices = nullptr; PagedArray<RID> *static_positional_lights; const Vector<RID> *directional_lights; diff --git a/servers/rendering/renderer_storage.h b/servers/rendering/renderer_storage.h index b9cd1f55ba..7bbd414465 100644 --- a/servers/rendering/renderer_storage.h +++ b/servers/rendering/renderer_storage.h @@ -119,94 +119,6 @@ public: Set<Dependency *> dependencies; }; - /* MESH API */ - - virtual RID mesh_allocate() = 0; - virtual void mesh_initialize(RID p_rid) = 0; - - virtual void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) = 0; - - /// Returns stride - virtual void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) = 0; - - virtual int mesh_get_blend_shape_count(RID p_mesh) const = 0; - - virtual void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) = 0; - virtual RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const = 0; - - virtual void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) = 0; - virtual void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) = 0; - virtual void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) = 0; - - virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) = 0; - virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const = 0; - - virtual RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const = 0; - - virtual int mesh_get_surface_count(RID p_mesh) const = 0; - - virtual void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) = 0; - virtual AABB mesh_get_custom_aabb(RID p_mesh) const = 0; - - virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) = 0; - - virtual void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) = 0; - - virtual void mesh_clear(RID p_mesh) = 0; - - virtual bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) = 0; - - /* MESH INSTANCE */ - - virtual RID mesh_instance_create(RID p_base) = 0; - virtual void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) = 0; - virtual void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) = 0; - virtual void mesh_instance_check_for_update(RID p_mesh_instance) = 0; - virtual void update_mesh_instances() = 0; - - /* MULTIMESH API */ - - virtual RID multimesh_allocate() = 0; - virtual void multimesh_initialize(RID p_rid) = 0; - - virtual void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) = 0; - - virtual int multimesh_get_instance_count(RID p_multimesh) const = 0; - - virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) = 0; - virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) = 0; - virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) = 0; - virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) = 0; - virtual void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) = 0; - - virtual RID multimesh_get_mesh(RID p_multimesh) const = 0; - - virtual Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const = 0; - virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const = 0; - virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const = 0; - virtual Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const = 0; - - virtual void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) = 0; - virtual Vector<float> multimesh_get_buffer(RID p_multimesh) const = 0; - - virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) = 0; - virtual int multimesh_get_visible_instances(RID p_multimesh) const = 0; - - virtual AABB multimesh_get_aabb(RID p_multimesh) const = 0; - - /* SKELETON API */ - - virtual RID skeleton_allocate() = 0; - virtual void skeleton_initialize(RID p_rid) = 0; - - virtual void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) = 0; - virtual int skeleton_get_bone_count(RID p_skeleton) const = 0; - virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) = 0; - virtual Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const = 0; - virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) = 0; - virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const = 0; - virtual void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) = 0; - /* Light API */ virtual RID directional_light_allocate() = 0; @@ -282,7 +194,6 @@ public: virtual float reflection_probe_get_mesh_lod_threshold(RID p_probe) const = 0; virtual void base_update_dependency(RID p_base, DependencyTracker *p_instance) = 0; - virtual void skeleton_update_dependency(RID p_base, DependencyTracker *p_instance) = 0; /* VOXEL GI API */ diff --git a/servers/rendering/renderer_viewport.cpp b/servers/rendering/renderer_viewport.cpp index f492c5e9bd..07d413b095 100644 --- a/servers/rendering/renderer_viewport.cpp +++ b/servers/rendering/renderer_viewport.cpp @@ -77,23 +77,21 @@ void RendererViewport::_configure_3d_render_buffers(Viewport *p_viewport) { RSG::scene->free(p_viewport->render_buffers); p_viewport->render_buffers = RID(); } else { - float scaling_3d_scale = p_viewport->scaling_3d_scale; - + const float scaling_3d_scale = p_viewport->scaling_3d_scale; RS::ViewportScaling3DMode scaling_3d_mode = p_viewport->scaling_3d_mode; bool scaling_enabled = true; if ((scaling_3d_mode == RS::VIEWPORT_SCALING_3D_MODE_FSR) && (scaling_3d_scale > 1.0)) { - // FSR is not design for downsampling. - // Throw a warning and fallback to VIEWPORT_SCALING_3D_MODE_BILINEAR - WARN_PRINT_ONCE("FSR 3D resolution scaling does not support supersampling. Falling back to bilinear scaling."); + // FSR is not designed for downsampling. + // Fall back to bilinear scaling. scaling_3d_mode = RS::VIEWPORT_SCALING_3D_MODE_BILINEAR; } if ((scaling_3d_mode == RS::VIEWPORT_SCALING_3D_MODE_FSR) && !p_viewport->fsr_enabled) { // FSR is not actually available. - // Throw a warning and fallback to disable scaling - WARN_PRINT_ONCE("FSR 3D resolution scaling is not available. Disabling 3D resolution scaling."); - scaling_enabled = false; + // Fall back to bilinear scaling. + WARN_PRINT_ONCE("FSR 1.0 3D resolution scaling is not available. Falling back to bilinear 3D resolution scaling."); + scaling_3d_mode = RS::VIEWPORT_SCALING_3D_MODE_BILINEAR; } if (scaling_3d_scale == 1.0) { diff --git a/servers/rendering/renderer_viewport.h b/servers/rendering/renderer_viewport.h index 2245d9a216..b6e44e8436 100644 --- a/servers/rendering/renderer_viewport.h +++ b/servers/rendering/renderer_viewport.h @@ -129,7 +129,7 @@ public: }; struct CanvasData { - CanvasBase *canvas; + CanvasBase *canvas = nullptr; Transform2D transform; int layer; int sublayer; diff --git a/servers/rendering/rendering_server_default.cpp b/servers/rendering/rendering_server_default.cpp index 3969682e15..2dab7cb84c 100644 --- a/servers/rendering/rendering_server_default.cpp +++ b/servers/rendering/rendering_server_default.cpp @@ -401,6 +401,7 @@ RenderingServerDefault::RenderingServerDefault(bool p_create_thread) : RSG::canvas_texture_storage = RSG::rasterizer->get_canvas_texture_storage(); RSG::decal_atlas_storage = RSG::rasterizer->get_decal_atlas_storage(); RSG::material_storage = RSG::rasterizer->get_material_storage(); + RSG::mesh_storage = RSG::rasterizer->get_mesh_storage(); RSG::texture_storage = RSG::rasterizer->get_texture_storage(); RSG::storage = RSG::rasterizer->get_storage(); RSG::canvas_render = RSG::rasterizer->get_canvas(); diff --git a/servers/rendering/rendering_server_default.h b/servers/rendering/rendering_server_default.h index 52e0c2c0ac..21e11c6d71 100644 --- a/servers/rendering/rendering_server_default.h +++ b/servers/rendering/rendering_server_default.h @@ -252,11 +252,11 @@ public: #undef ServerName #undef server_name -#define ServerName RendererStorage -#define server_name RSG::storage +#define ServerName RendererMeshStorage +#define server_name RSG::mesh_storage virtual RID mesh_create_from_surfaces(const Vector<SurfaceData> &p_surfaces, int p_blend_shape_count = 0) override { - RID mesh = RSG::storage->mesh_allocate(); + RID mesh = RSG::mesh_storage->mesh_allocate(); // TODO once we have RSG::mesh_storage, add can_create_resources_async and call here instead of texture_storage!! @@ -264,16 +264,16 @@ public: if (Thread::get_caller_id() == server_thread) { command_queue.flush_if_pending(); } - RSG::storage->mesh_initialize(mesh); - RSG::storage->mesh_set_blend_shape_count(mesh, p_blend_shape_count); + RSG::mesh_storage->mesh_initialize(mesh); + RSG::mesh_storage->mesh_set_blend_shape_count(mesh, p_blend_shape_count); for (int i = 0; i < p_surfaces.size(); i++) { - RSG::storage->mesh_add_surface(mesh, p_surfaces[i]); + RSG::mesh_storage->mesh_add_surface(mesh, p_surfaces[i]); } } else { - command_queue.push(RSG::storage, &RendererStorage::mesh_initialize, mesh); - command_queue.push(RSG::storage, &RendererStorage::mesh_set_blend_shape_count, mesh, p_blend_shape_count); + command_queue.push(RSG::mesh_storage, &RendererMeshStorage::mesh_initialize, mesh); + command_queue.push(RSG::mesh_storage, &RendererMeshStorage::mesh_set_blend_shape_count, mesh, p_blend_shape_count); for (int i = 0; i < p_surfaces.size(); i++) { - command_queue.push(RSG::storage, &RendererStorage::mesh_add_surface, mesh, p_surfaces[i]); + command_queue.push(RSG::mesh_storage, &RendererMeshStorage::mesh_add_surface, mesh, p_surfaces[i]); } } @@ -348,6 +348,11 @@ public: FUNC2(skeleton_set_base_transform_2d, RID, const Transform2D &) /* Light API */ +#undef ServerName +#undef server_name + +#define ServerName RendererStorage +#define server_name RSG::storage FUNCRIDSPLIT(directional_light) FUNCRIDSPLIT(omni_light) @@ -794,7 +799,7 @@ public: FUNC2(canvas_item_set_draw_behind_parent, RID, bool) - FUNC5(canvas_item_add_line, RID, const Point2 &, const Point2 &, const Color &, float) + FUNC6(canvas_item_add_line, RID, const Point2 &, const Point2 &, const Color &, float, bool) FUNC5(canvas_item_add_polyline, RID, const Vector<Point2> &, const Vector<Color> &, float, bool) FUNC4(canvas_item_add_multiline, RID, const Vector<Point2> &, const Vector<Color> &, float) FUNC3(canvas_item_add_rect, RID, const Rect2 &, const Color &) diff --git a/servers/rendering/rendering_server_globals.cpp b/servers/rendering/rendering_server_globals.cpp index 6a2ba5ee6b..2be87c27b1 100644 --- a/servers/rendering/rendering_server_globals.cpp +++ b/servers/rendering/rendering_server_globals.cpp @@ -35,6 +35,7 @@ bool RenderingServerGlobals::threaded = false; RendererCanvasTextureStorage *RenderingServerGlobals::canvas_texture_storage = nullptr; RendererDecalAtlasStorage *RenderingServerGlobals::decal_atlas_storage = nullptr; RendererMaterialStorage *RenderingServerGlobals::material_storage = nullptr; +RendererMeshStorage *RenderingServerGlobals::mesh_storage = nullptr; RendererTextureStorage *RenderingServerGlobals::texture_storage = nullptr; RendererStorage *RenderingServerGlobals::storage = nullptr; RendererCanvasRender *RenderingServerGlobals::canvas_render = nullptr; diff --git a/servers/rendering/rendering_server_globals.h b/servers/rendering/rendering_server_globals.h index 2f9eddff09..40fd638425 100644 --- a/servers/rendering/rendering_server_globals.h +++ b/servers/rendering/rendering_server_globals.h @@ -37,6 +37,7 @@ #include "servers/rendering/storage/canvas_texture_storage.h" #include "servers/rendering/storage/decal_atlas_storage.h" #include "servers/rendering/storage/material_storage.h" +#include "servers/rendering/storage/mesh_storage.h" #include "servers/rendering/storage/texture_storage.h" class RendererCanvasCull; @@ -49,6 +50,7 @@ public: static RendererCanvasTextureStorage *canvas_texture_storage; static RendererMaterialStorage *material_storage; + static RendererMeshStorage *mesh_storage; static RendererTextureStorage *texture_storage; static RendererDecalAtlasStorage *decal_atlas_storage; static RendererStorage *storage; diff --git a/servers/rendering/shader_language.cpp b/servers/rendering/shader_language.cpp index fa3e09f746..816a02761d 100644 --- a/servers/rendering/shader_language.cpp +++ b/servers/rendering/shader_language.cpp @@ -2813,7 +2813,7 @@ bool ShaderLanguage::_validate_function_call(BlockNode *p_block, const FunctionI bool error = false; if (p_func->arguments[arg]->type == Node::TYPE_VARIABLE) { - const VariableNode *vn = (VariableNode *)p_func->arguments[arg]; + const VariableNode *vn = static_cast<VariableNode *>(p_func->arguments[arg]); bool is_const = false; ConstantNode::Value value; @@ -2825,7 +2825,7 @@ bool ShaderLanguage::_validate_function_call(BlockNode *p_block, const FunctionI } } else { if (p_func->arguments[arg]->type == Node::TYPE_CONSTANT) { - ConstantNode *cn = (ConstantNode *)p_func->arguments[arg]; + const ConstantNode *cn = static_cast<ConstantNode *>(p_func->arguments[arg]); if (cn->get_datatype() == TYPE_INT && cn->values.size() == 1) { int value = cn->values[0].sint; @@ -4132,7 +4132,7 @@ bool ShaderLanguage::_validate_varying_assign(ShaderNode::Varying &p_varying, St bool ShaderLanguage::_check_node_constness(const Node *p_node) const { switch (p_node->type) { case Node::TYPE_OPERATOR: { - OperatorNode *op_node = (OperatorNode *)p_node; + const OperatorNode *op_node = static_cast<const OperatorNode *>(p_node); for (int i = int(op_node->op == OP_CALL); i < op_node->arguments.size(); i++) { if (!_check_node_constness(op_node->arguments[i])) { return false; @@ -4142,13 +4142,13 @@ bool ShaderLanguage::_check_node_constness(const Node *p_node) const { case Node::TYPE_CONSTANT: break; case Node::TYPE_VARIABLE: { - VariableNode *varn = (VariableNode *)p_node; + const VariableNode *varn = static_cast<const VariableNode *>(p_node); if (!varn->is_const) { return false; } } break; case Node::TYPE_ARRAY: { - ArrayNode *arrn = (ArrayNode *)p_node; + const ArrayNode *arrn = static_cast<const ArrayNode *>(p_node); if (!arrn->is_const) { return false; } @@ -5144,7 +5144,6 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons if (!call_expression) { return nullptr; } - data_type = call_expression->get_datatype(); } else if (tk.type == TK_BRACKET_OPEN) { // indexing index_expression = _parse_and_reduce_expression(p_block, p_function_info); if (!index_expression) { @@ -5157,7 +5156,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons } if (index_expression->type == Node::TYPE_CONSTANT) { - ConstantNode *cnode = (ConstantNode *)index_expression; + ConstantNode *cnode = static_cast<ConstantNode *>(index_expression); if (cnode) { if (!cnode->values.is_empty()) { int value = cnode->values[0].sint; @@ -5598,15 +5597,13 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons if (p_block != nullptr) { p_block->block_tag = SubClassTag::TAG_ARRAY; } - Node *call_expression = _parse_and_reduce_expression(p_block, p_function_info); + mn->call_expression = _parse_and_reduce_expression(p_block, p_function_info); if (p_block != nullptr) { p_block->block_tag = SubClassTag::TAG_GLOBAL; } - if (!call_expression) { + if (!mn->call_expression) { return nullptr; } - mn->datatype = call_expression->get_datatype(); - mn->call_expression = call_expression; } else if (tk.type == TK_BRACKET_OPEN) { Node *index_expression = _parse_and_reduce_expression(p_block, p_function_info); if (!index_expression) { @@ -5619,7 +5616,7 @@ ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, cons } if (index_expression->type == Node::TYPE_CONSTANT) { - ConstantNode *cnode = (ConstantNode *)index_expression; + ConstantNode *cnode = static_cast<ConstantNode *>(index_expression); if (cnode) { if (!cnode->values.is_empty()) { int value = cnode->values[0].sint; @@ -6702,7 +6699,7 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun return ERR_PARSE_ERROR; } - if (is_const && n->type == Node::TYPE_OPERATOR && ((OperatorNode *)n)->op == OP_CALL) { + if (is_const && n->type == Node::TYPE_OPERATOR && static_cast<OperatorNode *>(n)->op == OP_CALL) { _set_error(RTR("Expected a constant expression.")); return ERR_PARSE_ERROR; } @@ -6758,8 +6755,8 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun if (!n) { return ERR_PARSE_ERROR; } - if (is_const && n->type == Node::TYPE_OPERATOR && ((OperatorNode *)n)->op == OP_CALL) { - OperatorNode *op = ((OperatorNode *)n); + if (is_const && n->type == Node::TYPE_OPERATOR && static_cast<OperatorNode *>(n)->op == OP_CALL) { + OperatorNode *op = static_cast<OperatorNode *>(n); for (int i = 1; i < op->arguments.size(); i++) { if (!_check_node_constness(op->arguments[i])) { _set_error(vformat(RTR("Expected constant expression for argument %d of function call after '='."), i - 1)); @@ -6803,7 +6800,7 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun } } while (tk.type == TK_COMMA); //another variable - p_block->statements.push_back((Node *)vdnode); + p_block->statements.push_back(static_cast<Node *>(vdnode)); } else if (tk.type == TK_CURLY_BRACKET_OPEN) { //a sub block, just because.. BlockNode *block = alloc_node<BlockNode>(); @@ -6925,7 +6922,7 @@ Error ShaderLanguage::_parse_block(BlockNode *p_block, const FunctionInfo &p_fun } else { Set<int> constants; for (int i = 0; i < switch_block->statements.size(); i++) { // Checks for duplicates. - ControlFlowNode *flow = (ControlFlowNode *)switch_block->statements[i]; + ControlFlowNode *flow = static_cast<ControlFlowNode *>(switch_block->statements[i]); if (flow) { if (flow->flow_op == FLOW_OP_CASE) { if (flow->expressions[0]->type == Node::TYPE_CONSTANT) { @@ -8467,7 +8464,7 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct return ERR_PARSE_ERROR; } - if (n->type == Node::TYPE_OPERATOR && ((OperatorNode *)n)->op == OP_CALL) { + if (n->type == Node::TYPE_OPERATOR && static_cast<OperatorNode *>(n)->op == OP_CALL) { _set_error(RTR("Expected constant expression.")); return ERR_PARSE_ERROR; } @@ -8523,8 +8520,8 @@ Error ShaderLanguage::_parse_shader(const Map<StringName, FunctionInfo> &p_funct if (!expr) { return ERR_PARSE_ERROR; } - if (expr->type == Node::TYPE_OPERATOR && ((OperatorNode *)expr)->op == OP_CALL) { - OperatorNode *op = ((OperatorNode *)expr); + if (expr->type == Node::TYPE_OPERATOR && static_cast<OperatorNode *>(expr)->op == OP_CALL) { + OperatorNode *op = static_cast<OperatorNode *>(expr); for (int i = 1; i < op->arguments.size(); i++) { if (!_check_node_constness(op->arguments[i])) { _set_error(vformat(RTR("Expected constant expression for argument %d of function call after '='."), i - 1)); @@ -8861,7 +8858,7 @@ Error ShaderLanguage::_find_last_flow_op_in_op(ControlFlowNode *p_flow, FlowOper for (int i = p_flow->blocks.size() - 1; i >= 0; i--) { if (p_flow->blocks[i]->type == Node::TYPE_BLOCK) { - BlockNode *last_block = (BlockNode *)p_flow->blocks[i]; + BlockNode *last_block = static_cast<BlockNode *>(p_flow->blocks[i]); if (_find_last_flow_op_in_block(last_block, p_op) == OK) { found = true; break; @@ -8879,7 +8876,7 @@ Error ShaderLanguage::_find_last_flow_op_in_block(BlockNode *p_block, FlowOperat for (int i = p_block->statements.size() - 1; i >= 0; i--) { if (p_block->statements[i]->type == Node::TYPE_CONTROL_FLOW) { - ControlFlowNode *flow = (ControlFlowNode *)p_block->statements[i]; + ControlFlowNode *flow = static_cast<ControlFlowNode *>(p_block->statements[i]); if (flow->flow_op == p_op) { found = true; break; @@ -8890,7 +8887,7 @@ Error ShaderLanguage::_find_last_flow_op_in_block(BlockNode *p_block, FlowOperat } } } else if (p_block->statements[i]->type == Node::TYPE_BLOCK) { - BlockNode *block = (BlockNode *)p_block->statements[i]; + BlockNode *block = static_cast<BlockNode *>(p_block->statements[i]); if (_find_last_flow_op_in_block(block, p_op) == OK) { found = true; break; diff --git a/servers/rendering/shader_language.h b/servers/rendering/shader_language.h index e5ac14a7db..66ae220edf 100644 --- a/servers/rendering/shader_language.h +++ b/servers/rendering/shader_language.h @@ -386,7 +386,7 @@ public: return node; } - Node *nodes; + Node *nodes = nullptr; struct OperatorNode : public Node { DataType return_cache = TYPE_VOID; @@ -451,8 +451,8 @@ public: int array_size = 0; bool is_local = false; - virtual DataType get_datatype() const override { return datatype_cache; } - virtual String get_datatype_name() const override { return String(struct_name); } + virtual DataType get_datatype() const override { return call_expression ? call_expression->get_datatype() : datatype_cache; } + virtual String get_datatype_name() const override { return call_expression ? call_expression->get_datatype_name() : String(struct_name); } virtual int get_array_size() const override { return (index_expression || call_expression) ? 0 : array_size; } virtual bool is_indexed() const override { return index_expression != nullptr; } @@ -558,8 +558,8 @@ public: Node *call_expression = nullptr; bool has_swizzling_duplicates = false; - virtual DataType get_datatype() const override { return datatype; } - virtual String get_datatype_name() const override { return String(struct_name); } + virtual DataType get_datatype() const override { return call_expression ? call_expression->get_datatype() : datatype; } + virtual String get_datatype_name() const override { return call_expression ? call_expression->get_datatype_name() : String(struct_name); } virtual int get_array_size() const override { return (index_expression || call_expression) ? 0 : array_size; } virtual bool is_indexed() const override { return index_expression != nullptr || call_expression != nullptr; } @@ -615,20 +615,20 @@ public: DataType type; StringName type_str; DataPrecision precision; - ConstantNode *initializer; + ConstantNode *initializer = nullptr; int array_size; }; struct Function { StringName name; - FunctionNode *function; + FunctionNode *function = nullptr; Set<StringName> uses_function; bool callable; }; struct Struct { StringName name; - StructNode *shader_struct; + StructNode *shader_struct = nullptr; }; struct Varying { @@ -715,7 +715,7 @@ public: bool is_op; union { Operator op; - Node *node; + Node *node = nullptr; }; }; @@ -973,7 +973,7 @@ private: Token _make_token(TokenType p_type, const StringName &p_text = StringName()); Token _get_token(); - ShaderNode *shader; + ShaderNode *shader = nullptr; enum IdentifierType { IDENTIFIER_FUNCTION, @@ -1021,7 +1021,7 @@ private: CompletionType completion_type; int completion_line; - BlockNode *completion_block; + BlockNode *completion_block = nullptr; DataType completion_base; bool completion_base_array; SubClassTag completion_class; diff --git a/servers/rendering/storage/mesh_storage.h b/servers/rendering/storage/mesh_storage.h new file mode 100644 index 0000000000..1dac51319c --- /dev/null +++ b/servers/rendering/storage/mesh_storage.h @@ -0,0 +1,136 @@ +/*************************************************************************/ +/* mesh_storage.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef MESH_STORAGE_H +#define MESH_STORAGE_H + +#include "servers/rendering/renderer_storage.h" +#include "servers/rendering_server.h" + +class RendererMeshStorage { +public: + virtual ~RendererMeshStorage() {} + + /* MESH API */ + + virtual RID mesh_allocate() = 0; + virtual void mesh_initialize(RID p_rid) = 0; + virtual void mesh_free(RID p_rid) = 0; + + virtual void mesh_set_blend_shape_count(RID p_mesh, int p_blend_shape_count) = 0; + + /// Returns stride + virtual void mesh_add_surface(RID p_mesh, const RS::SurfaceData &p_surface) = 0; + + virtual int mesh_get_blend_shape_count(RID p_mesh) const = 0; + + virtual void mesh_set_blend_shape_mode(RID p_mesh, RS::BlendShapeMode p_mode) = 0; + virtual RS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const = 0; + + virtual void mesh_surface_update_vertex_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) = 0; + virtual void mesh_surface_update_attribute_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) = 0; + virtual void mesh_surface_update_skin_region(RID p_mesh, int p_surface, int p_offset, const Vector<uint8_t> &p_data) = 0; + + virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) = 0; + virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const = 0; + + virtual RS::SurfaceData mesh_get_surface(RID p_mesh, int p_surface) const = 0; + + virtual int mesh_get_surface_count(RID p_mesh) const = 0; + + virtual void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) = 0; + virtual AABB mesh_get_custom_aabb(RID p_mesh) const = 0; + + virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) = 0; + + virtual void mesh_set_shadow_mesh(RID p_mesh, RID p_shadow_mesh) = 0; + + virtual void mesh_clear(RID p_mesh) = 0; + + virtual bool mesh_needs_instance(RID p_mesh, bool p_has_skeleton) = 0; + + /* MESH INSTANCE */ + + virtual RID mesh_instance_create(RID p_base) = 0; + virtual void mesh_instance_free(RID p_rid) = 0; + virtual void mesh_instance_set_skeleton(RID p_mesh_instance, RID p_skeleton) = 0; + virtual void mesh_instance_set_blend_shape_weight(RID p_mesh_instance, int p_shape, float p_weight) = 0; + virtual void mesh_instance_check_for_update(RID p_mesh_instance) = 0; + virtual void update_mesh_instances() = 0; + + /* MULTIMESH API */ + + virtual RID multimesh_allocate() = 0; + virtual void multimesh_initialize(RID p_rid) = 0; + virtual void multimesh_free(RID p_rid) = 0; + + virtual void multimesh_allocate_data(RID p_multimesh, int p_instances, RS::MultimeshTransformFormat p_transform_format, bool p_use_colors = false, bool p_use_custom_data = false) = 0; + + virtual int multimesh_get_instance_count(RID p_multimesh) const = 0; + + virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) = 0; + virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform3D &p_transform) = 0; + virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) = 0; + virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) = 0; + virtual void multimesh_instance_set_custom_data(RID p_multimesh, int p_index, const Color &p_color) = 0; + + virtual RID multimesh_get_mesh(RID p_multimesh) const = 0; + + virtual Transform3D multimesh_instance_get_transform(RID p_multimesh, int p_index) const = 0; + virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const = 0; + virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const = 0; + virtual Color multimesh_instance_get_custom_data(RID p_multimesh, int p_index) const = 0; + + virtual void multimesh_set_buffer(RID p_multimesh, const Vector<float> &p_buffer) = 0; + virtual Vector<float> multimesh_get_buffer(RID p_multimesh) const = 0; + + virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) = 0; + virtual int multimesh_get_visible_instances(RID p_multimesh) const = 0; + + virtual AABB multimesh_get_aabb(RID p_multimesh) const = 0; + + /* SKELETON API */ + + virtual RID skeleton_allocate() = 0; + virtual void skeleton_initialize(RID p_rid) = 0; + virtual void skeleton_free(RID p_rid) = 0; + + virtual void skeleton_allocate_data(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) = 0; + virtual int skeleton_get_bone_count(RID p_skeleton) const = 0; + virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform3D &p_transform) = 0; + virtual Transform3D skeleton_bone_get_transform(RID p_skeleton, int p_bone) const = 0; + virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) = 0; + virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const = 0; + virtual void skeleton_set_base_transform_2d(RID p_skeleton, const Transform2D &p_base_transform) = 0; + + virtual void skeleton_update_dependency(RID p_base, RendererStorage::DependencyTracker *p_instance) = 0; +}; + +#endif // !MESH_STORAGE_H diff --git a/servers/rendering_server.cpp b/servers/rendering_server.cpp index 668bd31a49..b58e6138eb 100644 --- a/servers/rendering_server.cpp +++ b/servers/rendering_server.cpp @@ -979,7 +979,6 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa ERR_FAIL_COND_V_MSG(err != OK, ERR_INVALID_DATA, "Invalid array format for surface."); Vector<uint8_t> blend_shape_data; - uint32_t blend_shape_count = 0; if (p_blend_shapes.size()) { uint32_t bs_format = format & RS::ARRAY_FORMAT_BLEND_SHAPE_MASK; @@ -996,7 +995,6 @@ Error RenderingServer::mesh_create_surface_data_from_arrays(SurfaceData *r_surfa ERR_FAIL_COND_V_MSG(err2 != OK, ERR_INVALID_DATA, "Invalid blend shape array format for surface."); blend_shape_data.append_array(vertex_array_shape); - blend_shape_count++; } } Vector<SurfaceData::LOD> lods; @@ -2568,7 +2566,7 @@ void RenderingServer::_bind_methods() { /* Primitives */ - ClassDB::bind_method(D_METHOD("canvas_item_add_line", "item", "from", "to", "color", "width"), &RenderingServer::canvas_item_add_line, DEFVAL(1.0)); + ClassDB::bind_method(D_METHOD("canvas_item_add_line", "item", "from", "to", "color", "width", "antialiased"), &RenderingServer::canvas_item_add_line, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("canvas_item_add_polyline", "item", "points", "colors", "width", "antialiased"), &RenderingServer::canvas_item_add_polyline, DEFVAL(1.0), DEFVAL(false)); ClassDB::bind_method(D_METHOD("canvas_item_add_rect", "item", "rect", "color"), &RenderingServer::canvas_item_add_rect); ClassDB::bind_method(D_METHOD("canvas_item_add_circle", "item", "pos", "radius", "color"), &RenderingServer::canvas_item_add_circle); diff --git a/servers/rendering_server.h b/servers/rendering_server.h index 94692ba68d..71896e9d11 100644 --- a/servers/rendering_server.h +++ b/servers/rendering_server.h @@ -1293,7 +1293,7 @@ public: NINE_PATCH_TILE_FIT, }; - virtual void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0) = 0; + virtual void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false) = 0; virtual void canvas_item_add_polyline(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, float p_width = 1.0, bool p_antialiased = false) = 0; virtual void canvas_item_add_multiline(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, float p_width = 1.0) = 0; virtual void canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color) = 0; diff --git a/servers/text_server.cpp b/servers/text_server.cpp index ec31885cae..7e3fde6a1f 100644 --- a/servers/text_server.cpp +++ b/servers/text_server.cpp @@ -395,7 +395,7 @@ void TextServer::_bind_methods() { ClassDB::bind_method(D_METHOD("shaped_text_get_range", "shaped"), &TextServer::shaped_text_get_range); ClassDB::bind_method(D_METHOD("shaped_text_get_line_breaks_adv", "shaped", "width", "start", "once", "break_flags"), &TextServer::shaped_text_get_line_breaks_adv, DEFVAL(0), DEFVAL(true), DEFVAL(BREAK_MANDATORY | BREAK_WORD_BOUND)); ClassDB::bind_method(D_METHOD("shaped_text_get_line_breaks", "shaped", "width", "start", "break_flags"), &TextServer::shaped_text_get_line_breaks, DEFVAL(0), DEFVAL(BREAK_MANDATORY | BREAK_WORD_BOUND)); - ClassDB::bind_method(D_METHOD("shaped_text_get_word_breaks", "shaped", "grapheme_flags"), &TextServer::shaped_text_get_word_breaks); + ClassDB::bind_method(D_METHOD("shaped_text_get_word_breaks", "shaped", "grapheme_flags"), &TextServer::shaped_text_get_word_breaks, DEFVAL(GRAPHEME_IS_SPACE | GRAPHEME_IS_PUNCTUATION)); ClassDB::bind_method(D_METHOD("shaped_text_get_trim_pos", "shaped"), &TextServer::shaped_text_get_trim_pos); ClassDB::bind_method(D_METHOD("shaped_text_get_ellipsis_pos", "shaped"), &TextServer::shaped_text_get_ellipsis_pos); @@ -758,7 +758,7 @@ PackedInt32Array TextServer::shaped_text_get_word_breaks(const RID &p_shaped, in int word_start = range.x; - int l_size = shaped_text_get_glyph_count(p_shaped); + const int l_size = shaped_text_get_glyph_count(p_shaped); const Glyph *l_gl = const_cast<TextServer *>(this)->shaped_text_sort_logical(p_shaped); for (int i = 0; i < l_size; i++) { @@ -979,6 +979,14 @@ TextServer::Direction TextServer::shaped_text_get_dominant_direction_in_range(co } } +_FORCE_INLINE_ void _push_range(Vector<Vector2> &r_vector, real_t p_start, real_t p_end) { + if (!r_vector.is_empty() && Math::is_equal_approx(r_vector[r_vector.size() - 1].y, p_start, (real_t)UNIT_EPSILON)) { + r_vector.write[r_vector.size() - 1].y = p_end; + } else { + r_vector.push_back(Vector2(p_start, p_end)); + } +} + Vector<Vector2> TextServer::shaped_text_get_selection(const RID &p_shaped, int64_t p_start, int64_t p_end) const { Vector<Vector2> ranges; @@ -1003,7 +1011,7 @@ Vector<Vector2> TextServer::shaped_text_get_selection(const RID &p_shaped, int64 for (int j = 0; j < glyphs[i].count; j++) { advance += glyphs[i + j].advance; } - ranges.push_back(Vector2(off, off + advance)); + _push_range(ranges, off, off + advance); } // Only start of grapheme is in selection range. if (glyphs[i].start >= start && glyphs[i].end > end) { @@ -1013,9 +1021,9 @@ Vector<Vector2> TextServer::shaped_text_get_selection(const RID &p_shaped, int64 } real_t char_adv = advance / (real_t)(glyphs[i].end - glyphs[i].start); if ((glyphs[i].flags & GRAPHEME_IS_RTL) == GRAPHEME_IS_RTL) { - ranges.push_back(Vector2(off + char_adv * (glyphs[i].end - end), off + advance)); + _push_range(ranges, off + char_adv * (glyphs[i].end - end), off + advance); } else { - ranges.push_back(Vector2(off, off + char_adv * (end - glyphs[i].start))); + _push_range(ranges, off, off + char_adv * (end - glyphs[i].start)); } } // Only end of grapheme is in selection range. @@ -1026,9 +1034,9 @@ Vector<Vector2> TextServer::shaped_text_get_selection(const RID &p_shaped, int64 } real_t char_adv = advance / (real_t)(glyphs[i].end - glyphs[i].start); if ((glyphs[i].flags & GRAPHEME_IS_RTL) == GRAPHEME_IS_RTL) { - ranges.push_back(Vector2(off, off + char_adv * (glyphs[i].end - start))); + _push_range(ranges, off, off + char_adv * (glyphs[i].end - start)); } else { - ranges.push_back(Vector2(off + char_adv * (start - glyphs[i].start), off + advance)); + _push_range(ranges, off + char_adv * (start - glyphs[i].start), off + advance); } } // Selection range is within grapheme. @@ -1039,9 +1047,9 @@ Vector<Vector2> TextServer::shaped_text_get_selection(const RID &p_shaped, int64 } real_t char_adv = advance / (real_t)(glyphs[i].end - glyphs[i].start); if ((glyphs[i].flags & GRAPHEME_IS_RTL) == GRAPHEME_IS_RTL) { - ranges.push_back(Vector2(off + char_adv * (glyphs[i].end - end), off + char_adv * (glyphs[i].end - start))); + _push_range(ranges, off + char_adv * (glyphs[i].end - end), off + char_adv * (glyphs[i].end - start)); } else { - ranges.push_back(Vector2(off + char_adv * (start - glyphs[i].start), off + char_adv * (end - glyphs[i].start))); + _push_range(ranges, off + char_adv * (start - glyphs[i].start), off + char_adv * (end - glyphs[i].start)); } } } @@ -1050,25 +1058,6 @@ Vector<Vector2> TextServer::shaped_text_get_selection(const RID &p_shaped, int64 } } - // Merge intersecting ranges. - int i = 0; - while (i < ranges.size()) { - i++; - } - i = 0; - while (i < ranges.size()) { - int j = i + 1; - while (j < ranges.size()) { - if (Math::is_equal_approx(ranges[i].y, ranges[j].x, (real_t)UNIT_EPSILON)) { - ranges.write[i].y = ranges[j].y; - ranges.remove_at(j); - continue; - } - j++; - } - i++; - } - return ranges; } diff --git a/tests/SCsub b/tests/SCsub index 25b06f2312..c59ce69b92 100644 --- a/tests/SCsub +++ b/tests/SCsub @@ -18,11 +18,6 @@ if env_tests["platform"] == "windows": if env_tests.msvc: env_tests.Append(CCFLAGS=["/bigobj"]) -env_tests.add_source_files(env.tests_sources, "core/*.cpp") -env_tests.add_source_files(env.tests_sources, "core/math/*.cpp") -env_tests.add_source_files(env.tests_sources, "core/templates/*.cpp") -env_tests.add_source_files(env.tests_sources, "scene/*.cpp") -env_tests.add_source_files(env.tests_sources, "servers/*.cpp") env_tests.add_source_files(env.tests_sources, "*.cpp") lib = env_tests.add_library("tests", env.tests_sources) diff --git a/tests/core/io/test_config_file.h b/tests/core/io/test_config_file.h index 6e393c7a2d..355aca479e 100644 --- a/tests/core/io/test_config_file.h +++ b/tests/core/io/test_config_file.h @@ -155,7 +155,7 @@ antiAliasing=false "a=b"=7 )"); - FileAccessRef file = FileAccess::open(config_path, FileAccess::READ); + Ref<FileAccess> file = FileAccess::open(config_path, FileAccess::READ); CHECK_MESSAGE(file->get_as_utf8_string() == contents, "The saved configuration file should match the expected format."); } diff --git a/tests/core/io/test_file_access.h b/tests/core/io/test_file_access.h index eee57048cf..f0e1cceacf 100644 --- a/tests/core/io/test_file_access.h +++ b/tests/core/io/test_file_access.h @@ -38,7 +38,7 @@ namespace TestFileAccess { TEST_CASE("[FileAccess] CSV read") { - FileAccessRef f = FileAccess::open(TestUtils::get_data_path("translations.csv"), FileAccess::READ); + Ref<FileAccess> f = FileAccess::open(TestUtils::get_data_path("translations.csv"), FileAccess::READ); Vector<String> header = f->get_csv_line(); // Default delimiter: ",". REQUIRE(header.size() == 3); @@ -77,8 +77,6 @@ TEST_CASE("[FileAccess] CSV read") { CHECK(row5[0] == "What about"); CHECK(row5[1] == "tab separated"); CHECK(row5[2] == "lines, good?"); - - f->close(); } } // namespace TestFileAccess diff --git a/tests/core/io/test_image.h b/tests/core/io/test_image.h index dcf21dd7b0..1c778c3228 100644 --- a/tests/core/io/test_image.h +++ b/tests/core/io/test_image.h @@ -106,7 +106,7 @@ TEST_CASE("[Image] Saving and loading") { // Load BMP Ref<Image> image_bmp = memnew(Image()); - FileAccessRef f_bmp = FileAccess::open(TestUtils::get_data_path("images/icon.bmp"), FileAccess::READ, &err); + Ref<FileAccess> f_bmp = FileAccess::open(TestUtils::get_data_path("images/icon.bmp"), FileAccess::READ, &err); PackedByteArray data_bmp; data_bmp.resize(f_bmp->get_length() + 1); f_bmp->get_buffer(data_bmp.ptrw(), f_bmp->get_length()); @@ -116,7 +116,7 @@ TEST_CASE("[Image] Saving and loading") { // Load JPG Ref<Image> image_jpg = memnew(Image()); - FileAccessRef f_jpg = FileAccess::open(TestUtils::get_data_path("images/icon.jpg"), FileAccess::READ, &err); + Ref<FileAccess> f_jpg = FileAccess::open(TestUtils::get_data_path("images/icon.jpg"), FileAccess::READ, &err); PackedByteArray data_jpg; data_jpg.resize(f_jpg->get_length() + 1); f_jpg->get_buffer(data_jpg.ptrw(), f_jpg->get_length()); @@ -126,7 +126,7 @@ TEST_CASE("[Image] Saving and loading") { // Load WEBP Ref<Image> image_webp = memnew(Image()); - FileAccessRef f_webp = FileAccess::open(TestUtils::get_data_path("images/icon.webp"), FileAccess::READ, &err); + Ref<FileAccess> f_webp = FileAccess::open(TestUtils::get_data_path("images/icon.webp"), FileAccess::READ, &err); PackedByteArray data_webp; data_webp.resize(f_webp->get_length() + 1); f_webp->get_buffer(data_webp.ptrw(), f_webp->get_length()); @@ -136,7 +136,7 @@ TEST_CASE("[Image] Saving and loading") { // Load PNG Ref<Image> image_png = memnew(Image()); - FileAccessRef f_png = FileAccess::open(TestUtils::get_data_path("images/icon.png"), FileAccess::READ, &err); + Ref<FileAccess> f_png = FileAccess::open(TestUtils::get_data_path("images/icon.png"), FileAccess::READ, &err); PackedByteArray data_png; data_png.resize(f_png->get_length() + 1); f_png->get_buffer(data_png.ptrw(), f_png->get_length()); @@ -146,7 +146,7 @@ TEST_CASE("[Image] Saving and loading") { // Load TGA Ref<Image> image_tga = memnew(Image()); - FileAccessRef f_tga = FileAccess::open(TestUtils::get_data_path("images/icon.tga"), FileAccess::READ, &err); + Ref<FileAccess> f_tga = FileAccess::open(TestUtils::get_data_path("images/icon.tga"), FileAccess::READ, &err); PackedByteArray data_tga; data_tga.resize(f_tga->get_length() + 1); f_tga->get_buffer(data_tga.ptrw(), f_tga->get_length()); diff --git a/tests/core/io/test_pck_packer.h b/tests/core/io/test_pck_packer.h index 95adca6d68..d21fbdaf50 100644 --- a/tests/core/io/test_pck_packer.h +++ b/tests/core/io/test_pck_packer.h @@ -52,7 +52,7 @@ TEST_CASE("[PCKPacker] Pack an empty PCK file") { "Flushing the PCK should return an OK error code."); Error err; - FileAccessRef f = FileAccess::open(output_pck_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(output_pck_path, FileAccess::READ, &err); CHECK_MESSAGE( err == OK, "The generated empty PCK file should be opened successfully."); @@ -106,7 +106,7 @@ TEST_CASE("[PCKPacker] Pack a PCK file with some files and directories") { "Flushing the PCK should return an OK error code."); Error err; - FileAccessRef f = FileAccess::open(output_pck_path, FileAccess::READ, &err); + Ref<FileAccess> f = FileAccess::open(output_pck_path, FileAccess::READ, &err); CHECK_MESSAGE( err == OK, "The generated non-empty PCK file should be opened successfully."); diff --git a/tests/core/math/test_color.h b/tests/core/math/test_color.h index 6f40f8ecc0..51c3bc8bdc 100644 --- a/tests/core/math/test_color.h +++ b/tests/core/math/test_color.h @@ -146,8 +146,8 @@ TEST_CASE("[Color] Conversion methods") { TEST_CASE("[Color] Linear <-> sRGB conversion") { const Color color = Color(0.35, 0.5, 0.6, 0.7); - const Color color_linear = color.to_linear(); - const Color color_srgb = color.to_srgb(); + const Color color_linear = color.srgb_to_linear(); + const Color color_srgb = color.linear_to_srgb(); CHECK_MESSAGE( color_linear.is_equal_approx(Color(0.100481, 0.214041, 0.318547, 0.7)), "The color converted to linear color space should match the expected value."); @@ -155,10 +155,10 @@ TEST_CASE("[Color] Linear <-> sRGB conversion") { color_srgb.is_equal_approx(Color(0.62621, 0.735357, 0.797738, 0.7)), "The color converted to sRGB color space should match the expected value."); CHECK_MESSAGE( - color_linear.to_srgb().is_equal_approx(Color(0.35, 0.5, 0.6, 0.7)), + color_linear.linear_to_srgb().is_equal_approx(Color(0.35, 0.5, 0.6, 0.7)), "The linear color converted back to sRGB color space should match the expected value."); CHECK_MESSAGE( - color_srgb.to_linear().is_equal_approx(Color(0.35, 0.5, 0.6, 0.7)), + color_srgb.srgb_to_linear().is_equal_approx(Color(0.35, 0.5, 0.6, 0.7)), "The sRGB color converted back to linear color space should match the expected value."); } diff --git a/tests/core/math/test_geometry_3d.h b/tests/core/math/test_geometry_3d.h index 1b8d2eee34..99a4ef2d46 100644 --- a/tests/core/math/test_geometry_3d.h +++ b/tests/core/math/test_geometry_3d.h @@ -288,7 +288,7 @@ TEST_CASE("[Geometry3D] Is Point in Projected Triangle") { TEST_CASE("[Geometry3D] Does Ray Intersect Triangle") { struct Case { Vector3 from, direction, v_1, v_2, v_3; - Vector3 *result; + Vector3 *result = nullptr; bool want; Case(){}; Case(Vector3 p_from, Vector3 p_direction, Vector3 p_v_1, Vector3 p_v_2, Vector3 p_v_3, bool p_want) : @@ -390,7 +390,7 @@ TEST_CASE("[Geometry3D] Triangle and Box Overlap") { struct Case { Vector3 box_centre; Vector3 box_half_size; - Vector3 *tri_verts; + Vector3 *tri_verts = nullptr; bool want; Case(){}; Case(Vector3 p_centre, Vector3 p_half_size, Vector3 *p_verts, bool p_want) : diff --git a/tests/core/math/test_math.cpp b/tests/core/math/test_math.cpp deleted file mode 100644 index 4182455b7a..0000000000 --- a/tests/core/math/test_math.cpp +++ /dev/null @@ -1,690 +0,0 @@ -/*************************************************************************/ -/* test_math.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "test_math.h" - -#include "core/math/camera_matrix.h" -#include "core/math/delaunay_3d.h" -#include "core/math/geometry_2d.h" -#include "core/os/main_loop.h" -#include "core/os/os.h" - -namespace TestMath { - -class GetClassAndNamespace { - String code; - int idx; - int line; - String error_str; - bool error; - Variant value; - - String class_name; - - enum Token { - TK_BRACKET_OPEN, - TK_BRACKET_CLOSE, - TK_CURLY_BRACKET_OPEN, - TK_CURLY_BRACKET_CLOSE, - TK_PERIOD, - TK_COLON, - TK_COMMA, - TK_SYMBOL, - TK_IDENTIFIER, - TK_STRING, - TK_NUMBER, - TK_EOF, - TK_ERROR - }; - - Token get_token() { - while (true) { - switch (code[idx]) { - case '\n': { - line++; - idx++; - break; - }; - case 0: { - return TK_EOF; - - } break; - case '{': { - idx++; - return TK_CURLY_BRACKET_OPEN; - }; - case '}': { - idx++; - return TK_CURLY_BRACKET_CLOSE; - }; - case '[': { - idx++; - return TK_BRACKET_OPEN; - }; - case ']': { - idx++; - return TK_BRACKET_CLOSE; - }; - case ':': { - idx++; - return TK_COLON; - }; - case ',': { - idx++; - return TK_COMMA; - }; - case '.': { - idx++; - return TK_PERIOD; - }; - case '#': { - //compiler directive - while (code[idx] != '\n' && code[idx] != 0) { - idx++; - } - continue; - } break; - case '/': { - switch (code[idx + 1]) { - case '*': { // block comment - - idx += 2; - while (true) { - if (code[idx] == 0) { - error_str = "Unterminated comment"; - error = true; - return TK_ERROR; - } else if (code[idx] == '*' && code[idx + 1] == '/') { - idx += 2; - break; - } else if (code[idx] == '\n') { - line++; - } - - idx++; - } - - } break; - case '/': { // line comment skip - - while (code[idx] != '\n' && code[idx] != 0) { - idx++; - } - - } break; - default: { - value = "/"; - idx++; - return TK_SYMBOL; - } - } - - continue; // a comment - } break; - case '\'': - case '"': { - char32_t begin_str = code[idx]; - idx++; - String tk_string = String(); - while (true) { - if (code[idx] == 0) { - error_str = "Unterminated String"; - error = true; - return TK_ERROR; - } else if (code[idx] == begin_str) { - idx++; - break; - } else if (code[idx] == '\\') { - //escaped characters... - idx++; - char32_t next = code[idx]; - if (next == 0) { - error_str = "Unterminated String"; - error = true; - return TK_ERROR; - } - char32_t res = 0; - - switch (next) { - case 'b': - res = 8; - break; - case 't': - res = 9; - break; - case 'n': - res = 10; - break; - case 'f': - res = 12; - break; - case 'r': - res = 13; - break; - case '\"': - res = '\"'; - break; - case '\\': - res = '\\'; - break; - default: { - res = next; - } break; - } - - tk_string += res; - - } else { - if (code[idx] == '\n') { - line++; - } - tk_string += code[idx]; - } - idx++; - } - - value = tk_string; - - return TK_STRING; - - } break; - default: { - if (code[idx] <= 32) { - idx++; - break; - } - - if ((code[idx] >= 33 && code[idx] <= 47) || (code[idx] >= 58 && code[idx] <= 64) || (code[idx] >= 91 && code[idx] <= 96) || (code[idx] >= 123 && code[idx] <= 127)) { - value = String::chr(code[idx]); - idx++; - return TK_SYMBOL; - } - - if (code[idx] == '-' || is_digit(code[idx])) { - //a number - const char32_t *rptr; - double number = String::to_float(&code[idx], &rptr); - idx += (rptr - &code[idx]); - value = number; - return TK_NUMBER; - - } else if (is_ascii_char(code[idx]) || code[idx] > 127) { - String id; - - while (is_ascii_char(code[idx]) || code[idx] > 127) { - id += code[idx]; - idx++; - } - - value = id; - return TK_IDENTIFIER; - } else { - error_str = "Unexpected character."; - error = true; - return TK_ERROR; - } - } - } - } - } - -public: - Error parse(const String &p_code, const String &p_known_class_name = String()) { - code = p_code; - idx = 0; - line = 0; - error_str = String(); - error = false; - value = Variant(); - class_name = String(); - - bool use_next_class = false; - Token tk = get_token(); - - Map<int, String> namespace_stack; - int curly_stack = 0; - - while (!error || tk != TK_EOF) { - if (tk == TK_BRACKET_OPEN) { - tk = get_token(); - if (tk == TK_IDENTIFIER && String(value) == "ScriptClass") { - if (get_token() == TK_BRACKET_CLOSE) { - use_next_class = true; - } - } - } else if (tk == TK_IDENTIFIER && String(value) == "class") { - tk = get_token(); - if (tk == TK_IDENTIFIER) { - String name = value; - if (use_next_class || p_known_class_name == name) { - for (const KeyValue<int, String> &E : namespace_stack) { - class_name += E.value + "."; - } - class_name += String(value); - break; - } - } - - } else if (tk == TK_IDENTIFIER && String(value) == "namespace") { - String name; - int at_level = curly_stack; - while (true) { - tk = get_token(); - if (tk == TK_IDENTIFIER) { - name += String(value); - } - - tk = get_token(); - if (tk == TK_PERIOD) { - name += "."; - } else if (tk == TK_CURLY_BRACKET_OPEN) { - curly_stack++; - break; - } else { - break; //whatever else - } - } - - if (!name.is_empty()) { - namespace_stack[at_level] = name; - } - - } else if (tk == TK_CURLY_BRACKET_OPEN) { - curly_stack++; - } else if (tk == TK_CURLY_BRACKET_CLOSE) { - curly_stack--; - if (namespace_stack.has(curly_stack)) { - namespace_stack.erase(curly_stack); - } - } - - tk = get_token(); - } - - if (error) { - return ERR_PARSE_ERROR; - } - - return OK; - } - - String get_error() { - return error_str; - } - - String get_class() { - return class_name; - } -}; - -void test_vec(Plane p_vec) { - CameraMatrix cm; - cm.set_perspective(45, 1, 0, 100); - Plane v0 = cm.xform4(p_vec); - - print_line("out: " + v0); - v0.normal.z = (v0.d / 100.0 * 2.0 - 1.0) * v0.d; - print_line("out_F: " + v0); -} - -uint32_t ihash(uint32_t a) { - a = (a + 0x7ed55d16) + (a << 12); - a = (a ^ 0xc761c23c) ^ (a >> 19); - a = (a + 0x165667b1) + (a << 5); - a = (a + 0xd3a2646c) ^ (a << 9); - a = (a + 0xfd7046c5) + (a << 3); - a = (a ^ 0xb55a4f09) ^ (a >> 16); - return a; -} - -uint32_t ihash2(uint32_t a) { - a = (a ^ 61) ^ (a >> 16); - a = a + (a << 3); - a = a ^ (a >> 4); - a = a * 0x27d4eb2d; - a = a ^ (a >> 15); - return a; -} - -uint32_t ihash3(uint32_t a) { - a = (a + 0x479ab41d) + (a << 8); - a = (a ^ 0xe4aa10ce) ^ (a >> 5); - a = (a + 0x9942f0a6) - (a << 14); - a = (a ^ 0x5aedd67d) ^ (a >> 3); - a = (a + 0x17bea992) + (a << 7); - return a; -} - -MainLoop *test() { - { - Vector<Vector3> points; - points.push_back(Vector3(0, 0, 0)); - points.push_back(Vector3(0, 0, 1)); - points.push_back(Vector3(0, 1, 0)); - points.push_back(Vector3(0, 1, 1)); - points.push_back(Vector3(1, 1, 0)); - points.push_back(Vector3(1, 0, 0)); - points.push_back(Vector3(1, 0, 1)); - points.push_back(Vector3(1, 1, 1)); - - for (int i = 0; i < 800; i++) { - points.push_back(Vector3(Math::randf() * 2.0 - 1.0, Math::randf() * 2.0 - 1.0, Math::randf() * 2.0 - 1.0) * Vector3(25, 30, 33)); - } - - Vector<Delaunay3D::OutputSimplex> os = Delaunay3D::tetrahedralize(points); - print_line("simplices in the end: " + itos(os.size())); - for (int i = 0; i < os.size(); i++) { - print_line("Simplex " + itos(i) + ": "); - print_line(points[os[i].points[0]]); - print_line(points[os[i].points[1]]); - print_line(points[os[i].points[2]]); - print_line(points[os[i].points[3]]); - } - - { - FileAccessRef f = FileAccess::open("res://bsp.obj", FileAccess::WRITE); - for (int i = 0; i < os.size(); i++) { - f->store_line("o Simplex" + itos(i)); - for (int j = 0; j < 4; j++) { - f->store_line(vformat("v %f %f %f", points[os[i].points[j]].x, points[os[i].points[j]].y, points[os[i].points[j]].z)); - } - static const int face_order[4][3] = { - { 1, 2, 3 }, - { 1, 3, 4 }, - { 1, 2, 4 }, - { 2, 3, 4 } - }; - - for (int j = 0; j < 4; j++) { - f->store_line(vformat("f %d %d %d", 4 * i + face_order[j][0], 4 * i + face_order[j][1], 4 * i + face_order[j][2])); - } - } - f->close(); - } - - return nullptr; - } - - { - float r = 1; - float g = 0.5; - float b = 0.1; - - const float pow2to9 = 512.0f; - const float B = 15.0f; - const float N = 9.0f; - - float sharedexp = 65408.000f; - - float cRed = MAX(0.0f, MIN(sharedexp, r)); - float cGreen = MAX(0.0f, MIN(sharedexp, g)); - float cBlue = MAX(0.0f, MIN(sharedexp, b)); - - float cMax = MAX(cRed, MAX(cGreen, cBlue)); - - float expp = MAX(-B - 1.0f, floor(Math::log(cMax) / Math_LN2)) + 1.0f + B; - - float sMax = (float)floor((cMax / Math::pow(2.0f, expp - B - N)) + 0.5f); - - float exps = expp + 1.0f; - - if (0.0 <= sMax && sMax < pow2to9) { - exps = expp; - } - - float sRed = Math::floor((cRed / pow(2.0f, exps - B - N)) + 0.5f); - float sGreen = Math::floor((cGreen / pow(2.0f, exps - B - N)) + 0.5f); - float sBlue = Math::floor((cBlue / pow(2.0f, exps - B - N)) + 0.5f); - - print_line("R: " + rtos(sRed) + " G: " + rtos(sGreen) + " B: " + rtos(sBlue) + " EXP: " + rtos(exps)); - - uint32_t rgbe = (Math::fast_ftoi(sRed) & 0x1FF) | ((Math::fast_ftoi(sGreen) & 0x1FF) << 9) | ((Math::fast_ftoi(sBlue) & 0x1FF) << 18) | ((Math::fast_ftoi(exps) & 0x1F) << 27); - - float rb = rgbe & 0x1ff; - float gb = (rgbe >> 9) & 0x1ff; - float bb = (rgbe >> 18) & 0x1ff; - float eb = (rgbe >> 27); - float mb = Math::pow(2.0, eb - 15.0 - 9.0); - float rd = rb * mb; - float gd = gb * mb; - float bd = bb * mb; - - print_line("RGBE: " + Color(rd, gd, bd)); - } - - Vector<int> ints; - ints.resize(20); - - { - int *w; - w = ints.ptrw(); - for (int i = 0; i < ints.size(); i++) { - w[i] = i; - } - } - - Vector<int> posho = ints; - - { - const int *r = posho.ptr(); - for (int i = 0; i < posho.size(); i++) { - print_line(itos(i) + " : " + itos(r[i])); - } - } - - List<String> cmdlargs = OS::get_singleton()->get_cmdline_args(); - - if (cmdlargs.is_empty()) { - //try editor! - return nullptr; - } - - String test = cmdlargs.back()->get(); - if (test == "math") { - // Not a file name but the test name, abort. - // FIXME: This test is ugly as heck, needs fixing :) - return nullptr; - } - - FileAccess *fa = FileAccess::open(test, FileAccess::READ); - ERR_FAIL_COND_V_MSG(!fa, nullptr, "Could not open file: " + test); - - Vector<uint8_t> buf; - uint64_t flen = fa->get_length(); - buf.resize(fa->get_length() + 1); - fa->get_buffer(buf.ptrw(), flen); - buf.write[flen] = 0; - - String code; - code.parse_utf8((const char *)&buf[0]); - - GetClassAndNamespace getclass; - if (getclass.parse(code)) { - print_line("Parse error: " + getclass.get_error()); - } else { - print_line("Found class: " + getclass.get_class()); - } - - { - Vector<int> hashes; - List<StringName> tl; - ClassDB::get_class_list(&tl); - - for (const StringName &E : tl) { - Vector<uint8_t> m5b = E.operator String().md5_buffer(); - hashes.push_back(hashes.size()); - } - - for (int i = nearest_shift(hashes.size()); i < 20; i++) { - bool success = true; - for (int s = 0; s < 10000; s++) { - Set<uint32_t> existing; - success = true; - - for (int j = 0; j < hashes.size(); j++) { - uint32_t eh = ihash2(ihash3(hashes[j] + ihash(s) + s)) & ((1 << i) - 1); - if (existing.has(eh)) { - success = false; - break; - } - existing.insert(eh); - } - - if (success) { - print_line("success at " + itos(i) + "/" + itos(nearest_shift(hashes.size())) + " shift " + itos(s)); - break; - } - } - if (success) { - break; - } - } - - print_line("DONE"); - } - - { - print_line("NUM: " + itos(-128)); - } - - { - Vector3 v(1, 2, 3); - v.normalize(); - real_t a = 0.3; - - Basis m(v, a); - - Vector3 v2(7, 3, 1); - v2.normalize(); - real_t a2 = 0.8; - - Basis m2(v2, a2); - - Quaternion q = m; - Quaternion q2 = m2; - - Basis m3 = m.inverse() * m2; - Quaternion q3 = (q.inverse() * q2); //.normalized(); - - print_line(Quaternion(m3)); - print_line(q3); - - print_line("before v: " + v + " a: " + rtos(a)); - q.get_axis_angle(v, a); - print_line("after v: " + v + " a: " + rtos(a)); - } - - String ret; - - List<String> args; - args.push_back("-l"); - Error err = OS::get_singleton()->execute("/bin/ls", args, &ret); - print_line("error: " + itos(err)); - print_line(ret); - - Basis m3; - m3.rotate(Vector3(1, 0, 0), 0.2); - m3.rotate(Vector3(0, 1, 0), 1.77); - m3.rotate(Vector3(0, 0, 1), 212); - Basis m32; - m32.set_euler(m3.get_euler()); - print_line("ELEULEEEEEEEEEEEEEEEEEER: " + m3.get_euler() + " vs " + m32.get_euler()); - - { - Dictionary d; - d["momo"] = 1; - Dictionary b = d; - b["44"] = 4; - } - - print_line("inters: " + rtos(Geometry2D::segment_intersects_circle(Vector2(-5, 0), Vector2(-2, 0), Vector2(), 1.0))); - - print_line("cross: " + Vector3(1, 2, 3).cross(Vector3(4, 5, 7))); - print_line("dot: " + rtos(Vector3(1, 2, 3).dot(Vector3(4, 5, 7)))); - print_line("abs: " + Vector3(-1, 2, -3).abs()); - print_line("distance_to: " + rtos(Vector3(1, 2, 3).distance_to(Vector3(4, 5, 7)))); - print_line("distance_squared_to: " + rtos(Vector3(1, 2, 3).distance_squared_to(Vector3(4, 5, 7)))); - print_line("plus: " + (Vector3(1, 2, 3) + Vector3(Vector3(4, 5, 7)))); - print_line("minus: " + (Vector3(1, 2, 3) - Vector3(Vector3(4, 5, 7)))); - print_line("mul: " + (Vector3(1, 2, 3) * Vector3(Vector3(4, 5, 7)))); - print_line("div: " + (Vector3(1, 2, 3) / Vector3(Vector3(4, 5, 7)))); - print_line("mul scalar: " + (Vector3(1, 2, 3) * 2.0)); - print_line("premul scalar: " + (2.0 * Vector3(1, 2, 3))); - print_line("div scalar: " + (Vector3(1, 2, 3) / 3.0)); - print_line("length: " + rtos(Vector3(1, 2, 3).length())); - print_line("length squared: " + rtos(Vector3(1, 2, 3).length_squared())); - print_line("normalized: " + Vector3(1, 2, 3).normalized()); - print_line("inverse: " + Vector3(1, 2, 3).inverse()); - - { - Vector3 v(4, 5, 7); - v.normalize(); - print_line("normalize: " + v); - } - - { - Vector3 v(4, 5, 7); - v += Vector3(1, 2, 3); - print_line("+=: " + v); - } - - { - Vector3 v(4, 5, 7); - v -= Vector3(1, 2, 3); - print_line("-=: " + v); - } - - { - Vector3 v(4, 5, 7); - v *= Vector3(1, 2, 3); - print_line("*=: " + v); - } - - { - Vector3 v(4, 5, 7); - v /= Vector3(1, 2, 3); - print_line("/=: " + v); - } - - { - Vector3 v(4, 5, 7); - v *= 2.0; - print_line("scalar *=: " + v); - } - - { - Vector3 v(4, 5, 7); - v /= 2.0; - print_line("scalar /=: " + v); - } - - return nullptr; -} -} // namespace TestMath diff --git a/tests/core/math/test_math.h b/tests/core/math/test_math.h deleted file mode 100644 index a8aa8f6847..0000000000 --- a/tests/core/math/test_math.h +++ /dev/null @@ -1,41 +0,0 @@ -/*************************************************************************/ -/* test_math.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef TEST_MATH_H -#define TEST_MATH_H - -class MainLoop; - -namespace TestMath { - -MainLoop *test(); -} - -#endif diff --git a/tests/core/templates/test_oa_hash_map.cpp b/tests/core/templates/test_oa_hash_map.cpp deleted file mode 100644 index 87bf9feb83..0000000000 --- a/tests/core/templates/test_oa_hash_map.cpp +++ /dev/null @@ -1,301 +0,0 @@ -/*************************************************************************/ -/* test_oa_hash_map.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "test_oa_hash_map.h" - -#include "core/os/os.h" -#include "core/templates/oa_hash_map.h" - -namespace TestOAHashMap { - -struct CountedItem { - static int count; - - int id = -1; - bool destroyed = false; - - CountedItem() { - count++; - } - - CountedItem(int p_id) : - id(p_id) { - count++; - } - - CountedItem(const CountedItem &p_other) : - id(p_other.id) { - count++; - } - - void operator=(const CountedItem &p_other) { - id = p_other.id; - count++; - } - - ~CountedItem() { - CRASH_COND(destroyed); - count--; - destroyed = true; - } -}; - -int CountedItem::count; - -MainLoop *test() { - OS::get_singleton()->print("\n\n\nHello from test\n"); - - // test element tracking. - { - OAHashMap<int, int> map; - - map.set(42, 1337); - map.set(1337, 21); - map.set(42, 11880); - - int value = 0; - map.lookup(42, value); - - OS::get_singleton()->print("capacity %d\n", map.get_capacity()); - OS::get_singleton()->print("elements %d\n", map.get_num_elements()); - - OS::get_singleton()->print("map[42] = %d\n", value); - } - - // rehashing and deletion - { - OAHashMap<int, int> map; - - for (int i = 0; i < 500; i++) { - map.set(i, i * 2); - } - - for (int i = 0; i < 500; i += 2) { - map.remove(i); - } - - uint32_t num_elems = 0; - for (int i = 0; i < 500; i++) { - int tmp; - if (map.lookup(i, tmp) && tmp == i * 2) { - num_elems++; - } - } - - OS::get_singleton()->print("elements %d == %d.\n", map.get_num_elements(), num_elems); - } - - // iteration - { - OAHashMap<String, int> map; - - map.set("Hello", 1); - map.set("World", 2); - map.set("Godot rocks", 42); - - for (OAHashMap<String, int>::Iterator it = map.iter(); it.valid; it = map.next_iter(it)) { - OS::get_singleton()->print("map[\"%s\"] = %d\n", it.key->utf8().get_data(), *it.value); - } - } - - // stress test / test for issue #22928 - { - OAHashMap<int, int> map; - int dummy = 0; - const int N = 1000; - uint32_t *keys = new uint32_t[N]; - - Math::seed(0); - - // insert a couple of random keys (with a dummy value, which is ignored) - for (int i = 0; i < N; i++) { - keys[i] = Math::rand(); - map.set(keys[i], dummy); - - if (!map.lookup(keys[i], dummy)) { - OS::get_singleton()->print("could not find 0x%X despite it was just inserted!\n", unsigned(keys[i])); - } - } - - // check whether the keys are still present - for (int i = 0; i < N; i++) { - if (!map.lookup(keys[i], dummy)) { - OS::get_singleton()->print("could not find 0x%X despite it has been inserted previously! (not checking the other keys, breaking...)\n", unsigned(keys[i])); - break; - } - } - - delete[] keys; - } - - // regression test / test for issue related to #31402 - { - OS::get_singleton()->print("test for issue #31402 started...\n"); - - const int num_test_values = 12; - int test_values[num_test_values] = { 0, 24, 48, 72, 96, 120, 144, 168, 192, 216, 240, 264 }; - - int dummy = 0; - OAHashMap<int, int> map; - map.clear(); - - for (int i = 0; i < num_test_values; ++i) { - map.set(test_values[i], dummy); - } - - OS::get_singleton()->print("test for issue #31402 passed.\n"); - } - - // test collision resolution, should not crash or run indefinitely - { - OAHashMap<int, int> map(4); - map.set(1, 1); - map.set(5, 1); - map.set(9, 1); - map.set(13, 1); - map.remove(5); - map.remove(9); - map.remove(13); - map.set(5, 1); - } - - // test memory management of items, should not crash or leak items - { - // Exercise different patterns of removal - for (int i = 0; i < 4; ++i) { - { - OAHashMap<String, CountedItem> map; - int id = 0; - for (int j = 0; j < 100; ++j) { - map.insert(itos(j), CountedItem(id)); - } - if (i <= 1) { - for (int j = 0; j < 100; ++j) { - map.remove(itos(j)); - } - } - if (i % 2 == 0) { - map.clear(); - } - } - - if (CountedItem::count != 0) { - OS::get_singleton()->print("%d != 0 (not performing the other test sub-cases, breaking...)\n", CountedItem::count); - break; - } - } - } - - // Test map with 0 capacity. - { - OAHashMap<int, String> original_map(0); - original_map.set(1, "1"); - OS::get_singleton()->print("OAHashMap 0 capacity initialization passed.\n"); - } - - // Test copy constructor. - { - OAHashMap<int, String> original_map; - original_map.set(1, "1"); - original_map.set(2, "2"); - original_map.set(3, "3"); - original_map.set(4, "4"); - original_map.set(5, "5"); - - OAHashMap<int, String> map_copy(original_map); - - bool pass = true; - for ( - OAHashMap<int, String>::Iterator it = original_map.iter(); - it.valid; - it = original_map.next_iter(it)) { - if (map_copy.lookup_ptr(*it.key) == nullptr) { - pass = false; - } - if (*it.value != *map_copy.lookup_ptr(*it.key)) { - pass = false; - } - } - if (pass) { - OS::get_singleton()->print("OAHashMap copy constructor test passed.\n"); - } else { - OS::get_singleton()->print("OAHashMap copy constructor test FAILED.\n"); - } - - map_copy.set(1, "Random String"); - if (*map_copy.lookup_ptr(1) == *original_map.lookup_ptr(1)) { - OS::get_singleton()->print("OAHashMap copy constructor, atomic copy test FAILED.\n"); - } else { - OS::get_singleton()->print("OAHashMap copy constructor, atomic copy test passed.\n"); - } - } - - // Test assign operator. - { - OAHashMap<int, String> original_map; - original_map.set(1, "1"); - original_map.set(2, "2"); - original_map.set(3, "3"); - original_map.set(4, "4"); - original_map.set(5, "5"); - - OAHashMap<int, String> map_copy(100000); - map_copy.set(1, "Just a string."); - map_copy = original_map; - - bool pass = true; - for ( - OAHashMap<int, String>::Iterator it = map_copy.iter(); - it.valid; - it = map_copy.next_iter(it)) { - if (original_map.lookup_ptr(*it.key) == nullptr) { - pass = false; - } - if (*it.value != *original_map.lookup_ptr(*it.key)) { - pass = false; - } - } - if (pass) { - OS::get_singleton()->print("OAHashMap assign operation test passed.\n"); - } else { - OS::get_singleton()->print("OAHashMap assign operation test FAILED.\n"); - } - - map_copy.set(1, "Random String"); - if (*map_copy.lookup_ptr(1) == *original_map.lookup_ptr(1)) { - OS::get_singleton()->print("OAHashMap assign operation atomic copy test FAILED.\n"); - } else { - OS::get_singleton()->print("OAHashMap assign operation atomic copy test passed.\n"); - } - } - - return nullptr; -} -} // namespace TestOAHashMap diff --git a/tests/scene/test_gui.cpp b/tests/scene/test_gui.cpp deleted file mode 100644 index cd5624b70c..0000000000 --- a/tests/scene/test_gui.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/*************************************************************************/ -/* test_gui.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef _3D_DISABLED - -#include "test_gui.h" - -#include "scene/gui/button.h" -#include "scene/gui/label.h" -#include "scene/gui/line_edit.h" -#include "scene/gui/menu_button.h" -#include "scene/gui/option_button.h" -#include "scene/gui/panel.h" -#include "scene/gui/progress_bar.h" -#include "scene/gui/rich_text_label.h" -#include "scene/gui/scroll_bar.h" -#include "scene/gui/spin_box.h" -#include "scene/gui/tab_container.h" -#include "scene/gui/tree.h" - -namespace TestGUI { - -class TestMainLoop : public SceneTree { -public: - virtual void request_quit() { - quit(); - } - virtual void initialize() { - SceneTree::initialize(); - - Panel *frame = memnew(Panel); - frame->set_anchor(SIDE_RIGHT, Control::ANCHOR_END); - frame->set_anchor(SIDE_BOTTOM, Control::ANCHOR_END); - frame->set_end(Point2(0, 0)); - - Ref<Theme> t = memnew(Theme); - frame->set_theme(t); - - get_root()->add_child(frame); - - Label *label = memnew(Label); - - label->set_position(Point2(80, 90)); - label->set_size(Point2(170, 80)); - label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_FILL); - label->set_text("There was once upon a time a beautiful unicorn that loved to play with little girls..."); - - frame->add_child(label); - - Button *button = memnew(Button); - - button->set_position(Point2(20, 20)); - button->set_size(Point2(1, 1)); - button->set_text("This is a biggie button"); - - frame->add_child(button); - - Tree *tree = memnew(Tree); - tree->set_columns(2); - - tree->set_position(Point2(230, 210)); - tree->set_size(Point2(150, 250)); - - TreeItem *item = tree->create_item(); - item->set_editable(0, true); - item->set_text(0, "root"); - item = tree->create_item(tree->get_root()); - item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK); - item->set_editable(0, true); - item->set_text(0, "check"); - item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK); - item->set_editable(1, true); - item->set_text(1, "check2"); - item = tree->create_item(tree->get_root()); - item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE); - item->set_editable(0, true); - item->set_range_config(0, 0, 20, 0.1); - item->set_range(0, 2); - item->add_button(0, Theme::get_default()->get_icon("folder", "FileDialog")); - item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE); - item->set_editable(1, true); - item->set_range_config(1, 0, 20, 0.1); - item->set_range(1, 3); - - item = tree->create_item(tree->get_root()); - item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE); - item->set_editable(0, true); - item->set_text(0, "Have,Many,Several,Options!"); - item->set_range(0, 2); - - item = tree->create_item(item); - item->set_editable(0, true); - item->set_text(0, "Gershwin!"); - - frame->add_child(tree); - - LineEdit *line_edit = memnew(LineEdit); - - line_edit->set_position(Point2(30, 190)); - line_edit->set_size(Point2(180, 1)); - - frame->add_child(line_edit); - - HScrollBar *hscroll = memnew(HScrollBar); - - hscroll->set_position(Point2(30, 290)); - hscroll->set_size(Point2(180, 1)); - hscroll->set_max(10); - hscroll->set_page(4); - - frame->add_child(hscroll); - - SpinBox *spin = memnew(SpinBox); - - spin->set_position(Point2(30, 260)); - spin->set_size(Point2(120, 1)); - - frame->add_child(spin); - hscroll->share(spin); - - ProgressBar *progress = memnew(ProgressBar); - - progress->set_position(Point2(30, 330)); - progress->set_size(Point2(120, 1)); - - frame->add_child(progress); - hscroll->share(progress); - - MenuButton *menu_button = memnew(MenuButton); - - menu_button->set_text("I'm a menu!"); - menu_button->set_position(Point2(30, 380)); - menu_button->set_size(Point2(1, 1)); - - frame->add_child(menu_button); - - PopupMenu *popup = menu_button->get_popup(); - - popup->add_item("Hello, testing"); - popup->add_item("My Dearest"); - popup->add_separator(); - popup->add_item("Popup"); - popup->add_check_item("Check Popup"); - popup->set_item_checked(4, true); - popup->add_separator(); - popup->add_radio_check_item("Option A"); - popup->set_item_checked(6, true); - popup->add_radio_check_item("Option B"); - - OptionButton *options = memnew(OptionButton); - - options->add_item("Hello, testing"); - options->add_item("My Dearest"); - - options->set_position(Point2(230, 180)); - options->set_size(Point2(1, 1)); - - frame->add_child(options); - - RichTextLabel *richtext = memnew(RichTextLabel); - - richtext->set_position(Point2(600, 210)); - richtext->set_size(Point2(180, 250)); - richtext->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -20); - - frame->add_child(richtext); - - richtext->add_text("Hello, My Friends!\n\nWelcome to the amazing world of "); - - richtext->add_newline(); - richtext->add_newline(); - - richtext->push_color(Color(1, 0.5, 0.5)); - richtext->add_text("leprechauns"); - richtext->pop(); - - richtext->add_text(" and "); - richtext->push_color(Color(0, 1.0, 0.5)); - richtext->add_text("faeries.\n"); - richtext->pop(); - richtext->add_text("In this new episode, we will attempt to "); - richtext->push_font(richtext->get_theme_font(SNAME("mono_font"), SNAME("Fonts"))); - richtext->push_color(Color(0.7, 0.5, 1.0)); - richtext->add_text("deliver something nice"); - richtext->pop(); - richtext->pop(); - richtext->add_text(" to all the viewers! Unfortunately, I need to "); - richtext->push_underline(); - richtext->add_text("keep writing a lot of text"); - richtext->pop(); - richtext->add_text(" so the label control overflows and the scrollbar appears.\n"); - richtext->push_meta("http://www.scrollingcapabilities.xz"); - richtext->add_text("This allows to test for the scrolling capabilities "); - richtext->pop(); - richtext->add_text("of the rich text label for huge text (not like this text will really be huge but, you know).\nAs long as it is so long that it will work nicely for a test/demo, then it's welcomed in my book...\nChanging subject, the day is cloudy today and I'm wondering if I'll get che chance to travel somewhere nice. Sometimes, watching the clouds from satellite images may give a nice insight about how pressure zones in our planet work, although it also makes it pretty obvious to see why most weather forecasts get it wrong so often.\nClouds are so difficult to predict!\nBut it's pretty cool how our civilization has adapted to having water falling from the sky each time it rains..."); - - TabContainer *tabc = memnew(TabContainer); - - Control *ctl = memnew(Control); - ctl->set_name("tab 1"); - tabc->add_child(ctl); - - ctl = memnew(Control); - ctl->set_name("tab 2"); - tabc->add_child(ctl); - label = memnew(Label); - label->set_text("Some Label"); - label->set_position(Point2(20, 20)); - ctl->add_child(label); - - ctl = memnew(Control); - ctl->set_name("tab 3"); - button = memnew(Button); - button->set_text("Some Button"); - button->set_position(Point2(30, 50)); - ctl->add_child(button); - - tabc->add_child(ctl); - - frame->add_child(tabc); - - tabc->set_position(Point2(400, 210)); - tabc->set_size(Point2(180, 250)); - } -}; - -MainLoop *test() { - return memnew(TestMainLoop); -} -} // namespace TestGUI - -#endif // _3D_DISABLED diff --git a/tests/servers/test_physics_2d.cpp b/tests/servers/test_physics_2d.cpp deleted file mode 100644 index 138412ec09..0000000000 --- a/tests/servers/test_physics_2d.cpp +++ /dev/null @@ -1,374 +0,0 @@ -/*************************************************************************/ -/* test_physics_2d.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "test_physics_2d.h" - -#include "core/os/main_loop.h" -#include "servers/physics_server_2d.h" -#include "servers/rendering_server.h" - -static const unsigned char convex_png[] = { - 0x89, 0x50, 0x4e, 0x47, 0xd, 0xa, 0x1a, 0xa, 0x0, 0x0, 0x0, 0xd, 0x49, 0x48, 0x44, 0x52, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x40, 0x8, 0x6, 0x0, 0x0, 0x0, 0xaa, 0x69, 0x71, 0xde, 0x0, 0x0, 0x0, 0x1, 0x73, 0x52, 0x47, 0x42, 0x0, 0xae, 0xce, 0x1c, 0xe9, 0x0, 0x0, 0x0, 0x6, 0x62, 0x4b, 0x47, 0x44, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf9, 0x43, 0xbb, 0x7f, 0x0, 0x0, 0x0, 0x9, 0x70, 0x48, 0x59, 0x73, 0x0, 0x0, 0xb, 0x13, 0x0, 0x0, 0xb, 0x13, 0x1, 0x0, 0x9a, 0x9c, 0x18, 0x0, 0x0, 0x0, 0x7, 0x74, 0x49, 0x4d, 0x45, 0x7, 0xdb, 0x6, 0xa, 0x3, 0x13, 0x31, 0x66, 0xa7, 0xac, 0x79, 0x0, 0x0, 0x4, 0xef, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0xed, 0x9b, 0xdd, 0x4e, 0x2a, 0x57, 0x14, 0xc7, 0xf7, 0x1e, 0xc0, 0x19, 0x38, 0x32, 0x80, 0xa, 0x6a, 0xda, 0x18, 0xa3, 0xc6, 0x47, 0x50, 0x7b, 0xa1, 0xd9, 0x36, 0x27, 0x7e, 0x44, 0xed, 0x45, 0x4d, 0x93, 0x3e, 0x40, 0x1f, 0x64, 0x90, 0xf4, 0x1, 0xbc, 0xf0, 0xc2, 0x9c, 0x57, 0x30, 0x4d, 0xbc, 0xa8, 0x6d, 0xc, 0x69, 0x26, 0xb5, 0x68, 0x8b, 0x35, 0x7e, 0x20, 0xb4, 0xf5, 0x14, 0xbf, 0x51, 0x3c, 0x52, 0xe, 0xc, 0xe, 0xc8, 0xf0, 0xb1, 0x7a, 0x51, 0x3d, 0xb1, 0x9e, 0x19, 0x1c, 0x54, 0x70, 0x1c, 0xdc, 0x9, 0x17, 0x64, 0x8, 0xc9, 0xff, 0xb7, 0xd6, 0x7f, 0xcd, 0x3f, 0x2b, 0xd9, 0x8, 0xbd, 0x9c, 0xda, 0x3e, 0xf8, 0x31, 0xff, 0xc, 0x0, 0x8, 0x42, 0x88, 0x9c, 0x9f, 0x9f, 0xbf, 0xa, 0x87, 0xc3, 0xad, 0x7d, 0x7d, 0x7d, 0x7f, 0x23, 0x84, 0x78, 0x8c, 0x31, 0xaf, 0x55, 0x0, 0xc6, 0xc7, 0x14, 0x1e, 0x8f, 0xc7, 0xbf, 0x38, 0x3c, 0x3c, 0x6c, 0x9b, 0x9f, 0x9f, 0x6f, 0xb8, 0x82, 0x9b, 0xee, 0xe8, 0xe8, 0xf8, 0x12, 0x0, 0xbe, 0xd3, 0x2a, 0x8, 0xfc, 0x50, 0xd1, 0xf9, 0x7c, 0x9e, 0x8a, 0x46, 0xa3, 0x5f, 0x9d, 0x9e, 0x9e, 0x7e, 0xb2, 0xb0, 0xb0, 0x60, 0xe5, 0x79, 0x1e, 0xf1, 0xfc, 0x7f, 0x3a, 0x9, 0x21, 0x88, 0x10, 0x82, 0x26, 0x26, 0x26, 0xde, 0x77, 0x75, 0x75, 0x85, 0x59, 0x96, 0xfd, 0x5e, 0x6b, 0x20, 0xf0, 0x7d, 0x85, 0x4b, 0x92, 0xf4, 0xfa, 0xe0, 0xe0, 0xe0, 0xd3, 0xb9, 0xb9, 0xb9, 0x46, 0x49, 0x92, 0xea, 0x6f, 0xa, 0xbf, 0x7d, 0x8, 0x21, 0x68, 0x70, 0x70, 0xb0, 0x38, 0x39, 0x39, 0x79, 0xd6, 0xd9, 0xd9, 0xb9, 0xcf, 0x30, 0xcc, 0xa2, 0xd6, 0xad, 0x21, 0x2b, 0x1c, 0x0, 0x38, 0x41, 0x10, 0xfc, 0xdb, 0xdb, 0xdb, 0x27, 0x1e, 0x8f, 0x27, 0x4b, 0x8, 0x1, 0x84, 0x90, 0xea, 0xf, 0x21, 0x4, 0x3c, 0x1e, 0x4f, 0x76, 0x67, 0x67, 0x67, 0x3f, 0x9f, 0xcf, 0xff, 0x7c, 0x5, 0xf3, 0xd9, 0x0, 0xe0, 0x2, 0x81, 0xc0, 0xa9, 0xdb, 0xed, 0x2e, 0x94, 0x2b, 0x5c, 0xe, 0xc4, 0xca, 0xca, 0x8a, 0x18, 0x8d, 0x46, 0x3, 0x0, 0xc0, 0x69, 0x1e, 0x4, 0x0, 0x90, 0x48, 0x24, 0x12, 0xe4, 0x38, 0xee, 0x41, 0xc2, 0x6f, 0x43, 0xe0, 0x38, 0xe, 0xfc, 0x7e, 0xbf, 0x10, 0x8b, 0xc5, 0xd6, 0x35, 0xd, 0x22, 0x9b, 0xcd, 0x7a, 0x96, 0x97, 0x97, 0x33, 0xf, 0xad, 0x7c, 0x29, 0x10, 0x9b, 0x9b, 0x9b, 0xef, 0x2e, 0x2e, 0x2e, 0x7e, 0xd5, 0x1c, 0x8, 0x0, 0x20, 0xe1, 0x70, 0x38, 0xfc, 0x98, 0xd5, 0x57, 0x2, 0xe1, 0x76, 0xbb, 0xf3, 0xa1, 0x50, 0xe8, 0x38, 0x9b, 0xcd, 0xfe, 0xa2, 0x9, 0x8, 0x0, 0x40, 0x2e, 0x2f, 0x2f, 0x7d, 0x4b, 0x4b, 0x4b, 0xb9, 0x4a, 0x54, 0x5f, 0x9, 0xc4, 0xd2, 0xd2, 0x92, 0xb4, 0xb7, 0xb7, 0xf7, 0x36, 0x97, 0xcb, 0x4d, 0x3d, 0x29, 0x8, 0x0, 0xe0, 0x42, 0xa1, 0xd0, 0x71, 0xb5, 0xc4, 0xdf, 0xb6, 0xc5, 0x93, 0xe, 0x4a, 0x0, 0x20, 0xa9, 0x54, 0xea, 0x37, 0xb7, 0xdb, 0x5d, 0xa8, 0xa6, 0x78, 0x39, 0x10, 0x6b, 0x6b, 0x6b, 0xf1, 0x64, 0x32, 0xb9, 0x5a, 0x55, 0x10, 0x0, 0xc0, 0x6d, 0x6c, 0x6c, 0x9c, 0x57, 0xbb, 0xfa, 0x25, 0x40, 0x14, 0x3, 0x81, 0x40, 0x34, 0x93, 0xc9, 0x2c, 0x57, 0x1c, 0x4, 0x0, 0x90, 0x58, 0x2c, 0xb6, 0x5e, 0xe9, 0xc1, 0x77, 0x1f, 0x10, 0x53, 0x53, 0x53, 0x52, 0xc5, 0x83, 0x14, 0x0, 0x70, 0x7e, 0xbf, 0x5f, 0xd0, 0x42, 0xf5, 0x95, 0x40, 0xf8, 0x7c, 0xbe, 0xcb, 0xa3, 0xa3, 0xa3, 0x3f, 0x1e, 0xbd, 0x1b, 0x0, 0x80, 0x1c, 0x1f, 0x1f, 0x87, 0xb4, 0x56, 0xfd, 0xaa, 0x5, 0x29, 0x51, 0x14, 0xbf, 0xf5, 0xf9, 0x7c, 0x97, 0x5a, 0xad, 0xbe, 0x12, 0x88, 0xf5, 0xf5, 0xf5, 0xd8, 0x83, 0x83, 0x54, 0xb5, 0x42, 0x8f, 0x66, 0x83, 0x94, 0xd6, 0xbd, 0x5f, 0xce, 0x7c, 0x38, 0x3c, 0x3c, 0xfc, 0xb3, 0x50, 0x28, 0xb8, 0xcb, 0x2, 0x1, 0x0, 0xdc, 0xf4, 0xf4, 0xf4, 0xfe, 0x73, 0x15, 0x2f, 0x17, 0xa4, 0x22, 0x91, 0x48, 0x50, 0xb5, 0x2d, 0x0, 0x80, 0x9b, 0x99, 0x99, 0x79, 0xfb, 0xdc, 0x1, 0xc8, 0x5, 0xa9, 0x44, 0x22, 0xf1, 0xfb, 0x9d, 0x10, 0x0, 0x80, 0x9b, 0x9d, 0x9d, 0xd, 0xea, 0x5, 0xc0, 0xad, 0xfd, 0x43, 0x1a, 0x0, 0xb8, 0xdb, 0x9a, 0xa9, 0x8f, 0xb6, 0xa4, 0x46, 0xa3, 0xa4, 0xb7, 0xd5, 0x37, 0xcf, 0xf3, 0x68, 0x75, 0x75, 0xf5, 0x4c, 0xee, 0x99, 0x1c, 0x80, 0x9c, 0x1e, 0xf7, 0xff, 0x16, 0x8b, 0x45, 0x50, 0x5, 0xa0, 0xb7, 0xb7, 0xb7, 0x85, 0x10, 0xa2, 0x2b, 0xf1, 0x84, 0x10, 0xd4, 0xdf, 0xdf, 0x6f, 0x57, 0x3, 0x80, 0x37, 0x18, 0xc, 0x5, 0x3d, 0x2, 0xa0, 0x69, 0x3a, 0x8b, 0x10, 0xe2, 0x4b, 0x2, 0xc0, 0x18, 0xf3, 0xc1, 0x60, 0x70, 0x47, 0x8f, 0x16, 0x38, 0x3a, 0x3a, 0x5a, 0x93, 0x5b, 0xc3, 0x7f, 0x64, 0x81, 0xba, 0xba, 0x3a, 0x49, 0x8f, 0x0, 0x1a, 0x1a, 0x1a, 0xd4, 0xcd, 0x0, 0x93, 0xc9, 0xa4, 0xcb, 0x21, 0xe8, 0x74, 0x3a, 0xd5, 0x1, 0xa0, 0x69, 0x5a, 0x77, 0x1d, 0x80, 0x31, 0x2e, 0x38, 0x9d, 0x4e, 0xb1, 0x66, 0x1, 0x30, 0xc, 0x23, 0x28, 0x3d, 0x93, 0x9b, 0x1, 0xb9, 0x9a, 0x6, 0x60, 0x36, 0x9b, 0x75, 0xd7, 0x1, 0x4a, 0x21, 0xa8, 0x26, 0x0, 0x94, 0xa, 0x41, 0xb2, 0x0, 0x18, 0x86, 0xc9, 0xe9, 0xd, 0x80, 0x52, 0x8, 0x92, 0x5, 0x60, 0xb1, 0x58, 0x74, 0x67, 0x1, 0xa5, 0x10, 0xa4, 0x4, 0x40, 0x77, 0x43, 0xd0, 0xe1, 0x70, 0xa8, 0x9f, 0x1, 0x14, 0x45, 0x1, 0x45, 0x51, 0x79, 0x3d, 0x1, 0x68, 0x6e, 0x6e, 0x4e, 0xaa, 0x6, 0x80, 0x10, 0x42, 0x6, 0x83, 0x41, 0x37, 0x36, 0x28, 0x15, 0x82, 0x6a, 0x2, 0x0, 0x4d, 0xd3, 0xa9, 0x52, 0xcf, 0x95, 0x0, 0xe8, 0x66, 0xe, 0x98, 0xcd, 0x66, 0xa1, 0x6c, 0x0, 0x7a, 0x5a, 0x8b, 0x59, 0x2c, 0x96, 0x64, 0xcd, 0x2, 0xb8, 0x2b, 0x4, 0xe9, 0xde, 0x2, 0x77, 0x85, 0xa0, 0x9a, 0xb0, 0x40, 0xa9, 0x10, 0xa4, 0x8, 0xc0, 0x64, 0x32, 0xe9, 0x6, 0x40, 0xa9, 0x10, 0x54, 0xaa, 0x3, 0x74, 0xf3, 0x16, 0x70, 0xb9, 0x5c, 0xe5, 0x3, 0xe8, 0xe9, 0xe9, 0x69, 0xd5, 0xc3, 0x66, 0x18, 0x63, 0x5c, 0x68, 0x6a, 0x6a, 0x12, 0xcb, 0x5, 0xa0, 0x9b, 0xd5, 0x38, 0x4d, 0xd3, 0x29, 0x8a, 0xa2, 0xa0, 0x2c, 0x0, 0x18, 0x63, 0x3e, 0x14, 0xa, 0xfd, 0x55, 0xb, 0x21, 0x48, 0xd1, 0x2, 0x7a, 0x59, 0x8d, 0xdf, 0x1b, 0x80, 0x1e, 0x56, 0xe3, 0x84, 0x10, 0x34, 0x30, 0x30, 0x60, 0xbb, 0xeb, 0x77, 0x46, 0x5, 0xef, 0x48, 0xcf, 0x4d, 0xec, 0x8d, 0x99, 0x5, 0xf5, 0xf5, 0xf5, 0xef, 0x46, 0x47, 0x47, 0xb, 0x2e, 0x97, 0xeb, 0xbc, 0x54, 0x8, 0x52, 0x4, 0xc0, 0x30, 0x8c, 0xf4, 0x5c, 0x4, 0x9b, 0x4c, 0xa6, 0xf4, 0xf8, 0xf8, 0xb8, 0xc8, 0xb2, 0x6c, 0x32, 0x9d, 0x4e, 0xff, 0xd4, 0xdd, 0xdd, 0x7d, 0x66, 0x34, 0x1a, 0x8b, 0xd7, 0x3, 0xfd, 0xae, 0x5b, 0x29, 0xb2, 0x57, 0x66, 0xb6, 0xb6, 0xb6, 0xde, 0xc4, 0xe3, 0xf1, 0x6f, 0xae, 0xaf, 0xc1, 0x28, 0x5d, 0x85, 0x79, 0x2, 0xc1, 0x60, 0xb5, 0x5a, 0xa3, 0xa3, 0xa3, 0xa3, 0x45, 0xab, 0xd5, 0x9a, 0x2a, 0x16, 0x8b, 0x8b, 0x6d, 0x6d, 0x6d, 0xef, 0xd5, 0x8a, 0x55, 0xd, 0x20, 0x91, 0x48, 0xbc, 0x3e, 0x38, 0x38, 0xf8, 0xda, 0x6e, 0xb7, 0xf7, 0x5f, 0x5c, 0x5c, 0xd4, 0x7b, 0xbd, 0xde, 0xbc, 0x20, 0x8, 0xcd, 0x85, 0x42, 0x81, 0xfe, 0xf0, 0xae, 0xac, 0x10, 0x98, 0x9b, 0xd5, 0xc5, 0x18, 0x17, 0x59, 0x96, 0x3d, 0x1d, 0x19, 0x19, 0x1, 0x96, 0x65, 0x5, 0x8a, 0xa2, 0x7e, 0x6c, 0x69, 0x69, 0x49, 0x3d, 0x44, 0xb0, 0x2a, 0x0, 0x1f, 0xcc, 0x74, 0x75, 0x41, 0xea, 0xfa, 0x7b, 0x32, 0x99, 0x64, 0x76, 0x77, 0x77, 0x5d, 0xe, 0x87, 0xa3, 0x5f, 0x14, 0xc5, 0x57, 0x57, 0x60, 0x5a, 0x8b, 0xc5, 0xa2, 0xf1, 0xbe, 0x50, 0x6e, 0xa, 0x66, 0x18, 0x26, 0x31, 0x36, 0x36, 0x96, 0x65, 0x59, 0x36, 0x29, 0x49, 0x92, 0xb7, 0xbd, 0xbd, 0xfd, 0x9f, 0x72, 0xda, 0xf9, 0xd1, 0x1, 0xa8, 0x1, 0x93, 0xcf, 0xe7, 0xa9, 0x93, 0x93, 0x13, 0x1b, 0x4d, 0xd3, 0x9f, 0xb, 0x82, 0x60, 0xf5, 0x7a, 0xbd, 0xd9, 0x54, 0x2a, 0xe5, 0xcc, 0x64, 0x32, 0xe, 0xb9, 0x6e, 0xb9, 0x16, 0x8c, 0x31, 0x2e, 0xda, 0x6c, 0xb6, 0xc8, 0xd0, 0xd0, 0x10, 0x65, 0xb3, 0xd9, 0x92, 0x95, 0xa8, 0x6e, 0xc5, 0x0, 0xa8, 0xe9, 0x96, 0x68, 0x34, 0x6a, 0xdd, 0xdf, 0xdf, 0x6f, 0x76, 0xb9, 0x5c, 0x9f, 0x89, 0xa2, 0x58, 0xbf, 0xb8, 0xb8, 0x8, 0x26, 0x93, 0x29, 0x3b, 0x3c, 0x3c, 0x8c, 0xed, 0x76, 0x7b, 0xd2, 0x68, 0x34, 0xfe, 0xd0, 0xd8, 0xd8, 0x98, 0xae, 0xb6, 0xe0, 0x8a, 0x1, 0x50, 0xb, 0xe6, 0xa9, 0x5, 0xbf, 0x9c, 0x97, 0xf3, 0xff, 0xf3, 0x2f, 0x6a, 0x82, 0x7f, 0xf6, 0x4e, 0xca, 0x1b, 0xf5, 0x0, 0x0, 0x0, 0x0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82 -}; - -class TestPhysics2DMainLoop : public MainLoop { - GDCLASS(TestPhysics2DMainLoop, MainLoop); - - RID circle_img; - RID circle_shape; - RID space; - RID canvas; - RID ray; - RID ray_query; - Transform2D view_xform; - - Vector2 ray_from, ray_to; - - struct BodyShapeData { - RID image; - RID shape; - }; - - BodyShapeData body_shape_data[8]; - - void _create_body_shape_data() { - RenderingServer *vs = RenderingServer::get_singleton(); - PhysicsServer2D *ps = PhysicsServer2D::get_singleton(); - - // SEGMENT - - { - Vector<uint8_t> pixels; - pixels.resize(32 * 2 * 2); - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 32; j++) { - pixels.set(i * 32 * 2 + j * 2 + 0, (j == 0) ? 255 : 0); - pixels.set(i * 32 * 2 + j * 2 + 1, 255); - } - } - - Ref<Image> image = memnew(Image(32, 2, 0, Image::FORMAT_LA8, pixels)); - - body_shape_data[PhysicsServer2D::SHAPE_SEGMENT].image = vs->texture_2d_create(image); - - RID segment_shape = ps->segment_shape_create(); - Rect2 sg(Point2(-16, 0), Point2(16, 0)); - ps->shape_set_data(segment_shape, sg); - - body_shape_data[PhysicsServer2D::SHAPE_SEGMENT].shape = segment_shape; - } - - // CIRCLE - - { - Vector<uint8_t> pixels; - pixels.resize(32 * 32 * 2); - for (int i = 0; i < 32; i++) { - for (int j = 0; j < 32; j++) { - bool black = Vector2(i - 16, j - 16).length_squared() < 16 * 16; - - pixels.set(i * 32 * 2 + j * 2 + 0, (i == 16 || j == 16) ? 255 : 0); - pixels.set(i * 32 * 2 + j * 2 + 1, black ? 255 : 0); - } - } - - Ref<Image> image = memnew(Image(32, 32, 0, Image::FORMAT_LA8, pixels)); - - body_shape_data[PhysicsServer2D::SHAPE_CIRCLE].image = vs->texture_2d_create(image); - - RID circle_shape = ps->circle_shape_create(); - ps->shape_set_data(circle_shape, 16); - - body_shape_data[PhysicsServer2D::SHAPE_CIRCLE].shape = circle_shape; - } - - // BOX - - { - Vector<uint8_t> pixels; - pixels.resize(32 * 32 * 2); - for (int i = 0; i < 32; i++) { - for (int j = 0; j < 32; j++) { - bool black = i > 0 && i < 31 && j > 0 && j < 31; - - pixels.set(i * 32 * 2 + j * 2 + 0, black ? 0 : 255); - pixels.set(i * 32 * 2 + j * 2 + 1, 255); - } - } - - Ref<Image> image = memnew(Image(32, 32, 0, Image::FORMAT_LA8, pixels)); - - body_shape_data[PhysicsServer2D::SHAPE_RECTANGLE].image = vs->texture_2d_create(image); - - RID rectangle_shape = ps->rectangle_shape_create(); - ps->shape_set_data(rectangle_shape, Vector2(16, 16)); - - body_shape_data[PhysicsServer2D::SHAPE_RECTANGLE].shape = rectangle_shape; - } - - // CAPSULE - - { - Vector<uint8_t> pixels; - pixels.resize(32 * 64 * 2); - for (int i = 0; i < 64; i++) { - for (int j = 0; j < 32; j++) { - int si = i > 48 ? i - 32 : (i < 16 ? i : 16); - bool black = Vector2(si - 16, j - 16).length_squared() < 16 * 16; - - pixels.set(i * 32 * 2 + j * 2 + 0, (i == 16 || j == 16 || i == 48) ? 255 : 0); - pixels.set(i * 32 * 2 + j * 2 + 1, black ? 255 : 0); - } - } - - Ref<Image> image = memnew(Image(32, 64, 0, Image::FORMAT_LA8, pixels)); - - body_shape_data[PhysicsServer2D::SHAPE_CAPSULE].image = vs->texture_2d_create(image); - - RID capsule_shape = ps->capsule_shape_create(); - ps->shape_set_data(capsule_shape, Vector2(16, 32)); - - body_shape_data[PhysicsServer2D::SHAPE_CAPSULE].shape = capsule_shape; - } - - // CONVEX - - { - Ref<Image> image = memnew(Image(convex_png)); - - body_shape_data[PhysicsServer2D::SHAPE_CONVEX_POLYGON].image = vs->texture_2d_create(image); - - RID convex_polygon_shape = ps->convex_polygon_shape_create(); - - Vector<Vector2> arr; - Point2 sb(32, 32); - arr.push_back(Point2(20, 3) - sb); - arr.push_back(Point2(58, 23) - sb); - arr.push_back(Point2(55, 54) - sb); - arr.push_back(Point2(27, 60) - sb); - arr.push_back(Point2(5, 56) - sb); - arr.push_back(Point2(4, 20) - sb); - arr.push_back(Point2(11, 7) - sb); - ps->shape_set_data(convex_polygon_shape, arr); - - body_shape_data[PhysicsServer2D::SHAPE_CONVEX_POLYGON].shape = convex_polygon_shape; - } - } - - void _do_ray_query() { - // FIXME: Do something? - } - -protected: - void input_event(const Ref<InputEvent> &p_event) { - Ref<InputEventMouseButton> mb = p_event; - - if (mb.is_valid()) { - if (mb->is_pressed()) { - Point2 p = mb->get_position(); - - if (mb->get_button_index() == MouseButton::LEFT) { - ray_to = p; - _do_ray_query(); - } else if (mb->get_button_index() == MouseButton::RIGHT) { - ray_from = p; - _do_ray_query(); - } - } - } - - Ref<InputEventMouseMotion> mm = p_event; - - if (mm.is_valid()) { - Point2 p = mm->get_position(); - - if ((mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE) { - ray_to = p; - _do_ray_query(); - } else if ((mm->get_button_mask() & MouseButton::MASK_RIGHT) != MouseButton::NONE) { - ray_from = p; - _do_ray_query(); - } - } - } - - RID _add_body(PhysicsServer2D::ShapeType p_shape, const Transform2D &p_xform) { - RenderingServer *vs = RenderingServer::get_singleton(); - PhysicsServer2D *ps = PhysicsServer2D::get_singleton(); - - RID body = ps->body_create(); - ps->body_add_shape(body, body_shape_data[p_shape].shape); - ps->body_set_space(body, space); - ps->body_set_continuous_collision_detection_mode(body, PhysicsServer2D::CCD_MODE_CAST_SHAPE); - ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, p_xform); - - RID sprite = vs->canvas_item_create(); - vs->canvas_item_set_parent(sprite, canvas); - vs->canvas_item_set_transform(sprite, p_xform); - Size2 imgsize(5, 5); - vs->canvas_item_add_texture_rect(sprite, Rect2(-imgsize / 2.0, imgsize), body_shape_data[p_shape].image); - - ps->body_set_force_integration_callback(body, callable_mp(this, &TestPhysics2DMainLoop::_body_moved), sprite); - - return body; - } - - void _add_world_boundary(const Vector2 &p_normal, real_t p_d) { - PhysicsServer2D *ps = PhysicsServer2D::get_singleton(); - - Array arr; - arr.push_back(p_normal); - arr.push_back(p_d); - - RID world_boundary = ps->world_boundary_shape_create(); - ps->shape_set_data(world_boundary, arr); - - RID plane_body = ps->body_create(); - ps->body_set_mode(plane_body, PhysicsServer2D::BODY_MODE_STATIC); - ps->body_set_space(plane_body, space); - ps->body_add_shape(plane_body, world_boundary); - } - - void _add_concave(const Vector<Vector2> &p_points, const Transform2D &p_xform = Transform2D()) { - PhysicsServer2D *ps = PhysicsServer2D::get_singleton(); - RenderingServer *vs = RenderingServer::get_singleton(); - - RID concave = ps->concave_polygon_shape_create(); - ps->shape_set_data(concave, p_points); - RID body = ps->body_create(); - ps->body_set_mode(body, PhysicsServer2D::BODY_MODE_STATIC); - ps->body_set_space(body, space); - ps->body_add_shape(body, concave); - ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, p_xform); - - RID sprite = vs->canvas_item_create(); - vs->canvas_item_set_parent(sprite, canvas); - vs->canvas_item_set_transform(sprite, p_xform); - for (int i = 0; i < p_points.size(); i += 2) { - vs->canvas_item_add_line(sprite, p_points[i], p_points[i + 1], Color(0, 0, 0), 2); - } - } - - void _body_moved(Object *p_state, RID p_sprite) { - PhysicsDirectBodyState2D *state = (PhysicsDirectBodyState2D *)p_state; - RenderingServer::get_singleton()->canvas_item_set_transform(p_sprite, state->get_transform()); - } - - void _ray_query_callback(const RID &p_rid, ObjectID p_id, int p_shape, const Vector2 &p_point, const Vector2 &p_normal) { - Vector2 ray_end; - - if (p_rid.is_valid()) { - ray_end = p_point; - } else { - ray_end = ray_to; - } - - RenderingServer *vs = RenderingServer::get_singleton(); - - vs->canvas_item_clear(ray); - vs->canvas_item_add_line(ray, ray_from, ray_end, p_rid.is_valid() ? Color(0, 1, 0.4) : Color(1, 0.4, 0), 2); - if (p_rid.is_valid()) { - vs->canvas_item_add_line(ray, ray_end, ray_end + p_normal * 20, p_rid.is_valid() ? Color(0, 1, 0.4) : Color(1, 0.4, 0), 2); - } - } - - static void _bind_methods() { - ClassDB::bind_method(D_METHOD("_ray_query_callback"), &TestPhysics2DMainLoop::_ray_query_callback); - } - -public: - virtual void initialize() override { - RenderingServer *vs = RenderingServer::get_singleton(); - PhysicsServer2D *ps = PhysicsServer2D::get_singleton(); - - space = ps->space_create(); - ps->space_set_active(space, true); - ps->set_active(true); - ps->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY_VECTOR, Vector2(0, 1)); - ps->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY, 980); - - { - RID vp = vs->viewport_create(); - canvas = vs->canvas_create(); - - Size2i screen_size = DisplayServer::get_singleton()->window_get_size(); - vs->viewport_attach_canvas(vp, canvas); - vs->viewport_set_size(vp, screen_size.x, screen_size.y); - vs->viewport_attach_to_screen(vp, Rect2(Vector2(), screen_size)); - vs->viewport_set_active(vp, true); - vs->viewport_set_canvas_transform(vp, canvas, view_xform); - } - - ray = vs->canvas_item_create(); - vs->canvas_item_set_parent(ray, canvas); - - for (int i = 0; i < 32; i++) { - PhysicsServer2D::ShapeType types[4] = { - PhysicsServer2D::SHAPE_CIRCLE, - PhysicsServer2D::SHAPE_CAPSULE, - PhysicsServer2D::SHAPE_RECTANGLE, - PhysicsServer2D::SHAPE_CONVEX_POLYGON, - - }; - - PhysicsServer2D::ShapeType type = types[i % 4]; - _add_body(type, Transform2D(i * 0.8, Point2(152 + i * 40, 100 - 40 * i))); - } - - Point2 prev; - - Vector<Point2> parr; - for (int i = 0; i < 30; i++) { - Point2 p(i * 60, Math::randf() * 70 + 340); - if (i > 0) { - parr.push_back(prev); - parr.push_back(p); - } - prev = p; - } - - _add_concave(parr); - } - - virtual bool process(double p_time) override { - return false; - } - virtual void finalize() override { - } - - TestPhysics2DMainLoop() {} -}; - -namespace TestPhysics2D { - -MainLoop *test() { - return memnew(TestPhysics2DMainLoop); -} -} // namespace TestPhysics2D diff --git a/tests/servers/test_physics_2d.h b/tests/servers/test_physics_2d.h deleted file mode 100644 index b6c47574cd..0000000000 --- a/tests/servers/test_physics_2d.h +++ /dev/null @@ -1,41 +0,0 @@ -/*************************************************************************/ -/* test_physics_2d.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef TEST_PHYSICS_2D_H -#define TEST_PHYSICS_2D_H - -class MainLoop; - -namespace TestPhysics2D { - -MainLoop *test(); -} - -#endif // TEST_PHYSICS_2D_H diff --git a/tests/servers/test_physics_3d.cpp b/tests/servers/test_physics_3d.cpp deleted file mode 100644 index 3d38b9d901..0000000000 --- a/tests/servers/test_physics_3d.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/*************************************************************************/ -/* test_physics_3d.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "test_physics_3d.h" - -#include "core/math/convex_hull.h" -#include "core/math/geometry_3d.h" -#include "core/os/main_loop.h" -#include "servers/physics_server_3d.h" -#include "servers/rendering_server.h" - -class TestPhysics3DMainLoop : public MainLoop { - GDCLASS(TestPhysics3DMainLoop, MainLoop); - - enum { - LINK_COUNT = 20, - }; - - RID test_cube; - - RID plane; - RID sphere; - RID light; - RID camera; - RID mover; - RID scenario; - RID space; - - RID character; - - real_t ofs_x, ofs_y; - - Point2 joy_direction; - - List<RID> bodies; - Map<PhysicsServer3D::ShapeType, RID> type_shape_map; - Map<PhysicsServer3D::ShapeType, RID> type_mesh_map; - - void body_changed_transform(Object *p_state, RID p_visual_instance) { - PhysicsDirectBodyState3D *state = (PhysicsDirectBodyState3D *)p_state; - RenderingServer *vs = RenderingServer::get_singleton(); - Transform3D t = state->get_transform(); - vs->instance_set_transform(p_visual_instance, t); - } - - bool quit; - -protected: - RID create_body(PhysicsServer3D::ShapeType p_shape, PhysicsServer3D::BodyMode p_body, const Transform3D p_location, bool p_active_default = true, const Transform3D &p_shape_xform = Transform3D()) { - RenderingServer *vs = RenderingServer::get_singleton(); - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - - RID mesh_instance = vs->instance_create2(type_mesh_map[p_shape], scenario); - RID body = ps->body_create(); - ps->body_set_mode(body, p_body); - ps->body_set_state(body, PhysicsServer3D::BODY_STATE_SLEEPING, !p_active_default); - ps->body_set_space(body, space); - ps->body_set_param(body, PhysicsServer3D::BODY_PARAM_BOUNCE, 0.0); - //todo set space - ps->body_add_shape(body, type_shape_map[p_shape]); - ps->body_set_force_integration_callback(body, callable_mp(this, &TestPhysics3DMainLoop::body_changed_transform), mesh_instance); - - ps->body_set_state(body, PhysicsServer3D::BODY_STATE_TRANSFORM, p_location); - bodies.push_back(body); - - if (p_body == PhysicsServer3D::BODY_MODE_STATIC) { - vs->instance_set_transform(mesh_instance, p_location); - } - return body; - } - - RID create_world_boundary(const Plane &p_plane) { - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - - RID world_boundary_shape = ps->shape_create(PhysicsServer3D::SHAPE_WORLD_BOUNDARY); - ps->shape_set_data(world_boundary_shape, p_plane); - - RID b = ps->body_create(); - ps->body_set_mode(b, PhysicsServer3D::BODY_MODE_STATIC); - - ps->body_set_space(b, space); - ps->body_add_shape(b, world_boundary_shape); - return b; - } - - void configure_body(RID p_body, real_t p_mass, real_t p_friction, real_t p_bounce) { - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - ps->body_set_param(p_body, PhysicsServer3D::BODY_PARAM_MASS, p_mass); - ps->body_set_param(p_body, PhysicsServer3D::BODY_PARAM_FRICTION, p_friction); - ps->body_set_param(p_body, PhysicsServer3D::BODY_PARAM_BOUNCE, p_bounce); - } - - void initialize_shapes() { - RenderingServer *vs = RenderingServer::get_singleton(); - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - - /* SPHERE SHAPE */ - RID sphere_mesh = vs->make_sphere_mesh(10, 20, 0.5); - type_mesh_map[PhysicsServer3D::SHAPE_SPHERE] = sphere_mesh; - - RID sphere_shape = ps->shape_create(PhysicsServer3D::SHAPE_SPHERE); - ps->shape_set_data(sphere_shape, 0.5); - type_shape_map[PhysicsServer3D::SHAPE_SPHERE] = sphere_shape; - - /* BOX SHAPE */ - - Vector<Plane> box_planes = Geometry3D::build_box_planes(Vector3(0.5, 0.5, 0.5)); - RID box_mesh = vs->mesh_create(); - Geometry3D::MeshData box_data = Geometry3D::build_convex_mesh(box_planes); - vs->mesh_add_surface_from_mesh_data(box_mesh, box_data); - type_mesh_map[PhysicsServer3D::SHAPE_BOX] = box_mesh; - - RID box_shape = ps->shape_create(PhysicsServer3D::SHAPE_BOX); - ps->shape_set_data(box_shape, Vector3(0.5, 0.5, 0.5)); - type_shape_map[PhysicsServer3D::SHAPE_BOX] = box_shape; - - /* CAPSULE SHAPE */ - - Vector<Plane> capsule_planes = Geometry3D::build_capsule_planes(0.5, 0.7, 12, Vector3::AXIS_Z); - - RID capsule_mesh = vs->mesh_create(); - Geometry3D::MeshData capsule_data = Geometry3D::build_convex_mesh(capsule_planes); - vs->mesh_add_surface_from_mesh_data(capsule_mesh, capsule_data); - - type_mesh_map[PhysicsServer3D::SHAPE_CAPSULE] = capsule_mesh; - - RID capsule_shape = ps->shape_create(PhysicsServer3D::SHAPE_CAPSULE); - Dictionary capsule_params; - capsule_params["radius"] = 0.5; - capsule_params["height"] = 1.4; - ps->shape_set_data(capsule_shape, capsule_params); - type_shape_map[PhysicsServer3D::SHAPE_CAPSULE] = capsule_shape; - - /* CONVEX SHAPE */ - - Vector<Plane> convex_planes = Geometry3D::build_cylinder_planes(0.5, 0.7, 5, Vector3::AXIS_Z); - - RID convex_mesh = vs->mesh_create(); - Geometry3D::MeshData convex_data = Geometry3D::build_convex_mesh(convex_planes); - ConvexHullComputer::convex_hull(convex_data.vertices, convex_data); - vs->mesh_add_surface_from_mesh_data(convex_mesh, convex_data); - - type_mesh_map[PhysicsServer3D::SHAPE_CONVEX_POLYGON] = convex_mesh; - - RID convex_shape = ps->shape_create(PhysicsServer3D::SHAPE_CONVEX_POLYGON); - ps->shape_set_data(convex_shape, convex_data.vertices); - type_shape_map[PhysicsServer3D::SHAPE_CONVEX_POLYGON] = convex_shape; - } - - void make_trimesh(Vector<Vector3> p_faces, const Transform3D &p_xform = Transform3D()) { - RenderingServer *vs = RenderingServer::get_singleton(); - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - RID trimesh_shape = ps->shape_create(PhysicsServer3D::SHAPE_CONCAVE_POLYGON); - Dictionary trimesh_params; - trimesh_params["faces"] = p_faces; - trimesh_params["backface_collision"] = false; - ps->shape_set_data(trimesh_shape, trimesh_params); - Vector<Vector3> normals; // for drawing - for (int i = 0; i < p_faces.size() / 3; i++) { - Plane p(p_faces[i * 3 + 0], p_faces[i * 3 + 1], p_faces[i * 3 + 2]); - normals.push_back(p.normal); - normals.push_back(p.normal); - normals.push_back(p.normal); - } - - RID trimesh_mesh = vs->mesh_create(); - Array d; - d.resize(RS::ARRAY_MAX); - d[RS::ARRAY_VERTEX] = p_faces; - d[RS::ARRAY_NORMAL] = normals; - vs->mesh_add_surface_from_arrays(trimesh_mesh, RS::PRIMITIVE_TRIANGLES, d); - - RID triins = vs->instance_create2(trimesh_mesh, scenario); - - RID tribody = ps->body_create(); - ps->body_set_mode(tribody, PhysicsServer3D::BODY_MODE_STATIC); - ps->body_set_space(tribody, space); - //todo set space - ps->body_add_shape(tribody, trimesh_shape); - Transform3D tritrans = p_xform; - ps->body_set_state(tribody, PhysicsServer3D::BODY_STATE_TRANSFORM, tritrans); - vs->instance_set_transform(triins, tritrans); - } - - void make_grid(int p_width, int p_height, real_t p_cellsize, real_t p_cellheight, const Transform3D &p_xform = Transform3D()) { - Vector<Vector<real_t>> grid; - - grid.resize(p_width); - - for (int i = 0; i < p_width; i++) { - grid.write[i].resize(p_height); - - for (int j = 0; j < p_height; j++) { - grid.write[i].write[j] = 1.0 + Math::random(-p_cellheight, p_cellheight); - } - } - - Vector<Vector3> faces; - - for (int i = 1; i < p_width; i++) { - for (int j = 1; j < p_height; j++) { -#define MAKE_VERTEX(m_x, m_z) \ - faces.push_back(Vector3((m_x - p_width / 2) * p_cellsize, grid[m_x][m_z], (m_z - p_height / 2) * p_cellsize)) - - MAKE_VERTEX(i, j - 1); - MAKE_VERTEX(i, j); - MAKE_VERTEX(i - 1, j); - - MAKE_VERTEX(i - 1, j - 1); - MAKE_VERTEX(i, j - 1); - MAKE_VERTEX(i - 1, j); - } - } - - make_trimesh(faces, p_xform); - } - -public: - virtual void input_event(const Ref<InputEvent> &p_event) { - Ref<InputEventMouseMotion> mm = p_event; - if (mm.is_valid() && (mm->get_button_mask() & MouseButton::MASK_MIDDLE) != MouseButton::NONE) { - ofs_y -= mm->get_relative().y / 200.0; - ofs_x += mm->get_relative().x / 200.0; - } - - if (mm.is_valid() && (mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE) { - real_t y = -mm->get_relative().y / 20.0; - real_t x = mm->get_relative().x / 20.0; - - if (mover.is_valid()) { - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - Transform3D t = ps->body_get_state(mover, PhysicsServer3D::BODY_STATE_TRANSFORM); - t.origin += Vector3(x, y, 0); - - ps->body_set_state(mover, PhysicsServer3D::BODY_STATE_TRANSFORM, t); - } - } - } - - virtual void request_quit() { - quit = true; - } - virtual void initialize() override { - ofs_x = ofs_y = 0; - initialize_shapes(); - - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - space = ps->space_create(); - ps->space_set_active(space, true); - - RenderingServer *vs = RenderingServer::get_singleton(); - - /* LIGHT */ - RID lightaux = vs->directional_light_create(); - scenario = vs->scenario_create(); - vs->light_set_shadow(lightaux, true); - light = vs->instance_create2(lightaux, scenario); - Transform3D t; - t.rotate(Vector3(1.0, 0, 0), 0.6); - vs->instance_set_transform(light, t); - - /* CAMERA */ - - camera = vs->camera_create(); - - RID viewport = vs->viewport_create(); - Size2i screen_size = DisplayServer::get_singleton()->window_get_size(); - vs->viewport_set_size(viewport, screen_size.x, screen_size.y); - vs->viewport_attach_to_screen(viewport, Rect2(Vector2(), screen_size)); - vs->viewport_set_active(viewport, true); - vs->viewport_attach_camera(viewport, camera); - vs->viewport_set_scenario(viewport, scenario); - - vs->camera_set_perspective(camera, 60, 0.1, 40.0); - vs->camera_set_transform(camera, Transform3D(Basis(), Vector3(0, 9, 12))); - - Transform3D gxf; - gxf.basis.scale(Vector3(1.4, 0.4, 1.4)); - gxf.origin = Vector3(-2, 1, -2); - make_grid(5, 5, 2.5, 1, gxf); - test_fall(); - quit = false; - } - virtual bool physics_process(double p_time) override { - if (mover.is_valid()) { - static real_t joy_speed = 10; - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - Transform3D t = ps->body_get_state(mover, PhysicsServer3D::BODY_STATE_TRANSFORM); - t.origin += Vector3(joy_speed * joy_direction.x * p_time, -joy_speed * joy_direction.y * p_time, 0); - ps->body_set_state(mover, PhysicsServer3D::BODY_STATE_TRANSFORM, t); - }; - - Transform3D cameratr; - cameratr.rotate(Vector3(0, 1, 0), ofs_x); - cameratr.rotate(Vector3(1, 0, 0), -ofs_y); - cameratr.translate(Vector3(0, 2, 8)); - RenderingServer *vs = RenderingServer::get_singleton(); - vs->camera_set_transform(camera, cameratr); - - return quit; - } - virtual void finalize() override { - } - - void test_joint() { - } - - void test_hinge() { - } - - void test_character() { - RenderingServer *vs = RenderingServer::get_singleton(); - PhysicsServer3D *ps = PhysicsServer3D::get_singleton(); - - Vector<Plane> capsule_planes = Geometry3D::build_capsule_planes(0.5, 1, 12, 5, Vector3::AXIS_Y); - - RID capsule_mesh = vs->mesh_create(); - Geometry3D::MeshData capsule_data = Geometry3D::build_convex_mesh(capsule_planes); - vs->mesh_add_surface_from_mesh_data(capsule_mesh, capsule_data); - type_mesh_map[PhysicsServer3D::SHAPE_CAPSULE] = capsule_mesh; - - RID capsule_shape = ps->shape_create(PhysicsServer3D::SHAPE_CAPSULE); - Dictionary capsule_params; - capsule_params["radius"] = 0.5; - capsule_params["height"] = 1; - Transform3D shape_xform; - shape_xform.rotate(Vector3(1, 0, 0), Math_PI / 2.0); - //shape_xform.origin=Vector3(1,1,1); - ps->shape_set_data(capsule_shape, capsule_params); - - RID mesh_instance = vs->instance_create2(capsule_mesh, scenario); - character = ps->body_create(); - ps->body_set_mode(character, PhysicsServer3D::BODY_MODE_DYNAMIC_LINEAR); - ps->body_set_space(character, space); - //todo add space - ps->body_add_shape(character, capsule_shape); - ps->body_set_force_integration_callback(character, callable_mp(this, &TestPhysics3DMainLoop::body_changed_transform), mesh_instance); - - ps->body_set_state(character, PhysicsServer3D::BODY_STATE_TRANSFORM, Transform3D(Basis(), Vector3(-2, 5, -2))); - bodies.push_back(character); - } - - void test_fall() { - for (int i = 0; i < 35; i++) { - static const PhysicsServer3D::ShapeType shape_idx[] = { - PhysicsServer3D::SHAPE_CAPSULE, - PhysicsServer3D::SHAPE_BOX, - PhysicsServer3D::SHAPE_SPHERE, - PhysicsServer3D::SHAPE_CONVEX_POLYGON - }; - - PhysicsServer3D::ShapeType type = shape_idx[i % 4]; - - Transform3D t; - - t.origin = Vector3(0.0 * i, 3.5 + 1.1 * i, 0.7 + 0.0 * i); - t.basis.rotate(Vector3(0.2, -1, 0), Math_PI / 2 * 0.6); - - create_body(type, PhysicsServer3D::BODY_MODE_DYNAMIC, t); - } - - create_world_boundary(Plane(Vector3(0, 1, 0), -1)); - } - - void test_activate() { - create_body(PhysicsServer3D::SHAPE_BOX, PhysicsServer3D::BODY_MODE_DYNAMIC, Transform3D(Basis(), Vector3(0, 2, 0)), true); - create_world_boundary(Plane(Vector3(0, 1, 0), -1)); - } - - virtual bool process(double p_time) override { - return false; - } - - TestPhysics3DMainLoop() { - } -}; - -namespace TestPhysics3D { - -MainLoop *test() { - return memnew(TestPhysics3DMainLoop); -} -} // namespace TestPhysics3D diff --git a/tests/servers/test_physics_3d.h b/tests/servers/test_physics_3d.h deleted file mode 100644 index f618d0fb4f..0000000000 --- a/tests/servers/test_physics_3d.h +++ /dev/null @@ -1,41 +0,0 @@ -/*************************************************************************/ -/* test_physics_3d.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef TEST_PHYSICS_H -#define TEST_PHYSICS_H - -class MainLoop; - -namespace TestPhysics3D { - -MainLoop *test(); -} - -#endif diff --git a/tests/servers/test_render.cpp b/tests/servers/test_render.cpp deleted file mode 100644 index 44403e3724..0000000000 --- a/tests/servers/test_render.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/*************************************************************************/ -/* test_render.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "test_render.h" - -#include "core/math/convex_hull.h" -#include "core/os/main_loop.h" -#include "servers/rendering_server.h" - -#define OBJECT_COUNT 50 - -namespace TestRender { - -class TestMainLoop : public MainLoop { - RID test_cube; - RID instance; - RID camera; - RID viewport; - RID light; - RID scenario; - - struct InstanceInfo { - RID instance; - Transform3D base; - Vector3 rot_axis; - }; - - List<InstanceInfo> instances; - - float ofs; - bool quit; - -protected: -public: - virtual void input_event(const Ref<InputEvent> &p_event) { - if (p_event->is_pressed()) { - quit = true; - } - } - - virtual void init() { - print_line("INITIALIZING TEST RENDER"); - RenderingServer *vs = RenderingServer::get_singleton(); - test_cube = vs->get_test_cube(); - scenario = vs->scenario_create(); - - Vector<Vector3> vts; - - /* - Vector<Plane> sp = Geometry3D::build_sphere_planes(2,5,5); - Geometry3D::MeshData md2 = Geometry3D::build_convex_mesh(sp); - vts=md2.vertices; -*/ - /* - - static const int s = 20; - for(int i=0;i<s;i++) { - Basis rot(Vector3(0,1,0),i*Math_PI/s); - - for(int j=0;j<s;j++) { - Vector3 v; - v.x=Math::sin(j*Math_PI*2/s); - v.y=Math::cos(j*Math_PI*2/s); - - vts.push_back( rot.xform(v*2 ) ); - } - }*/ - /*for(int i=0;i<100;i++) { - vts.push_back( Vector3(Math::randf()*2-1.0,Math::randf()*2-1.0,Math::randf()*2-1.0).normalized()*2); - }*/ - /* - vts.push_back(Vector3(0,0,1)); - vts.push_back(Vector3(0,0,-1)); - vts.push_back(Vector3(0,1,0)); - vts.push_back(Vector3(0,-1,0)); - vts.push_back(Vector3(1,0,0)); - vts.push_back(Vector3(-1,0,0));*/ - - vts.push_back(Vector3(1, 1, 1)); - vts.push_back(Vector3(1, -1, 1)); - vts.push_back(Vector3(-1, 1, 1)); - vts.push_back(Vector3(-1, -1, 1)); - vts.push_back(Vector3(1, 1, -1)); - vts.push_back(Vector3(1, -1, -1)); - vts.push_back(Vector3(-1, 1, -1)); - vts.push_back(Vector3(-1, -1, -1)); - - Geometry3D::MeshData md; - Error err = ConvexHullComputer::convex_hull(vts, md); - print_line("ERR: " + itos(err)); - test_cube = vs->mesh_create(); - vs->mesh_add_surface_from_mesh_data(test_cube, md); - //vs->scenario_set_debug(scenario,RS::SCENARIO_DEBUG_WIREFRAME); - - /* - RID sm = vs->shader_create(); - //vs->shader_set_fragment_code(sm,"OUT_ALPHA=mod(TIME,1);"); - //vs->shader_set_vertex_code(sm,"OUT_VERTEX=IN_VERTEX*mod(TIME,1);"); - vs->shader_set_fragment_code(sm,"OUT_DIFFUSE=vec3(1,0,1);OUT_GLOW=abs(sin(TIME));"); - RID tcmat = vs->mesh_surface_get_material(test_cube,0); - vs->material_set_shader(tcmat,sm); - */ - - List<String> cmdline = OS::get_singleton()->get_cmdline_args(); - int object_count = OBJECT_COUNT; - if (cmdline.size() > 0 && cmdline[cmdline.size() - 1].to_int()) { - object_count = cmdline[cmdline.size() - 1].to_int(); - }; - - for (int i = 0; i < object_count; i++) { - InstanceInfo ii; - - ii.instance = vs->instance_create2(test_cube, scenario); - - ii.base.translate(Math::random(-20, 20), Math::random(-20, 20), Math::random(-20, 18)); - ii.base.rotate(Vector3(0, 1, 0), Math::randf() * Math_PI); - ii.base.rotate(Vector3(1, 0, 0), Math::randf() * Math_PI); - vs->instance_set_transform(ii.instance, ii.base); - - ii.rot_axis = Vector3(Math::random(-1, 1), Math::random(-1, 1), Math::random(-1, 1)).normalized(); - - instances.push_back(ii); - } - - camera = vs->camera_create(); - - // vs->camera_set_perspective( camera, 60.0,0.1, 100.0 ); - - viewport = vs->viewport_create(); - Size2i screen_size = DisplayServer::get_singleton()->window_get_size(); - vs->viewport_set_size(viewport, screen_size.x, screen_size.y); - vs->viewport_attach_to_screen(viewport, Rect2(Vector2(), screen_size)); - vs->viewport_set_active(viewport, true); - vs->viewport_attach_camera(viewport, camera); - vs->viewport_set_scenario(viewport, scenario); - vs->camera_set_transform(camera, Transform3D(Basis(), Vector3(0, 3, 30))); - vs->camera_set_perspective(camera, 60, 0.1, 1000); - - /* - RID lightaux = vs->light_create( RenderingServer::LIGHT_OMNI ); - vs->light_set_var( lightaux, RenderingServer::LIGHT_VAR_RADIUS, 80 ); - vs->light_set_var( lightaux, RenderingServer::LIGHT_VAR_ATTENUATION, 1 ); - vs->light_set_var( lightaux, RenderingServer::LIGHT_VAR_ENERGY, 1.5 ); - light = vs->instance_create( lightaux ); - */ - RID lightaux; - - lightaux = vs->directional_light_create(); - //vs->light_set_color( lightaux, RenderingServer::LIGHT_COLOR_AMBIENT, Color(0.0,0.0,0.0) ); - vs->light_set_color(lightaux, Color(1.0, 1.0, 1.0)); - //vs->light_set_shadow( lightaux, true ); - light = vs->instance_create2(lightaux, scenario); - Transform3D lla; - //lla.set_look_at(Vector3(),Vector3(1, -1, 1)); - lla.basis = Basis::looking_at(Vector3(0.0, -0.836026, -0.548690)); - - vs->instance_set_transform(light, lla); - - lightaux = vs->omni_light_create(); - //vs->light_set_color( lightaux, RenderingServer::LIGHT_COLOR_AMBIENT, Color(0.0,0.0,1.0) ); - vs->light_set_color(lightaux, Color(1.0, 1.0, 0.0)); - vs->light_set_param(lightaux, RenderingServer::LIGHT_PARAM_RANGE, 4); - vs->light_set_param(lightaux, RenderingServer::LIGHT_PARAM_ENERGY, 8); - //vs->light_set_shadow( lightaux, true ); - //light = vs->instance_create( lightaux ); - - ofs = 0; - quit = false; - } - virtual bool iteration(double p_time) { - RenderingServer *vs = RenderingServer::get_singleton(); - //Transform3D t; - //t.rotate(Vector3(0, 1, 0), ofs); - //t.translate(Vector3(0,0,20 )); - //vs->camera_set_transform(camera, t); - - ofs += p_time * 0.05; - - //return quit; - - for (const InstanceInfo &E : instances) { - Transform3D pre(Basis(E.rot_axis, ofs), Vector3()); - vs->instance_set_transform(E.instance, pre * E.base); - /* - if( !E->next() ) { - vs->free( E.instance ); - instances.erase(E ); - }*/ - } - - return quit; - } - - virtual bool idle(double p_time) { - return quit; - } - - virtual void finish() { - } -}; - -MainLoop *test() { - return memnew(TestMainLoop); -} -} // namespace TestRender diff --git a/tests/servers/test_render.h b/tests/servers/test_render.h deleted file mode 100644 index d5a3e01ee5..0000000000 --- a/tests/servers/test_render.h +++ /dev/null @@ -1,41 +0,0 @@ -/*************************************************************************/ -/* test_render.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef TEST_RENDER_H -#define TEST_RENDER_H - -class MainLoop; - -namespace TestRender { - -MainLoop *test(); -} - -#endif // TEST_RENDER_H diff --git a/tests/servers/test_shader_lang.cpp b/tests/servers/test_shader_lang.cpp deleted file mode 100644 index 06e28212d2..0000000000 --- a/tests/servers/test_shader_lang.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/*************************************************************************/ -/* test_shader_lang.cpp */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#include "test_shader_lang.h" - -#include "core/os/main_loop.h" -#include "core/os/os.h" -#include "servers/rendering/shader_language.h" - -typedef ShaderLanguage SL; - -namespace TestShaderLang { - -static String _mktab(int p_level) { - String tb; - for (int i = 0; i < p_level; i++) { - tb += "\t"; - } - - return tb; -} - -static String _typestr(SL::DataType p_type) { - return ShaderLanguage::get_datatype_name(p_type); -} - -static String _prestr(SL::DataPrecision p_pres) { - switch (p_pres) { - case SL::PRECISION_LOWP: - return "lowp "; - case SL::PRECISION_MEDIUMP: - return "mediump "; - case SL::PRECISION_HIGHP: - return "highp "; - case SL::PRECISION_DEFAULT: - return ""; - } - return ""; -} - -static String _opstr(SL::Operator p_op) { - return ShaderLanguage::get_operator_text(p_op); -} - -static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value> &p_values) { - switch (p_type) { - case SL::TYPE_BOOL: - return p_values[0].boolean ? "true" : "false"; - case SL::TYPE_BVEC2: - return String() + "bvec2(" + (p_values[0].boolean ? "true" : "false") + (p_values[1].boolean ? "true" : "false") + ")"; - case SL::TYPE_BVEC3: - return String() + "bvec3(" + (p_values[0].boolean ? "true" : "false") + "," + (p_values[1].boolean ? "true" : "false") + "," + (p_values[2].boolean ? "true" : "false") + ")"; - case SL::TYPE_BVEC4: - return String() + "bvec4(" + (p_values[0].boolean ? "true" : "false") + "," + (p_values[1].boolean ? "true" : "false") + "," + (p_values[2].boolean ? "true" : "false") + "," + (p_values[3].boolean ? "true" : "false") + ")"; - case SL::TYPE_INT: - return rtos(p_values[0].sint); - case SL::TYPE_IVEC2: - return String() + "ivec2(" + rtos(p_values[0].sint) + "," + rtos(p_values[1].sint) + ")"; - case SL::TYPE_IVEC3: - return String() + "ivec3(" + rtos(p_values[0].sint) + "," + rtos(p_values[1].sint) + "," + rtos(p_values[2].sint) + ")"; - case SL::TYPE_IVEC4: - return String() + "ivec4(" + rtos(p_values[0].sint) + "," + rtos(p_values[1].sint) + "," + rtos(p_values[2].sint) + "," + rtos(p_values[3].sint) + ")"; - case SL::TYPE_UINT: - return rtos(p_values[0].real); - case SL::TYPE_UVEC2: - return String() + "uvec2(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + ")"; - case SL::TYPE_UVEC3: - return String() + "uvec3(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + ")"; - case SL::TYPE_UVEC4: - return String() + "uvec4(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + "," + rtos(p_values[3].real) + ")"; - case SL::TYPE_FLOAT: - return rtos(p_values[0].real); - case SL::TYPE_VEC2: - return String() + "vec2(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + ")"; - case SL::TYPE_VEC3: - return String() + "vec3(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + ")"; - case SL::TYPE_VEC4: - return String() + "vec4(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + "," + rtos(p_values[3].real) + ")"; - default: - ERR_FAIL_V(String()); - } -} - -static String dump_node_code(SL::Node *p_node, int p_level) { - String code; - - switch (p_node->type) { - case SL::Node::TYPE_SHADER: { - SL::ShaderNode *pnode = (SL::ShaderNode *)p_node; - - for (const KeyValue<StringName, SL::ShaderNode::Uniform> &E : pnode->uniforms) { - String ucode = "uniform "; - ucode += _prestr(E.value.precision); - ucode += _typestr(E.value.type); - ucode += " " + String(E.key); - if (E.value.array_size > 0) { - ucode += "["; - ucode += itos(E.value.array_size); - ucode += "]"; - } else { - if (E.value.default_value.size()) { - ucode += " = " + get_constant_text(E.value.type, E.value.default_value); - } - - static const char *hint_name[SL::ShaderNode::Uniform::HINT_MAX] = { - "", - "color", - "range", - "albedo", - "normal", - "black", - "white" - }; - - if (E.value.hint) { - ucode += " : " + String(hint_name[E.value.hint]); - } - } - - code += ucode + "\n"; - } - - for (const KeyValue<StringName, SL::ShaderNode::Varying> &E : pnode->varyings) { - String vcode = "varying "; - vcode += _prestr(E.value.precision); - vcode += _typestr(E.value.type); - vcode += " " + String(E.key); - - code += vcode + "\n"; - } - for (int i = 0; i < pnode->functions.size(); i++) { - SL::FunctionNode *fnode = pnode->functions[i].function; - - String header; - header = _typestr(fnode->return_type) + " " + fnode->name + "("; - for (int j = 0; j < fnode->arguments.size(); j++) { - if (j > 0) { - header += ", "; - } - header += _prestr(fnode->arguments[j].precision) + _typestr(fnode->arguments[j].type) + " " + fnode->arguments[j].name; - } - - header += ")\n"; - code += header; - code += dump_node_code(fnode->body, p_level + 1); - } - - //code+=dump_node_code(pnode->body,p_level); - } break; - case SL::Node::TYPE_STRUCT: { - } break; - case SL::Node::TYPE_FUNCTION: { - } break; - case SL::Node::TYPE_BLOCK: { - SL::BlockNode *bnode = (SL::BlockNode *)p_node; - - //variables - code += _mktab(p_level - 1) + "{\n"; - for (const KeyValue<StringName, SL::BlockNode::Variable> &E : bnode->variables) { - code += _mktab(p_level) + _prestr(E.value.precision) + _typestr(E.value.type) + " " + E.key + ";\n"; - } - - for (int i = 0; i < bnode->statements.size(); i++) { - String scode = dump_node_code(bnode->statements[i], p_level); - - if (bnode->statements[i]->type == SL::Node::TYPE_CONTROL_FLOW) { - code += scode; //use directly - } else { - code += _mktab(p_level) + scode + ";\n"; - } - } - code += _mktab(p_level - 1) + "}\n"; - - } break; - case SL::Node::TYPE_VARIABLE: { - SL::VariableNode *vnode = (SL::VariableNode *)p_node; - code = vnode->name; - - } break; - case SL::Node::TYPE_VARIABLE_DECLARATION: { - // FIXME: Implement - } break; - case SL::Node::TYPE_ARRAY: { - SL::ArrayNode *vnode = (SL::ArrayNode *)p_node; - code = vnode->name; - } break; - case SL::Node::TYPE_ARRAY_CONSTRUCT: { - // FIXME: Implement - } break; - case SL::Node::TYPE_CONSTANT: { - SL::ConstantNode *cnode = (SL::ConstantNode *)p_node; - return get_constant_text(cnode->datatype, cnode->values); - - } break; - case SL::Node::TYPE_OPERATOR: { - SL::OperatorNode *onode = (SL::OperatorNode *)p_node; - - switch (onode->op) { - case SL::OP_ASSIGN: - case SL::OP_ASSIGN_ADD: - case SL::OP_ASSIGN_SUB: - case SL::OP_ASSIGN_MUL: - case SL::OP_ASSIGN_DIV: - case SL::OP_ASSIGN_SHIFT_LEFT: - case SL::OP_ASSIGN_SHIFT_RIGHT: - case SL::OP_ASSIGN_MOD: - case SL::OP_ASSIGN_BIT_AND: - case SL::OP_ASSIGN_BIT_OR: - case SL::OP_ASSIGN_BIT_XOR: - code = dump_node_code(onode->arguments[0], p_level) + _opstr(onode->op) + dump_node_code(onode->arguments[1], p_level); - break; - case SL::OP_BIT_INVERT: - case SL::OP_NEGATE: - case SL::OP_NOT: - case SL::OP_DECREMENT: - case SL::OP_INCREMENT: - code = _opstr(onode->op) + dump_node_code(onode->arguments[0], p_level); - break; - case SL::OP_POST_DECREMENT: - case SL::OP_POST_INCREMENT: - code = dump_node_code(onode->arguments[0], p_level) + _opstr(onode->op); - break; - case SL::OP_CALL: - case SL::OP_CONSTRUCT: - code = dump_node_code(onode->arguments[0], p_level) + "("; - for (int i = 1; i < onode->arguments.size(); i++) { - if (i > 1) { - code += ", "; - } - code += dump_node_code(onode->arguments[i], p_level); - } - code += ")"; - break; - case SL::OP_EMPTY: - break; - default: { - code = "(" + dump_node_code(onode->arguments[0], p_level) + _opstr(onode->op) + dump_node_code(onode->arguments[1], p_level) + ")"; - break; - } - } - - } break; - case SL::Node::TYPE_CONTROL_FLOW: { - SL::ControlFlowNode *cfnode = (SL::ControlFlowNode *)p_node; - if (cfnode->flow_op == SL::FLOW_OP_IF) { - code += _mktab(p_level) + "if (" + dump_node_code(cfnode->expressions[0], p_level) + ")\n"; - code += dump_node_code(cfnode->blocks[0], p_level + 1); - if (cfnode->blocks.size() == 2) { - code += _mktab(p_level) + "else\n"; - code += dump_node_code(cfnode->blocks[1], p_level + 1); - } - - } else if (cfnode->flow_op == SL::FLOW_OP_RETURN) { - if (cfnode->blocks.size()) { - code = "return " + dump_node_code(cfnode->blocks[0], p_level); - } else { - code = "return"; - } - } - - } break; - case SL::Node::TYPE_MEMBER: { - SL::MemberNode *mnode = (SL::MemberNode *)p_node; - code = dump_node_code(mnode->owner, p_level) + "." + mnode->name; - - } break; - } - - return code; -} - -static Error recreate_code(void *p_str, SL::ShaderNode *p_program) { - String *str = (String *)p_str; - - *str = dump_node_code(p_program, 0); - - return OK; -} - -MainLoop *test() { - List<String> cmdlargs = OS::get_singleton()->get_cmdline_args(); - - if (cmdlargs.is_empty()) { - //try editor! - print_line("usage: godot -test shader_lang <shader>"); - return nullptr; - } - - String test = cmdlargs.back()->get(); - - FileAccess *fa = FileAccess::open(test, FileAccess::READ); - - if (!fa) { - ERR_FAIL_V(nullptr); - } - - String code; - - while (true) { - char32_t c = fa->get_8(); - if (fa->eof_reached()) { - break; - } - code += c; - } - - SL sl; - print_line("tokens:\n\n" + sl.token_debug(code)); - - Map<StringName, SL::FunctionInfo> dt; - dt["fragment"].built_ins["ALBEDO"] = SL::TYPE_VEC3; - dt["fragment"].can_discard = true; - - Vector<SL::ModeInfo> rm; - rm.push_back({ "popo" }); - Set<String> types; - types.insert("spatial"); - - ShaderLanguage::ShaderCompileInfo info; - info.functions = dt; - info.render_modes = rm; - info.shader_types = types; - - Error err = sl.compile(code, info); - - if (err) { - print_line("Error at line: " + rtos(sl.get_error_line()) + ": " + sl.get_error_text()); - return nullptr; - } else { - String code2; - recreate_code(&code2, sl.get_shader()); - print_line("code:\n\n" + code2); - } - - return nullptr; -} -} // namespace TestShaderLang diff --git a/tests/servers/test_shader_lang.h b/tests/servers/test_shader_lang.h deleted file mode 100644 index 31e1bfbeea..0000000000 --- a/tests/servers/test_shader_lang.h +++ /dev/null @@ -1,41 +0,0 @@ -/*************************************************************************/ -/* test_shader_lang.h */ -/*************************************************************************/ -/* This file is part of: */ -/* GODOT ENGINE */ -/* https://godotengine.org */ -/*************************************************************************/ -/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ -/* */ -/* Permission is hereby granted, free of charge, to any person obtaining */ -/* a copy of this software and associated documentation files (the */ -/* "Software"), to deal in the Software without restriction, including */ -/* without limitation the rights to use, copy, modify, merge, publish, */ -/* distribute, sublicense, and/or sell copies of the Software, and to */ -/* permit persons to whom the Software is furnished to do so, subject to */ -/* the following conditions: */ -/* */ -/* The above copyright notice and this permission notice shall be */ -/* included in all copies or substantial portions of the Software. */ -/* */ -/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ -/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ -/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ -/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ -/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ -/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ -/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/*************************************************************************/ - -#ifndef TEST_SHADER_LANG_H -#define TEST_SHADER_LANG_H - -class MainLoop; - -namespace TestShaderLang { - -MainLoop *test(); -} - -#endif // TEST_SHADER_LANG_H diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 830731abcd..344e2fa101 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -45,7 +45,6 @@ #include "tests/core/math/test_expression.h" #include "tests/core/math/test_geometry_2d.h" #include "tests/core/math/test_geometry_3d.h" -#include "tests/core/math/test_math.h" #include "tests/core/math/test_random_number_generator.h" #include "tests/core/math/test_rect2.h" #include "tests/core/math/test_rect2i.h" @@ -63,7 +62,6 @@ #include "tests/core/templates/test_list.h" #include "tests/core/templates/test_local_vector.h" #include "tests/core/templates/test_lru.h" -#include "tests/core/templates/test_oa_hash_map.h" #include "tests/core/templates/test_ordered_hash_map.h" #include "tests/core/templates/test_paged_array.h" #include "tests/core/templates/test_vector.h" @@ -77,12 +75,7 @@ #include "tests/scene/test_code_edit.h" #include "tests/scene/test_curve.h" #include "tests/scene/test_gradient.h" -#include "tests/scene/test_gui.h" #include "tests/scene/test_path_3d.h" -#include "tests/servers/test_physics_2d.h" -#include "tests/servers/test_physics_3d.h" -#include "tests/servers/test_render.h" -#include "tests/servers/test_shader_lang.h" #include "tests/servers/test_text_server.h" #include "tests/test_validate_testing.h" |