| 57 | namespace GDScriptTests { |
| 58 | |
| 59 | void init_autoloads() { |
| 60 | HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list(); |
| 61 | |
| 62 | // First pass, add the constants so they exist before any script is loaded. |
| 63 | for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) { |
| 64 | const ProjectSettings::AutoloadInfo &info = E.value; |
| 65 | |
| 66 | if (info.is_singleton) { |
| 67 | for (int i = 0; i < ScriptServer::get_language_count(); i++) { |
| 68 | ScriptServer::get_language(i)->add_global_constant(info.name, Variant()); |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | // Second pass, load into global constants. |
| 74 | for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) { |
| 75 | const ProjectSettings::AutoloadInfo &info = E.value; |
| 76 | |
| 77 | if (!info.is_singleton) { |
| 78 | // Skip non-singletons since we don't have a scene tree here anyway. |
| 79 | continue; |
| 80 | } |
| 81 | |
| 82 | Node *n = nullptr; |
| 83 | if (ResourceLoader::get_resource_type(info.path) == "PackedScene") { |
| 84 | // Cache the scene reference before loading it (for cyclic references) |
| 85 | Ref<PackedScene> scn; |
| 86 | scn.instantiate(); |
| 87 | scn->set_path(info.path); |
| 88 | scn->reload_from_file(); |
| 89 | ERR_CONTINUE_MSG(scn.is_null(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path)); |
| 90 | |
| 91 | if (scn.is_valid()) { |
| 92 | n = scn->instantiate(); |
| 93 | } |
| 94 | } else { |
| 95 | Ref<Resource> res = ResourceLoader::load(info.path); |
| 96 | ERR_CONTINUE_MSG(res.is_null(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path)); |
| 97 | |
| 98 | Ref<Script> scr = res; |
| 99 | if (scr.is_valid()) { |
| 100 | StringName ibt = scr->get_instance_base_type(); |
| 101 | bool valid_type = ClassDB::is_parent_class(ibt, "Node"); |
| 102 | ERR_CONTINUE_MSG(!valid_type, vformat("Failed to instantiate an autoload, script '%s' does not inherit from 'Node'.", info.path)); |
| 103 | |
| 104 | Object *obj = ClassDB::instantiate(ibt); |
| 105 | ERR_CONTINUE_MSG(!obj, vformat("Failed to instantiate an autoload, cannot instantiate '%s'.", ibt)); |
| 106 | |
| 107 | n = Object::cast_to<Node>(obj); |
| 108 | n->set_script(scr); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | ERR_CONTINUE_MSG(!n, vformat("Failed to instantiate an autoload, path is not pointing to a scene or a script: %s.", info.path)); |
| 113 | n->set_name(info.name); |
| 114 | |
| 115 | for (int i = 0; i < ScriptServer::get_language_count(); i++) { |
| 116 | ScriptServer::get_language(i)->add_global_constant(info.name, n); |
no test coverage detected