resource_importer_scene.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460
  1. /*************************************************************************/
  2. /* resource_importer_scene.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  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. #include "resource_importer_scene.h"
  31. #include "core/io/resource_saver.h"
  32. #include "editor/editor_node.h"
  33. #include "scene/resources/packed_scene.h"
  34. #include "scene/3d/collision_shape.h"
  35. #include "scene/3d/mesh_instance.h"
  36. #include "scene/3d/navigation.h"
  37. #include "scene/3d/physics_body.h"
  38. #include "scene/3d/portal.h"
  39. #include "scene/3d/room_instance.h"
  40. #include "scene/3d/vehicle_body.h"
  41. #include "scene/animation/animation_player.h"
  42. #include "scene/resources/animation.h"
  43. #include "scene/resources/box_shape.h"
  44. #include "scene/resources/plane_shape.h"
  45. #include "scene/resources/ray_shape.h"
  46. #include "scene/resources/scene_format_text.h"
  47. #include "scene/resources/sphere_shape.h"
  48. uint32_t EditorSceneImporter::get_import_flags() const {
  49. if (get_script_instance()) {
  50. return get_script_instance()->call("_get_import_flags");
  51. }
  52. ERR_FAIL_V(0);
  53. }
  54. void EditorSceneImporter::get_extensions(List<String> *r_extensions) const {
  55. if (get_script_instance()) {
  56. Array arr = get_script_instance()->call("_get_extensions");
  57. for (int i = 0; i < arr.size(); i++) {
  58. r_extensions->push_back(arr[i]);
  59. }
  60. return;
  61. }
  62. ERR_FAIL();
  63. }
  64. Node *EditorSceneImporter::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
  65. if (get_script_instance()) {
  66. return get_script_instance()->call("_import_scene", p_path, p_flags, p_bake_fps);
  67. }
  68. ERR_FAIL_V(NULL);
  69. }
  70. Ref<Animation> EditorSceneImporter::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  71. if (get_script_instance()) {
  72. return get_script_instance()->call("_import_animation", p_path, p_flags);
  73. }
  74. ERR_FAIL_V(NULL);
  75. }
  76. //for documenters, these functions are useful when an importer calls an external conversion helper (like, fbx2gltf),
  77. //and you want to load the resulting file
  78. Node *EditorSceneImporter::import_scene_from_other_importer(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  79. return ResourceImporterScene::get_singleton()->import_scene_from_other_importer(this, p_path, p_flags, p_bake_fps);
  80. }
  81. Ref<Animation> EditorSceneImporter::import_animation_from_other_importer(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  82. return ResourceImporterScene::get_singleton()->import_animation_from_other_importer(this, p_path, p_flags, p_bake_fps);
  83. }
  84. void EditorSceneImporter::_bind_methods() {
  85. ClassDB::bind_method(D_METHOD("import_scene_from_other_importer", "path", "flags", "bake_fps"), &EditorSceneImporter::import_scene_from_other_importer);
  86. ClassDB::bind_method(D_METHOD("import_animation_from_other_importer", "path", "flags", "bake_fps"), &EditorSceneImporter::import_animation_from_other_importer);
  87. BIND_VMETHOD(MethodInfo(Variant::INT, "_get_import_flags"));
  88. BIND_VMETHOD(MethodInfo(Variant::ARRAY, "_get_extensions"));
  89. MethodInfo mi = MethodInfo(Variant::OBJECT, "_import_scene", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::INT, "flags"), PropertyInfo(Variant::INT, "bake_fps"));
  90. mi.return_val.class_name = "Node";
  91. BIND_VMETHOD(mi);
  92. mi = MethodInfo(Variant::OBJECT, "_import_animation", PropertyInfo(Variant::STRING, "path"), PropertyInfo(Variant::INT, "flags"), PropertyInfo(Variant::INT, "bake_fps"));
  93. mi.return_val.class_name = "Animation";
  94. BIND_VMETHOD(mi);
  95. BIND_CONSTANT(IMPORT_SCENE);
  96. BIND_CONSTANT(IMPORT_ANIMATION);
  97. BIND_CONSTANT(IMPORT_ANIMATION_DETECT_LOOP);
  98. BIND_CONSTANT(IMPORT_ANIMATION_OPTIMIZE);
  99. BIND_CONSTANT(IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS);
  100. BIND_CONSTANT(IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
  101. BIND_CONSTANT(IMPORT_GENERATE_TANGENT_ARRAYS);
  102. BIND_CONSTANT(IMPORT_FAIL_ON_MISSING_DEPENDENCIES);
  103. BIND_CONSTANT(IMPORT_MATERIALS_IN_INSTANCES);
  104. BIND_CONSTANT(IMPORT_USE_COMPRESSION);
  105. }
  106. /////////////////////////////////
  107. void EditorScenePostImport::_bind_methods() {
  108. BIND_VMETHOD(MethodInfo(Variant::OBJECT, "post_import", PropertyInfo(Variant::OBJECT, "scene")));
  109. ClassDB::bind_method(D_METHOD("get_source_folder"), &EditorScenePostImport::get_source_folder);
  110. ClassDB::bind_method(D_METHOD("get_source_file"), &EditorScenePostImport::get_source_file);
  111. }
  112. Node *EditorScenePostImport::post_import(Node *p_scene) {
  113. if (get_script_instance())
  114. return get_script_instance()->call("post_import", p_scene);
  115. return p_scene;
  116. }
  117. String EditorScenePostImport::get_source_folder() const {
  118. return source_folder;
  119. }
  120. String EditorScenePostImport::get_source_file() const {
  121. return source_file;
  122. }
  123. void EditorScenePostImport::init(const String &p_source_folder, const String &p_source_file) {
  124. source_folder = p_source_folder;
  125. source_file = p_source_file;
  126. }
  127. EditorScenePostImport::EditorScenePostImport() {
  128. }
  129. String ResourceImporterScene::get_importer_name() const {
  130. return "scene";
  131. }
  132. String ResourceImporterScene::get_visible_name() const {
  133. return "Scene";
  134. }
  135. void ResourceImporterScene::get_recognized_extensions(List<String> *p_extensions) const {
  136. for (Set<Ref<EditorSceneImporter> >::Element *E = importers.front(); E; E = E->next()) {
  137. E->get()->get_extensions(p_extensions);
  138. }
  139. }
  140. String ResourceImporterScene::get_save_extension() const {
  141. return "scn";
  142. }
  143. String ResourceImporterScene::get_resource_type() const {
  144. return "PackedScene";
  145. }
  146. bool ResourceImporterScene::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
  147. if (p_option.begins_with("animation/")) {
  148. if (p_option != "animation/import" && !bool(p_options["animation/import"]))
  149. return false;
  150. if (p_option == "animation/keep_custom_tracks" && int(p_options["animation/storage"]) == 0)
  151. return false;
  152. if (p_option.begins_with("animation/optimizer/") && p_option != "animation/optimizer/enabled" && !bool(p_options["animation/optimizer/enabled"]))
  153. return false;
  154. if (p_option.begins_with("animation/clip_")) {
  155. int max_clip = p_options["animation/clips/amount"];
  156. int clip = p_option.get_slice("/", 1).get_slice("_", 1).to_int() - 1;
  157. if (clip >= max_clip)
  158. return false;
  159. }
  160. }
  161. if (p_option == "materials/keep_on_reimport" && int(p_options["materials/storage"]) == 0) {
  162. return false;
  163. }
  164. if (p_option == "meshes/lightmap_texel_size" && int(p_options["meshes/light_baking"]) < 2) {
  165. return false;
  166. }
  167. return true;
  168. }
  169. int ResourceImporterScene::get_preset_count() const {
  170. return PRESET_MAX;
  171. }
  172. String ResourceImporterScene::get_preset_name(int p_idx) const {
  173. switch (p_idx) {
  174. case PRESET_SINGLE_SCENE: return TTR("Import as Single Scene");
  175. case PRESET_SEPARATE_ANIMATIONS: return TTR("Import with Separate Animations");
  176. case PRESET_SEPARATE_MATERIALS: return TTR("Import with Separate Materials");
  177. case PRESET_SEPARATE_MESHES: return TTR("Import with Separate Objects");
  178. case PRESET_SEPARATE_MESHES_AND_MATERIALS: return TTR("Import with Separate Objects+Materials");
  179. case PRESET_SEPARATE_MESHES_AND_ANIMATIONS: return TTR("Import with Separate Objects+Animations");
  180. case PRESET_SEPARATE_MATERIALS_AND_ANIMATIONS: return TTR("Import with Separate Materials+Animations");
  181. case PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS: return TTR("Import with Separate Objects+Materials+Animations");
  182. case PRESET_MULTIPLE_SCENES: return TTR("Import as Multiple Scenes");
  183. case PRESET_MULTIPLE_SCENES_AND_MATERIALS: return TTR("Import as Multiple Scenes+Materials");
  184. }
  185. return "";
  186. }
  187. static bool _teststr(const String &p_what, const String &p_str) {
  188. String what = p_what;
  189. //remove trailing spaces and numbers, some apps like blender add ".number" to duplicates so also compensate for this
  190. while (what.length() && ((what[what.length() - 1] >= '0' && what[what.length() - 1] <= '9') || what[what.length() - 1] <= 32 || what[what.length() - 1] == '.')) {
  191. what = what.substr(0, what.length() - 1);
  192. }
  193. if (what.findn("$" + p_str) != -1) //blender and other stuff
  194. return true;
  195. if (what.to_lower().ends_with("-" + p_str)) //collada only supports "_" and "-" besides letters
  196. return true;
  197. if (what.to_lower().ends_with("_" + p_str)) //collada only supports "_" and "-" besides letters
  198. return true;
  199. return false;
  200. }
  201. static String _fixstr(const String &p_what, const String &p_str) {
  202. String what = p_what;
  203. //remove trailing spaces and numbers, some apps like blender add ".number" to duplicates so also compensate for this
  204. while (what.length() && ((what[what.length() - 1] >= '0' && what[what.length() - 1] <= '9') || what[what.length() - 1] <= 32 || what[what.length() - 1] == '.')) {
  205. what = what.substr(0, what.length() - 1);
  206. }
  207. String end = p_what.substr(what.length(), p_what.length() - what.length());
  208. if (what.findn("$" + p_str) != -1) //blender and other stuff
  209. return what.replace("$" + p_str, "") + end;
  210. if (what.to_lower().ends_with("-" + p_str)) //collada only supports "_" and "-" besides letters
  211. return what.substr(0, what.length() - (p_str.length() + 1)) + end;
  212. if (what.to_lower().ends_with("_" + p_str)) //collada only supports "_" and "-" besides letters
  213. return what.substr(0, what.length() - (p_str.length() + 1)) + end;
  214. return what;
  215. }
  216. Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<ArrayMesh>, Ref<Shape> > &collision_map, LightBakeMode p_light_bake_mode) {
  217. // children first
  218. for (int i = 0; i < p_node->get_child_count(); i++) {
  219. Node *r = _fix_node(p_node->get_child(i), p_root, collision_map, p_light_bake_mode);
  220. if (!r) {
  221. i--; //was erased
  222. }
  223. }
  224. String name = p_node->get_name();
  225. bool isroot = p_node == p_root;
  226. if (!isroot && _teststr(name, "noimp")) {
  227. memdelete(p_node);
  228. return NULL;
  229. }
  230. if (Object::cast_to<MeshInstance>(p_node)) {
  231. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  232. Ref<ArrayMesh> m = mi->get_mesh();
  233. if (m.is_valid()) {
  234. for (int i = 0; i < m->get_surface_count(); i++) {
  235. Ref<SpatialMaterial> mat = m->surface_get_material(i);
  236. if (!mat.is_valid())
  237. continue;
  238. if (_teststr(mat->get_name(), "alpha")) {
  239. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  240. mat->set_name(_fixstr(mat->get_name(), "alpha"));
  241. }
  242. if (_teststr(mat->get_name(), "vcol")) {
  243. mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  244. mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  245. mat->set_name(_fixstr(mat->get_name(), "vcol"));
  246. }
  247. }
  248. }
  249. if (p_light_bake_mode != LIGHT_BAKE_DISABLED) {
  250. mi->set_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT, true);
  251. }
  252. }
  253. if (Object::cast_to<AnimationPlayer>(p_node)) {
  254. //remove animations referencing non-importable nodes
  255. AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
  256. List<StringName> anims;
  257. ap->get_animation_list(&anims);
  258. for (List<StringName>::Element *E = anims.front(); E; E = E->next()) {
  259. Ref<Animation> anim = ap->get_animation(E->get());
  260. ERR_CONTINUE(anim.is_null());
  261. for (int i = 0; i < anim->get_track_count(); i++) {
  262. NodePath path = anim->track_get_path(i);
  263. for (int j = 0; j < path.get_name_count(); j++) {
  264. String node = path.get_name(j);
  265. if (_teststr(node, "noimp")) {
  266. anim->remove_track(i);
  267. i--;
  268. break;
  269. }
  270. }
  271. }
  272. }
  273. }
  274. if (_teststr(name, "colonly") || _teststr(name, "convcolonly")) {
  275. if (isroot)
  276. return p_node;
  277. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  278. if (mi) {
  279. Node *col = NULL;
  280. if (_teststr(name, "colonly")) {
  281. col = mi->create_trimesh_collision_node();
  282. if (col == NULL) {
  283. ERR_PRINTS("Error generating collision for mesh: " + name);
  284. } else {
  285. col->set_name(_fixstr(name, "colonly"));
  286. }
  287. } else {
  288. col = mi->create_convex_collision_node();
  289. if (col == NULL) {
  290. ERR_PRINTS("Error generating collision for mesh: " + name);
  291. } else {
  292. col->set_name(_fixstr(name, "convcolonly"));
  293. }
  294. }
  295. if (col) {
  296. Object::cast_to<Spatial>(col)->set_transform(mi->get_transform());
  297. p_node->replace_by(col);
  298. memdelete(p_node);
  299. p_node = col;
  300. StaticBody *sb = Object::cast_to<StaticBody>(col);
  301. CollisionShape *colshape = Object::cast_to<CollisionShape>(sb->get_child(0));
  302. colshape->set_name("shape");
  303. colshape->set_owner(p_node->get_owner());
  304. }
  305. } else if (p_node->has_meta("empty_draw_type")) {
  306. String empty_draw_type = String(p_node->get_meta("empty_draw_type"));
  307. StaticBody *sb = memnew(StaticBody);
  308. sb->set_name(_fixstr(name, "colonly"));
  309. Object::cast_to<Spatial>(sb)->set_transform(Object::cast_to<Spatial>(p_node)->get_transform());
  310. p_node->replace_by(sb);
  311. memdelete(p_node);
  312. CollisionShape *colshape = memnew(CollisionShape);
  313. if (empty_draw_type == "CUBE") {
  314. BoxShape *boxShape = memnew(BoxShape);
  315. boxShape->set_extents(Vector3(1, 1, 1));
  316. colshape->set_shape(boxShape);
  317. colshape->set_name("BoxShape");
  318. } else if (empty_draw_type == "SINGLE_ARROW") {
  319. RayShape *rayShape = memnew(RayShape);
  320. rayShape->set_length(1);
  321. colshape->set_shape(rayShape);
  322. colshape->set_name("RayShape");
  323. Object::cast_to<Spatial>(sb)->rotate_x(Math_PI / 2);
  324. } else if (empty_draw_type == "IMAGE") {
  325. PlaneShape *planeShape = memnew(PlaneShape);
  326. colshape->set_shape(planeShape);
  327. colshape->set_name("PlaneShape");
  328. } else {
  329. SphereShape *sphereShape = memnew(SphereShape);
  330. sphereShape->set_radius(1);
  331. colshape->set_shape(sphereShape);
  332. colshape->set_name("SphereShape");
  333. }
  334. sb->add_child(colshape);
  335. colshape->set_owner(sb->get_owner());
  336. }
  337. } else if (_teststr(name, "rigid") && Object::cast_to<MeshInstance>(p_node)) {
  338. if (isroot)
  339. return p_node;
  340. // get mesh instance and bounding box
  341. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  342. AABB aabb = mi->get_aabb();
  343. // create a new rigid body collision node
  344. RigidBody *rigid_body = memnew(RigidBody);
  345. Node *col = rigid_body;
  346. ERR_FAIL_COND_V(!col, NULL);
  347. // remove node name postfix
  348. col->set_name(_fixstr(name, "rigid"));
  349. // get mesh instance xform matrix to the rigid body collision node
  350. Object::cast_to<Spatial>(col)->set_transform(mi->get_transform());
  351. // save original node by duplicating it into a new instance and correcting the name
  352. Node *mesh = p_node->duplicate();
  353. mesh->set_name(_fixstr(name, "rigid"));
  354. // reset the xform matrix of the duplicated node so it can inherit parent node xform
  355. Object::cast_to<Spatial>(mesh)->set_transform(Transform(Basis()));
  356. // reparent the new mesh node to the rigid body collision node
  357. p_node->add_child(mesh);
  358. mesh->set_owner(p_node->get_owner());
  359. // replace the original node with the rigid body collision node
  360. p_node->replace_by(col);
  361. memdelete(p_node);
  362. p_node = col;
  363. // create an alias for the rigid body collision node
  364. RigidBody *rb = Object::cast_to<RigidBody>(col);
  365. // create a new Box collision shape and set the right extents
  366. Ref<BoxShape> shape = memnew(BoxShape);
  367. shape->set_extents(aabb.get_size() * 0.5);
  368. CollisionShape *colshape = memnew(CollisionShape);
  369. colshape->set_name("shape");
  370. colshape->set_shape(shape);
  371. // reparent the new collision shape to the rigid body collision node
  372. rb->add_child(colshape);
  373. colshape->set_owner(p_node->get_owner());
  374. } else if ((_teststr(name, "col") || (_teststr(name, "convcol"))) && Object::cast_to<MeshInstance>(p_node)) {
  375. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  376. Node *col;
  377. if (_teststr(name, "col")) {
  378. String new_name = _fixstr(name, "col");
  379. if (mi->get_parent() && !mi->get_parent()->has_node(new_name)) {
  380. mi->set_name(new_name);
  381. }
  382. col = mi->create_trimesh_collision_node();
  383. ERR_FAIL_COND_V(!col, NULL);
  384. col->set_name("col");
  385. } else {
  386. String new_name = _fixstr(name, "convcol");
  387. if (mi->get_parent() && !mi->get_parent()->has_node(new_name)) {
  388. mi->set_name(new_name);
  389. }
  390. col = mi->create_convex_collision_node();
  391. ERR_FAIL_COND_V(!col, NULL);
  392. col->set_name("convcol");
  393. }
  394. p_node->add_child(col);
  395. StaticBody *sb = Object::cast_to<StaticBody>(col);
  396. CollisionShape *colshape = Object::cast_to<CollisionShape>(sb->get_child(0));
  397. colshape->set_name("shape");
  398. col->add_child(colshape);
  399. colshape->set_owner(p_node->get_owner());
  400. sb->set_owner(p_node->get_owner());
  401. } else if (_teststr(name, "navmesh") && Object::cast_to<MeshInstance>(p_node)) {
  402. if (isroot)
  403. return p_node;
  404. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  405. Ref<ArrayMesh> mesh = mi->get_mesh();
  406. ERR_FAIL_COND_V(mesh.is_null(), NULL);
  407. NavigationMeshInstance *nmi = memnew(NavigationMeshInstance);
  408. nmi->set_name(_fixstr(name, "navmesh"));
  409. Ref<NavigationMesh> nmesh = memnew(NavigationMesh);
  410. nmesh->create_from_mesh(mesh);
  411. nmi->set_navigation_mesh(nmesh);
  412. Object::cast_to<Spatial>(nmi)->set_transform(mi->get_transform());
  413. p_node->replace_by(nmi);
  414. memdelete(p_node);
  415. p_node = nmi;
  416. } else if (_teststr(name, "vehicle")) {
  417. if (isroot)
  418. return p_node;
  419. Node *owner = p_node->get_owner();
  420. Spatial *s = Object::cast_to<Spatial>(p_node);
  421. VehicleBody *bv = memnew(VehicleBody);
  422. String n = _fixstr(p_node->get_name(), "vehicle");
  423. bv->set_name(n);
  424. p_node->replace_by(bv);
  425. p_node->set_name(n);
  426. bv->add_child(p_node);
  427. bv->set_owner(owner);
  428. p_node->set_owner(owner);
  429. bv->set_transform(s->get_transform());
  430. s->set_transform(Transform());
  431. p_node = bv;
  432. } else if (_teststr(name, "wheel")) {
  433. if (isroot)
  434. return p_node;
  435. Node *owner = p_node->get_owner();
  436. Spatial *s = Object::cast_to<Spatial>(p_node);
  437. VehicleWheel *bv = memnew(VehicleWheel);
  438. String n = _fixstr(p_node->get_name(), "wheel");
  439. bv->set_name(n);
  440. p_node->replace_by(bv);
  441. p_node->set_name(n);
  442. bv->add_child(p_node);
  443. bv->set_owner(owner);
  444. p_node->set_owner(owner);
  445. bv->set_transform(s->get_transform());
  446. s->set_transform(Transform());
  447. p_node = bv;
  448. } else if (Object::cast_to<MeshInstance>(p_node)) {
  449. //last attempt, maybe collision inside the mesh data
  450. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  451. Ref<ArrayMesh> mesh = mi->get_mesh();
  452. if (!mesh.is_null()) {
  453. if (_teststr(mesh->get_name(), "col") || _teststr(mesh->get_name(), "convcol")) {
  454. Ref<Shape> shape;
  455. if (_teststr(mesh->get_name(), "col")) {
  456. mesh->set_name(_fixstr(mesh->get_name(), "col"));
  457. if (collision_map.has(mesh)) {
  458. shape = collision_map[mesh];
  459. } else {
  460. shape = mesh->create_trimesh_shape();
  461. if (!shape.is_null())
  462. collision_map[mesh] = shape;
  463. }
  464. } else if (_teststr(mesh->get_name(), "convcol")) {
  465. mesh->set_name(_fixstr(mesh->get_name(), "convcol"));
  466. if (collision_map.has(mesh)) {
  467. shape = collision_map[mesh];
  468. } else {
  469. shape = mesh->create_convex_shape();
  470. if (!shape.is_null())
  471. collision_map[mesh] = shape;
  472. }
  473. }
  474. if (!shape.is_null()) {
  475. StaticBody *col = memnew(StaticBody);
  476. CollisionShape *cshape = memnew(CollisionShape);
  477. cshape->set_shape(shape);
  478. col->add_child(cshape);
  479. col->set_transform(mi->get_transform());
  480. col->set_name(mi->get_name());
  481. p_node->replace_by(col);
  482. memdelete(p_node);
  483. p_node = col;
  484. cshape->set_name("shape");
  485. cshape->set_owner(p_node->get_owner());
  486. }
  487. }
  488. }
  489. }
  490. return p_node;
  491. }
  492. void ResourceImporterScene::_create_clips(Node *scene, const Array &p_clips, bool p_bake_all) {
  493. if (!scene->has_node(String("AnimationPlayer")))
  494. return;
  495. Node *n = scene->get_node(String("AnimationPlayer"));
  496. ERR_FAIL_COND(!n);
  497. AnimationPlayer *anim = Object::cast_to<AnimationPlayer>(n);
  498. ERR_FAIL_COND(!anim);
  499. if (!anim->has_animation("default"))
  500. return;
  501. Ref<Animation> default_anim = anim->get_animation("default");
  502. for (int i = 0; i < p_clips.size(); i += 4) {
  503. String name = p_clips[i];
  504. float from = p_clips[i + 1];
  505. float to = p_clips[i + 2];
  506. bool loop = p_clips[i + 3];
  507. if (from >= to)
  508. continue;
  509. Ref<Animation> new_anim = memnew(Animation);
  510. for (int j = 0; j < default_anim->get_track_count(); j++) {
  511. List<float> keys;
  512. int kc = default_anim->track_get_key_count(j);
  513. int dtrack = -1;
  514. for (int k = 0; k < kc; k++) {
  515. float kt = default_anim->track_get_key_time(j, k);
  516. if (kt >= from && kt < to) {
  517. //found a key within range, so create track
  518. if (dtrack == -1) {
  519. new_anim->add_track(default_anim->track_get_type(j));
  520. dtrack = new_anim->get_track_count() - 1;
  521. new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
  522. if (kt > (from + 0.01) && k > 0) {
  523. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  524. Quat q;
  525. Vector3 p;
  526. Vector3 s;
  527. default_anim->transform_track_interpolate(j, from, &p, &q, &s);
  528. new_anim->transform_track_insert_key(dtrack, 0, p, q, s);
  529. }
  530. }
  531. }
  532. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  533. Quat q;
  534. Vector3 p;
  535. Vector3 s;
  536. default_anim->transform_track_get_key(j, k, &p, &q, &s);
  537. new_anim->transform_track_insert_key(dtrack, kt - from, p, q, s);
  538. }
  539. }
  540. if (dtrack != -1 && kt >= to) {
  541. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  542. Quat q;
  543. Vector3 p;
  544. Vector3 s;
  545. default_anim->transform_track_interpolate(j, to, &p, &q, &s);
  546. new_anim->transform_track_insert_key(dtrack, to - from, p, q, s);
  547. }
  548. }
  549. }
  550. if (dtrack == -1 && p_bake_all) {
  551. new_anim->add_track(default_anim->track_get_type(j));
  552. dtrack = new_anim->get_track_count() - 1;
  553. new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
  554. if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
  555. Quat q;
  556. Vector3 p;
  557. Vector3 s;
  558. default_anim->transform_track_interpolate(j, from, &p, &q, &s);
  559. new_anim->transform_track_insert_key(dtrack, 0, p, q, s);
  560. default_anim->transform_track_interpolate(j, to, &p, &q, &s);
  561. new_anim->transform_track_insert_key(dtrack, to - from, p, q, s);
  562. }
  563. }
  564. }
  565. new_anim->set_loop(loop);
  566. new_anim->set_length(to - from);
  567. anim->add_animation(name, new_anim);
  568. }
  569. anim->remove_animation("default"); //remove default (no longer needed)
  570. }
  571. void ResourceImporterScene::_filter_anim_tracks(Ref<Animation> anim, Set<String> &keep) {
  572. Ref<Animation> a = anim;
  573. ERR_FAIL_COND(!a.is_valid());
  574. for (int j = 0; j < a->get_track_count(); j++) {
  575. String path = a->track_get_path(j);
  576. if (!keep.has(path)) {
  577. a->remove_track(j);
  578. j--;
  579. }
  580. }
  581. }
  582. void ResourceImporterScene::_filter_tracks(Node *scene, const String &p_text) {
  583. if (!scene->has_node(String("AnimationPlayer")))
  584. return;
  585. Node *n = scene->get_node(String("AnimationPlayer"));
  586. ERR_FAIL_COND(!n);
  587. AnimationPlayer *anim = Object::cast_to<AnimationPlayer>(n);
  588. ERR_FAIL_COND(!anim);
  589. Vector<String> strings = p_text.split("\n");
  590. for (int i = 0; i < strings.size(); i++) {
  591. strings.write[i] = strings[i].strip_edges();
  592. }
  593. List<StringName> anim_names;
  594. anim->get_animation_list(&anim_names);
  595. for (List<StringName>::Element *E = anim_names.front(); E; E = E->next()) {
  596. String name = E->get();
  597. bool valid_for_this = false;
  598. bool valid = false;
  599. Set<String> keep;
  600. Set<String> keep_local;
  601. for (int i = 0; i < strings.size(); i++) {
  602. if (strings[i].begins_with("@")) {
  603. valid_for_this = false;
  604. for (Set<String>::Element *F = keep_local.front(); F; F = F->next()) {
  605. keep.insert(F->get());
  606. }
  607. keep_local.clear();
  608. Vector<String> filters = strings[i].substr(1, strings[i].length()).split(",");
  609. for (int j = 0; j < filters.size(); j++) {
  610. String fname = filters[j].strip_edges();
  611. if (fname == "")
  612. continue;
  613. int fc = fname[0];
  614. bool plus;
  615. if (fc == '+')
  616. plus = true;
  617. else if (fc == '-')
  618. plus = false;
  619. else
  620. continue;
  621. String filter = fname.substr(1, fname.length()).strip_edges();
  622. if (!name.matchn(filter))
  623. continue;
  624. valid_for_this = plus;
  625. }
  626. if (valid_for_this)
  627. valid = true;
  628. } else if (valid_for_this) {
  629. Ref<Animation> a = anim->get_animation(name);
  630. if (!a.is_valid())
  631. continue;
  632. for (int j = 0; j < a->get_track_count(); j++) {
  633. String path = a->track_get_path(j);
  634. String tname = strings[i];
  635. if (tname == "")
  636. continue;
  637. int fc = tname[0];
  638. bool plus;
  639. if (fc == '+')
  640. plus = true;
  641. else if (fc == '-')
  642. plus = false;
  643. else
  644. continue;
  645. String filter = tname.substr(1, tname.length()).strip_edges();
  646. if (!path.matchn(filter))
  647. continue;
  648. if (plus)
  649. keep_local.insert(path);
  650. else if (!keep.has(path)) {
  651. keep_local.erase(path);
  652. }
  653. }
  654. }
  655. }
  656. if (valid) {
  657. for (Set<String>::Element *F = keep_local.front(); F; F = F->next()) {
  658. keep.insert(F->get());
  659. }
  660. _filter_anim_tracks(anim->get_animation(name), keep);
  661. } else {
  662. }
  663. }
  664. }
  665. void ResourceImporterScene::_optimize_animations(Node *scene, float p_max_lin_error, float p_max_ang_error, float p_max_angle) {
  666. if (!scene->has_node(String("AnimationPlayer")))
  667. return;
  668. Node *n = scene->get_node(String("AnimationPlayer"));
  669. ERR_FAIL_COND(!n);
  670. AnimationPlayer *anim = Object::cast_to<AnimationPlayer>(n);
  671. ERR_FAIL_COND(!anim);
  672. List<StringName> anim_names;
  673. anim->get_animation_list(&anim_names);
  674. for (List<StringName>::Element *E = anim_names.front(); E; E = E->next()) {
  675. Ref<Animation> a = anim->get_animation(E->get());
  676. a->optimize(p_max_lin_error, p_max_ang_error, Math::deg2rad(p_max_angle));
  677. }
  678. }
  679. static String _make_extname(const String &p_str) {
  680. String ext_name = p_str.replace(".", "_");
  681. ext_name = ext_name.replace(":", "_");
  682. ext_name = ext_name.replace("\"", "_");
  683. ext_name = ext_name.replace("<", "_");
  684. ext_name = ext_name.replace(">", "_");
  685. ext_name = ext_name.replace("/", "_");
  686. ext_name = ext_name.replace("|", "_");
  687. ext_name = ext_name.replace("\\", "_");
  688. ext_name = ext_name.replace("?", "_");
  689. ext_name = ext_name.replace("*", "_");
  690. return ext_name;
  691. }
  692. void ResourceImporterScene::_find_meshes(Node *p_node, Map<Ref<ArrayMesh>, Transform> &meshes) {
  693. List<PropertyInfo> pi;
  694. p_node->get_property_list(&pi);
  695. MeshInstance *mi = Object::cast_to<MeshInstance>(p_node);
  696. if (mi) {
  697. Ref<ArrayMesh> mesh = mi->get_mesh();
  698. if (mesh.is_valid() && !meshes.has(mesh)) {
  699. Spatial *s = mi;
  700. Transform transform;
  701. while (s) {
  702. transform = transform * s->get_transform();
  703. s = s->get_parent_spatial();
  704. }
  705. meshes[mesh] = transform;
  706. }
  707. }
  708. for (int i = 0; i < p_node->get_child_count(); i++) {
  709. _find_meshes(p_node->get_child(i), meshes);
  710. }
  711. }
  712. void ResourceImporterScene::_make_external_resources(Node *p_node, const String &p_base_path, bool p_make_animations, bool p_keep_animations, bool p_make_materials, bool p_keep_materials, bool p_make_meshes, Map<Ref<Animation>, Ref<Animation> > &p_animations, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<ArrayMesh>, Ref<ArrayMesh> > &p_meshes) {
  713. List<PropertyInfo> pi;
  714. if (p_make_animations) {
  715. if (Object::cast_to<AnimationPlayer>(p_node)) {
  716. AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
  717. List<StringName> anims;
  718. ap->get_animation_list(&anims);
  719. for (List<StringName>::Element *E = anims.front(); E; E = E->next()) {
  720. Ref<Animation> anim = ap->get_animation(E->get());
  721. ERR_CONTINUE(anim.is_null());
  722. if (!p_animations.has(anim)) {
  723. //mark what comes from the file first, this helps eventually keep user data
  724. for (int i = 0; i < anim->get_track_count(); i++) {
  725. anim->track_set_imported(i, true);
  726. }
  727. String ext_name = p_base_path.plus_file(_make_extname(E->get()) + ".anim");
  728. if (FileAccess::exists(ext_name) && p_keep_animations) {
  729. //try to keep custom animation tracks
  730. Ref<Animation> old_anim = ResourceLoader::load(ext_name, "Animation", true);
  731. if (old_anim.is_valid()) {
  732. //meergeee
  733. for (int i = 0; i < old_anim->get_track_count(); i++) {
  734. if (!old_anim->track_is_imported(i)) {
  735. old_anim->copy_track(i, anim);
  736. }
  737. }
  738. }
  739. }
  740. anim->set_path(ext_name, true); //if not set, then its never saved externally
  741. ResourceSaver::save(ext_name, anim, ResourceSaver::FLAG_CHANGE_PATH);
  742. p_animations[anim] = anim;
  743. }
  744. }
  745. }
  746. }
  747. p_node->get_property_list(&pi);
  748. for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
  749. if (E->get().type == Variant::OBJECT) {
  750. Ref<Material> mat = p_node->get(E->get().name);
  751. if (p_make_materials && mat.is_valid() && mat->get_name() != "") {
  752. if (!p_materials.has(mat)) {
  753. String ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
  754. if (p_keep_materials && FileAccess::exists(ext_name)) {
  755. //if exists, use it
  756. p_materials[mat] = ResourceLoader::load(ext_name);
  757. } else {
  758. ResourceSaver::save(ext_name, mat, ResourceSaver::FLAG_CHANGE_PATH);
  759. p_materials[mat] = ResourceLoader::load(ext_name);
  760. }
  761. }
  762. if (p_materials[mat] != mat) {
  763. p_node->set(E->get().name, p_materials[mat]);
  764. }
  765. } else {
  766. Ref<ArrayMesh> mesh = p_node->get(E->get().name);
  767. if (mesh.is_valid()) {
  768. bool mesh_just_added = false;
  769. if (p_make_meshes) {
  770. if (!p_meshes.has(mesh)) {
  771. //meshes are always overwritten, keeping them is not practical
  772. String ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
  773. ResourceSaver::save(ext_name, mesh, ResourceSaver::FLAG_CHANGE_PATH);
  774. p_meshes[mesh] = ResourceLoader::load(ext_name);
  775. p_node->set(E->get().name, p_meshes[mesh]);
  776. mesh_just_added = true;
  777. }
  778. }
  779. if (p_make_materials) {
  780. if (mesh_just_added || !p_meshes.has(mesh)) {
  781. for (int i = 0; i < mesh->get_surface_count(); i++) {
  782. mat = mesh->surface_get_material(i);
  783. if (!mat.is_valid())
  784. continue;
  785. if (mat->get_name() == "")
  786. continue;
  787. if (!p_materials.has(mat)) {
  788. String ext_name = p_base_path.plus_file(_make_extname(mat->get_name()) + ".material");
  789. ;
  790. if (FileAccess::exists(ext_name)) {
  791. //if exists, use it
  792. p_materials[mat] = ResourceLoader::load(ext_name);
  793. } else {
  794. ResourceSaver::save(ext_name, mat, ResourceSaver::FLAG_CHANGE_PATH);
  795. p_materials[mat] = ResourceLoader::load(ext_name);
  796. }
  797. }
  798. if (p_materials[mat] != mat) {
  799. mesh->surface_set_material(i, p_materials[mat]);
  800. //re-save the mesh since a material is now assigned
  801. if (p_make_meshes) {
  802. String ext_name = p_base_path.plus_file(_make_extname(mesh->get_name()) + ".mesh");
  803. ResourceSaver::save(ext_name, mesh, ResourceSaver::FLAG_CHANGE_PATH);
  804. p_meshes[mesh] = ResourceLoader::load(ext_name);
  805. }
  806. }
  807. }
  808. if (!p_make_meshes) {
  809. p_meshes[mesh] = Ref<ArrayMesh>(); //save it anyway, so it won't be checked again
  810. }
  811. }
  812. }
  813. }
  814. }
  815. }
  816. }
  817. for (int i = 0; i < p_node->get_child_count(); i++) {
  818. _make_external_resources(p_node->get_child(i), p_base_path, p_make_animations, p_keep_animations, p_make_materials, p_keep_materials, p_make_meshes, p_animations, p_materials, p_meshes);
  819. }
  820. }
  821. void ResourceImporterScene::get_import_options(List<ImportOption> *r_options, int p_preset) const {
  822. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_type", PROPERTY_HINT_TYPE_STRING, "Node"), "Spatial"));
  823. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_name"), "Scene Root"));
  824. List<String> script_extentions;
  825. ResourceLoader::get_recognized_extensions_for_type("Script", &script_extentions);
  826. String script_ext_hint;
  827. for (List<String>::Element *E = script_extentions.front(); E; E = E->next()) {
  828. if (script_ext_hint != "")
  829. script_ext_hint += ",";
  830. script_ext_hint += "*." + E->get();
  831. }
  832. bool materials_out = p_preset == PRESET_SEPARATE_MATERIALS || p_preset == PRESET_SEPARATE_MESHES_AND_MATERIALS || p_preset == PRESET_MULTIPLE_SCENES_AND_MATERIALS || p_preset == PRESET_SEPARATE_MATERIALS_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS;
  833. bool meshes_out = p_preset == PRESET_SEPARATE_MESHES || p_preset == PRESET_SEPARATE_MESHES_AND_MATERIALS || p_preset == PRESET_SEPARATE_MESHES_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS;
  834. bool scenes_out = p_preset == PRESET_MULTIPLE_SCENES || p_preset == PRESET_MULTIPLE_SCENES_AND_MATERIALS;
  835. bool animations_out = p_preset == PRESET_SEPARATE_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MATERIALS_AND_ANIMATIONS || p_preset == PRESET_SEPARATE_MESHES_MATERIALS_AND_ANIMATIONS;
  836. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "nodes/root_scale", PROPERTY_HINT_RANGE, "0.001,1000,0.001"), 1.0));
  837. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/custom_script", PROPERTY_HINT_FILE, script_ext_hint), ""));
  838. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "nodes/storage", PROPERTY_HINT_ENUM, "Single Scene,Instanced Sub-Scenes"), scenes_out ? 1 : 0));
  839. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/location", PROPERTY_HINT_ENUM, "Node,Mesh"), (meshes_out || materials_out) ? 1 : 0));
  840. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/storage", PROPERTY_HINT_ENUM, "Built-In,Files", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), materials_out ? 1 : 0));
  841. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "materials/keep_on_reimport"), materials_out ? true : false));
  842. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/compress"), true));
  843. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "meshes/ensure_tangents"), true));
  844. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/storage", PROPERTY_HINT_ENUM, "Built-In,Files"), meshes_out ? 1 : 0));
  845. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "meshes/light_baking", PROPERTY_HINT_ENUM, "Disabled,Enable,Gen Lightmaps", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
  846. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "meshes/lightmap_texel_size", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 0.1));
  847. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "external_files/store_in_subdir"), false));
  848. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
  849. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/fps", PROPERTY_HINT_RANGE, "1,120,1"), 15));
  850. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "animation/filter_script", PROPERTY_HINT_MULTILINE_TEXT), ""));
  851. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/storage", PROPERTY_HINT_ENUM, "Built-In,Files"), animations_out ? true : false));
  852. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/keep_custom_tracks"), animations_out ? true : false));
  853. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/optimizer/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
  854. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_linear_error"), 0.05));
  855. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_angular_error"), 0.01));
  856. r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_angle"), 22));
  857. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/optimizer/remove_unused_tracks"), true));
  858. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clips/amount", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
  859. for (int i = 0; i < 256; i++) {
  860. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "animation/clip_" + itos(i + 1) + "/name"), ""));
  861. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clip_" + itos(i + 1) + "/start_frame"), 0));
  862. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clip_" + itos(i + 1) + "/end_frame"), 0));
  863. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/clip_" + itos(i + 1) + "/loops"), false));
  864. }
  865. }
  866. void ResourceImporterScene::_replace_owner(Node *p_node, Node *p_scene, Node *p_new_owner) {
  867. if (p_node != p_new_owner && p_node->get_owner() == p_scene) {
  868. p_node->set_owner(p_new_owner);
  869. }
  870. for (int i = 0; i < p_node->get_child_count(); i++) {
  871. Node *n = p_node->get_child(i);
  872. _replace_owner(n, p_scene, p_new_owner);
  873. }
  874. }
  875. Node *ResourceImporterScene::import_scene_from_other_importer(EditorSceneImporter *p_exception, const String &p_path, uint32_t p_flags, int p_bake_fps) {
  876. Ref<EditorSceneImporter> importer;
  877. String ext = p_path.get_extension().to_lower();
  878. for (Set<Ref<EditorSceneImporter> >::Element *E = importers.front(); E; E = E->next()) {
  879. if (E->get().ptr() == p_exception)
  880. continue;
  881. List<String> extensions;
  882. E->get()->get_extensions(&extensions);
  883. for (List<String>::Element *F = extensions.front(); F; F = F->next()) {
  884. if (F->get().to_lower() == ext) {
  885. importer = E->get();
  886. break;
  887. }
  888. }
  889. if (importer.is_valid())
  890. break;
  891. }
  892. ERR_FAIL_COND_V(!importer.is_valid(), NULL);
  893. List<String> missing;
  894. Error err;
  895. return importer->import_scene(p_path, p_flags, p_bake_fps, &missing, &err);
  896. }
  897. Ref<Animation> ResourceImporterScene::import_animation_from_other_importer(EditorSceneImporter *p_exception, const String &p_path, uint32_t p_flags, int p_bake_fps) {
  898. Ref<EditorSceneImporter> importer;
  899. String ext = p_path.get_extension().to_lower();
  900. for (Set<Ref<EditorSceneImporter> >::Element *E = importers.front(); E; E = E->next()) {
  901. if (E->get().ptr() == p_exception)
  902. continue;
  903. List<String> extensions;
  904. E->get()->get_extensions(&extensions);
  905. for (List<String>::Element *F = extensions.front(); F; F = F->next()) {
  906. if (F->get().to_lower() == ext) {
  907. importer = E->get();
  908. break;
  909. }
  910. }
  911. if (importer.is_valid())
  912. break;
  913. }
  914. ERR_FAIL_COND_V(!importer.is_valid(), NULL);
  915. return importer->import_animation(p_path, p_flags, p_bake_fps);
  916. }
  917. Error ResourceImporterScene::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files) {
  918. String src_path = p_source_file;
  919. Ref<EditorSceneImporter> importer;
  920. String ext = src_path.get_extension().to_lower();
  921. EditorProgress progress("import", TTR("Import Scene"), 104);
  922. progress.step(TTR("Importing Scene..."), 0);
  923. for (Set<Ref<EditorSceneImporter> >::Element *E = importers.front(); E; E = E->next()) {
  924. List<String> extensions;
  925. E->get()->get_extensions(&extensions);
  926. for (List<String>::Element *F = extensions.front(); F; F = F->next()) {
  927. if (F->get().to_lower() == ext) {
  928. importer = E->get();
  929. break;
  930. }
  931. }
  932. if (importer.is_valid())
  933. break;
  934. }
  935. ERR_FAIL_COND_V(!importer.is_valid(), ERR_FILE_UNRECOGNIZED);
  936. float fps = p_options["animation/fps"];
  937. int import_flags = EditorSceneImporter::IMPORT_ANIMATION_DETECT_LOOP;
  938. if (!bool(p_options["animation/optimizer/remove_unused_tracks"]))
  939. import_flags |= EditorSceneImporter::IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS;
  940. if (bool(p_options["animation/import"]))
  941. import_flags |= EditorSceneImporter::IMPORT_ANIMATION;
  942. if (int(p_options["meshes/compress"]))
  943. import_flags |= EditorSceneImporter::IMPORT_USE_COMPRESSION;
  944. if (bool(p_options["meshes/ensure_tangents"]))
  945. import_flags |= EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS;
  946. if (int(p_options["materials/location"]) == 0)
  947. import_flags |= EditorSceneImporter::IMPORT_MATERIALS_IN_INSTANCES;
  948. Error err = OK;
  949. List<String> missing_deps; // for now, not much will be done with this
  950. Node *scene = importer->import_scene(src_path, import_flags, fps, &missing_deps, &err);
  951. if (!scene || err != OK) {
  952. return err;
  953. }
  954. String root_type = p_options["nodes/root_type"];
  955. if (scene->get_class() != root_type) {
  956. Node *base_node = Object::cast_to<Node>(ClassDB::instance(root_type));
  957. if (base_node) {
  958. scene->replace_by(base_node);
  959. memdelete(scene);
  960. scene = base_node;
  961. }
  962. }
  963. if (Object::cast_to<Spatial>(scene)) {
  964. float root_scale = p_options["nodes/root_scale"];
  965. Object::cast_to<Spatial>(scene)->scale(Vector3(root_scale, root_scale, root_scale));
  966. }
  967. scene->set_name(p_options["nodes/root_name"]);
  968. err = OK;
  969. String animation_filter = String(p_options["animation/filter_script"]).strip_edges();
  970. bool use_optimizer = p_options["animation/optimizer/enabled"];
  971. float anim_optimizer_linerr = p_options["animation/optimizer/max_linear_error"];
  972. float anim_optimizer_angerr = p_options["animation/optimizer/max_angular_error"];
  973. float anim_optimizer_maxang = p_options["animation/optimizer/max_angle"];
  974. int light_bake_mode = p_options["meshes/light_baking"];
  975. Map<Ref<ArrayMesh>, Ref<Shape> > collision_map;
  976. scene = _fix_node(scene, scene, collision_map, LightBakeMode(light_bake_mode));
  977. if (use_optimizer) {
  978. _optimize_animations(scene, anim_optimizer_linerr, anim_optimizer_angerr, anim_optimizer_maxang);
  979. }
  980. Array animation_clips;
  981. {
  982. int clip_count = p_options["animation/clips/amount"];
  983. for (int i = 0; i < clip_count; i++) {
  984. String name = p_options["animation/clip_" + itos(i + 1) + "/name"];
  985. int from_frame = p_options["animation/clip_" + itos(i + 1) + "/start_frame"];
  986. int end_frame = p_options["animation/clip_" + itos(i + 1) + "/end_frame"];
  987. bool loop = p_options["animation/clip_" + itos(i + 1) + "/loops"];
  988. animation_clips.push_back(name);
  989. animation_clips.push_back(from_frame / fps);
  990. animation_clips.push_back(end_frame / fps);
  991. animation_clips.push_back(loop);
  992. }
  993. }
  994. if (animation_clips.size()) {
  995. _create_clips(scene, animation_clips, !bool(p_options["animation/optimizer/remove_unused_tracks"]));
  996. }
  997. if (animation_filter != "") {
  998. _filter_tracks(scene, animation_filter);
  999. }
  1000. bool external_animations = int(p_options["animation/storage"]) == 1;
  1001. bool keep_custom_tracks = p_options["animation/keep_custom_tracks"];
  1002. bool external_materials = p_options["materials/storage"];
  1003. bool external_meshes = p_options["meshes/storage"];
  1004. bool external_scenes = int(p_options["nodes/storage"]) == 1;
  1005. String base_path = p_source_file.get_base_dir();
  1006. if (external_animations || external_materials || external_meshes || external_scenes) {
  1007. if (bool(p_options["external_files/store_in_subdir"])) {
  1008. String subdir_name = p_source_file.get_file().get_basename();
  1009. DirAccess *da = DirAccess::open(base_path);
  1010. Error err = da->make_dir(subdir_name);
  1011. memdelete(da);
  1012. ERR_FAIL_COND_V(err != OK && err != ERR_ALREADY_EXISTS, err);
  1013. base_path = base_path.plus_file(subdir_name);
  1014. }
  1015. }
  1016. if (light_bake_mode == 2 /* || generate LOD */) {
  1017. Map<Ref<ArrayMesh>, Transform> meshes;
  1018. _find_meshes(scene, meshes);
  1019. if (light_bake_mode == 2) {
  1020. float texel_size = p_options["meshes/lightmap_texel_size"];
  1021. texel_size = MAX(0.001, texel_size);
  1022. EditorProgress progress("gen_lightmaps", TTR("Generating Lightmaps"), meshes.size());
  1023. int step = 0;
  1024. for (Map<Ref<ArrayMesh>, Transform>::Element *E = meshes.front(); E; E = E->next()) {
  1025. Ref<ArrayMesh> mesh = E->key();
  1026. String name = mesh->get_name();
  1027. if (name == "") { //should not happen but..
  1028. name = "Mesh " + itos(step);
  1029. }
  1030. progress.step(TTR("Generating for Mesh: ") + name + " (" + itos(step) + "/" + itos(meshes.size()) + ")", step);
  1031. Error err = mesh->lightmap_unwrap(E->get(), texel_size);
  1032. if (err != OK) {
  1033. EditorNode::add_io_error("Mesh '" + name + "' failed lightmap generation. Please fix geometry.");
  1034. }
  1035. step++;
  1036. }
  1037. }
  1038. }
  1039. if (external_animations || external_materials || external_meshes) {
  1040. Map<Ref<Animation>, Ref<Animation> > anim_map;
  1041. Map<Ref<Material>, Ref<Material> > mat_map;
  1042. Map<Ref<ArrayMesh>, Ref<ArrayMesh> > mesh_map;
  1043. bool keep_materials = bool(p_options["materials/keep_on_reimport"]);
  1044. _make_external_resources(scene, base_path, external_animations, keep_custom_tracks, external_materials, keep_materials, external_meshes, anim_map, mat_map, mesh_map);
  1045. }
  1046. progress.step(TTR("Running Custom Script..."), 2);
  1047. String post_import_script_path = p_options["nodes/custom_script"];
  1048. Ref<EditorScenePostImport> post_import_script;
  1049. if (post_import_script_path != "") {
  1050. Ref<Script> scr = ResourceLoader::load(post_import_script_path);
  1051. if (!scr.is_valid()) {
  1052. EditorNode::add_io_error(TTR("Couldn't load post-import script:") + " " + post_import_script_path);
  1053. } else {
  1054. post_import_script = Ref<EditorScenePostImport>(memnew(EditorScenePostImport));
  1055. post_import_script->set_script(scr.get_ref_ptr());
  1056. if (!post_import_script->get_script_instance()) {
  1057. EditorNode::add_io_error(TTR("Invalid/broken script for post-import (check console):") + " " + post_import_script_path);
  1058. post_import_script.unref();
  1059. return ERR_CANT_CREATE;
  1060. }
  1061. }
  1062. }
  1063. if (post_import_script.is_valid()) {
  1064. post_import_script->init(base_path, p_source_file);
  1065. scene = post_import_script->post_import(scene);
  1066. if (!scene) {
  1067. EditorNode::add_io_error(TTR("Error running post-import script:") + " " + post_import_script_path);
  1068. return err;
  1069. }
  1070. }
  1071. progress.step(TTR("Saving..."), 104);
  1072. if (external_scenes) {
  1073. //save sub-scenes as instances!
  1074. for (int i = 0; i < scene->get_child_count(); i++) {
  1075. Node *child = scene->get_child(i);
  1076. if (child->get_owner() != scene)
  1077. continue; //not a real child probably created by scene type (ig, a scrollbar)
  1078. _replace_owner(child, scene, child);
  1079. String cn = String(child->get_name()).strip_edges().replace(".", "_").replace(":", "_");
  1080. if (cn == String()) {
  1081. cn = "ChildNode" + itos(i);
  1082. }
  1083. String path = base_path.plus_file(cn + ".scn");
  1084. child->set_filename(path);
  1085. Ref<PackedScene> packer = memnew(PackedScene);
  1086. packer->pack(child);
  1087. err = ResourceSaver::save(path, packer); //do not take over, let the changed files reload themselves
  1088. ERR_FAIL_COND_V(err != OK, err);
  1089. }
  1090. }
  1091. Ref<PackedScene> packer = memnew(PackedScene);
  1092. packer->pack(scene);
  1093. print_verbose("Saving scene to: " + p_save_path + ".scn");
  1094. err = ResourceSaver::save(p_save_path + ".scn", packer); //do not take over, let the changed files reload themselves
  1095. ERR_FAIL_COND_V(err != OK, err);
  1096. memdelete(scene);
  1097. //this is not the time to reimport, wait until import process is done, import file is saved, etc.
  1098. //EditorNode::get_singleton()->reload_scene(p_source_file);
  1099. return OK;
  1100. }
  1101. ResourceImporterScene *ResourceImporterScene::singleton = NULL;
  1102. ResourceImporterScene::ResourceImporterScene() {
  1103. singleton = this;
  1104. }
  1105. ///////////////////////////////////////
  1106. uint32_t EditorSceneImporterESCN::get_import_flags() const {
  1107. return IMPORT_SCENE;
  1108. }
  1109. void EditorSceneImporterESCN::get_extensions(List<String> *r_extensions) const {
  1110. r_extensions->push_back("escn");
  1111. }
  1112. Node *EditorSceneImporterESCN::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
  1113. Error error;
  1114. Ref<PackedScene> ps = ResourceFormatLoaderText::singleton->load(p_path, p_path, &error);
  1115. ERR_FAIL_COND_V(!ps.is_valid(), NULL);
  1116. Node *scene = ps->instance();
  1117. ERR_FAIL_COND_V(!scene, NULL);
  1118. return scene;
  1119. }
  1120. Ref<Animation> EditorSceneImporterESCN::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  1121. ERR_FAIL_V(Ref<Animation>());
  1122. }