1/**************************************************************************/
2/* resource_importer_scene.cpp */
3/**************************************************************************/
4/* This file is part of: */
5/* GODOT ENGINE */
6/* https://godotengine.org */
7/**************************************************************************/
8/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10/* */
11/* Permission is hereby granted, free of charge, to any person obtaining */
12/* a copy of this software and associated documentation files (the */
13/* "Software"), to deal in the Software without restriction, including */
14/* without limitation the rights to use, copy, modify, merge, publish, */
15/* distribute, sublicense, and/or sell copies of the Software, and to */
16/* permit persons to whom the Software is furnished to do so, subject to */
17/* the following conditions: */
18/* */
19/* The above copyright notice and this permission notice shall be */
20/* included in all copies or substantial portions of the Software. */
21/* */
22/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29/**************************************************************************/
30
31#include "resource_importer_scene.h"
32
33#include "core/error/error_macros.h"
34#include "core/io/resource_saver.h"
35#include "core/object/script_language.h"
36#include "editor/editor_node.h"
37#include "editor/editor_settings.h"
38#include "editor/import/scene_import_settings.h"
39#include "scene/3d/area_3d.h"
40#include "scene/3d/collision_shape_3d.h"
41#include "scene/3d/importer_mesh_instance_3d.h"
42#include "scene/3d/mesh_instance_3d.h"
43#include "scene/3d/navigation_region_3d.h"
44#include "scene/3d/occluder_instance_3d.h"
45#include "scene/3d/physics_body_3d.h"
46#include "scene/3d/vehicle_body_3d.h"
47#include "scene/animation/animation_player.h"
48#include "scene/resources/animation.h"
49#include "scene/resources/box_shape_3d.h"
50#include "scene/resources/importer_mesh.h"
51#include "scene/resources/packed_scene.h"
52#include "scene/resources/resource_format_text.h"
53#include "scene/resources/separation_ray_shape_3d.h"
54#include "scene/resources/sphere_shape_3d.h"
55#include "scene/resources/surface_tool.h"
56#include "scene/resources/world_boundary_shape_3d.h"
57
58uint32_t EditorSceneFormatImporter::get_import_flags() const {
59 uint32_t ret;
60 if (GDVIRTUAL_CALL(_get_import_flags, ret)) {
61 return ret;
62 }
63
64 ERR_FAIL_V(0);
65}
66
67void EditorSceneFormatImporter::get_extensions(List<String> *r_extensions) const {
68 Vector<String> arr;
69 if (GDVIRTUAL_CALL(_get_extensions, arr)) {
70 for (int i = 0; i < arr.size(); i++) {
71 r_extensions->push_back(arr[i]);
72 }
73 return;
74 }
75
76 ERR_FAIL();
77}
78
79Node *EditorSceneFormatImporter::import_scene(const String &p_path, uint32_t p_flags, const HashMap<StringName, Variant> &p_options, List<String> *r_missing_deps, Error *r_err) {
80 Dictionary options_dict;
81 for (const KeyValue<StringName, Variant> &elem : p_options) {
82 options_dict[elem.key] = elem.value;
83 }
84 Object *ret = nullptr;
85 if (GDVIRTUAL_CALL(_import_scene, p_path, p_flags, options_dict, ret)) {
86 return Object::cast_to<Node>(ret);
87 }
88
89 ERR_FAIL_V(nullptr);
90}
91
92void EditorSceneFormatImporter::get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options) {
93 GDVIRTUAL_CALL(_get_import_options, p_path);
94}
95
96Variant EditorSceneFormatImporter::get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const HashMap<StringName, Variant> &p_options) {
97 Variant ret;
98 GDVIRTUAL_CALL(_get_option_visibility, p_path, p_for_animation, p_option, ret);
99 return ret;
100}
101
102void EditorSceneFormatImporter::_bind_methods() {
103 GDVIRTUAL_BIND(_get_import_flags);
104 GDVIRTUAL_BIND(_get_extensions);
105 GDVIRTUAL_BIND(_import_scene, "path", "flags", "options");
106 GDVIRTUAL_BIND(_get_import_options, "path");
107 GDVIRTUAL_BIND(_get_option_visibility, "path", "for_animation", "option");
108
109 BIND_CONSTANT(IMPORT_SCENE);
110 BIND_CONSTANT(IMPORT_ANIMATION);
111 BIND_CONSTANT(IMPORT_FAIL_ON_MISSING_DEPENDENCIES);
112 BIND_CONSTANT(IMPORT_GENERATE_TANGENT_ARRAYS);
113 BIND_CONSTANT(IMPORT_USE_NAMED_SKIN_BINDS);
114 BIND_CONSTANT(IMPORT_DISCARD_MESHES_AND_MATERIALS);
115}
116
117/////////////////////////////////
118void EditorScenePostImport::_bind_methods() {
119 GDVIRTUAL_BIND(_post_import, "scene")
120 ClassDB::bind_method(D_METHOD("get_source_file"), &EditorScenePostImport::get_source_file);
121}
122
123Node *EditorScenePostImport::post_import(Node *p_scene) {
124 Object *ret;
125 if (GDVIRTUAL_CALL(_post_import, p_scene, ret)) {
126 return Object::cast_to<Node>(ret);
127 }
128
129 return p_scene;
130}
131
132String EditorScenePostImport::get_source_file() const {
133 return source_file;
134}
135
136void EditorScenePostImport::init(const String &p_source_file) {
137 source_file = p_source_file;
138}
139
140EditorScenePostImport::EditorScenePostImport() {
141}
142
143///////////////////////////////////////////////////////
144
145Variant EditorScenePostImportPlugin::get_option_value(const StringName &p_name) const {
146 ERR_FAIL_COND_V_MSG(current_options == nullptr && current_options_dict == nullptr, Variant(), "get_option_value called from a function where option values are not available.");
147 ERR_FAIL_COND_V_MSG(current_options && !current_options->has(p_name), Variant(), "get_option_value called with unexisting option argument: " + String(p_name));
148 ERR_FAIL_COND_V_MSG(current_options_dict && !current_options_dict->has(p_name), Variant(), "get_option_value called with unexisting option argument: " + String(p_name));
149 if (current_options && current_options->has(p_name)) {
150 return (*current_options)[p_name];
151 }
152 if (current_options_dict && current_options_dict->has(p_name)) {
153 return (*current_options_dict)[p_name];
154 }
155 return Variant();
156}
157void EditorScenePostImportPlugin::add_import_option(const String &p_name, Variant p_default_value) {
158 ERR_FAIL_NULL_MSG(current_option_list, "add_import_option() can only be called from get_import_options().");
159 add_import_option_advanced(p_default_value.get_type(), p_name, p_default_value);
160}
161void EditorScenePostImportPlugin::add_import_option_advanced(Variant::Type p_type, const String &p_name, Variant p_default_value, PropertyHint p_hint, const String &p_hint_string, int p_usage_flags) {
162 ERR_FAIL_NULL_MSG(current_option_list, "add_import_option_advanced() can only be called from get_import_options().");
163 current_option_list->push_back(ResourceImporter::ImportOption(PropertyInfo(p_type, p_name, p_hint, p_hint_string, p_usage_flags), p_default_value));
164}
165
166void EditorScenePostImportPlugin::get_internal_import_options(InternalImportCategory p_category, List<ResourceImporter::ImportOption> *r_options) {
167 current_option_list = r_options;
168 GDVIRTUAL_CALL(_get_internal_import_options, p_category);
169 current_option_list = nullptr;
170}
171Variant EditorScenePostImportPlugin::get_internal_option_visibility(InternalImportCategory p_category, bool p_for_animation, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
172 current_options = &p_options;
173 Variant ret;
174 GDVIRTUAL_CALL(_get_internal_option_visibility, p_category, p_for_animation, p_option, ret);
175 current_options = nullptr;
176 return ret;
177}
178Variant EditorScenePostImportPlugin::get_internal_option_update_view_required(InternalImportCategory p_category, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
179 current_options = &p_options;
180 Variant ret;
181 GDVIRTUAL_CALL(_get_internal_option_update_view_required, p_category, p_option, ret);
182 current_options = nullptr;
183 return ret;
184}
185
186void EditorScenePostImportPlugin::internal_process(InternalImportCategory p_category, Node *p_base_scene, Node *p_node, Ref<Resource> p_resource, const Dictionary &p_options) {
187 current_options_dict = &p_options;
188 GDVIRTUAL_CALL(_internal_process, p_category, p_base_scene, p_node, p_resource);
189 current_options_dict = nullptr;
190}
191
192void EditorScenePostImportPlugin::get_import_options(const String &p_path, List<ResourceImporter::ImportOption> *r_options) {
193 current_option_list = r_options;
194 GDVIRTUAL_CALL(_get_import_options, p_path);
195 current_option_list = nullptr;
196}
197Variant EditorScenePostImportPlugin::get_option_visibility(const String &p_path, bool p_for_animation, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
198 current_options = &p_options;
199 Variant ret;
200 GDVIRTUAL_CALL(_get_option_visibility, p_path, p_for_animation, p_option, ret);
201 current_options = nullptr;
202 return ret;
203}
204
205void EditorScenePostImportPlugin::pre_process(Node *p_scene, const HashMap<StringName, Variant> &p_options) {
206 current_options = &p_options;
207 GDVIRTUAL_CALL(_pre_process, p_scene);
208 current_options = nullptr;
209}
210void EditorScenePostImportPlugin::post_process(Node *p_scene, const HashMap<StringName, Variant> &p_options) {
211 current_options = &p_options;
212 GDVIRTUAL_CALL(_post_process, p_scene);
213 current_options = nullptr;
214}
215
216void EditorScenePostImportPlugin::_bind_methods() {
217 ClassDB::bind_method(D_METHOD("get_option_value", "name"), &EditorScenePostImportPlugin::get_option_value);
218
219 ClassDB::bind_method(D_METHOD("add_import_option", "name", "value"), &EditorScenePostImportPlugin::add_import_option);
220 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));
221
222 GDVIRTUAL_BIND(_get_internal_import_options, "category");
223 GDVIRTUAL_BIND(_get_internal_option_visibility, "category", "for_animation", "option");
224 GDVIRTUAL_BIND(_get_internal_option_update_view_required, "category", "option");
225 GDVIRTUAL_BIND(_internal_process, "category", "base_node", "node", "resource");
226 GDVIRTUAL_BIND(_get_import_options, "path");
227 GDVIRTUAL_BIND(_get_option_visibility, "path", "for_animation", "option");
228 GDVIRTUAL_BIND(_pre_process, "scene");
229 GDVIRTUAL_BIND(_post_process, "scene");
230
231 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_NODE);
232 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE);
233 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_MESH);
234 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_MATERIAL);
235 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_ANIMATION);
236 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE);
237 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE);
238 BIND_ENUM_CONSTANT(INTERNAL_IMPORT_CATEGORY_MAX);
239}
240
241/////////////////////////////////////////////////////////
242
243String ResourceImporterScene::get_importer_name() const {
244 return animation_importer ? "animation_library" : "scene";
245}
246
247String ResourceImporterScene::get_visible_name() const {
248 return animation_importer ? "Animation Library" : "Scene";
249}
250
251void ResourceImporterScene::get_recognized_extensions(List<String> *p_extensions) const {
252 for (Ref<EditorSceneFormatImporter> importer_elem : importers) {
253 importer_elem->get_extensions(p_extensions);
254 }
255}
256
257String ResourceImporterScene::get_save_extension() const {
258 return animation_importer ? "res" : "scn";
259}
260
261String ResourceImporterScene::get_resource_type() const {
262 return animation_importer ? "AnimationLibrary" : "PackedScene";
263}
264
265int ResourceImporterScene::get_format_version() const {
266 return 1;
267}
268
269bool ResourceImporterScene::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
270 if (animation_importer) {
271 if (p_option == "animation/import") { // Option ignored, animation always imported.
272 return false;
273 }
274 } else if (p_option.begins_with("animation/")) {
275 if (p_option != "animation/import" && !bool(p_options["animation/import"])) {
276 return false;
277 }
278 }
279
280 if (animation_importer && (p_option.begins_with("nodes/") || p_option.begins_with("meshes/") || p_option.begins_with("skins/"))) {
281 return false; // Nothing to do here for animations.
282 }
283
284 if (p_option == "meshes/lightmap_texel_size" && int(p_options["meshes/light_baking"]) != 2) {
285 // Only display the lightmap texel size import option when using the Static Lightmaps light baking mode.
286 return false;
287 }
288
289 for (int i = 0; i < post_importer_plugins.size(); i++) {
290 Variant ret = post_importer_plugins.write[i]->get_option_visibility(p_path, animation_importer, p_option, p_options);
291 if (ret.get_type() == Variant::BOOL) {
292 return ret;
293 }
294 }
295
296 for (Ref<EditorSceneFormatImporter> importer : importers) {
297 Variant ret = importer->get_option_visibility(p_path, animation_importer, p_option, p_options);
298 if (ret.get_type() == Variant::BOOL) {
299 return ret;
300 }
301 }
302
303 return true;
304}
305
306int ResourceImporterScene::get_preset_count() const {
307 return 0;
308}
309
310String ResourceImporterScene::get_preset_name(int p_idx) const {
311 return String();
312}
313
314static bool _teststr(const String &p_what, const String &p_str) {
315 String what = p_what;
316
317 // Remove trailing spaces and numbers, some apps like blender add ".number" to duplicates
318 // (dot is replaced with _ as invalid character) so also compensate for this.
319 while (what.length() && (is_digit(what[what.length() - 1]) || what[what.length() - 1] <= 32 || what[what.length() - 1] == '_')) {
320 what = what.substr(0, what.length() - 1);
321 }
322
323 if (what.findn("$" + p_str) != -1) { //blender and other stuff
324 return true;
325 }
326 if (what.to_lower().ends_with("-" + p_str)) { //collada only supports "_" and "-" besides letters
327 return true;
328 }
329 if (what.to_lower().ends_with("_" + p_str)) { //collada only supports "_" and "-" besides letters
330 return true;
331 }
332 return false;
333}
334
335static String _fixstr(const String &p_what, const String &p_str) {
336 String what = p_what;
337
338 // Remove trailing spaces and numbers, some apps like blender add ".number" to duplicates
339 // (dot is replaced with _ as invalid character) so also compensate for this.
340 while (what.length() && (is_digit(what[what.length() - 1]) || what[what.length() - 1] <= 32 || what[what.length() - 1] == '_')) {
341 what = what.substr(0, what.length() - 1);
342 }
343
344 String end = p_what.substr(what.length(), p_what.length() - what.length());
345
346 if (what.findn("$" + p_str) != -1) { //blender and other stuff
347 return what.replace("$" + p_str, "") + end;
348 }
349 if (what.to_lower().ends_with("-" + p_str)) { //collada only supports "_" and "-" besides letters
350 return what.substr(0, what.length() - (p_str.length() + 1)) + end;
351 }
352 if (what.to_lower().ends_with("_" + p_str)) { //collada only supports "_" and "-" besides letters
353 return what.substr(0, what.length() - (p_str.length() + 1)) + end;
354 }
355 return what;
356}
357
358static void _pre_gen_shape_list(Ref<ImporterMesh> &mesh, Vector<Ref<Shape3D>> &r_shape_list, bool p_convex) {
359 ERR_FAIL_NULL_MSG(mesh, "Cannot generate shape list with null mesh value.");
360 if (!p_convex) {
361 Ref<ConcavePolygonShape3D> shape = mesh->create_trimesh_shape();
362 r_shape_list.push_back(shape);
363 } else {
364 Vector<Ref<Shape3D>> cd;
365 cd.push_back(mesh->create_convex_shape(true, /*Passing false, otherwise VHACD will be used to simplify (Decompose) the Mesh.*/ false));
366 if (cd.size()) {
367 for (int i = 0; i < cd.size(); i++) {
368 r_shape_list.push_back(cd[i]);
369 }
370 }
371 }
372}
373
374struct ScalableNodeCollection {
375 HashSet<Node3D *> node_3ds;
376 HashSet<Ref<ImporterMesh>> importer_meshes;
377 HashSet<Ref<Skin>> skins;
378 HashSet<Ref<Animation>> animations;
379};
380
381void _rescale_importer_mesh(Vector3 p_scale, Ref<ImporterMesh> p_mesh, bool is_shadow = false) {
382 // MESH and SKIN data divide, to compensate for object position multiplying.
383
384 const int surf_count = p_mesh->get_surface_count();
385 const int blendshape_count = p_mesh->get_blend_shape_count();
386 struct LocalSurfData {
387 Mesh::PrimitiveType prim = {};
388 Array arr;
389 Array bsarr;
390 Dictionary lods;
391 String name;
392 Ref<Material> mat;
393 int fmt_compress_flags = 0;
394 };
395
396 Vector<LocalSurfData> surf_data_by_mesh;
397
398 Vector<String> blendshape_names;
399 for (int bsidx = 0; bsidx < blendshape_count; bsidx++) {
400 blendshape_names.append(p_mesh->get_blend_shape_name(bsidx));
401 }
402
403 for (int surf_idx = 0; surf_idx < surf_count; surf_idx++) {
404 Mesh::PrimitiveType prim = p_mesh->get_surface_primitive_type(surf_idx);
405 const int fmt_compress_flags = p_mesh->get_surface_format(surf_idx);
406 Array arr = p_mesh->get_surface_arrays(surf_idx);
407 String name = p_mesh->get_surface_name(surf_idx);
408 Dictionary lods;
409 Ref<Material> mat = p_mesh->get_surface_material(surf_idx);
410 {
411 Vector<Vector3> vertex_array = arr[ArrayMesh::ARRAY_VERTEX];
412 for (int vert_arr_i = 0; vert_arr_i < vertex_array.size(); vert_arr_i++) {
413 vertex_array.write[vert_arr_i] = vertex_array[vert_arr_i] * p_scale;
414 }
415 arr[ArrayMesh::ARRAY_VERTEX] = vertex_array;
416 }
417 Array blendshapes;
418 for (int bsidx = 0; bsidx < blendshape_count; bsidx++) {
419 Array current_bsarr = p_mesh->get_surface_blend_shape_arrays(surf_idx, bsidx);
420 Vector<Vector3> current_bs_vertex_array = current_bsarr[ArrayMesh::ARRAY_VERTEX];
421 int current_bs_vert_arr_len = current_bs_vertex_array.size();
422 for (int32_t bs_vert_arr_i = 0; bs_vert_arr_i < current_bs_vert_arr_len; bs_vert_arr_i++) {
423 current_bs_vertex_array.write[bs_vert_arr_i] = current_bs_vertex_array[bs_vert_arr_i] * p_scale;
424 }
425 current_bsarr[ArrayMesh::ARRAY_VERTEX] = current_bs_vertex_array;
426 blendshapes.push_back(current_bsarr);
427 }
428
429 LocalSurfData surf_data_dictionary = LocalSurfData();
430 surf_data_dictionary.prim = prim;
431 surf_data_dictionary.arr = arr;
432 surf_data_dictionary.bsarr = blendshapes;
433 surf_data_dictionary.lods = lods;
434 surf_data_dictionary.fmt_compress_flags = fmt_compress_flags;
435 surf_data_dictionary.name = name;
436 surf_data_dictionary.mat = mat;
437
438 surf_data_by_mesh.push_back(surf_data_dictionary);
439 }
440
441 p_mesh->clear();
442
443 for (int bsidx = 0; bsidx < blendshape_count; bsidx++) {
444 p_mesh->add_blend_shape(blendshape_names[bsidx]);
445 }
446
447 for (int surf_idx = 0; surf_idx < surf_count; surf_idx++) {
448 const Mesh::PrimitiveType prim = surf_data_by_mesh[surf_idx].prim;
449 const Array arr = surf_data_by_mesh[surf_idx].arr;
450 const Array bsarr = surf_data_by_mesh[surf_idx].bsarr;
451 const Dictionary lods = surf_data_by_mesh[surf_idx].lods;
452 const int fmt_compress_flags = surf_data_by_mesh[surf_idx].fmt_compress_flags;
453 const String name = surf_data_by_mesh[surf_idx].name;
454 const Ref<Material> mat = surf_data_by_mesh[surf_idx].mat;
455
456 p_mesh->add_surface(prim, arr, bsarr, lods, mat, name, fmt_compress_flags);
457 }
458
459 if (!is_shadow && p_mesh->get_shadow_mesh() != p_mesh && p_mesh->get_shadow_mesh().is_valid()) {
460 _rescale_importer_mesh(p_scale, p_mesh->get_shadow_mesh(), true);
461 }
462}
463
464void _rescale_skin(Vector3 p_scale, Ref<Skin> p_skin) {
465 // MESH and SKIN data divide, to compensate for object position multiplying.
466 for (int i = 0; i < p_skin->get_bind_count(); i++) {
467 Transform3D transform = p_skin->get_bind_pose(i);
468 p_skin->set_bind_pose(i, Transform3D(transform.basis, p_scale * transform.origin));
469 }
470}
471
472void _rescale_animation(Vector3 p_scale, Ref<Animation> p_animation) {
473 for (int track_idx = 0; track_idx < p_animation->get_track_count(); track_idx++) {
474 if (p_animation->track_get_type(track_idx) == Animation::TYPE_POSITION_3D) {
475 for (int key_idx = 0; key_idx < p_animation->track_get_key_count(track_idx); key_idx++) {
476 Vector3 value = p_animation->track_get_key_value(track_idx, key_idx);
477 value = p_scale * value;
478 p_animation->track_set_key_value(track_idx, key_idx, value);
479 }
480 }
481 }
482}
483
484void _apply_scale_to_scalable_node_collection(ScalableNodeCollection &p_collection, Vector3 p_scale) {
485 for (Node3D *node_3d : p_collection.node_3ds) {
486 node_3d->set_position(p_scale * node_3d->get_position());
487 Skeleton3D *skeleton_3d = Object::cast_to<Skeleton3D>(node_3d);
488 if (skeleton_3d) {
489 for (int i = 0; i < skeleton_3d->get_bone_count(); i++) {
490 Transform3D rest = skeleton_3d->get_bone_rest(i);
491 skeleton_3d->set_bone_rest(i, Transform3D(rest.basis, p_scale * rest.origin));
492 skeleton_3d->set_bone_pose_position(i, p_scale * rest.origin);
493 }
494 }
495 }
496 for (Ref<ImporterMesh> mesh : p_collection.importer_meshes) {
497 _rescale_importer_mesh(p_scale, mesh, false);
498 }
499 for (Ref<Skin> skin : p_collection.skins) {
500 _rescale_skin(p_scale, skin);
501 }
502 for (Ref<Animation> animation : p_collection.animations) {
503 _rescale_animation(p_scale, animation);
504 }
505}
506
507void _populate_scalable_nodes_collection(Node *p_node, ScalableNodeCollection &p_collection) {
508 if (!p_node) {
509 return;
510 }
511 Node3D *node_3d = Object::cast_to<Node3D>(p_node);
512 if (node_3d) {
513 p_collection.node_3ds.insert(node_3d);
514 ImporterMeshInstance3D *mesh_instance_3d = Object::cast_to<ImporterMeshInstance3D>(p_node);
515 if (mesh_instance_3d) {
516 Ref<ImporterMesh> mesh = mesh_instance_3d->get_mesh();
517 if (mesh.is_valid()) {
518 p_collection.importer_meshes.insert(mesh);
519 }
520 Ref<Skin> skin = mesh_instance_3d->get_skin();
521 if (skin.is_valid()) {
522 p_collection.skins.insert(skin);
523 }
524 }
525 }
526 AnimationPlayer *animation_player = Object::cast_to<AnimationPlayer>(p_node);
527 if (animation_player) {
528 List<StringName> animation_list;
529 animation_player->get_animation_list(&animation_list);
530
531 for (const StringName &E : animation_list) {
532 Ref<Animation> animation = animation_player->get_animation(E);
533 p_collection.animations.insert(animation);
534 }
535 }
536
537 for (int i = 0; i < p_node->get_child_count(); i++) {
538 Node *child = p_node->get_child(i);
539 _populate_scalable_nodes_collection(child, p_collection);
540 }
541}
542
543void _apply_permanent_scale_to_descendants(Node *p_root_node, Vector3 p_scale) {
544 ScalableNodeCollection scalable_node_collection;
545 _populate_scalable_nodes_collection(p_root_node, scalable_node_collection);
546 _apply_scale_to_scalable_node_collection(scalable_node_collection, p_scale);
547}
548
549Node *ResourceImporterScene::_pre_fix_node(Node *p_node, Node *p_root, HashMap<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &r_collision_map, Pair<PackedVector3Array, PackedInt32Array> *r_occluder_arrays, List<Pair<NodePath, Node *>> &r_node_renames) {
550 // Children first.
551 for (int i = 0; i < p_node->get_child_count(); i++) {
552 Node *r = _pre_fix_node(p_node->get_child(i), p_root, r_collision_map, r_occluder_arrays, r_node_renames);
553 if (!r) {
554 i--; // Was erased.
555 }
556 }
557
558 String name = p_node->get_name();
559 NodePath original_path = p_root->get_path_to(p_node); // Used to detect renames due to import hints.
560
561 bool isroot = p_node == p_root;
562
563 if (!isroot && _teststr(name, "noimp")) {
564 p_node->set_owner(nullptr);
565 memdelete(p_node);
566 return nullptr;
567 }
568
569 if (Object::cast_to<ImporterMeshInstance3D>(p_node)) {
570 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
571
572 Ref<ImporterMesh> m = mi->get_mesh();
573
574 if (m.is_valid()) {
575 for (int i = 0; i < m->get_surface_count(); i++) {
576 Ref<BaseMaterial3D> mat = m->get_surface_material(i);
577 if (!mat.is_valid()) {
578 continue;
579 }
580
581 if (_teststr(mat->get_name(), "alpha")) {
582 mat->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
583 mat->set_name(_fixstr(mat->get_name(), "alpha"));
584 }
585 if (_teststr(mat->get_name(), "vcol")) {
586 mat->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
587 mat->set_flag(BaseMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
588 mat->set_name(_fixstr(mat->get_name(), "vcol"));
589 }
590 }
591 }
592 }
593
594 if (Object::cast_to<AnimationPlayer>(p_node)) {
595 AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
596
597 // Node paths in animation tracks are relative to the following path (this is used to fix node paths below).
598 Node *ap_root = ap->get_node(ap->get_root());
599 NodePath path_prefix = p_root->get_path_to(ap_root);
600
601 bool nodes_were_renamed = r_node_renames.size() != 0;
602
603 List<StringName> anims;
604 ap->get_animation_list(&anims);
605 for (const StringName &E : anims) {
606 Ref<Animation> anim = ap->get_animation(E);
607 ERR_CONTINUE(anim.is_null());
608
609 // Remove animation tracks referencing non-importable nodes.
610 for (int i = 0; i < anim->get_track_count(); i++) {
611 NodePath path = anim->track_get_path(i);
612
613 for (int j = 0; j < path.get_name_count(); j++) {
614 String node = path.get_name(j);
615 if (_teststr(node, "noimp")) {
616 anim->remove_track(i);
617 i--;
618 break;
619 }
620 }
621 }
622
623 // Fix node paths in animations, in case nodes were renamed earlier due to import hints.
624 if (nodes_were_renamed) {
625 for (int i = 0; i < anim->get_track_count(); i++) {
626 NodePath path = anim->track_get_path(i);
627 // Convert track path to absolute node path without subnames (some manual work because we are not in the scene tree).
628 Vector<StringName> absolute_path_names = path_prefix.get_names();
629 absolute_path_names.append_array(path.get_names());
630 NodePath absolute_path(absolute_path_names, false);
631 absolute_path.simplify();
632 // Fix paths to renamed nodes.
633 for (const Pair<NodePath, Node *> &F : r_node_renames) {
634 if (F.first == absolute_path) {
635 NodePath new_path(ap_root->get_path_to(F.second).get_names(), path.get_subnames(), false);
636 print_verbose(vformat("Fix: Correcting node path in animation track: %s should be %s", path, new_path));
637 anim->track_set_path(i, new_path);
638 break; // Only one match is possible.
639 }
640 }
641 }
642 }
643
644 String animname = E;
645 const int loop_string_count = 3;
646 static const char *loop_strings[loop_string_count] = { "loop_mode", "loop", "cycle" };
647 for (int i = 0; i < loop_string_count; i++) {
648 if (_teststr(animname, loop_strings[i])) {
649 anim->set_loop_mode(Animation::LOOP_LINEAR);
650 animname = _fixstr(animname, loop_strings[i]);
651
652 Ref<AnimationLibrary> library = ap->get_animation_library(ap->find_animation_library(anim));
653 library->rename_animation(E, animname);
654 }
655 }
656 }
657 }
658
659 if (_teststr(name, "colonly") || _teststr(name, "convcolonly")) {
660 if (isroot) {
661 return p_node;
662 }
663
664 String fixed_name;
665 if (_teststr(name, "colonly")) {
666 fixed_name = _fixstr(name, "colonly");
667 } else if (_teststr(name, "convcolonly")) {
668 fixed_name = _fixstr(name, "convcolonly");
669 }
670
671 ERR_FAIL_COND_V(fixed_name.is_empty(), nullptr);
672
673 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
674 if (mi) {
675 Ref<ImporterMesh> mesh = mi->get_mesh();
676
677 if (mesh.is_valid()) {
678 Vector<Ref<Shape3D>> shapes;
679 if (r_collision_map.has(mesh)) {
680 shapes = r_collision_map[mesh];
681 } else if (_teststr(name, "colonly")) {
682 _pre_gen_shape_list(mesh, shapes, false);
683 r_collision_map[mesh] = shapes;
684 } else if (_teststr(name, "convcolonly")) {
685 _pre_gen_shape_list(mesh, shapes, true);
686 r_collision_map[mesh] = shapes;
687 }
688
689 if (shapes.size()) {
690 StaticBody3D *col = memnew(StaticBody3D);
691 col->set_transform(mi->get_transform());
692 col->set_name(fixed_name);
693 p_node->replace_by(col);
694 p_node->set_owner(nullptr);
695 memdelete(p_node);
696 p_node = col;
697
698 _add_shapes(col, shapes);
699 }
700 }
701
702 } else if (p_node->has_meta("empty_draw_type")) {
703 String empty_draw_type = String(p_node->get_meta("empty_draw_type"));
704 StaticBody3D *sb = memnew(StaticBody3D);
705 sb->set_name(fixed_name);
706 Object::cast_to<Node3D>(sb)->set_transform(Object::cast_to<Node3D>(p_node)->get_transform());
707 p_node->replace_by(sb);
708 p_node->set_owner(nullptr);
709 memdelete(p_node);
710 p_node = sb;
711 CollisionShape3D *colshape = memnew(CollisionShape3D);
712 if (empty_draw_type == "CUBE") {
713 BoxShape3D *boxShape = memnew(BoxShape3D);
714 boxShape->set_size(Vector3(2, 2, 2));
715 colshape->set_shape(boxShape);
716 } else if (empty_draw_type == "SINGLE_ARROW") {
717 SeparationRayShape3D *rayShape = memnew(SeparationRayShape3D);
718 rayShape->set_length(1);
719 colshape->set_shape(rayShape);
720 Object::cast_to<Node3D>(sb)->rotate_x(Math_PI / 2);
721 } else if (empty_draw_type == "IMAGE") {
722 WorldBoundaryShape3D *world_boundary_shape = memnew(WorldBoundaryShape3D);
723 colshape->set_shape(world_boundary_shape);
724 } else {
725 SphereShape3D *sphereShape = memnew(SphereShape3D);
726 sphereShape->set_radius(1);
727 colshape->set_shape(sphereShape);
728 }
729 sb->add_child(colshape, true);
730 colshape->set_owner(sb->get_owner());
731 }
732
733 } else if (_teststr(name, "rigid") && Object::cast_to<ImporterMeshInstance3D>(p_node)) {
734 if (isroot) {
735 return p_node;
736 }
737
738 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
739 Ref<ImporterMesh> mesh = mi->get_mesh();
740
741 if (mesh.is_valid()) {
742 Vector<Ref<Shape3D>> shapes;
743 if (r_collision_map.has(mesh)) {
744 shapes = r_collision_map[mesh];
745 } else {
746 _pre_gen_shape_list(mesh, shapes, true);
747 }
748
749 RigidBody3D *rigid_body = memnew(RigidBody3D);
750 rigid_body->set_name(_fixstr(name, "rigid_body"));
751 p_node->replace_by(rigid_body);
752 rigid_body->set_transform(mi->get_transform());
753 p_node = rigid_body;
754 mi->set_transform(Transform3D());
755 rigid_body->add_child(mi, true);
756 mi->set_owner(rigid_body->get_owner());
757
758 _add_shapes(rigid_body, shapes);
759 }
760
761 } else if ((_teststr(name, "col") || (_teststr(name, "convcol"))) && Object::cast_to<ImporterMeshInstance3D>(p_node)) {
762 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
763
764 Ref<ImporterMesh> mesh = mi->get_mesh();
765
766 if (mesh.is_valid()) {
767 Vector<Ref<Shape3D>> shapes;
768 String fixed_name;
769 if (r_collision_map.has(mesh)) {
770 shapes = r_collision_map[mesh];
771 } else if (_teststr(name, "col")) {
772 _pre_gen_shape_list(mesh, shapes, false);
773 r_collision_map[mesh] = shapes;
774 } else if (_teststr(name, "convcol")) {
775 _pre_gen_shape_list(mesh, shapes, true);
776 r_collision_map[mesh] = shapes;
777 }
778
779 if (_teststr(name, "col")) {
780 fixed_name = _fixstr(name, "col");
781 } else if (_teststr(name, "convcol")) {
782 fixed_name = _fixstr(name, "convcol");
783 }
784
785 if (!fixed_name.is_empty()) {
786 if (mi->get_parent() && !mi->get_parent()->has_node(fixed_name)) {
787 mi->set_name(fixed_name);
788 }
789 }
790
791 if (shapes.size()) {
792 StaticBody3D *col = memnew(StaticBody3D);
793 mi->add_child(col, true);
794 col->set_owner(mi->get_owner());
795
796 _add_shapes(col, shapes);
797 }
798 }
799
800 } else if (_teststr(name, "navmesh") && Object::cast_to<ImporterMeshInstance3D>(p_node)) {
801 if (isroot) {
802 return p_node;
803 }
804
805 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
806
807 Ref<ImporterMesh> mesh = mi->get_mesh();
808 ERR_FAIL_COND_V(mesh.is_null(), nullptr);
809 NavigationRegion3D *nmi = memnew(NavigationRegion3D);
810
811 nmi->set_name(_fixstr(name, "navmesh"));
812 Ref<NavigationMesh> nmesh = mesh->create_navigation_mesh();
813 nmi->set_navigation_mesh(nmesh);
814 Object::cast_to<Node3D>(nmi)->set_transform(mi->get_transform());
815 p_node->replace_by(nmi);
816 p_node->set_owner(nullptr);
817 memdelete(p_node);
818 p_node = nmi;
819 } else if (_teststr(name, "occ") || _teststr(name, "occonly")) {
820 if (isroot) {
821 return p_node;
822 }
823 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
824 if (mi) {
825 Ref<ImporterMesh> mesh = mi->get_mesh();
826
827 if (mesh.is_valid()) {
828 if (r_occluder_arrays) {
829 OccluderInstance3D::bake_single_node(mi, 0.0f, r_occluder_arrays->first, r_occluder_arrays->second);
830 }
831 if (_teststr(name, "occ")) {
832 String fixed_name = _fixstr(name, "occ");
833 if (!fixed_name.is_empty()) {
834 if (mi->get_parent() && !mi->get_parent()->has_node(fixed_name)) {
835 mi->set_name(fixed_name);
836 }
837 }
838 } else {
839 p_node->set_owner(nullptr);
840 memdelete(p_node);
841 p_node = nullptr;
842 }
843 }
844 }
845 } else if (_teststr(name, "vehicle")) {
846 if (isroot) {
847 return p_node;
848 }
849
850 Node *owner = p_node->get_owner();
851 Node3D *s = Object::cast_to<Node3D>(p_node);
852 VehicleBody3D *bv = memnew(VehicleBody3D);
853 String n = _fixstr(p_node->get_name(), "vehicle");
854 bv->set_name(n);
855 p_node->replace_by(bv);
856 p_node->set_name(n);
857 bv->add_child(p_node);
858 bv->set_owner(owner);
859 p_node->set_owner(owner);
860 bv->set_transform(s->get_transform());
861 s->set_transform(Transform3D());
862
863 p_node = bv;
864 } else if (_teststr(name, "wheel")) {
865 if (isroot) {
866 return p_node;
867 }
868
869 Node *owner = p_node->get_owner();
870 Node3D *s = Object::cast_to<Node3D>(p_node);
871 VehicleWheel3D *bv = memnew(VehicleWheel3D);
872 String n = _fixstr(p_node->get_name(), "wheel");
873 bv->set_name(n);
874 p_node->replace_by(bv);
875 p_node->set_name(n);
876 bv->add_child(p_node);
877 bv->set_owner(owner);
878 p_node->set_owner(owner);
879 bv->set_transform(s->get_transform());
880 s->set_transform(Transform3D());
881
882 p_node = bv;
883 } else if (Object::cast_to<ImporterMeshInstance3D>(p_node)) {
884 //last attempt, maybe collision inside the mesh data
885
886 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
887
888 Ref<ImporterMesh> mesh = mi->get_mesh();
889 if (!mesh.is_null()) {
890 Vector<Ref<Shape3D>> shapes;
891 if (r_collision_map.has(mesh)) {
892 shapes = r_collision_map[mesh];
893 } else if (_teststr(mesh->get_name(), "col")) {
894 _pre_gen_shape_list(mesh, shapes, false);
895 r_collision_map[mesh] = shapes;
896 mesh->set_name(_fixstr(mesh->get_name(), "col"));
897 } else if (_teststr(mesh->get_name(), "convcol")) {
898 _pre_gen_shape_list(mesh, shapes, true);
899 r_collision_map[mesh] = shapes;
900 mesh->set_name(_fixstr(mesh->get_name(), "convcol"));
901 } else if (_teststr(mesh->get_name(), "occ")) {
902 if (r_occluder_arrays) {
903 OccluderInstance3D::bake_single_node(mi, 0.0f, r_occluder_arrays->first, r_occluder_arrays->second);
904 }
905 mesh->set_name(_fixstr(mesh->get_name(), "occ"));
906 }
907
908 if (shapes.size()) {
909 StaticBody3D *col = memnew(StaticBody3D);
910 p_node->add_child(col, true);
911 col->set_owner(p_node->get_owner());
912
913 _add_shapes(col, shapes);
914 }
915 }
916 }
917
918 if (p_node) {
919 NodePath new_path = p_root->get_path_to(p_node);
920 if (new_path != original_path) {
921 print_verbose(vformat("Fix: Renamed %s to %s", original_path, new_path));
922 r_node_renames.push_back({ original_path, p_node });
923 }
924 }
925
926 return p_node;
927}
928
929Node *ResourceImporterScene::_pre_fix_animations(Node *p_node, Node *p_root, const Dictionary &p_node_data, const Dictionary &p_animation_data, float p_animation_fps) {
930 // children first
931 for (int i = 0; i < p_node->get_child_count(); i++) {
932 Node *r = _pre_fix_animations(p_node->get_child(i), p_root, p_node_data, p_animation_data, p_animation_fps);
933 if (!r) {
934 i--; //was erased
935 }
936 }
937
938 String import_id = p_node->get_meta("import_id", "PATH:" + p_root->get_path_to(p_node));
939
940 Dictionary node_settings;
941 if (p_node_data.has(import_id)) {
942 node_settings = p_node_data[import_id];
943 }
944
945 {
946 //make sure this is unique
947 node_settings = node_settings.duplicate(true);
948 //fill node settings for this node with default values
949 List<ImportOption> iopts;
950 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE, &iopts);
951 for (const ImportOption &E : iopts) {
952 if (!node_settings.has(E.option.name)) {
953 node_settings[E.option.name] = E.default_value;
954 }
955 }
956 }
957
958 if (Object::cast_to<AnimationPlayer>(p_node)) {
959 AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
960 List<StringName> anims;
961 ap->get_animation_list(&anims);
962
963 for (const StringName &name : anims) {
964 Ref<Animation> anim = ap->get_animation(name);
965 Array animation_slices;
966
967 if (p_animation_data.has(name)) {
968 Dictionary anim_settings = p_animation_data[name];
969 int slices_count = anim_settings["slices/amount"];
970
971 for (int i = 0; i < slices_count; i++) {
972 String slice_name = anim_settings["slice_" + itos(i + 1) + "/name"];
973 int from_frame = anim_settings["slice_" + itos(i + 1) + "/start_frame"];
974 int end_frame = anim_settings["slice_" + itos(i + 1) + "/end_frame"];
975 Animation::LoopMode loop_mode = static_cast<Animation::LoopMode>((int)anim_settings["slice_" + itos(i + 1) + "/loop_mode"]);
976 bool save_to_file = anim_settings["slice_" + itos(i + 1) + "/save_to_file/enabled"];
977 bool save_to_path = anim_settings["slice_" + itos(i + 1) + "/save_to_file/path"];
978 bool save_to_file_keep_custom = anim_settings["slice_" + itos(i + 1) + "/save_to_file/keep_custom_tracks"];
979
980 animation_slices.push_back(slice_name);
981 animation_slices.push_back(from_frame / p_animation_fps);
982 animation_slices.push_back(end_frame / p_animation_fps);
983 animation_slices.push_back(loop_mode);
984 animation_slices.push_back(save_to_file);
985 animation_slices.push_back(save_to_path);
986 animation_slices.push_back(save_to_file_keep_custom);
987 }
988 }
989
990 if (animation_slices.size() > 0) {
991 _create_slices(ap, anim, animation_slices, true);
992 }
993 }
994
995 AnimationImportTracks import_tracks_mode[TRACK_CHANNEL_MAX] = {
996 AnimationImportTracks(int(node_settings["import_tracks/position"])),
997 AnimationImportTracks(int(node_settings["import_tracks/rotation"])),
998 AnimationImportTracks(int(node_settings["import_tracks/scale"]))
999 };
1000
1001 if (!anims.is_empty() && (import_tracks_mode[0] != ANIMATION_IMPORT_TRACKS_IF_PRESENT || import_tracks_mode[1] != ANIMATION_IMPORT_TRACKS_IF_PRESENT || import_tracks_mode[2] != ANIMATION_IMPORT_TRACKS_IF_PRESENT)) {
1002 _optimize_track_usage(ap, import_tracks_mode);
1003 }
1004 }
1005
1006 return p_node;
1007}
1008
1009Node *ResourceImporterScene::_post_fix_animations(Node *p_node, Node *p_root, const Dictionary &p_node_data, const Dictionary &p_animation_data, float p_animation_fps) {
1010 // children first
1011 for (int i = 0; i < p_node->get_child_count(); i++) {
1012 Node *r = _post_fix_animations(p_node->get_child(i), p_root, p_node_data, p_animation_data, p_animation_fps);
1013 if (!r) {
1014 i--; //was erased
1015 }
1016 }
1017
1018 String import_id = p_node->get_meta("import_id", "PATH:" + p_root->get_path_to(p_node));
1019
1020 Dictionary node_settings;
1021 if (p_node_data.has(import_id)) {
1022 node_settings = p_node_data[import_id];
1023 }
1024
1025 {
1026 //make sure this is unique
1027 node_settings = node_settings.duplicate(true);
1028 //fill node settings for this node with default values
1029 List<ImportOption> iopts;
1030 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE, &iopts);
1031 for (const ImportOption &E : iopts) {
1032 if (!node_settings.has(E.option.name)) {
1033 node_settings[E.option.name] = E.default_value;
1034 }
1035 }
1036 }
1037
1038 if (Object::cast_to<AnimationPlayer>(p_node)) {
1039 AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
1040
1041 bool use_optimizer = node_settings["optimizer/enabled"];
1042 float anim_optimizer_linerr = node_settings["optimizer/max_velocity_error"];
1043 float anim_optimizer_angerr = node_settings["optimizer/max_angular_error"];
1044 int anim_optimizer_preerr = node_settings["optimizer/max_precision_error"];
1045
1046 if (use_optimizer) {
1047 _optimize_animations(ap, anim_optimizer_linerr, anim_optimizer_angerr, anim_optimizer_preerr);
1048 }
1049
1050 bool use_compression = node_settings["compression/enabled"];
1051 int anim_compression_page_size = node_settings["compression/page_size"];
1052
1053 if (use_compression) {
1054 _compress_animations(ap, anim_compression_page_size);
1055 }
1056
1057 List<StringName> anims;
1058 ap->get_animation_list(&anims);
1059 for (const StringName &name : anims) {
1060 Ref<Animation> anim = ap->get_animation(name);
1061 if (p_animation_data.has(name)) {
1062 Dictionary anim_settings = p_animation_data[name];
1063 {
1064 //fill with default values
1065 List<ImportOption> iopts;
1066 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_ANIMATION, &iopts);
1067 for (const ImportOption &F : iopts) {
1068 if (!anim_settings.has(F.option.name)) {
1069 anim_settings[F.option.name] = F.default_value;
1070 }
1071 }
1072 }
1073
1074 anim->set_loop_mode(static_cast<Animation::LoopMode>((int)anim_settings["settings/loop_mode"]));
1075 bool save = anim_settings["save_to_file/enabled"];
1076 String path = anim_settings["save_to_file/path"];
1077 bool keep_custom = anim_settings["save_to_file/keep_custom_tracks"];
1078
1079 Ref<Animation> saved_anim = _save_animation_to_file(anim, save, path, keep_custom);
1080
1081 if (saved_anim != anim) {
1082 Ref<AnimationLibrary> al = ap->get_animation_library(ap->find_animation_library(anim));
1083 al->add_animation(name, saved_anim); //replace
1084 }
1085 }
1086 }
1087 }
1088
1089 return p_node;
1090}
1091
1092Node *ResourceImporterScene::_post_fix_node(Node *p_node, Node *p_root, HashMap<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> &collision_map, Pair<PackedVector3Array, PackedInt32Array> &r_occluder_arrays, HashSet<Ref<ImporterMesh>> &r_scanned_meshes, const Dictionary &p_node_data, const Dictionary &p_material_data, const Dictionary &p_animation_data, float p_animation_fps, float p_applied_root_scale) {
1093 // children first
1094 for (int i = 0; i < p_node->get_child_count(); i++) {
1095 Node *r = _post_fix_node(p_node->get_child(i), p_root, collision_map, r_occluder_arrays, r_scanned_meshes, p_node_data, p_material_data, p_animation_data, p_animation_fps, p_applied_root_scale);
1096 if (!r) {
1097 i--; //was erased
1098 }
1099 }
1100
1101 bool isroot = p_node == p_root;
1102
1103 String import_id = p_node->get_meta("import_id", "PATH:" + p_root->get_path_to(p_node));
1104
1105 Dictionary node_settings;
1106 if (p_node_data.has(import_id)) {
1107 node_settings = p_node_data[import_id];
1108 }
1109
1110 if (!isroot && (node_settings.has("import/skip_import") && bool(node_settings["import/skip_import"]))) {
1111 p_node->set_owner(nullptr);
1112 memdelete(p_node);
1113 return nullptr;
1114 }
1115
1116 {
1117 //make sure this is unique
1118 node_settings = node_settings.duplicate(true);
1119 //fill node settings for this node with default values
1120 List<ImportOption> iopts;
1121 if (Object::cast_to<ImporterMeshInstance3D>(p_node)) {
1122 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE, &iopts);
1123 } else if (Object::cast_to<AnimationPlayer>(p_node)) {
1124 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE, &iopts);
1125 } else if (Object::cast_to<Skeleton3D>(p_node)) {
1126 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE, &iopts);
1127 } else {
1128 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_NODE, &iopts);
1129 }
1130 for (const ImportOption &E : iopts) {
1131 if (!node_settings.has(E.option.name)) {
1132 node_settings[E.option.name] = E.default_value;
1133 }
1134 }
1135 }
1136
1137 {
1138 ObjectID node_id = p_node->get_instance_id();
1139 for (int i = 0; i < post_importer_plugins.size(); i++) {
1140 post_importer_plugins.write[i]->internal_process(EditorScenePostImportPlugin::INTERNAL_IMPORT_CATEGORY_NODE, p_root, p_node, Ref<Resource>(), node_settings);
1141 if (ObjectDB::get_instance(node_id) == nullptr) { //may have been erased, so do not continue
1142 break;
1143 }
1144 }
1145 }
1146
1147 if (Object::cast_to<ImporterMeshInstance3D>(p_node)) {
1148 ObjectID node_id = p_node->get_instance_id();
1149 for (int i = 0; i < post_importer_plugins.size(); i++) {
1150 post_importer_plugins.write[i]->internal_process(EditorScenePostImportPlugin::INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE, p_root, p_node, Ref<Resource>(), node_settings);
1151 if (ObjectDB::get_instance(node_id) == nullptr) { //may have been erased, so do not continue
1152 break;
1153 }
1154 }
1155 }
1156
1157 if (Object::cast_to<Skeleton3D>(p_node)) {
1158 ObjectID node_id = p_node->get_instance_id();
1159 for (int i = 0; i < post_importer_plugins.size(); i++) {
1160 post_importer_plugins.write[i]->internal_process(EditorScenePostImportPlugin::INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE, p_root, p_node, Ref<Resource>(), node_settings);
1161 if (ObjectDB::get_instance(node_id) == nullptr) { //may have been erased, so do not continue
1162 break;
1163 }
1164 }
1165 }
1166
1167 if (Object::cast_to<ImporterMeshInstance3D>(p_node)) {
1168 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
1169
1170 Ref<ImporterMesh> m = mi->get_mesh();
1171
1172 if (m.is_valid()) {
1173 if (!r_scanned_meshes.has(m)) {
1174 for (int i = 0; i < m->get_surface_count(); i++) {
1175 Ref<Material> mat = m->get_surface_material(i);
1176 if (mat.is_valid()) {
1177 String mat_id = mat->get_meta("import_id", mat->get_name());
1178
1179 if (!mat_id.is_empty() && p_material_data.has(mat_id)) {
1180 Dictionary matdata = p_material_data[mat_id];
1181 {
1182 //fill node settings for this node with default values
1183 List<ImportOption> iopts;
1184 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_MATERIAL, &iopts);
1185 for (const ImportOption &E : iopts) {
1186 if (!matdata.has(E.option.name)) {
1187 matdata[E.option.name] = E.default_value;
1188 }
1189 }
1190 }
1191
1192 for (int j = 0; j < post_importer_plugins.size(); j++) {
1193 post_importer_plugins.write[j]->internal_process(EditorScenePostImportPlugin::INTERNAL_IMPORT_CATEGORY_MATERIAL, p_root, p_node, mat, matdata);
1194 }
1195
1196 if (matdata.has("use_external/enabled") && bool(matdata["use_external/enabled"]) && matdata.has("use_external/path")) {
1197 String path = matdata["use_external/path"];
1198 Ref<Material> external_mat = ResourceLoader::load(path);
1199 if (external_mat.is_valid()) {
1200 m->set_surface_material(i, external_mat);
1201 }
1202 }
1203 }
1204 }
1205 }
1206
1207 r_scanned_meshes.insert(m);
1208 }
1209
1210 if (node_settings.has("generate/physics")) {
1211 int mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_DISABLED;
1212
1213 const bool generate_collider = node_settings["generate/physics"];
1214 if (generate_collider) {
1215 mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_MESH_AND_STATIC_COLLIDER;
1216 if (node_settings.has("physics/body_type")) {
1217 const BodyType body_type = (BodyType)node_settings["physics/body_type"].operator int();
1218 switch (body_type) {
1219 case BODY_TYPE_STATIC:
1220 mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_MESH_AND_STATIC_COLLIDER;
1221 break;
1222 case BODY_TYPE_DYNAMIC:
1223 mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_RIGID_BODY_AND_MESH;
1224 break;
1225 case BODY_TYPE_AREA:
1226 mesh_physics_mode = MeshPhysicsMode::MESH_PHYSICS_AREA_ONLY;
1227 break;
1228 }
1229 }
1230 }
1231
1232 if (mesh_physics_mode != MeshPhysicsMode::MESH_PHYSICS_DISABLED) {
1233 Vector<Ref<Shape3D>> shapes;
1234 if (collision_map.has(m)) {
1235 shapes = collision_map[m];
1236 } else {
1237 shapes = get_collision_shapes(
1238 m,
1239 node_settings,
1240 p_applied_root_scale);
1241 }
1242
1243 if (shapes.size()) {
1244 CollisionObject3D *base = nullptr;
1245 switch (mesh_physics_mode) {
1246 case MESH_PHYSICS_MESH_AND_STATIC_COLLIDER: {
1247 StaticBody3D *col = memnew(StaticBody3D);
1248 p_node->add_child(col, true);
1249 col->set_owner(p_node->get_owner());
1250 col->set_transform(get_collision_shapes_transform(node_settings));
1251 col->set_position(p_applied_root_scale * col->get_position());
1252 const Ref<PhysicsMaterial> &pmo = node_settings["physics/physics_material_override"];
1253 if (!pmo.is_null()) {
1254 col->set_physics_material_override(pmo);
1255 }
1256 base = col;
1257 } break;
1258 case MESH_PHYSICS_RIGID_BODY_AND_MESH: {
1259 RigidBody3D *rigid_body = memnew(RigidBody3D);
1260 rigid_body->set_name(p_node->get_name());
1261 p_node->replace_by(rigid_body);
1262 rigid_body->set_transform(mi->get_transform() * get_collision_shapes_transform(node_settings));
1263 rigid_body->set_position(p_applied_root_scale * rigid_body->get_position());
1264 p_node = rigid_body;
1265 mi->set_transform(Transform3D());
1266 rigid_body->add_child(mi, true);
1267 mi->set_owner(rigid_body->get_owner());
1268 const Ref<PhysicsMaterial> &pmo = node_settings["physics/physics_material_override"];
1269 if (!pmo.is_null()) {
1270 rigid_body->set_physics_material_override(pmo);
1271 }
1272 base = rigid_body;
1273 } break;
1274 case MESH_PHYSICS_STATIC_COLLIDER_ONLY: {
1275 StaticBody3D *col = memnew(StaticBody3D);
1276 col->set_transform(mi->get_transform() * get_collision_shapes_transform(node_settings));
1277 col->set_position(p_applied_root_scale * col->get_position());
1278 col->set_name(p_node->get_name());
1279 p_node->replace_by(col);
1280 p_node->set_owner(nullptr);
1281 memdelete(p_node);
1282 p_node = col;
1283 const Ref<PhysicsMaterial> &pmo = node_settings["physics/physics_material_override"];
1284 if (!pmo.is_null()) {
1285 col->set_physics_material_override(pmo);
1286 }
1287 base = col;
1288 } break;
1289 case MESH_PHYSICS_AREA_ONLY: {
1290 Area3D *area = memnew(Area3D);
1291 area->set_transform(mi->get_transform() * get_collision_shapes_transform(node_settings));
1292 area->set_position(p_applied_root_scale * area->get_position());
1293 area->set_name(p_node->get_name());
1294 p_node->replace_by(area);
1295 p_node->set_owner(nullptr);
1296 memdelete(p_node);
1297 p_node = area;
1298 base = area;
1299
1300 } break;
1301 }
1302
1303 base->set_collision_layer(node_settings["physics/layer"]);
1304 base->set_collision_mask(node_settings["physics/mask"]);
1305
1306 for (const Ref<Shape3D> &E : shapes) {
1307 CollisionShape3D *cshape = memnew(CollisionShape3D);
1308 cshape->set_shape(E);
1309 base->add_child(cshape, true);
1310
1311 cshape->set_owner(base->get_owner());
1312 }
1313 }
1314 }
1315 }
1316 }
1317 }
1318
1319 //navmesh (node may have changed type above)
1320 if (Object::cast_to<ImporterMeshInstance3D>(p_node)) {
1321 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
1322
1323 Ref<ImporterMesh> m = mi->get_mesh();
1324
1325 if (m.is_valid()) {
1326 if (node_settings.has("generate/navmesh")) {
1327 int navmesh_mode = node_settings["generate/navmesh"];
1328
1329 if (navmesh_mode != NAVMESH_DISABLED) {
1330 NavigationRegion3D *nmi = memnew(NavigationRegion3D);
1331
1332 Ref<NavigationMesh> nmesh = m->create_navigation_mesh();
1333 nmi->set_navigation_mesh(nmesh);
1334
1335 if (navmesh_mode == NAVMESH_NAVMESH_ONLY) {
1336 nmi->set_transform(mi->get_transform());
1337 p_node->replace_by(nmi);
1338 p_node->set_owner(nullptr);
1339 memdelete(p_node);
1340 p_node = nmi;
1341 } else {
1342 mi->add_child(nmi, true);
1343 nmi->set_owner(mi->get_owner());
1344 }
1345 }
1346 }
1347 }
1348 }
1349
1350 if (Object::cast_to<ImporterMeshInstance3D>(p_node)) {
1351 ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(p_node);
1352
1353 Ref<ImporterMesh> m = mi->get_mesh();
1354
1355 if (m.is_valid()) {
1356 if (node_settings.has("generate/occluder")) {
1357 int occluder_mode = node_settings["generate/occluder"];
1358
1359 if (occluder_mode != OCCLUDER_DISABLED) {
1360 float simplification_dist = 0.0f;
1361 if (node_settings.has("occluder/simplification_distance")) {
1362 simplification_dist = node_settings["occluder/simplification_distance"];
1363 }
1364
1365 OccluderInstance3D::bake_single_node(mi, simplification_dist, r_occluder_arrays.first, r_occluder_arrays.second);
1366
1367 if (occluder_mode == OCCLUDER_OCCLUDER_ONLY) {
1368 p_node->set_owner(nullptr);
1369 memdelete(p_node);
1370 p_node = nullptr;
1371 }
1372 }
1373 }
1374 }
1375 }
1376
1377 if (Object::cast_to<AnimationPlayer>(p_node)) {
1378 AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
1379
1380 for (int i = 0; i < post_importer_plugins.size(); i++) {
1381 post_importer_plugins.write[i]->internal_process(EditorScenePostImportPlugin::INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE, p_root, p_node, Ref<Resource>(), node_settings);
1382 }
1383
1384 if (post_importer_plugins.size()) {
1385 List<StringName> anims;
1386 ap->get_animation_list(&anims);
1387 for (const StringName &name : anims) {
1388 if (p_animation_data.has(name)) {
1389 Ref<Animation> anim = ap->get_animation(name);
1390 Dictionary anim_settings = p_animation_data[name];
1391 {
1392 //fill with default values
1393 List<ImportOption> iopts;
1394 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_ANIMATION, &iopts);
1395 for (const ImportOption &F : iopts) {
1396 if (!anim_settings.has(F.option.name)) {
1397 anim_settings[F.option.name] = F.default_value;
1398 }
1399 }
1400 }
1401
1402 for (int i = 0; i < post_importer_plugins.size(); i++) {
1403 post_importer_plugins.write[i]->internal_process(EditorScenePostImportPlugin::INTERNAL_IMPORT_CATEGORY_ANIMATION, p_root, p_node, anim, anim_settings);
1404 }
1405 }
1406 }
1407 }
1408 }
1409
1410 return p_node;
1411}
1412
1413Ref<Animation> ResourceImporterScene::_save_animation_to_file(Ref<Animation> anim, bool p_save_to_file, String p_save_to_path, bool p_keep_custom_tracks) {
1414 if (!p_save_to_file || !p_save_to_path.is_resource_file()) {
1415 return anim;
1416 }
1417
1418 if (FileAccess::exists(p_save_to_path) && p_keep_custom_tracks) {
1419 // Copy custom animation tracks from previously imported files.
1420 Ref<Animation> old_anim = ResourceLoader::load(p_save_to_path, "Animation", ResourceFormatLoader::CACHE_MODE_IGNORE);
1421 if (old_anim.is_valid()) {
1422 for (int i = 0; i < old_anim->get_track_count(); i++) {
1423 if (!old_anim->track_is_imported(i)) {
1424 old_anim->copy_track(i, anim);
1425 }
1426 }
1427 anim->set_loop_mode(old_anim->get_loop_mode());
1428 }
1429 }
1430
1431 if (ResourceCache::has(p_save_to_path)) {
1432 Ref<Animation> old_anim = ResourceCache::get_ref(p_save_to_path);
1433 if (old_anim.is_valid()) {
1434 old_anim->copy_from(anim);
1435 anim = old_anim;
1436 }
1437 }
1438 anim->set_path(p_save_to_path, true); // Set path to save externally.
1439 Error err = ResourceSaver::save(anim, p_save_to_path, ResourceSaver::FLAG_CHANGE_PATH);
1440 ERR_FAIL_COND_V_MSG(err != OK, anim, "Saving of animation failed: " + p_save_to_path);
1441 return anim;
1442}
1443
1444void ResourceImporterScene::_create_slices(AnimationPlayer *ap, Ref<Animation> anim, const Array &p_slices, bool p_bake_all) {
1445 Ref<AnimationLibrary> al = ap->get_animation_library(ap->find_animation_library(anim));
1446
1447 for (int i = 0; i < p_slices.size(); i += 7) {
1448 String name = p_slices[i];
1449 float from = p_slices[i + 1];
1450 float to = p_slices[i + 2];
1451 Animation::LoopMode loop_mode = static_cast<Animation::LoopMode>((int)p_slices[i + 3]);
1452 bool save_to_file = p_slices[i + 4];
1453 String save_to_path = p_slices[i + 5];
1454 bool keep_current = p_slices[i + 6];
1455 if (from >= to) {
1456 continue;
1457 }
1458
1459 Ref<Animation> new_anim = memnew(Animation);
1460
1461 for (int j = 0; j < anim->get_track_count(); j++) {
1462 List<float> keys;
1463 int kc = anim->track_get_key_count(j);
1464 int dtrack = -1;
1465 for (int k = 0; k < kc; k++) {
1466 float kt = anim->track_get_key_time(j, k);
1467 if (kt >= from && kt < to) {
1468 //found a key within range, so create track
1469 if (dtrack == -1) {
1470 new_anim->add_track(anim->track_get_type(j));
1471 dtrack = new_anim->get_track_count() - 1;
1472 new_anim->track_set_path(dtrack, anim->track_get_path(j));
1473
1474 if (kt > (from + 0.01) && k > 0) {
1475 if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
1476 Vector3 p;
1477 anim->try_position_track_interpolate(j, from, &p);
1478 new_anim->position_track_insert_key(dtrack, 0, p);
1479 } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
1480 Quaternion r;
1481 anim->try_rotation_track_interpolate(j, from, &r);
1482 new_anim->rotation_track_insert_key(dtrack, 0, r);
1483 } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
1484 Vector3 s;
1485 anim->try_scale_track_interpolate(j, from, &s);
1486 new_anim->scale_track_insert_key(dtrack, 0, s);
1487 } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
1488 Variant var = anim->value_track_interpolate(j, from);
1489 new_anim->track_insert_key(dtrack, 0, var);
1490 } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
1491 float interp;
1492 anim->try_blend_shape_track_interpolate(j, from, &interp);
1493 new_anim->blend_shape_track_insert_key(dtrack, 0, interp);
1494 }
1495 }
1496 }
1497
1498 if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
1499 Vector3 p;
1500 anim->position_track_get_key(j, k, &p);
1501 new_anim->position_track_insert_key(dtrack, kt - from, p);
1502 } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
1503 Quaternion r;
1504 anim->rotation_track_get_key(j, k, &r);
1505 new_anim->rotation_track_insert_key(dtrack, kt - from, r);
1506 } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
1507 Vector3 s;
1508 anim->scale_track_get_key(j, k, &s);
1509 new_anim->scale_track_insert_key(dtrack, kt - from, s);
1510 } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
1511 Variant var = anim->track_get_key_value(j, k);
1512 new_anim->track_insert_key(dtrack, kt - from, var);
1513 } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
1514 float interp;
1515 anim->blend_shape_track_get_key(j, k, &interp);
1516 new_anim->blend_shape_track_insert_key(dtrack, kt - from, interp);
1517 }
1518 }
1519
1520 if (dtrack != -1 && kt >= to) {
1521 if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
1522 Vector3 p;
1523 anim->try_position_track_interpolate(j, to, &p);
1524 new_anim->position_track_insert_key(dtrack, to - from, p);
1525 } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
1526 Quaternion r;
1527 anim->try_rotation_track_interpolate(j, to, &r);
1528 new_anim->rotation_track_insert_key(dtrack, to - from, r);
1529 } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
1530 Vector3 s;
1531 anim->try_scale_track_interpolate(j, to, &s);
1532 new_anim->scale_track_insert_key(dtrack, to - from, s);
1533 } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
1534 Variant var = anim->value_track_interpolate(j, to);
1535 new_anim->track_insert_key(dtrack, to - from, var);
1536 } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
1537 float interp;
1538 anim->try_blend_shape_track_interpolate(j, to, &interp);
1539 new_anim->blend_shape_track_insert_key(dtrack, to - from, interp);
1540 }
1541 }
1542 }
1543
1544 if (dtrack == -1 && p_bake_all) {
1545 new_anim->add_track(anim->track_get_type(j));
1546 dtrack = new_anim->get_track_count() - 1;
1547 new_anim->track_set_path(dtrack, anim->track_get_path(j));
1548 if (anim->track_get_type(j) == Animation::TYPE_POSITION_3D) {
1549 Vector3 p;
1550 anim->try_position_track_interpolate(j, from, &p);
1551 new_anim->position_track_insert_key(dtrack, 0, p);
1552 anim->try_position_track_interpolate(j, to, &p);
1553 new_anim->position_track_insert_key(dtrack, to - from, p);
1554 } else if (anim->track_get_type(j) == Animation::TYPE_ROTATION_3D) {
1555 Quaternion r;
1556 anim->try_rotation_track_interpolate(j, from, &r);
1557 new_anim->rotation_track_insert_key(dtrack, 0, r);
1558 anim->try_rotation_track_interpolate(j, to, &r);
1559 new_anim->rotation_track_insert_key(dtrack, to - from, r);
1560 } else if (anim->track_get_type(j) == Animation::TYPE_SCALE_3D) {
1561 Vector3 s;
1562 anim->try_scale_track_interpolate(j, from, &s);
1563 new_anim->scale_track_insert_key(dtrack, 0, s);
1564 anim->try_scale_track_interpolate(j, to, &s);
1565 new_anim->scale_track_insert_key(dtrack, to - from, s);
1566 } else if (anim->track_get_type(j) == Animation::TYPE_VALUE) {
1567 Variant var = anim->value_track_interpolate(j, from);
1568 new_anim->track_insert_key(dtrack, 0, var);
1569 Variant to_var = anim->value_track_interpolate(j, to);
1570 new_anim->track_insert_key(dtrack, to - from, to_var);
1571 } else if (anim->track_get_type(j) == Animation::TYPE_BLEND_SHAPE) {
1572 float interp;
1573 anim->try_blend_shape_track_interpolate(j, from, &interp);
1574 new_anim->blend_shape_track_insert_key(dtrack, 0, interp);
1575 anim->try_blend_shape_track_interpolate(j, to, &interp);
1576 new_anim->blend_shape_track_insert_key(dtrack, to - from, interp);
1577 }
1578 }
1579 }
1580
1581 new_anim->set_loop_mode(loop_mode);
1582 new_anim->set_length(to - from);
1583
1584 al->add_animation(name, new_anim);
1585
1586 Ref<Animation> saved_anim = _save_animation_to_file(new_anim, save_to_file, save_to_path, keep_current);
1587 if (saved_anim != new_anim) {
1588 al->add_animation(name, saved_anim);
1589 }
1590 }
1591
1592 al->remove_animation(ap->find_animation(anim)); // Remove original animation (no longer needed).
1593}
1594
1595void ResourceImporterScene::_optimize_animations(AnimationPlayer *anim, float p_max_vel_error, float p_max_ang_error, int p_prc_error) {
1596 List<StringName> anim_names;
1597 anim->get_animation_list(&anim_names);
1598 for (const StringName &E : anim_names) {
1599 Ref<Animation> a = anim->get_animation(E);
1600 a->optimize(p_max_vel_error, p_max_ang_error, p_prc_error);
1601 }
1602}
1603
1604void ResourceImporterScene::_compress_animations(AnimationPlayer *anim, int p_page_size_kb) {
1605 List<StringName> anim_names;
1606 anim->get_animation_list(&anim_names);
1607 for (const StringName &E : anim_names) {
1608 Ref<Animation> a = anim->get_animation(E);
1609 a->compress(p_page_size_kb * 1024);
1610 }
1611}
1612
1613void ResourceImporterScene::get_internal_import_options(InternalImportCategory p_category, List<ImportOption> *r_options) const {
1614 switch (p_category) {
1615 case INTERNAL_IMPORT_CATEGORY_NODE: {
1616 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "import/skip_import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1617 } break;
1618 case INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE: {
1619 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "import/skip_import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1620 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate/physics", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1621 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/navmesh", PROPERTY_HINT_ENUM, "Disabled,Mesh + NavMesh,NavMesh Only"), 0));
1622 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "physics/body_type", PROPERTY_HINT_ENUM, "Static,Dynamic,Area"), 0));
1623 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "physics/shape_type", PROPERTY_HINT_ENUM, "Decompose Convex,Simple Convex,Trimesh,Box,Sphere,Cylinder,Capsule", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
1624 r_options->push_back(ImportOption(PropertyInfo(Variant::OBJECT, "physics/physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), Variant()));
1625 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "physics/layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), 1));
1626 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "physics/mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), 1));
1627
1628 // Decomposition
1629 Ref<MeshConvexDecompositionSettings> decomposition_default = Ref<MeshConvexDecompositionSettings>();
1630 decomposition_default.instantiate();
1631 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/advanced", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1632 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/precision", PROPERTY_HINT_RANGE, "1,10,1"), 5));
1633 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/max_concavity", PROPERTY_HINT_RANGE, "0.0,1.0,0.001", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_max_concavity()));
1634 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/symmetry_planes_clipping_bias", PROPERTY_HINT_RANGE, "0.0,1.0,0.001", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_symmetry_planes_clipping_bias()));
1635 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/revolution_axes_clipping_bias", PROPERTY_HINT_RANGE, "0.0,1.0,0.001", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_revolution_axes_clipping_bias()));
1636 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "decomposition/min_volume_per_convex_hull", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_min_volume_per_convex_hull()));
1637 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/resolution", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_resolution()));
1638 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/max_num_vertices_per_convex_hull", PROPERTY_HINT_RANGE, "5,512,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_max_num_vertices_per_convex_hull()));
1639 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/plane_downsampling", PROPERTY_HINT_RANGE, "1,16,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_plane_downsampling()));
1640 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/convexhull_downsampling", PROPERTY_HINT_RANGE, "1,16,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_convex_hull_downsampling()));
1641 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/normalize_mesh", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_normalize_mesh()));
1642 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/mode", PROPERTY_HINT_ENUM, "Voxel,Tetrahedron", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), static_cast<int>(decomposition_default->get_mode())));
1643 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/convexhull_approximation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_convex_hull_approximation()));
1644 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "decomposition/max_convex_hulls", PROPERTY_HINT_RANGE, "1,100,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_max_convex_hulls()));
1645 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "decomposition/project_hull_vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), decomposition_default->get_project_hull_vertices()));
1646
1647 // Primitives: Box, Sphere, Cylinder, Capsule.
1648 r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3(2.0, 2.0, 2.0)));
1649 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "primitive/height", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1.0));
1650 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "primitive/radius", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1.0));
1651 r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3()));
1652 r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "primitive/rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Vector3()));
1653
1654 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/occluder", PROPERTY_HINT_ENUM, "Disabled,Mesh + Occluder,Occluder Only", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
1655 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "occluder/simplification_distance", PROPERTY_HINT_RANGE, "0.0,2.0,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0.1f));
1656 } break;
1657 case INTERNAL_IMPORT_CATEGORY_MESH: {
1658 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "save_to_file/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1659 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "save_to_file/path", PROPERTY_HINT_SAVE_FILE, "*.res,*.tres"), ""));
1660 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "save_to_file/make_streamable"), ""));
1661 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/shadow_meshes", PROPERTY_HINT_ENUM, "Default,Enable,Disable"), 0));
1662 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/lightmap_uv", PROPERTY_HINT_ENUM, "Default,Enable,Disable"), 0));
1663 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "generate/lods", PROPERTY_HINT_ENUM, "Default,Enable,Disable"), 0));
1664 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "lods/normal_split_angle", PROPERTY_HINT_RANGE, "0,180,0.1,degrees"), 25.0f));
1665 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "lods/normal_merge_angle", PROPERTY_HINT_RANGE, "0,180,0.1,degrees"), 60.0f));
1666 } break;
1667 case INTERNAL_IMPORT_CATEGORY_MATERIAL: {
1668 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "use_external/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1669 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "use_external/path", PROPERTY_HINT_FILE, "*.material,*.res,*.tres"), ""));
1670 } break;
1671 case INTERNAL_IMPORT_CATEGORY_ANIMATION: {
1672 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "settings/loop_mode", PROPERTY_HINT_ENUM, "None,Linear,Pingpong"), 0));
1673 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "save_to_file/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1674 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "save_to_file/path", PROPERTY_HINT_SAVE_FILE, "*.res,*.tres"), ""));
1675 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "save_to_file/keep_custom_tracks"), ""));
1676 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slices/amount", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
1677
1678 for (int i = 0; i < 256; i++) {
1679 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "slice_" + itos(i + 1) + "/name"), ""));
1680 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/start_frame"), 0));
1681 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/end_frame"), 0));
1682 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "slice_" + itos(i + 1) + "/loop_mode", PROPERTY_HINT_ENUM, "None,Linear,Pingpong"), 0));
1683 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "slice_" + itos(i + 1) + "/save_to_file/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1684 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "slice_" + itos(i + 1) + "/save_to_file/path", PROPERTY_HINT_SAVE_FILE, ".res,*.tres"), ""));
1685 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "slice_" + itos(i + 1) + "/save_to_file/keep_custom_tracks"), false));
1686 }
1687 } break;
1688 case INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE: {
1689 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "import/skip_import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1690 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "optimizer/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
1691 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "optimizer/max_velocity_error", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.01));
1692 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "optimizer/max_angular_error", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.01));
1693 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "optimizer/max_precision_error", PROPERTY_HINT_NONE, "1,6,1"), 3));
1694 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compression/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1695 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compression/page_size", PROPERTY_HINT_RANGE, "4,512,1,suffix:kb"), 8));
1696 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_tracks/position", PROPERTY_HINT_ENUM, "IfPresent,IfPresentForAll,Never"), 1));
1697 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_tracks/rotation", PROPERTY_HINT_ENUM, "IfPresent,IfPresentForAll,Never"), 1));
1698 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_tracks/scale", PROPERTY_HINT_ENUM, "IfPresent,IfPresentForAll,Never"), 1));
1699 } break;
1700 case INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE: {
1701 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "import/skip_import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
1702 r_options->push_back(ImportOption(PropertyInfo(Variant::OBJECT, "retarget/bone_map", PROPERTY_HINT_RESOURCE_TYPE, "BoneMap", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), Variant()));
1703 } break;
1704 default: {
1705 }
1706 }
1707
1708 for (int i = 0; i < post_importer_plugins.size(); i++) {
1709 post_importer_plugins.write[i]->get_internal_import_options(EditorScenePostImportPlugin::InternalImportCategory(p_category), r_options);
1710 }
1711}
1712
1713bool ResourceImporterScene::get_internal_option_visibility(InternalImportCategory p_category, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
1714 if (p_options.has("import/skip_import") && p_option != "import/skip_import" && bool(p_options["import/skip_import"])) {
1715 return false; //if skip import
1716 }
1717 switch (p_category) {
1718 case INTERNAL_IMPORT_CATEGORY_NODE: {
1719 } break;
1720 case INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE: {
1721 const bool generate_physics =
1722 p_options.has("generate/physics") &&
1723 p_options["generate/physics"].operator bool();
1724
1725 if (p_option.find("physics/") >= 0) {
1726 // Show if need to generate collisions.
1727 return generate_physics;
1728 }
1729
1730 if (p_option.find("decomposition/") >= 0) {
1731 // Show if need to generate collisions.
1732 if (generate_physics &&
1733 // Show if convex is enabled.
1734 p_options["physics/shape_type"] == Variant(SHAPE_TYPE_DECOMPOSE_CONVEX)) {
1735 if (p_option == "decomposition/advanced") {
1736 return true;
1737 }
1738
1739 const bool decomposition_advanced =
1740 p_options.has("decomposition/advanced") &&
1741 p_options["decomposition/advanced"].operator bool();
1742
1743 if (p_option == "decomposition/precision") {
1744 return !decomposition_advanced;
1745 } else {
1746 return decomposition_advanced;
1747 }
1748 }
1749
1750 return false;
1751 }
1752
1753 if (p_option == "primitive/position" || p_option == "primitive/rotation") {
1754 const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
1755 return generate_physics &&
1756 physics_shape >= SHAPE_TYPE_BOX;
1757 }
1758
1759 if (p_option == "primitive/size") {
1760 const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
1761 return generate_physics &&
1762 physics_shape == SHAPE_TYPE_BOX;
1763 }
1764
1765 if (p_option == "primitive/radius") {
1766 const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
1767 return generate_physics &&
1768 (physics_shape == SHAPE_TYPE_SPHERE ||
1769 physics_shape == SHAPE_TYPE_CYLINDER ||
1770 physics_shape == SHAPE_TYPE_CAPSULE);
1771 }
1772
1773 if (p_option == "primitive/height") {
1774 const ShapeType physics_shape = (ShapeType)p_options["physics/shape_type"].operator int();
1775 return generate_physics &&
1776 (physics_shape == SHAPE_TYPE_CYLINDER ||
1777 physics_shape == SHAPE_TYPE_CAPSULE);
1778 }
1779
1780 if (p_option == "occluder/simplification_distance") {
1781 // Show only if occluder generation is enabled
1782 return p_options.has("generate/occluder") && p_options["generate/occluder"].operator signed int() != OCCLUDER_DISABLED;
1783 }
1784 } break;
1785 case INTERNAL_IMPORT_CATEGORY_MESH: {
1786 if (p_option == "save_to_file/path" || p_option == "save_to_file/make_streamable") {
1787 return p_options["save_to_file/enabled"];
1788 }
1789 } break;
1790 case INTERNAL_IMPORT_CATEGORY_MATERIAL: {
1791 if (p_option == "use_external/path") {
1792 return p_options["use_external/enabled"];
1793 }
1794 } break;
1795 case INTERNAL_IMPORT_CATEGORY_ANIMATION: {
1796 if (p_option == "save_to_file/path" || p_option == "save_to_file/keep_custom_tracks") {
1797 return p_options["save_to_file/enabled"];
1798 }
1799 if (p_option.begins_with("slice_")) {
1800 int max_slice = p_options["slices/amount"];
1801 int slice = p_option.get_slice("_", 1).to_int() - 1;
1802 if (slice >= max_slice) {
1803 return false;
1804 }
1805 }
1806 } break;
1807 case INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE: {
1808 if (p_option.begins_with("optimizer/") && p_option != "optimizer/enabled" && !bool(p_options["optimizer/enabled"])) {
1809 return false;
1810 }
1811 if (p_option.begins_with("compression/") && p_option != "compression/enabled" && !bool(p_options["compression/enabled"])) {
1812 return false;
1813 }
1814 } break;
1815 case INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE: {
1816 const bool use_retarget = p_options["retarget/bone_map"].get_validated_object() != nullptr;
1817 if (p_option != "retarget/bone_map" && p_option.begins_with("retarget/")) {
1818 return use_retarget;
1819 }
1820 } break;
1821 default: {
1822 }
1823 }
1824
1825 for (int i = 0; i < post_importer_plugins.size(); i++) {
1826 Variant ret = post_importer_plugins.write[i]->get_internal_option_visibility(EditorScenePostImportPlugin::InternalImportCategory(p_category), animation_importer, p_option, p_options);
1827 if (ret.get_type() == Variant::BOOL) {
1828 return ret;
1829 }
1830 }
1831
1832 return true;
1833}
1834
1835bool ResourceImporterScene::get_internal_option_update_view_required(InternalImportCategory p_category, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
1836 switch (p_category) {
1837 case INTERNAL_IMPORT_CATEGORY_NODE: {
1838 } break;
1839 case INTERNAL_IMPORT_CATEGORY_MESH_3D_NODE: {
1840 if (
1841 p_option == "generate/physics" ||
1842 p_option == "physics/shape_type" ||
1843 p_option.find("decomposition/") >= 0 ||
1844 p_option.find("primitive/") >= 0) {
1845 return true;
1846 }
1847 } break;
1848 case INTERNAL_IMPORT_CATEGORY_MESH: {
1849 } break;
1850 case INTERNAL_IMPORT_CATEGORY_MATERIAL: {
1851 } break;
1852 case INTERNAL_IMPORT_CATEGORY_ANIMATION: {
1853 } break;
1854 case INTERNAL_IMPORT_CATEGORY_ANIMATION_NODE: {
1855 } break;
1856 case INTERNAL_IMPORT_CATEGORY_SKELETON_3D_NODE: {
1857 } break;
1858 default: {
1859 }
1860 }
1861
1862 for (int i = 0; i < post_importer_plugins.size(); i++) {
1863 Variant ret = post_importer_plugins.write[i]->get_internal_option_update_view_required(EditorScenePostImportPlugin::InternalImportCategory(p_category), p_option, p_options);
1864 if (ret.get_type() == Variant::BOOL) {
1865 return ret;
1866 }
1867 }
1868
1869 return false;
1870}
1871
1872void ResourceImporterScene::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
1873 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_type", PROPERTY_HINT_TYPE_STRING, "Node"), ""));
1874 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_name"), ""));
1875
1876 List<String> script_extentions;
1877 ResourceLoader::get_recognized_extensions_for_type("Script", &script_extentions);
1878
1879 String script_ext_hint;
1880
1881 for (const String &E : script_extentions) {
1882 if (!script_ext_hint.is_empty()) {
1883 script_ext_hint += ",";
1884 }
1885 script_ext_hint += "*." + E;
1886 }
1887
1888 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "nodes/apply_root_scale"), true));
1889 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "nodes/root_scale", PROPERTY_HINT_RANGE, "0.001,1000,0.001"), 1.0));
1890 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/ensure_tangents"), true));
1891 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/generate_lods"), true));
1892 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/create_shadow_meshes"), true));
1893 r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/light_baking", PROPERTY_HINT_ENUM, "Disabled,Static (VoxelGI/SDFGI),Static Lightmaps (VoxelGI/SDFGI/LightmapGI),Dynamic (VoxelGI only)", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 1));
1894 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "meshes/lightmap_texel_size", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 0.2));
1895 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "skins/use_named_skins"), true));
1896 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/import"), true));
1897 r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "animation/fps", PROPERTY_HINT_RANGE, "1,120,1"), 30));
1898 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/trimming"), false));
1899 r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/remove_immutable_tracks"), true));
1900 r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "import_script/path", PROPERTY_HINT_FILE, script_ext_hint), ""));
1901
1902 r_options->push_back(ImportOption(PropertyInfo(Variant::DICTIONARY, "_subresources", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), Dictionary()));
1903
1904 for (int i = 0; i < post_importer_plugins.size(); i++) {
1905 post_importer_plugins.write[i]->get_import_options(p_path, r_options);
1906 }
1907
1908 for (Ref<EditorSceneFormatImporter> importer_elem : importers) {
1909 importer_elem->get_import_options(p_path, r_options);
1910 }
1911}
1912
1913void ResourceImporterScene::_replace_owner(Node *p_node, Node *p_scene, Node *p_new_owner) {
1914 if (p_node != p_new_owner && p_node->get_owner() == p_scene) {
1915 p_node->set_owner(p_new_owner);
1916 }
1917
1918 for (int i = 0; i < p_node->get_child_count(); i++) {
1919 Node *n = p_node->get_child(i);
1920 _replace_owner(n, p_scene, p_new_owner);
1921 }
1922}
1923
1924Array ResourceImporterScene::_get_skinned_pose_transforms(ImporterMeshInstance3D *p_src_mesh_node) {
1925 Array skin_pose_transform_array;
1926
1927 const Ref<Skin> skin = p_src_mesh_node->get_skin();
1928 if (skin.is_valid()) {
1929 NodePath skeleton_path = p_src_mesh_node->get_skeleton_path();
1930 const Node *node = p_src_mesh_node->get_node_or_null(skeleton_path);
1931 const Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(node);
1932 if (skeleton) {
1933 int bind_count = skin->get_bind_count();
1934
1935 for (int i = 0; i < bind_count; i++) {
1936 Transform3D bind_pose = skin->get_bind_pose(i);
1937 String bind_name = skin->get_bind_name(i);
1938
1939 int bone_idx = bind_name.is_empty() ? skin->get_bind_bone(i) : skeleton->find_bone(bind_name);
1940 ERR_FAIL_COND_V(bone_idx >= skeleton->get_bone_count(), Array());
1941
1942 Transform3D bp_global_rest;
1943 if (bone_idx >= 0) {
1944 bp_global_rest = skeleton->get_bone_global_pose(bone_idx);
1945 } else {
1946 bp_global_rest = skeleton->get_bone_global_pose(i);
1947 }
1948
1949 skin_pose_transform_array.push_back(bp_global_rest * bind_pose);
1950 }
1951 }
1952 }
1953
1954 return skin_pose_transform_array;
1955}
1956
1957void ResourceImporterScene::_generate_meshes(Node *p_node, const Dictionary &p_mesh_data, bool p_generate_lods, bool p_create_shadow_meshes, LightBakeMode p_light_bake_mode, float p_lightmap_texel_size, const Vector<uint8_t> &p_src_lightmap_cache, Vector<Vector<uint8_t>> &r_lightmap_caches) {
1958 ImporterMeshInstance3D *src_mesh_node = Object::cast_to<ImporterMeshInstance3D>(p_node);
1959 if (src_mesh_node) {
1960 //is mesh
1961 MeshInstance3D *mesh_node = memnew(MeshInstance3D);
1962 mesh_node->set_name(src_mesh_node->get_name());
1963 mesh_node->set_transform(src_mesh_node->get_transform());
1964 mesh_node->set_skin(src_mesh_node->get_skin());
1965 mesh_node->set_skeleton_path(src_mesh_node->get_skeleton_path());
1966 if (src_mesh_node->get_mesh().is_valid()) {
1967 Ref<ArrayMesh> mesh;
1968 if (!src_mesh_node->get_mesh()->has_mesh()) {
1969 //do mesh processing
1970
1971 bool generate_lods = p_generate_lods;
1972 float split_angle = 25.0f;
1973 float merge_angle = 60.0f;
1974 bool create_shadow_meshes = p_create_shadow_meshes;
1975 bool bake_lightmaps = p_light_bake_mode == LIGHT_BAKE_STATIC_LIGHTMAPS;
1976 String save_to_file;
1977
1978 String mesh_id = src_mesh_node->get_mesh()->get_meta("import_id", src_mesh_node->get_mesh()->get_name());
1979
1980 if (!mesh_id.is_empty() && p_mesh_data.has(mesh_id)) {
1981 Dictionary mesh_settings = p_mesh_data[mesh_id];
1982 {
1983 //fill node settings for this node with default values
1984 List<ImportOption> iopts;
1985 get_internal_import_options(INTERNAL_IMPORT_CATEGORY_MESH, &iopts);
1986 for (const ImportOption &E : iopts) {
1987 if (!mesh_settings.has(E.option.name)) {
1988 mesh_settings[E.option.name] = E.default_value;
1989 }
1990 }
1991 }
1992
1993 if (mesh_settings.has("generate/shadow_meshes")) {
1994 int shadow_meshes = mesh_settings["generate/shadow_meshes"];
1995 if (shadow_meshes == MESH_OVERRIDE_ENABLE) {
1996 create_shadow_meshes = true;
1997 } else if (shadow_meshes == MESH_OVERRIDE_DISABLE) {
1998 create_shadow_meshes = false;
1999 }
2000 }
2001
2002 if (mesh_settings.has("generate/lightmap_uv")) {
2003 int lightmap_uv = mesh_settings["generate/lightmap_uv"];
2004 if (lightmap_uv == MESH_OVERRIDE_ENABLE) {
2005 bake_lightmaps = true;
2006 } else if (lightmap_uv == MESH_OVERRIDE_DISABLE) {
2007 bake_lightmaps = false;
2008 }
2009 }
2010
2011 if (mesh_settings.has("generate/lods")) {
2012 int lods = mesh_settings["generate/lods"];
2013 if (lods == MESH_OVERRIDE_ENABLE) {
2014 generate_lods = true;
2015 } else if (lods == MESH_OVERRIDE_DISABLE) {
2016 generate_lods = false;
2017 }
2018 }
2019
2020 if (mesh_settings.has("lods/normal_split_angle")) {
2021 split_angle = mesh_settings["lods/normal_split_angle"];
2022 }
2023
2024 if (mesh_settings.has("lods/normal_merge_angle")) {
2025 merge_angle = mesh_settings["lods/normal_merge_angle"];
2026 }
2027
2028 if (mesh_settings.has("save_to_file/enabled") && bool(mesh_settings["save_to_file/enabled"]) && mesh_settings.has("save_to_file/path")) {
2029 save_to_file = mesh_settings["save_to_file/path"];
2030 if (!save_to_file.is_resource_file()) {
2031 save_to_file = "";
2032 }
2033 }
2034
2035 for (int i = 0; i < post_importer_plugins.size(); i++) {
2036 post_importer_plugins.write[i]->internal_process(EditorScenePostImportPlugin::INTERNAL_IMPORT_CATEGORY_MESH, nullptr, src_mesh_node, src_mesh_node->get_mesh(), mesh_settings);
2037 }
2038 }
2039
2040 if (bake_lightmaps) {
2041 Transform3D xf;
2042 Node3D *n = src_mesh_node;
2043 while (n) {
2044 xf = n->get_transform() * xf;
2045 n = n->get_parent_node_3d();
2046 }
2047
2048 Vector<uint8_t> lightmap_cache;
2049 src_mesh_node->get_mesh()->lightmap_unwrap_cached(xf, p_lightmap_texel_size, p_src_lightmap_cache, lightmap_cache);
2050
2051 if (!lightmap_cache.is_empty()) {
2052 if (r_lightmap_caches.is_empty()) {
2053 r_lightmap_caches.push_back(lightmap_cache);
2054 } else {
2055 String new_md5 = String::md5(lightmap_cache.ptr()); // MD5 is stored at the beginning of the cache data
2056
2057 for (int i = 0; i < r_lightmap_caches.size(); i++) {
2058 String md5 = String::md5(r_lightmap_caches[i].ptr());
2059 if (new_md5 < md5) {
2060 r_lightmap_caches.insert(i, lightmap_cache);
2061 break;
2062 }
2063
2064 if (new_md5 == md5) {
2065 break;
2066 }
2067 }
2068 }
2069 }
2070 }
2071
2072 if (generate_lods) {
2073 Array skin_pose_transform_array = _get_skinned_pose_transforms(src_mesh_node);
2074 src_mesh_node->get_mesh()->generate_lods(merge_angle, split_angle, skin_pose_transform_array);
2075 }
2076
2077 if (create_shadow_meshes) {
2078 src_mesh_node->get_mesh()->create_shadow_mesh();
2079 }
2080
2081 if (!save_to_file.is_empty()) {
2082 Ref<Mesh> existing = ResourceCache::get_ref(save_to_file);
2083 if (existing.is_valid()) {
2084 //if somehow an existing one is useful, create
2085 existing->reset_state();
2086 }
2087 mesh = src_mesh_node->get_mesh()->get_mesh(existing);
2088
2089 ResourceSaver::save(mesh, save_to_file); //override
2090
2091 mesh->set_path(save_to_file, true); //takeover existing, if needed
2092
2093 } else {
2094 mesh = src_mesh_node->get_mesh()->get_mesh();
2095 }
2096 } else {
2097 mesh = src_mesh_node->get_mesh()->get_mesh();
2098 }
2099
2100 if (mesh.is_valid()) {
2101 mesh_node->set_mesh(mesh);
2102 for (int i = 0; i < mesh->get_surface_count(); i++) {
2103 mesh_node->set_surface_override_material(i, src_mesh_node->get_surface_material(i));
2104 }
2105 }
2106 }
2107
2108 switch (p_light_bake_mode) {
2109 case LIGHT_BAKE_DISABLED: {
2110 mesh_node->set_gi_mode(GeometryInstance3D::GI_MODE_DISABLED);
2111 } break;
2112 case LIGHT_BAKE_DYNAMIC: {
2113 mesh_node->set_gi_mode(GeometryInstance3D::GI_MODE_DYNAMIC);
2114 } break;
2115 case LIGHT_BAKE_STATIC:
2116 case LIGHT_BAKE_STATIC_LIGHTMAPS: {
2117 mesh_node->set_gi_mode(GeometryInstance3D::GI_MODE_STATIC);
2118 } break;
2119 }
2120
2121 p_node->replace_by(mesh_node);
2122 p_node->set_owner(nullptr);
2123 memdelete(p_node);
2124 p_node = mesh_node;
2125 }
2126
2127 for (int i = 0; i < p_node->get_child_count(); i++) {
2128 _generate_meshes(p_node->get_child(i), p_mesh_data, p_generate_lods, p_create_shadow_meshes, p_light_bake_mode, p_lightmap_texel_size, p_src_lightmap_cache, r_lightmap_caches);
2129 }
2130}
2131
2132void ResourceImporterScene::_add_shapes(Node *p_node, const Vector<Ref<Shape3D>> &p_shapes) {
2133 for (const Ref<Shape3D> &E : p_shapes) {
2134 CollisionShape3D *cshape = memnew(CollisionShape3D);
2135 cshape->set_shape(E);
2136 p_node->add_child(cshape, true);
2137
2138 cshape->set_owner(p_node->get_owner());
2139 }
2140}
2141
2142void ResourceImporterScene::_optimize_track_usage(AnimationPlayer *p_player, AnimationImportTracks *p_track_actions) {
2143 List<StringName> anims;
2144 p_player->get_animation_list(&anims);
2145 Node *parent = p_player->get_parent();
2146 ERR_FAIL_NULL(parent);
2147 HashMap<NodePath, uint32_t> used_tracks[TRACK_CHANNEL_MAX];
2148 bool tracks_to_add = false;
2149 static const Animation::TrackType track_types[TRACK_CHANNEL_MAX] = { Animation::TYPE_POSITION_3D, Animation::TYPE_ROTATION_3D, Animation::TYPE_SCALE_3D, Animation::TYPE_BLEND_SHAPE };
2150 for (const StringName &I : anims) {
2151 Ref<Animation> anim = p_player->get_animation(I);
2152 for (int i = 0; i < anim->get_track_count(); i++) {
2153 for (int j = 0; j < TRACK_CHANNEL_MAX; j++) {
2154 if (anim->track_get_type(i) != track_types[j]) {
2155 continue;
2156 }
2157 switch (p_track_actions[j]) {
2158 case ANIMATION_IMPORT_TRACKS_IF_PRESENT: {
2159 // Do Nothing.
2160 } break;
2161 case ANIMATION_IMPORT_TRACKS_IF_PRESENT_FOR_ALL: {
2162 used_tracks[j].insert(anim->track_get_path(i), 0);
2163 tracks_to_add = true;
2164 } break;
2165 case ANIMATION_IMPORT_TRACKS_NEVER: {
2166 anim->remove_track(i);
2167 i--;
2168 } break;
2169 }
2170 }
2171 }
2172 }
2173
2174 if (!tracks_to_add) {
2175 return;
2176 }
2177
2178 uint32_t pass = 0;
2179 for (const StringName &I : anims) {
2180 Ref<Animation> anim = p_player->get_animation(I);
2181 for (int j = 0; j < TRACK_CHANNEL_MAX; j++) {
2182 if (p_track_actions[j] != ANIMATION_IMPORT_TRACKS_IF_PRESENT_FOR_ALL) {
2183 continue;
2184 }
2185
2186 pass++;
2187
2188 for (int i = 0; i < anim->get_track_count(); i++) {
2189 if (anim->track_get_type(i) != track_types[j]) {
2190 continue;
2191 }
2192
2193 NodePath path = anim->track_get_path(i);
2194
2195 ERR_CONTINUE(!used_tracks[j].has(path)); // Should never happen.
2196
2197 used_tracks[j][path] = pass;
2198 }
2199
2200 for (const KeyValue<NodePath, uint32_t> &J : used_tracks[j]) {
2201 if (J.value == pass) {
2202 continue;
2203 }
2204
2205 NodePath path = J.key;
2206 Node *n = parent->get_node(path);
2207
2208 if (j == TRACK_CHANNEL_BLEND_SHAPE) {
2209 MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(n);
2210 if (mi && path.get_subname_count() > 0) {
2211 StringName bs = path.get_subname(0);
2212 bool valid;
2213 float value = mi->get(bs, &valid);
2214 if (valid) {
2215 int track_idx = anim->add_track(track_types[j]);
2216 anim->track_set_path(track_idx, path);
2217 anim->track_set_imported(track_idx, true);
2218 anim->blend_shape_track_insert_key(track_idx, 0, value);
2219 }
2220 }
2221
2222 } else {
2223 Skeleton3D *skel = Object::cast_to<Skeleton3D>(n);
2224 Node3D *n3d = Object::cast_to<Node3D>(n);
2225 Vector3 loc;
2226 Quaternion rot;
2227 Vector3 scale;
2228 if (skel && path.get_subname_count() > 0) {
2229 StringName bone = path.get_subname(0);
2230 int bone_idx = skel->find_bone(bone);
2231 if (bone_idx == -1) {
2232 continue;
2233 }
2234 // Note that this is using get_bone_pose to update the bone pose cache.
2235 _ALLOW_DISCARD_ skel->get_bone_pose(bone_idx);
2236 loc = skel->get_bone_pose_position(bone_idx);
2237 rot = skel->get_bone_pose_rotation(bone_idx);
2238 scale = skel->get_bone_pose_scale(bone_idx);
2239 } else if (n3d) {
2240 loc = n3d->get_position();
2241 rot = n3d->get_transform().basis.get_rotation_quaternion();
2242 scale = n3d->get_scale();
2243 } else {
2244 continue;
2245 }
2246
2247 // Ensure insertion keeps tracks together and ordered by type (loc/rot/scale)
2248 int insert_at_pos = -1;
2249 for (int k = 0; k < anim->get_track_count(); k++) {
2250 NodePath tpath = anim->track_get_path(k);
2251
2252 if (path == tpath) {
2253 Animation::TrackType ttype = anim->track_get_type(k);
2254 if (insert_at_pos == -1) {
2255 // First insert, determine whether replacing or kicking back
2256 if (track_types[j] < ttype) {
2257 insert_at_pos = k;
2258 break; // No point in continuing.
2259 } else {
2260 insert_at_pos = k + 1;
2261 }
2262 } else if (ttype < track_types[j]) {
2263 // Kick back.
2264 insert_at_pos = k + 1;
2265 }
2266 } else if (insert_at_pos >= 0) {
2267 break;
2268 }
2269 }
2270 int track_idx = anim->add_track(track_types[j], insert_at_pos);
2271
2272 anim->track_set_path(track_idx, path);
2273 anim->track_set_imported(track_idx, true);
2274 switch (j) {
2275 case TRACK_CHANNEL_POSITION: {
2276 anim->position_track_insert_key(track_idx, 0, loc);
2277 } break;
2278 case TRACK_CHANNEL_ROTATION: {
2279 anim->rotation_track_insert_key(track_idx, 0, rot);
2280 } break;
2281 case TRACK_CHANNEL_SCALE: {
2282 anim->scale_track_insert_key(track_idx, 0, scale);
2283 } break;
2284 default: {
2285 }
2286 }
2287 }
2288 }
2289 }
2290 }
2291}
2292
2293Node *ResourceImporterScene::pre_import(const String &p_source_file, const HashMap<StringName, Variant> &p_options) {
2294 Ref<EditorSceneFormatImporter> importer;
2295 String ext = p_source_file.get_extension().to_lower();
2296
2297 // TRANSLATORS: This is an editor progress label.
2298 EditorProgress progress("pre-import", TTR("Pre-Import Scene"), 0);
2299 progress.step(TTR("Importing Scene..."), 0);
2300
2301 for (Ref<EditorSceneFormatImporter> importer_elem : importers) {
2302 List<String> extensions;
2303 importer_elem->get_extensions(&extensions);
2304
2305 for (const String &F : extensions) {
2306 if (F.to_lower() == ext) {
2307 importer = importer_elem;
2308 break;
2309 }
2310 }
2311
2312 if (importer.is_valid()) {
2313 break;
2314 }
2315 }
2316
2317 ERR_FAIL_COND_V(!importer.is_valid(), nullptr);
2318
2319 Error err = OK;
2320 HashMap<StringName, Variant> options_dupe = p_options;
2321
2322 Node *scene = importer->import_scene(p_source_file, EditorSceneFormatImporter::IMPORT_ANIMATION | EditorSceneFormatImporter::IMPORT_GENERATE_TANGENT_ARRAYS, options_dupe, nullptr, &err);
2323 if (!scene || err != OK) {
2324 return nullptr;
2325 }
2326
2327 HashMap<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> collision_map;
2328 List<Pair<NodePath, Node *>> node_renames;
2329 _pre_fix_node(scene, scene, collision_map, nullptr, node_renames);
2330
2331 return scene;
2332}
2333
2334Error ResourceImporterScene::import(const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
2335 const String &src_path = p_source_file;
2336
2337 Ref<EditorSceneFormatImporter> importer;
2338 String ext = src_path.get_extension().to_lower();
2339
2340 EditorProgress progress("import", TTR("Import Scene"), 104);
2341 progress.step(TTR("Importing Scene..."), 0);
2342
2343 for (Ref<EditorSceneFormatImporter> importer_elem : importers) {
2344 List<String> extensions;
2345 importer_elem->get_extensions(&extensions);
2346
2347 for (const String &F : extensions) {
2348 if (F.to_lower() == ext) {
2349 importer = importer_elem;
2350 break;
2351 }
2352 }
2353
2354 if (importer.is_valid()) {
2355 break;
2356 }
2357 }
2358
2359 ERR_FAIL_COND_V(!importer.is_valid(), ERR_FILE_UNRECOGNIZED);
2360
2361 int import_flags = 0;
2362
2363 if (animation_importer) {
2364 import_flags |= EditorSceneFormatImporter::IMPORT_ANIMATION;
2365 import_flags |= EditorSceneFormatImporter::IMPORT_DISCARD_MESHES_AND_MATERIALS;
2366 } else {
2367 if (bool(p_options["animation/import"])) {
2368 import_flags |= EditorSceneFormatImporter::IMPORT_ANIMATION;
2369 }
2370 }
2371
2372 if (bool(p_options["skins/use_named_skins"])) {
2373 import_flags |= EditorSceneFormatImporter::IMPORT_USE_NAMED_SKIN_BINDS;
2374 }
2375
2376 bool ensure_tangents = p_options["meshes/ensure_tangents"];
2377 if (ensure_tangents) {
2378 import_flags |= EditorSceneFormatImporter::IMPORT_GENERATE_TANGENT_ARRAYS;
2379 }
2380
2381 Error err = OK;
2382 List<String> missing_deps; // for now, not much will be done with this
2383 Node *scene = importer->import_scene(src_path, import_flags, p_options, &missing_deps, &err);
2384 if (!scene || err != OK) {
2385 return err;
2386 }
2387
2388 bool apply_root = true;
2389 if (p_options.has("nodes/apply_root_scale")) {
2390 apply_root = p_options["nodes/apply_root_scale"];
2391 }
2392 real_t root_scale = 1;
2393 if (p_options.has("nodes/root_scale")) {
2394 root_scale = p_options["nodes/root_scale"];
2395 }
2396 if (Object::cast_to<Node3D>(scene)) {
2397 Node3D *scene_3d = Object::cast_to<Node3D>(scene);
2398 Vector3 scale = Vector3(root_scale, root_scale, root_scale);
2399 if (apply_root) {
2400 _apply_permanent_scale_to_descendants(scene, scale);
2401 } else {
2402 scene_3d->scale(scale);
2403 }
2404 }
2405 Dictionary subresources = p_options["_subresources"];
2406
2407 Dictionary node_data;
2408 if (subresources.has("nodes")) {
2409 node_data = subresources["nodes"];
2410 }
2411
2412 Dictionary material_data;
2413 if (subresources.has("materials")) {
2414 material_data = subresources["materials"];
2415 }
2416
2417 Dictionary animation_data;
2418 if (subresources.has("animations")) {
2419 animation_data = subresources["animations"];
2420 }
2421
2422 HashSet<Ref<ImporterMesh>> scanned_meshes;
2423 HashMap<Ref<ImporterMesh>, Vector<Ref<Shape3D>>> collision_map;
2424 Pair<PackedVector3Array, PackedInt32Array> occluder_arrays;
2425 List<Pair<NodePath, Node *>> node_renames;
2426
2427 _pre_fix_node(scene, scene, collision_map, &occluder_arrays, node_renames);
2428
2429 for (int i = 0; i < post_importer_plugins.size(); i++) {
2430 post_importer_plugins.write[i]->pre_process(scene, p_options);
2431 }
2432
2433 float fps = 30;
2434 if (p_options.has(SNAME("animation/fps"))) {
2435 fps = (float)p_options[SNAME("animation/fps")];
2436 }
2437 _pre_fix_animations(scene, scene, node_data, animation_data, fps);
2438 _post_fix_node(scene, scene, collision_map, occluder_arrays, scanned_meshes, node_data, material_data, animation_data, fps, apply_root ? root_scale : 1.0);
2439 _post_fix_animations(scene, scene, node_data, animation_data, fps);
2440
2441 String root_type = p_options["nodes/root_type"];
2442 if (!root_type.is_empty()) {
2443 root_type = root_type.split(" ")[0]; // Full root_type is "ClassName (filename.gd)" for a script global class.
2444 Ref<Script> root_script = nullptr;
2445 if (ScriptServer::is_global_class(root_type)) {
2446 root_script = ResourceLoader::load(ScriptServer::get_global_class_path(root_type));
2447 root_type = ScriptServer::get_global_class_base(root_type);
2448 }
2449 if (scene->get_class_name() != root_type) {
2450 // If the user specified a Godot node type that does not match
2451 // what the scene import gave us, replace the root node.
2452 Node *base_node = Object::cast_to<Node>(ClassDB::instantiate(root_type));
2453 if (base_node) {
2454 scene->replace_by(base_node);
2455 scene->set_owner(nullptr);
2456 memdelete(scene);
2457 scene = base_node;
2458 }
2459 }
2460 if (root_script.is_valid()) {
2461 scene->set_script(Variant(root_script));
2462 }
2463 }
2464
2465 String root_name = p_options["nodes/root_name"];
2466 if (!root_name.is_empty() && root_name != "Scene Root") {
2467 // TODO: Remove `&& root_name != "Scene Root"` for Godot 5.0.
2468 // For backwards compatibility with existing .import files,
2469 // treat "Scene Root" as having no root name override.
2470 scene->set_name(root_name);
2471 } else if (String(scene->get_name()).is_empty()) {
2472 scene->set_name(p_save_path.get_file().get_basename());
2473 }
2474
2475 if (!occluder_arrays.first.is_empty() && !occluder_arrays.second.is_empty()) {
2476 Ref<ArrayOccluder3D> occ = memnew(ArrayOccluder3D);
2477 occ->set_arrays(occluder_arrays.first, occluder_arrays.second);
2478 OccluderInstance3D *occluder_instance = memnew(OccluderInstance3D);
2479 occluder_instance->set_occluder(occ);
2480 scene->add_child(occluder_instance, true);
2481 occluder_instance->set_owner(scene);
2482 }
2483
2484 bool gen_lods = bool(p_options["meshes/generate_lods"]);
2485 bool create_shadow_meshes = bool(p_options["meshes/create_shadow_meshes"]);
2486 int light_bake_mode = p_options["meshes/light_baking"];
2487 float texel_size = p_options["meshes/lightmap_texel_size"];
2488 float lightmap_texel_size = MAX(0.001, texel_size);
2489
2490 Vector<uint8_t> src_lightmap_cache;
2491 Vector<Vector<uint8_t>> mesh_lightmap_caches;
2492
2493 {
2494 src_lightmap_cache = FileAccess::get_file_as_bytes(p_source_file + ".unwrap_cache", &err);
2495 if (err != OK) {
2496 src_lightmap_cache.clear();
2497 }
2498 }
2499
2500 Dictionary mesh_data;
2501 if (subresources.has("meshes")) {
2502 mesh_data = subresources["meshes"];
2503 }
2504 _generate_meshes(scene, mesh_data, gen_lods, create_shadow_meshes, LightBakeMode(light_bake_mode), lightmap_texel_size, src_lightmap_cache, mesh_lightmap_caches);
2505
2506 if (mesh_lightmap_caches.size()) {
2507 Ref<FileAccess> f = FileAccess::open(p_source_file + ".unwrap_cache", FileAccess::WRITE);
2508 if (f.is_valid()) {
2509 f->store_32(mesh_lightmap_caches.size());
2510 for (int i = 0; i < mesh_lightmap_caches.size(); i++) {
2511 String md5 = String::md5(mesh_lightmap_caches[i].ptr());
2512 f->store_buffer(mesh_lightmap_caches[i].ptr(), mesh_lightmap_caches[i].size());
2513 }
2514 }
2515 }
2516 err = OK;
2517
2518 progress.step(TTR("Running Custom Script..."), 2);
2519
2520 String post_import_script_path = p_options["import_script/path"];
2521 Ref<EditorScenePostImport> post_import_script;
2522
2523 if (!post_import_script_path.is_empty()) {
2524 Ref<Script> scr = ResourceLoader::load(post_import_script_path);
2525 if (!scr.is_valid()) {
2526 EditorNode::add_io_error(TTR("Couldn't load post-import script:") + " " + post_import_script_path);
2527 } else {
2528 post_import_script = Ref<EditorScenePostImport>(memnew(EditorScenePostImport));
2529 post_import_script->set_script(scr);
2530 if (!post_import_script->get_script_instance()) {
2531 EditorNode::add_io_error(TTR("Invalid/broken script for post-import (check console):") + " " + post_import_script_path);
2532 post_import_script.unref();
2533 return ERR_CANT_CREATE;
2534 }
2535 }
2536 }
2537
2538 if (post_import_script.is_valid()) {
2539 post_import_script->init(p_source_file);
2540 scene = post_import_script->post_import(scene);
2541 if (!scene) {
2542 EditorNode::add_io_error(
2543 TTR("Error running post-import script:") + " " + post_import_script_path + "\n" +
2544 TTR("Did you return a Node-derived object in the `_post_import()` method?"));
2545 return err;
2546 }
2547 }
2548
2549 for (int i = 0; i < post_importer_plugins.size(); i++) {
2550 post_importer_plugins.write[i]->post_process(scene, p_options);
2551 }
2552
2553 progress.step(TTR("Saving..."), 104);
2554
2555 int flags = 0;
2556 if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) {
2557 flags |= ResourceSaver::FLAG_COMPRESS;
2558 }
2559
2560 if (animation_importer) {
2561 Ref<AnimationLibrary> library;
2562 for (int i = 0; i < scene->get_child_count(); i++) {
2563 AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(scene->get_child(i));
2564 if (ap) {
2565 List<StringName> libs;
2566 ap->get_animation_library_list(&libs);
2567 if (libs.size()) {
2568 library = ap->get_animation_library(libs.front()->get());
2569 break;
2570 }
2571 }
2572 }
2573
2574 if (!library.is_valid()) {
2575 library.instantiate(); // Will be empty
2576 }
2577
2578 print_verbose("Saving animation to: " + p_save_path + ".res");
2579 err = ResourceSaver::save(library, p_save_path + ".res", flags); //do not take over, let the changed files reload themselves
2580 ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save animation to file '" + p_save_path + ".res'.");
2581
2582 } else {
2583 Ref<PackedScene> packer = memnew(PackedScene);
2584 packer->pack(scene);
2585 print_verbose("Saving scene to: " + p_save_path + ".scn");
2586 err = ResourceSaver::save(packer, p_save_path + ".scn", flags); //do not take over, let the changed files reload themselves
2587 ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save scene to file '" + p_save_path + ".scn'.");
2588 }
2589
2590 memdelete(scene);
2591
2592 //this is not the time to reimport, wait until import process is done, import file is saved, etc.
2593 //EditorNode::get_singleton()->reload_scene(p_source_file);
2594
2595 return OK;
2596}
2597
2598ResourceImporterScene *ResourceImporterScene::scene_singleton = nullptr;
2599ResourceImporterScene *ResourceImporterScene::animation_singleton = nullptr;
2600
2601Vector<Ref<EditorSceneFormatImporter>> ResourceImporterScene::importers;
2602Vector<Ref<EditorScenePostImportPlugin>> ResourceImporterScene::post_importer_plugins;
2603
2604bool ResourceImporterScene::ResourceImporterScene::has_advanced_options() const {
2605 return true;
2606}
2607void ResourceImporterScene::ResourceImporterScene::show_advanced_options(const String &p_path) {
2608 SceneImportSettings::get_singleton()->open_settings(p_path, animation_importer);
2609}
2610
2611ResourceImporterScene::ResourceImporterScene(bool p_animation_import, bool p_singleton) {
2612 // This should only be set through the EditorNode.
2613 if (p_singleton) {
2614 if (p_animation_import) {
2615 animation_singleton = this;
2616 } else {
2617 scene_singleton = this;
2618 }
2619 }
2620
2621 animation_importer = p_animation_import;
2622}
2623
2624ResourceImporterScene::~ResourceImporterScene() {
2625 if (animation_singleton == this) {
2626 animation_singleton = nullptr;
2627 }
2628 if (scene_singleton == this) {
2629 scene_singleton = nullptr;
2630 }
2631}
2632
2633void ResourceImporterScene::add_importer(Ref<EditorSceneFormatImporter> p_importer, bool p_first_priority) {
2634 ERR_FAIL_COND(p_importer.is_null());
2635 if (p_first_priority) {
2636 importers.insert(0, p_importer);
2637 } else {
2638 importers.push_back(p_importer);
2639 }
2640}
2641
2642void ResourceImporterScene::remove_post_importer_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin) {
2643 post_importer_plugins.erase(p_plugin);
2644}
2645
2646void ResourceImporterScene::add_post_importer_plugin(const Ref<EditorScenePostImportPlugin> &p_plugin, bool p_first_priority) {
2647 ERR_FAIL_COND(p_plugin.is_null());
2648 if (p_first_priority) {
2649 post_importer_plugins.insert(0, p_plugin);
2650 } else {
2651 post_importer_plugins.push_back(p_plugin);
2652 }
2653}
2654
2655void ResourceImporterScene::remove_importer(Ref<EditorSceneFormatImporter> p_importer) {
2656 importers.erase(p_importer);
2657}
2658
2659void ResourceImporterScene::clean_up_importer_plugins() {
2660 importers.clear();
2661 post_importer_plugins.clear();
2662}
2663
2664///////////////////////////////////////
2665
2666uint32_t EditorSceneFormatImporterESCN::get_import_flags() const {
2667 return IMPORT_SCENE;
2668}
2669
2670void EditorSceneFormatImporterESCN::get_extensions(List<String> *r_extensions) const {
2671 r_extensions->push_back("escn");
2672}
2673
2674Node *EditorSceneFormatImporterESCN::import_scene(const String &p_path, uint32_t p_flags, const HashMap<StringName, Variant> &p_options, List<String> *r_missing_deps, Error *r_err) {
2675 Error error;
2676 Ref<PackedScene> ps = ResourceFormatLoaderText::singleton->load(p_path, p_path, &error);
2677 ERR_FAIL_COND_V_MSG(!ps.is_valid(), nullptr, "Cannot load scene as text resource from path '" + p_path + "'.");
2678 Node *scene = ps->instantiate();
2679 TypedArray<Node> nodes = scene->find_children("*", "MeshInstance3D");
2680 for (int32_t node_i = 0; node_i < nodes.size(); node_i++) {
2681 MeshInstance3D *mesh_3d = cast_to<MeshInstance3D>(nodes[node_i]);
2682 Ref<ImporterMesh> mesh;
2683 mesh.instantiate();
2684 // Ignore the aabb, it will be recomputed.
2685 ImporterMeshInstance3D *importer_mesh_3d = memnew(ImporterMeshInstance3D);
2686 importer_mesh_3d->set_name(mesh_3d->get_name());
2687 importer_mesh_3d->set_transform(mesh_3d->get_relative_transform(mesh_3d->get_parent()));
2688 importer_mesh_3d->set_skin(mesh_3d->get_skin());
2689 importer_mesh_3d->set_skeleton_path(mesh_3d->get_skeleton_path());
2690 Ref<ArrayMesh> array_mesh_3d_mesh = mesh_3d->get_mesh();
2691 if (array_mesh_3d_mesh.is_valid()) {
2692 // For the MeshInstance3D nodes, we need to convert the ArrayMesh to an ImporterMesh specially.
2693 mesh->set_name(array_mesh_3d_mesh->get_name());
2694 for (int32_t blend_i = 0; blend_i < array_mesh_3d_mesh->get_blend_shape_count(); blend_i++) {
2695 mesh->add_blend_shape(array_mesh_3d_mesh->get_blend_shape_name(blend_i));
2696 }
2697 for (int32_t surface_i = 0; surface_i < array_mesh_3d_mesh->get_surface_count(); surface_i++) {
2698 mesh->add_surface(array_mesh_3d_mesh->surface_get_primitive_type(surface_i),
2699 array_mesh_3d_mesh->surface_get_arrays(surface_i),
2700 array_mesh_3d_mesh->surface_get_blend_shape_arrays(surface_i),
2701 array_mesh_3d_mesh->surface_get_lods(surface_i),
2702 array_mesh_3d_mesh->surface_get_material(surface_i),
2703 array_mesh_3d_mesh->surface_get_name(surface_i),
2704 array_mesh_3d_mesh->surface_get_format(surface_i));
2705 }
2706 mesh->set_blend_shape_mode(array_mesh_3d_mesh->get_blend_shape_mode());
2707 importer_mesh_3d->set_mesh(mesh);
2708 mesh_3d->replace_by(importer_mesh_3d);
2709 continue;
2710 }
2711 Ref<Mesh> mesh_3d_mesh = mesh_3d->get_mesh();
2712 if (mesh_3d_mesh.is_valid()) {
2713 // For the MeshInstance3D nodes, we need to convert the Mesh to an ImporterMesh specially.
2714 mesh->set_name(mesh_3d_mesh->get_name());
2715 for (int32_t surface_i = 0; surface_i < mesh_3d_mesh->get_surface_count(); surface_i++) {
2716 mesh->add_surface(mesh_3d_mesh->surface_get_primitive_type(surface_i),
2717 mesh_3d_mesh->surface_get_arrays(surface_i),
2718 Array(),
2719 mesh_3d_mesh->surface_get_lods(surface_i),
2720 mesh_3d_mesh->surface_get_material(surface_i),
2721 mesh_3d_mesh->surface_get_material(surface_i).is_valid() ? mesh_3d_mesh->surface_get_material(surface_i)->get_name() : String(),
2722 mesh_3d_mesh->surface_get_format(surface_i));
2723 }
2724 importer_mesh_3d->set_mesh(mesh);
2725 mesh_3d->replace_by(importer_mesh_3d);
2726 continue;
2727 }
2728 }
2729
2730 ERR_FAIL_NULL_V(scene, nullptr);
2731
2732 return scene;
2733}
2734