2
0

editor_import_collada.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  1. /**************************************************************************/
  2. /* editor_import_collada.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. #include "editor_import_collada.h"
  31. #include "core/config/project_settings.h"
  32. #include "editor/import/3d/collada.h"
  33. #include "scene/3d/camera_3d.h"
  34. #include "scene/3d/importer_mesh_instance_3d.h"
  35. #include "scene/3d/light_3d.h"
  36. #include "scene/3d/node_3d.h"
  37. #include "scene/3d/path_3d.h"
  38. #include "scene/3d/skeleton_3d.h"
  39. #include "scene/animation/animation_player.h"
  40. #include "scene/resources/3d/importer_mesh.h"
  41. #include "scene/resources/animation.h"
  42. #include "scene/resources/surface_tool.h"
  43. struct ColladaImport {
  44. Collada collada;
  45. Node3D *scene = nullptr;
  46. Vector<Ref<Animation>> animations;
  47. struct NodeMap {
  48. //String path;
  49. Node3D *node = nullptr;
  50. int bone = -1;
  51. List<int> anim_tracks;
  52. };
  53. bool found_ambient = false;
  54. Color ambient;
  55. bool found_directional = false;
  56. bool force_make_tangents = false;
  57. bool apply_mesh_xform_to_vertices = true;
  58. bool use_mesh_builtin_materials = false;
  59. float bake_fps = 30;
  60. HashMap<String, NodeMap> node_map; //map from collada node to engine node
  61. HashMap<String, String> node_name_map; //map from collada node to engine node
  62. HashMap<String, Ref<ImporterMesh>> mesh_cache;
  63. HashMap<String, Ref<Curve3D>> curve_cache;
  64. HashMap<String, Ref<Material>> material_cache;
  65. HashMap<Collada::Node *, Skeleton3D *> skeleton_map;
  66. HashMap<Skeleton3D *, HashMap<String, int>> skeleton_bone_map;
  67. HashSet<String> valid_animated_nodes;
  68. Vector<int> valid_animated_properties;
  69. HashMap<String, bool> bones_with_animation;
  70. HashSet<String> mesh_unique_names;
  71. HashSet<String> material_unique_names;
  72. Error _populate_skeleton(Skeleton3D *p_skeleton, Collada::Node *p_node, int &r_bone, int p_parent);
  73. Error _create_scene_skeletons(Collada::Node *p_node);
  74. Error _create_scene(Collada::Node *p_node, Node3D *p_parent);
  75. Error _create_resources(Collada::Node *p_node, bool p_use_compression);
  76. Error _create_material(const String &p_target);
  77. Error _create_mesh_surfaces(bool p_optimize, Ref<ImporterMesh> &p_mesh, const HashMap<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform3D &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_controller, const Collada::MorphControllerData *p_morph_data, const Vector<Ref<ImporterMesh>> &p_morph_meshes = Vector<Ref<ImporterMesh>>(), bool p_use_compression = false, bool p_use_mesh_material = false);
  78. Error load(const String &p_path, int p_flags, bool p_force_make_tangents = false, bool p_use_compression = false);
  79. void _fix_param_animation_tracks();
  80. void create_animation(int p_clip, bool p_import_value_tracks);
  81. void create_animations(bool p_import_value_tracks);
  82. HashSet<String> tracks_in_clips;
  83. Vector<String> missing_textures;
  84. void _pre_process_lights(Collada::Node *p_node);
  85. };
  86. Error ColladaImport::_populate_skeleton(Skeleton3D *p_skeleton, Collada::Node *p_node, int &r_bone, int p_parent) {
  87. if (p_node->type != Collada::Node::TYPE_JOINT) {
  88. return OK;
  89. }
  90. Collada::NodeJoint *joint = static_cast<Collada::NodeJoint *>(p_node);
  91. p_skeleton->add_bone(p_node->name);
  92. if (p_parent >= 0) {
  93. p_skeleton->set_bone_parent(r_bone, p_parent);
  94. }
  95. NodeMap nm;
  96. nm.node = p_skeleton;
  97. nm.bone = r_bone;
  98. node_map[p_node->id] = nm;
  99. node_name_map[p_node->name] = p_node->id;
  100. skeleton_bone_map[p_skeleton][joint->sid] = r_bone;
  101. {
  102. Transform3D xform = joint->compute_transform(collada);
  103. xform = collada.fix_transform(xform) * joint->post_transform;
  104. p_skeleton->set_bone_pose_position(r_bone, xform.origin);
  105. p_skeleton->set_bone_pose_rotation(r_bone, xform.basis.get_rotation_quaternion());
  106. p_skeleton->set_bone_pose_scale(r_bone, xform.basis.get_scale());
  107. }
  108. if (collada.state.bone_rest_map.has(joint->sid)) {
  109. p_skeleton->set_bone_rest(r_bone, collada.fix_transform(collada.state.bone_rest_map[joint->sid]));
  110. //should map this bone to something for animation?
  111. } else {
  112. WARN_PRINT("Collada: Joint has no rest.");
  113. }
  114. int id = r_bone++;
  115. for (int i = 0; i < p_node->children.size(); i++) {
  116. Error err = _populate_skeleton(p_skeleton, p_node->children[i], r_bone, id);
  117. if (err) {
  118. return err;
  119. }
  120. }
  121. return OK;
  122. }
  123. void ColladaImport::_pre_process_lights(Collada::Node *p_node) {
  124. if (p_node->type == Collada::Node::TYPE_LIGHT) {
  125. Collada::NodeLight *light = static_cast<Collada::NodeLight *>(p_node);
  126. if (collada.state.light_data_map.has(light->light)) {
  127. Collada::LightData &ld = collada.state.light_data_map[light->light];
  128. if (ld.mode == Collada::LightData::MODE_AMBIENT) {
  129. found_ambient = true;
  130. ambient = ld.color;
  131. }
  132. if (ld.mode == Collada::LightData::MODE_DIRECTIONAL) {
  133. found_directional = true;
  134. }
  135. }
  136. }
  137. for (int i = 0; i < p_node->children.size(); i++) {
  138. _pre_process_lights(p_node->children[i]);
  139. }
  140. }
  141. Error ColladaImport::_create_scene_skeletons(Collada::Node *p_node) {
  142. if (p_node->type == Collada::Node::TYPE_SKELETON) {
  143. Skeleton3D *sk = memnew(Skeleton3D);
  144. int bone = 0;
  145. for (int i = 0; i < p_node->children.size(); i++) {
  146. _populate_skeleton(sk, p_node->children[i], bone, -1);
  147. }
  148. sk->localize_rests(); //after creating skeleton, rests must be localized...!
  149. skeleton_map[p_node] = sk;
  150. }
  151. for (int i = 0; i < p_node->children.size(); i++) {
  152. Error err = _create_scene_skeletons(p_node->children[i]);
  153. if (err) {
  154. return err;
  155. }
  156. }
  157. return OK;
  158. }
  159. Error ColladaImport::_create_scene(Collada::Node *p_node, Node3D *p_parent) {
  160. Node3D *node = nullptr;
  161. switch (p_node->type) {
  162. case Collada::Node::TYPE_NODE: {
  163. node = memnew(Node3D);
  164. } break;
  165. case Collada::Node::TYPE_JOINT: {
  166. return OK; // do nothing
  167. } break;
  168. case Collada::Node::TYPE_LIGHT: {
  169. //node = memnew( Light)
  170. Collada::NodeLight *light = static_cast<Collada::NodeLight *>(p_node);
  171. if (collada.state.light_data_map.has(light->light)) {
  172. Collada::LightData &ld = collada.state.light_data_map[light->light];
  173. if (ld.mode == Collada::LightData::MODE_AMBIENT) {
  174. if (found_directional) {
  175. return OK; //do nothing not needed
  176. }
  177. if (!bool(GLOBAL_GET("collada/use_ambient"))) {
  178. return OK;
  179. }
  180. //well, it's an ambient light..
  181. Light3D *l = memnew(DirectionalLight3D);
  182. //l->set_color(Light::COLOR_AMBIENT,ld.color);
  183. //l->set_color(Light::COLOR_DIFFUSE,Color(0,0,0));
  184. //l->set_color(Light::COLOR_SPECULAR,Color(0,0,0));
  185. node = l;
  186. } else if (ld.mode == Collada::LightData::MODE_DIRECTIONAL) {
  187. //well, it's an ambient light..
  188. Light3D *l = memnew(DirectionalLight3D);
  189. /*
  190. if (found_ambient) //use it here
  191. l->set_color(Light::COLOR_AMBIENT,ambient);
  192. l->set_color(Light::COLOR_DIFFUSE,ld.color);
  193. l->set_color(Light::COLOR_SPECULAR,Color(1,1,1));
  194. */
  195. node = l;
  196. } else {
  197. Light3D *l;
  198. if (ld.mode == Collada::LightData::MODE_OMNI) {
  199. l = memnew(OmniLight3D);
  200. } else {
  201. l = memnew(SpotLight3D);
  202. //l->set_parameter(Light::PARAM_SPOT_ANGLE,ld.spot_angle);
  203. //l->set_parameter(Light::PARAM_SPOT_ATTENUATION,ld.spot_exp);
  204. }
  205. //
  206. //l->set_color(Light::COLOR_DIFFUSE,ld.color);
  207. //l->set_color(Light::COLOR_SPECULAR,Color(1,1,1));
  208. //l->approximate_opengl_attenuation(ld.constant_att,ld.linear_att,ld.quad_att);
  209. node = l;
  210. }
  211. } else {
  212. node = memnew(Node3D);
  213. }
  214. } break;
  215. case Collada::Node::TYPE_CAMERA: {
  216. Collada::NodeCamera *cam = static_cast<Collada::NodeCamera *>(p_node);
  217. Camera3D *camera = memnew(Camera3D);
  218. if (collada.state.camera_data_map.has(cam->camera)) {
  219. const Collada::CameraData &cd = collada.state.camera_data_map[cam->camera];
  220. switch (cd.mode) {
  221. case Collada::CameraData::MODE_ORTHOGONAL: {
  222. if (cd.orthogonal.y_mag) {
  223. camera->set_keep_aspect_mode(Camera3D::KEEP_HEIGHT);
  224. camera->set_orthogonal(cd.orthogonal.y_mag * 2.0, cd.z_near, cd.z_far);
  225. } else if (!cd.orthogonal.y_mag && cd.orthogonal.x_mag) {
  226. camera->set_keep_aspect_mode(Camera3D::KEEP_WIDTH);
  227. camera->set_orthogonal(cd.orthogonal.x_mag * 2.0, cd.z_near, cd.z_far);
  228. }
  229. } break;
  230. case Collada::CameraData::MODE_PERSPECTIVE: {
  231. if (cd.perspective.y_fov) {
  232. camera->set_perspective(cd.perspective.y_fov, cd.z_near, cd.z_far);
  233. } else if (!cd.perspective.y_fov && cd.perspective.x_fov) {
  234. camera->set_perspective(cd.perspective.x_fov / cd.aspect, cd.z_near, cd.z_far);
  235. }
  236. } break;
  237. }
  238. }
  239. node = camera;
  240. } break;
  241. case Collada::Node::TYPE_GEOMETRY: {
  242. Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
  243. if (collada.state.curve_data_map.has(ng->source)) {
  244. node = memnew(Path3D);
  245. } else {
  246. //mesh since nothing else
  247. node = memnew(ImporterMeshInstance3D);
  248. //Object::cast_to<ImporterMeshInstance3D>(node)->set_flag(GeometryInstance3D::FLAG_USE_BAKED_LIGHT, true);
  249. }
  250. } break;
  251. case Collada::Node::TYPE_SKELETON: {
  252. ERR_FAIL_COND_V(!skeleton_map.has(p_node), ERR_CANT_CREATE);
  253. Skeleton3D *sk = skeleton_map[p_node];
  254. node = sk;
  255. } break;
  256. }
  257. if (!p_node->name.is_empty()) {
  258. node->set_name(p_node->name);
  259. }
  260. NodeMap nm;
  261. nm.node = node;
  262. node_map[p_node->id] = nm;
  263. node_name_map[node->get_name()] = p_node->id;
  264. Transform3D xf = p_node->default_transform;
  265. xf = collada.fix_transform(xf) * p_node->post_transform;
  266. node->set_transform(xf);
  267. p_parent->add_child(node, true);
  268. node->set_owner(scene);
  269. if (!p_node->empty_draw_type.is_empty()) {
  270. node->set_meta("empty_draw_type", Variant(p_node->empty_draw_type));
  271. }
  272. for (int i = 0; i < p_node->children.size(); i++) {
  273. Error err = _create_scene(p_node->children[i], node);
  274. if (err) {
  275. return err;
  276. }
  277. }
  278. return OK;
  279. }
  280. Error ColladaImport::_create_material(const String &p_target) {
  281. ERR_FAIL_COND_V(material_cache.has(p_target), ERR_ALREADY_EXISTS);
  282. ERR_FAIL_COND_V(!collada.state.material_map.has(p_target), ERR_INVALID_PARAMETER);
  283. Collada::Material &src_mat = collada.state.material_map[p_target];
  284. ERR_FAIL_COND_V(!collada.state.effect_map.has(src_mat.instance_effect), ERR_INVALID_PARAMETER);
  285. Collada::Effect &effect = collada.state.effect_map[src_mat.instance_effect];
  286. Ref<StandardMaterial3D> material = memnew(StandardMaterial3D);
  287. String base_name;
  288. if (!src_mat.name.is_empty()) {
  289. base_name = src_mat.name;
  290. } else if (!effect.name.is_empty()) {
  291. base_name = effect.name;
  292. } else {
  293. base_name = "Material";
  294. }
  295. String name = base_name;
  296. int counter = 2;
  297. while (material_unique_names.has(name)) {
  298. name = base_name + itos(counter++);
  299. }
  300. material_unique_names.insert(name);
  301. material->set_name(name);
  302. // DIFFUSE
  303. if (!effect.diffuse.texture.is_empty()) {
  304. String texfile = effect.get_texture_path(effect.diffuse.texture, collada);
  305. if (!texfile.is_empty()) {
  306. if (texfile.begins_with("/")) {
  307. texfile = texfile.replace_first("/", "res://");
  308. }
  309. Ref<Texture2D> texture = ResourceLoader::load(texfile, "Texture2D");
  310. if (texture.is_valid()) {
  311. material->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, texture);
  312. material->set_albedo(Color(1, 1, 1, 1));
  313. //material->set_parameter(StandardMaterial3D::PARAM_DIFFUSE,Color(1,1,1,1));
  314. } else {
  315. missing_textures.push_back(texfile.get_file());
  316. }
  317. }
  318. } else {
  319. material->set_albedo(effect.diffuse.color);
  320. }
  321. // SPECULAR
  322. if (!effect.specular.texture.is_empty()) {
  323. String texfile = effect.get_texture_path(effect.specular.texture, collada);
  324. if (!texfile.is_empty()) {
  325. if (texfile.begins_with("/")) {
  326. texfile = texfile.replace_first("/", "res://");
  327. }
  328. Ref<Texture2D> texture = ResourceLoader::load(texfile, "Texture2D");
  329. if (texture.is_valid()) {
  330. material->set_texture(StandardMaterial3D::TEXTURE_METALLIC, texture);
  331. material->set_specular(1.0);
  332. //material->set_texture(StandardMaterial3D::PARAM_SPECULAR,texture);
  333. //material->set_parameter(StandardMaterial3D::PARAM_SPECULAR,Color(1,1,1,1));
  334. } else {
  335. missing_textures.push_back(texfile.get_file());
  336. }
  337. }
  338. } else {
  339. material->set_metallic(effect.specular.color.get_v());
  340. }
  341. // EMISSION
  342. if (!effect.emission.texture.is_empty()) {
  343. String texfile = effect.get_texture_path(effect.emission.texture, collada);
  344. if (!texfile.is_empty()) {
  345. if (texfile.begins_with("/")) {
  346. texfile = texfile.replace_first("/", "res://");
  347. }
  348. Ref<Texture2D> texture = ResourceLoader::load(texfile, "Texture2D");
  349. if (texture.is_valid()) {
  350. material->set_feature(StandardMaterial3D::FEATURE_EMISSION, true);
  351. material->set_texture(StandardMaterial3D::TEXTURE_EMISSION, texture);
  352. material->set_emission(Color(1, 1, 1, 1));
  353. //material->set_parameter(StandardMaterial3D::PARAM_EMISSION,Color(1,1,1,1));
  354. } else {
  355. missing_textures.push_back(texfile.get_file());
  356. }
  357. }
  358. } else {
  359. if (effect.emission.color != Color()) {
  360. material->set_feature(StandardMaterial3D::FEATURE_EMISSION, true);
  361. material->set_emission(effect.emission.color);
  362. }
  363. }
  364. // NORMAL
  365. if (!effect.bump.texture.is_empty()) {
  366. String texfile = effect.get_texture_path(effect.bump.texture, collada);
  367. if (!texfile.is_empty()) {
  368. if (texfile.begins_with("/")) {
  369. texfile = texfile.replace_first("/", "res://");
  370. }
  371. Ref<Texture2D> texture = ResourceLoader::load(texfile, "Texture2D");
  372. if (texture.is_valid()) {
  373. material->set_feature(StandardMaterial3D::FEATURE_NORMAL_MAPPING, true);
  374. material->set_texture(StandardMaterial3D::TEXTURE_NORMAL, texture);
  375. //material->set_emission(Color(1,1,1,1));
  376. //material->set_texture(StandardMaterial3D::PARAM_NORMAL,texture);
  377. } else {
  378. //missing_textures.push_back(texfile.get_file());
  379. }
  380. }
  381. }
  382. float roughness = (effect.shininess - 1.0) / 510;
  383. material->set_roughness(roughness);
  384. if (effect.double_sided) {
  385. material->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  386. }
  387. if (effect.unshaded) {
  388. material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  389. }
  390. material_cache[p_target] = material;
  391. return OK;
  392. }
  393. Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<ImporterMesh> &p_mesh, const HashMap<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform3D &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_controller, const Collada::MorphControllerData *p_morph_data, const Vector<Ref<ImporterMesh>> &p_morph_meshes, bool p_use_compression, bool p_use_mesh_material) {
  394. bool local_xform_mirror = p_local_xform.basis.determinant() < 0;
  395. if (p_morph_data) {
  396. //add morph target
  397. ERR_FAIL_COND_V(!p_morph_data->targets.has("MORPH_TARGET"), ERR_INVALID_DATA);
  398. String mt = p_morph_data->targets["MORPH_TARGET"];
  399. ERR_FAIL_COND_V(!p_morph_data->sources.has(mt), ERR_INVALID_DATA);
  400. int morph_targets = p_morph_data->sources[mt].sarray.size();
  401. for (int i = 0; i < morph_targets; i++) {
  402. String target = p_morph_data->sources[mt].sarray[i];
  403. ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(target), ERR_INVALID_DATA);
  404. String name = collada.state.mesh_data_map[target].name;
  405. p_mesh->add_blend_shape(name);
  406. }
  407. if (p_morph_data->mode == "RELATIVE") {
  408. p_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_RELATIVE);
  409. } else if (p_morph_data->mode == "NORMALIZED") {
  410. p_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  411. }
  412. }
  413. int surface = 0;
  414. for (int p_i = 0; p_i < meshdata.primitives.size(); p_i++) {
  415. const Collada::MeshData::Primitives &p = meshdata.primitives[p_i];
  416. /* VERTEX SOURCE */
  417. ERR_FAIL_COND_V(!p.sources.has("VERTEX"), ERR_INVALID_DATA);
  418. String vertex_src_id = p.sources["VERTEX"].source;
  419. int vertex_ofs = p.sources["VERTEX"].offset;
  420. ERR_FAIL_COND_V(!meshdata.vertices.has(vertex_src_id), ERR_INVALID_DATA);
  421. ERR_FAIL_COND_V(!meshdata.vertices[vertex_src_id].sources.has("POSITION"), ERR_INVALID_DATA);
  422. String position_src_id = meshdata.vertices[vertex_src_id].sources["POSITION"];
  423. ERR_FAIL_COND_V(!meshdata.sources.has(position_src_id), ERR_INVALID_DATA);
  424. const Collada::MeshData::Source *vertex_src = &meshdata.sources[position_src_id];
  425. /* NORMAL SOURCE */
  426. const Collada::MeshData::Source *normal_src = nullptr;
  427. int normal_ofs = 0;
  428. {
  429. String normal_source_id = "";
  430. if (p.sources.has("NORMAL")) {
  431. normal_source_id = p.sources["NORMAL"].source;
  432. normal_ofs = p.sources["NORMAL"].offset;
  433. } else if (meshdata.vertices[vertex_src_id].sources.has("NORMAL")) {
  434. normal_source_id = meshdata.vertices[vertex_src_id].sources["NORMAL"];
  435. normal_ofs = vertex_ofs;
  436. }
  437. if (!normal_source_id.is_empty()) {
  438. ERR_FAIL_COND_V(!meshdata.sources.has(normal_source_id), ERR_INVALID_DATA);
  439. normal_src = &meshdata.sources[normal_source_id];
  440. }
  441. }
  442. const Collada::MeshData::Source *binormal_src = nullptr;
  443. int binormal_ofs = 0;
  444. {
  445. String binormal_source_id = "";
  446. if (p.sources.has("TEXBINORMAL")) {
  447. binormal_source_id = p.sources["TEXBINORMAL"].source;
  448. binormal_ofs = p.sources["TEXBINORMAL"].offset;
  449. } else if (meshdata.vertices[vertex_src_id].sources.has("TEXBINORMAL")) {
  450. binormal_source_id = meshdata.vertices[vertex_src_id].sources["TEXBINORMAL"];
  451. binormal_ofs = vertex_ofs;
  452. }
  453. if (!binormal_source_id.is_empty()) {
  454. ERR_FAIL_COND_V(!meshdata.sources.has(binormal_source_id), ERR_INVALID_DATA);
  455. binormal_src = &meshdata.sources[binormal_source_id];
  456. }
  457. }
  458. const Collada::MeshData::Source *tangent_src = nullptr;
  459. int tangent_ofs = 0;
  460. {
  461. String tangent_source_id = "";
  462. if (p.sources.has("TEXTANGENT")) {
  463. tangent_source_id = p.sources["TEXTANGENT"].source;
  464. tangent_ofs = p.sources["TEXTANGENT"].offset;
  465. } else if (meshdata.vertices[vertex_src_id].sources.has("TEXTANGENT")) {
  466. tangent_source_id = meshdata.vertices[vertex_src_id].sources["TEXTANGENT"];
  467. tangent_ofs = vertex_ofs;
  468. }
  469. if (!tangent_source_id.is_empty()) {
  470. ERR_FAIL_COND_V(!meshdata.sources.has(tangent_source_id), ERR_INVALID_DATA);
  471. tangent_src = &meshdata.sources[tangent_source_id];
  472. }
  473. }
  474. const Collada::MeshData::Source *uv_src = nullptr;
  475. int uv_ofs = 0;
  476. {
  477. String uv_source_id = "";
  478. if (p.sources.has("TEXCOORD0")) {
  479. uv_source_id = p.sources["TEXCOORD0"].source;
  480. uv_ofs = p.sources["TEXCOORD0"].offset;
  481. } else if (meshdata.vertices[vertex_src_id].sources.has("TEXCOORD0")) {
  482. uv_source_id = meshdata.vertices[vertex_src_id].sources["TEXCOORD0"];
  483. uv_ofs = vertex_ofs;
  484. }
  485. if (!uv_source_id.is_empty()) {
  486. ERR_FAIL_COND_V(!meshdata.sources.has(uv_source_id), ERR_INVALID_DATA);
  487. uv_src = &meshdata.sources[uv_source_id];
  488. }
  489. }
  490. const Collada::MeshData::Source *uv2_src = nullptr;
  491. int uv2_ofs = 0;
  492. {
  493. String uv2_source_id = "";
  494. if (p.sources.has("TEXCOORD1")) {
  495. uv2_source_id = p.sources["TEXCOORD1"].source;
  496. uv2_ofs = p.sources["TEXCOORD1"].offset;
  497. } else if (meshdata.vertices[vertex_src_id].sources.has("TEXCOORD1")) {
  498. uv2_source_id = meshdata.vertices[vertex_src_id].sources["TEXCOORD1"];
  499. uv2_ofs = vertex_ofs;
  500. }
  501. if (!uv2_source_id.is_empty()) {
  502. ERR_FAIL_COND_V(!meshdata.sources.has(uv2_source_id), ERR_INVALID_DATA);
  503. uv2_src = &meshdata.sources[uv2_source_id];
  504. }
  505. }
  506. const Collada::MeshData::Source *color_src = nullptr;
  507. int color_ofs = 0;
  508. {
  509. String color_source_id = "";
  510. if (p.sources.has("COLOR")) {
  511. color_source_id = p.sources["COLOR"].source;
  512. color_ofs = p.sources["COLOR"].offset;
  513. } else if (meshdata.vertices[vertex_src_id].sources.has("COLOR")) {
  514. color_source_id = meshdata.vertices[vertex_src_id].sources["COLOR"];
  515. color_ofs = vertex_ofs;
  516. }
  517. if (!color_source_id.is_empty()) {
  518. ERR_FAIL_COND_V(!meshdata.sources.has(color_source_id), ERR_INVALID_DATA);
  519. color_src = &meshdata.sources[color_source_id];
  520. }
  521. }
  522. //find largest source..
  523. /************************/
  524. /* ADD WEIGHTS IF EXIST */
  525. /************************/
  526. HashMap<int, Vector<Collada::Vertex::Weight>> pre_weights;
  527. bool has_weights = false;
  528. if (p_skin_controller) {
  529. const Collada::SkinControllerData::Source *weight_src = nullptr;
  530. int weight_ofs = 0;
  531. if (p_skin_controller->weights.sources.has("WEIGHT")) {
  532. String weight_id = p_skin_controller->weights.sources["WEIGHT"].source;
  533. weight_ofs = p_skin_controller->weights.sources["WEIGHT"].offset;
  534. if (p_skin_controller->sources.has(weight_id)) {
  535. weight_src = &p_skin_controller->sources[weight_id];
  536. }
  537. }
  538. int joint_ofs = 0;
  539. if (p_skin_controller->weights.sources.has("JOINT")) {
  540. joint_ofs = p_skin_controller->weights.sources["JOINT"].offset;
  541. }
  542. //should be OK, given this was pre-checked.
  543. int index_ofs = 0;
  544. int wstride = p_skin_controller->weights.sources.size();
  545. for (int w_i = 0; w_i < p_skin_controller->weights.sets.size(); w_i++) {
  546. int amount = p_skin_controller->weights.sets[w_i];
  547. Vector<Collada::Vertex::Weight> weights;
  548. for (int a_i = 0; a_i < amount; a_i++) {
  549. Collada::Vertex::Weight w;
  550. int read_from = index_ofs + a_i * wstride;
  551. ERR_FAIL_INDEX_V(read_from + wstride - 1, p_skin_controller->weights.indices.size(), ERR_INVALID_DATA);
  552. int weight_index = p_skin_controller->weights.indices[read_from + weight_ofs];
  553. ERR_FAIL_INDEX_V(weight_index, weight_src->array.size(), ERR_INVALID_DATA);
  554. w.weight = weight_src->array[weight_index];
  555. int bone_index = p_skin_controller->weights.indices[read_from + joint_ofs];
  556. if (bone_index == -1) {
  557. continue; //ignore this weight (refers to bind shape)
  558. }
  559. ERR_FAIL_INDEX_V(bone_index, bone_remap.size(), ERR_INVALID_DATA);
  560. w.bone_idx = bone_remap[bone_index];
  561. weights.push_back(w);
  562. }
  563. /* FIX WEIGHTS */
  564. weights.sort();
  565. if (weights.size() > 4) {
  566. //cap to 4 and make weights add up 1
  567. weights.resize(4);
  568. }
  569. //make sure weights always add up to 1
  570. float total = 0;
  571. for (int i = 0; i < weights.size(); i++) {
  572. total += weights[i].weight;
  573. }
  574. if (total) {
  575. for (int i = 0; i < weights.size(); i++) {
  576. weights.write[i].weight /= total;
  577. }
  578. }
  579. if (weights.size() == 0 || total == 0) { //if nothing, add a weight to bone 0
  580. //no weights assigned
  581. Collada::Vertex::Weight w;
  582. w.bone_idx = 0;
  583. w.weight = 1.0;
  584. weights.clear();
  585. weights.push_back(w);
  586. }
  587. pre_weights[w_i] = weights;
  588. index_ofs += wstride * amount;
  589. }
  590. //vertices need to be localized
  591. has_weights = true;
  592. }
  593. RBSet<Collada::Vertex> vertex_set; //vertex set will be the vertices
  594. List<int> indices_list; //indices will be the indices
  595. /**************************/
  596. /* CREATE PRIMITIVE ARRAY */
  597. /**************************/
  598. // The way collada uses indices is more optimal, and friendlier with 3D modeling software,
  599. // because it can index everything, not only vertices (similar to how the WII works).
  600. // This is, however, more incompatible with standard video cards, so arrays must be converted.
  601. // Must convert to GL/DX format.
  602. int _prim_ofs = 0;
  603. int vertidx = 0;
  604. for (int p_j = 0; p_j < p.count; p_j++) {
  605. int amount;
  606. if (p.polygons.size()) {
  607. ERR_FAIL_INDEX_V(p_j, p.polygons.size(), ERR_INVALID_DATA);
  608. amount = p.polygons[p_j];
  609. } else {
  610. amount = 3; //triangles;
  611. }
  612. //COLLADA_PRINT("amount: "+itos(amount));
  613. int prev2[2] = { 0, 0 };
  614. for (int j = 0; j < amount; j++) {
  615. int src = _prim_ofs;
  616. //_prim_ofs+=p.sources.size()
  617. ERR_FAIL_INDEX_V(src, p.indices.size(), ERR_INVALID_DATA);
  618. Collada::Vertex vertex;
  619. if (!p_optimize) {
  620. vertex.uid = vertidx++;
  621. }
  622. int vertex_index = p.indices[src + vertex_ofs]; //used for index field (later used by controllers)
  623. int vertex_pos = (vertex_src->stride ? vertex_src->stride : 3) * vertex_index;
  624. ERR_FAIL_INDEX_V(vertex_pos + 0, vertex_src->array.size(), ERR_INVALID_DATA);
  625. ERR_FAIL_INDEX_V(vertex_pos + 2, vertex_src->array.size(), ERR_INVALID_DATA);
  626. vertex.vertex = Vector3(vertex_src->array[vertex_pos + 0], vertex_src->array[vertex_pos + 1], vertex_src->array[vertex_pos + 2]);
  627. if (pre_weights.has(vertex_index)) {
  628. vertex.weights = pre_weights[vertex_index];
  629. }
  630. if (normal_src) {
  631. int normal_pos = (normal_src->stride ? normal_src->stride : 3) * p.indices[src + normal_ofs];
  632. ERR_FAIL_INDEX_V(normal_pos + 0, normal_src->array.size(), ERR_INVALID_DATA);
  633. ERR_FAIL_INDEX_V(normal_pos + 2, normal_src->array.size(), ERR_INVALID_DATA);
  634. vertex.normal = Vector3(normal_src->array[normal_pos + 0], normal_src->array[normal_pos + 1], normal_src->array[normal_pos + 2]);
  635. if (tangent_src && binormal_src) {
  636. int binormal_pos = (binormal_src->stride ? binormal_src->stride : 3) * p.indices[src + binormal_ofs];
  637. ERR_FAIL_INDEX_V(binormal_pos + 0, binormal_src->array.size(), ERR_INVALID_DATA);
  638. ERR_FAIL_INDEX_V(binormal_pos + 2, binormal_src->array.size(), ERR_INVALID_DATA);
  639. Vector3 binormal = Vector3(binormal_src->array[binormal_pos + 0], binormal_src->array[binormal_pos + 1], binormal_src->array[binormal_pos + 2]);
  640. int tangent_pos = (tangent_src->stride ? tangent_src->stride : 3) * p.indices[src + tangent_ofs];
  641. ERR_FAIL_INDEX_V(tangent_pos + 0, tangent_src->array.size(), ERR_INVALID_DATA);
  642. ERR_FAIL_INDEX_V(tangent_pos + 2, tangent_src->array.size(), ERR_INVALID_DATA);
  643. Vector3 tangent = Vector3(tangent_src->array[tangent_pos + 0], tangent_src->array[tangent_pos + 1], tangent_src->array[tangent_pos + 2]);
  644. vertex.tangent.normal = tangent;
  645. vertex.tangent.d = vertex.normal.cross(tangent).dot(binormal) > 0 ? 1 : -1;
  646. }
  647. }
  648. if (uv_src) {
  649. int uv_pos = (uv_src->stride ? uv_src->stride : 2) * p.indices[src + uv_ofs];
  650. ERR_FAIL_INDEX_V(uv_pos + 0, uv_src->array.size(), ERR_INVALID_DATA);
  651. ERR_FAIL_INDEX_V(uv_pos + 1, uv_src->array.size(), ERR_INVALID_DATA);
  652. vertex.uv = Vector3(uv_src->array[uv_pos + 0], 1.0 - uv_src->array[uv_pos + 1], 0);
  653. }
  654. if (uv2_src) {
  655. int uv2_pos = (uv2_src->stride ? uv2_src->stride : 2) * p.indices[src + uv2_ofs];
  656. ERR_FAIL_INDEX_V(uv2_pos + 0, uv2_src->array.size(), ERR_INVALID_DATA);
  657. ERR_FAIL_INDEX_V(uv2_pos + 1, uv2_src->array.size(), ERR_INVALID_DATA);
  658. vertex.uv2 = Vector3(uv2_src->array[uv2_pos + 0], 1.0 - uv2_src->array[uv2_pos + 1], 0);
  659. }
  660. if (color_src) {
  661. int color_pos = (color_src->stride ? color_src->stride : 3) * p.indices[src + color_ofs]; // colors are RGB in collada..
  662. ERR_FAIL_INDEX_V(color_pos + 0, color_src->array.size(), ERR_INVALID_DATA);
  663. ERR_FAIL_INDEX_V(color_pos + ((color_src->stride > 3) ? 3 : 2), color_src->array.size(), ERR_INVALID_DATA);
  664. vertex.color = Color(color_src->array[color_pos + 0], color_src->array[color_pos + 1], color_src->array[color_pos + 2], (color_src->stride > 3) ? color_src->array[color_pos + 3] : 1.0);
  665. }
  666. #ifndef NO_UP_AXIS_SWAP
  667. if (collada.state.up_axis == Vector3::AXIS_Z) {
  668. Vector3 bn = vertex.normal.cross(vertex.tangent.normal) * vertex.tangent.d;
  669. SWAP(vertex.vertex.z, vertex.vertex.y);
  670. vertex.vertex.z = -vertex.vertex.z;
  671. SWAP(vertex.normal.z, vertex.normal.y);
  672. vertex.normal.z = -vertex.normal.z;
  673. SWAP(vertex.tangent.normal.z, vertex.tangent.normal.y);
  674. vertex.tangent.normal.z = -vertex.tangent.normal.z;
  675. SWAP(bn.z, bn.y);
  676. bn.z = -bn.z;
  677. vertex.tangent.d = vertex.normal.cross(vertex.tangent.normal).dot(bn) > 0 ? 1 : -1;
  678. }
  679. #endif
  680. vertex.fix_unit_scale(collada);
  681. int index = 0;
  682. //COLLADA_PRINT("vertex: "+vertex.vertex);
  683. if (vertex_set.has(vertex)) {
  684. index = vertex_set.find(vertex)->get().idx;
  685. } else {
  686. index = vertex_set.size();
  687. vertex.idx = index;
  688. vertex_set.insert(vertex);
  689. }
  690. //build triangles if needed
  691. if (j == 0) {
  692. prev2[0] = index;
  693. }
  694. if (j >= 2) {
  695. //insert indices in reverse order (collada uses CCW as frontface)
  696. if (local_xform_mirror) {
  697. indices_list.push_back(prev2[0]);
  698. indices_list.push_back(prev2[1]);
  699. indices_list.push_back(index);
  700. } else {
  701. indices_list.push_back(prev2[0]);
  702. indices_list.push_back(index);
  703. indices_list.push_back(prev2[1]);
  704. }
  705. }
  706. prev2[1] = index;
  707. _prim_ofs += p.vertex_size;
  708. }
  709. }
  710. Vector<Collada::Vertex> vertex_array; //there we go, vertex array
  711. vertex_array.resize(vertex_set.size());
  712. for (const Collada::Vertex &F : vertex_set) {
  713. vertex_array.write[F.idx] = F;
  714. }
  715. if (has_weights) {
  716. //if skeleton, localize
  717. Transform3D local_xform = p_local_xform;
  718. for (int i = 0; i < vertex_array.size(); i++) {
  719. vertex_array.write[i].vertex = local_xform.xform(vertex_array[i].vertex);
  720. vertex_array.write[i].normal = local_xform.basis.xform(vertex_array[i].normal).normalized();
  721. vertex_array.write[i].tangent.normal = local_xform.basis.xform(vertex_array[i].tangent.normal).normalized();
  722. if (local_xform_mirror) {
  723. //i shouldn't do this? wtf?
  724. //vertex_array[i].normal*=-1.0;
  725. //vertex_array[i].tangent.normal*=-1.0;
  726. }
  727. }
  728. }
  729. /*****************/
  730. /* MAKE SURFACES */
  731. /*****************/
  732. {
  733. Ref<StandardMaterial3D> material;
  734. {
  735. if (p_material_map.has(p.material)) {
  736. String target = p_material_map[p.material].target;
  737. if (!material_cache.has(target)) {
  738. Error err = _create_material(target);
  739. if (!err) {
  740. material = material_cache[target];
  741. }
  742. } else {
  743. material = material_cache[target];
  744. }
  745. } else if (!p.material.is_empty()) {
  746. WARN_PRINT("Collada: Unreferenced material in geometry instance: " + p.material);
  747. }
  748. }
  749. uint64_t mesh_flags = 0;
  750. if (p_use_compression) {
  751. mesh_flags = RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  752. }
  753. // We can't generate tangents without UVs, so create dummy tangents.
  754. bool generate_dummy_tangents = (!binormal_src || !tangent_src) && !uv_src && force_make_tangents;
  755. Ref<SurfaceTool> surftool;
  756. surftool.instantiate();
  757. surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
  758. for (int k = 0; k < vertex_array.size(); k++) {
  759. if (normal_src) {
  760. surftool->set_normal(vertex_array[k].normal);
  761. if (binormal_src && tangent_src) {
  762. surftool->set_tangent(vertex_array[k].tangent);
  763. } else if (generate_dummy_tangents) {
  764. Vector3 tan = Vector3(vertex_array[k].normal.z, -vertex_array[k].normal.x, vertex_array[k].normal.y).cross(vertex_array[k].normal.normalized()).normalized();
  765. surftool->set_tangent(Plane(tan.x, tan.y, tan.z, 1.0));
  766. }
  767. } else {
  768. // No normals, use a dummy tangent since normals will be generated.
  769. if (generate_dummy_tangents) {
  770. surftool->set_tangent(Plane(1.0, 0.0, 0.0, 1.0));
  771. }
  772. }
  773. if (uv_src) {
  774. surftool->set_uv(Vector2(vertex_array[k].uv.x, vertex_array[k].uv.y));
  775. }
  776. if (uv2_src) {
  777. surftool->set_uv2(Vector2(vertex_array[k].uv2.x, vertex_array[k].uv2.y));
  778. }
  779. if (color_src) {
  780. surftool->set_color(vertex_array[k].color);
  781. }
  782. if (has_weights) {
  783. Vector<float> weights;
  784. Vector<int> bones;
  785. weights.resize(RS::ARRAY_WEIGHTS_SIZE);
  786. bones.resize(RS::ARRAY_WEIGHTS_SIZE);
  787. //float sum=0.0;
  788. for (int l = 0; l < RS::ARRAY_WEIGHTS_SIZE; l++) {
  789. if (l < vertex_array[k].weights.size()) {
  790. weights.write[l] = vertex_array[k].weights[l].weight;
  791. bones.write[l] = vertex_array[k].weights[l].bone_idx;
  792. //sum += vertex_array[k].weights[l].weight;
  793. } else {
  794. weights.write[l] = 0;
  795. bones.write[l] = 0;
  796. }
  797. }
  798. surftool->set_bones(bones);
  799. surftool->set_weights(weights);
  800. }
  801. surftool->add_vertex(vertex_array[k].vertex);
  802. }
  803. for (int &E : indices_list) {
  804. surftool->add_index(E);
  805. }
  806. if (!normal_src) {
  807. // Should always have normals.
  808. surftool->generate_normals();
  809. }
  810. bool generate_tangents = (!binormal_src || !tangent_src) && uv_src && force_make_tangents;
  811. if (generate_tangents) {
  812. surftool->generate_tangents();
  813. }
  814. // Disable compression if all z equals 0 (the mesh is 2D).
  815. bool is_mesh_2d = true;
  816. for (int k = 0; k < vertex_array.size(); k++) {
  817. if (!Math::is_zero_approx(vertex_array[k].vertex.z)) {
  818. is_mesh_2d = false;
  819. break;
  820. }
  821. };
  822. if (p_mesh->get_blend_shape_count() != 0 || p_skin_controller || is_mesh_2d) {
  823. // Can't compress if attributes missing or if using vertex weights.
  824. mesh_flags &= ~RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  825. }
  826. ////////////////////////////
  827. // FINALLY CREATE SUFRACE //
  828. ////////////////////////////
  829. Array d = surftool->commit_to_arrays();
  830. d.resize(RS::ARRAY_MAX);
  831. if (mesh_flags & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES && (generate_dummy_tangents || generate_tangents)) {
  832. // Compression is enabled, so let's validate that the normals and tangents are correct.
  833. Vector<Vector3> normals = d[Mesh::ARRAY_NORMAL];
  834. Vector<float> tangents = d[Mesh::ARRAY_TANGENT];
  835. for (int vert = 0; vert < normals.size(); vert++) {
  836. Vector3 tan = Vector3(tangents[vert * 4 + 0], tangents[vert * 4 + 1], tangents[vert * 4 + 2]);
  837. if (abs(tan.dot(normals[vert])) > 0.0001) {
  838. // Tangent is not perpendicular to the normal, so we can't use compression.
  839. mesh_flags &= ~RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  840. }
  841. }
  842. }
  843. Array mr;
  844. ////////////////////////////
  845. // THEN THE MORPH TARGETS //
  846. ////////////////////////////
  847. for (int mi = 0; mi < p_morph_meshes.size(); mi++) {
  848. Array a = p_morph_meshes[mi]->get_surface_arrays(surface);
  849. //add valid weight and bone arrays if they exist, TODO check if they are unique to shape (generally not)
  850. // Enforce blend shape mask array format
  851. for (int mj = 0; mj < Mesh::ARRAY_MAX; mj++) {
  852. if (!(Mesh::ARRAY_FORMAT_BLEND_SHAPE_MASK & (1ULL << mj))) {
  853. a[mj] = Variant();
  854. }
  855. }
  856. mr.push_back(a);
  857. }
  858. String surface_name;
  859. Ref<Material> mat;
  860. if (material.is_valid()) {
  861. if (p_use_mesh_material) {
  862. mat = material;
  863. }
  864. surface_name = material->get_name();
  865. }
  866. p_mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES, d, mr, Dictionary(), mat, surface_name, mesh_flags);
  867. }
  868. /*****************/
  869. /* FIND MATERIAL */
  870. /*****************/
  871. surface++;
  872. }
  873. return OK;
  874. }
  875. Error ColladaImport::_create_resources(Collada::Node *p_node, bool p_use_compression) {
  876. if (p_node->type == Collada::Node::TYPE_GEOMETRY && node_map.has(p_node->id)) {
  877. Node3D *node = node_map[p_node->id].node;
  878. Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
  879. if (Object::cast_to<Path3D>(node)) {
  880. Path3D *path = Object::cast_to<Path3D>(node);
  881. if (curve_cache.has(ng->source)) {
  882. path->set_curve(curve_cache[ng->source]);
  883. } else {
  884. Ref<Curve3D> c = memnew(Curve3D);
  885. const Collada::CurveData &cd = collada.state.curve_data_map[ng->source];
  886. ERR_FAIL_COND_V(!cd.control_vertices.has("POSITION"), ERR_INVALID_DATA);
  887. ERR_FAIL_COND_V(!cd.control_vertices.has("IN_TANGENT"), ERR_INVALID_DATA);
  888. ERR_FAIL_COND_V(!cd.control_vertices.has("OUT_TANGENT"), ERR_INVALID_DATA);
  889. ERR_FAIL_COND_V(!cd.control_vertices.has("INTERPOLATION"), ERR_INVALID_DATA);
  890. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["POSITION"]), ERR_INVALID_DATA);
  891. const Collada::CurveData::Source &vertices = cd.sources[cd.control_vertices["POSITION"]];
  892. ERR_FAIL_COND_V(vertices.stride != 3, ERR_INVALID_DATA);
  893. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["IN_TANGENT"]), ERR_INVALID_DATA);
  894. const Collada::CurveData::Source &in_tangents = cd.sources[cd.control_vertices["IN_TANGENT"]];
  895. ERR_FAIL_COND_V(in_tangents.stride != 3, ERR_INVALID_DATA);
  896. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["OUT_TANGENT"]), ERR_INVALID_DATA);
  897. const Collada::CurveData::Source &out_tangents = cd.sources[cd.control_vertices["OUT_TANGENT"]];
  898. ERR_FAIL_COND_V(out_tangents.stride != 3, ERR_INVALID_DATA);
  899. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["INTERPOLATION"]), ERR_INVALID_DATA);
  900. const Collada::CurveData::Source &interps = cd.sources[cd.control_vertices["INTERPOLATION"]];
  901. ERR_FAIL_COND_V(interps.stride != 1, ERR_INVALID_DATA);
  902. const Collada::CurveData::Source *tilts = nullptr;
  903. if (cd.control_vertices.has("TILT") && cd.sources.has(cd.control_vertices["TILT"])) {
  904. tilts = &cd.sources[cd.control_vertices["TILT"]];
  905. }
  906. int pc = vertices.array.size() / 3;
  907. for (int i = 0; i < pc; i++) {
  908. Vector3 pos(vertices.array[i * 3 + 0], vertices.array[i * 3 + 1], vertices.array[i * 3 + 2]);
  909. Vector3 in(in_tangents.array[i * 3 + 0], in_tangents.array[i * 3 + 1], in_tangents.array[i * 3 + 2]);
  910. Vector3 out(out_tangents.array[i * 3 + 0], out_tangents.array[i * 3 + 1], out_tangents.array[i * 3 + 2]);
  911. #ifndef NO_UP_AXIS_SWAP
  912. if (collada.state.up_axis == Vector3::AXIS_Z) {
  913. SWAP(pos.y, pos.z);
  914. pos.z = -pos.z;
  915. SWAP(in.y, in.z);
  916. in.z = -in.z;
  917. SWAP(out.y, out.z);
  918. out.z = -out.z;
  919. }
  920. #endif
  921. pos *= collada.state.unit_scale;
  922. in *= collada.state.unit_scale;
  923. out *= collada.state.unit_scale;
  924. c->add_point(pos, in - pos, out - pos);
  925. if (tilts) {
  926. c->set_point_tilt(i, tilts->array[i]);
  927. }
  928. }
  929. if (cd.closed && pc > 1) {
  930. Vector3 pos = c->get_point_position(0);
  931. Vector3 in = c->get_point_in(0);
  932. Vector3 out = c->get_point_out(0);
  933. c->add_point(pos, in, out, -1);
  934. }
  935. curve_cache[ng->source] = c;
  936. path->set_curve(c);
  937. }
  938. }
  939. if (Object::cast_to<ImporterMeshInstance3D>(node)) {
  940. Collada::NodeGeometry *ng2 = static_cast<Collada::NodeGeometry *>(p_node);
  941. ImporterMeshInstance3D *mi = Object::cast_to<ImporterMeshInstance3D>(node);
  942. ERR_FAIL_NULL_V(mi, ERR_BUG);
  943. Collada::SkinControllerData *skin = nullptr;
  944. Collada::MorphControllerData *morph = nullptr;
  945. String meshid;
  946. Transform3D apply_xform;
  947. Vector<int> bone_remap;
  948. Vector<Ref<ImporterMesh>> morphs;
  949. if (ng2->controller) {
  950. String ngsource = ng2->source;
  951. if (collada.state.skin_controller_data_map.has(ngsource)) {
  952. ERR_FAIL_COND_V(!collada.state.skin_controller_data_map.has(ngsource), ERR_INVALID_DATA);
  953. skin = &collada.state.skin_controller_data_map[ngsource];
  954. Vector<String> skeletons = ng2->skeletons;
  955. ERR_FAIL_COND_V(skeletons.is_empty(), ERR_INVALID_DATA);
  956. const String &skname = skeletons[0];
  957. ERR_FAIL_COND_V(!node_map.has(skname), ERR_INVALID_DATA);
  958. NodeMap nmsk = node_map[skname];
  959. Skeleton3D *sk = Object::cast_to<Skeleton3D>(nmsk.node);
  960. ERR_FAIL_NULL_V(sk, ERR_INVALID_DATA);
  961. ERR_FAIL_COND_V(!skeleton_bone_map.has(sk), ERR_INVALID_DATA);
  962. HashMap<String, int> &bone_remap_map = skeleton_bone_map[sk];
  963. meshid = skin->base;
  964. if (collada.state.morph_controller_data_map.has(meshid)) {
  965. //it's a morph!!
  966. morph = &collada.state.morph_controller_data_map[meshid];
  967. ngsource = meshid;
  968. meshid = morph->mesh;
  969. } else {
  970. ngsource = "";
  971. }
  972. if (apply_mesh_xform_to_vertices) {
  973. apply_xform = collada.fix_transform(p_node->default_transform);
  974. node->set_transform(Transform3D());
  975. } else {
  976. apply_xform = Transform3D();
  977. }
  978. ERR_FAIL_COND_V(!skin->weights.sources.has("JOINT"), ERR_INVALID_DATA);
  979. String joint_id = skin->weights.sources["JOINT"].source;
  980. ERR_FAIL_COND_V(!skin->sources.has(joint_id), ERR_INVALID_DATA);
  981. Collada::SkinControllerData::Source *joint_src = &skin->sources[joint_id];
  982. bone_remap.resize(joint_src->sarray.size());
  983. for (int i = 0; i < bone_remap.size(); i++) {
  984. String str = joint_src->sarray[i];
  985. ERR_FAIL_COND_V(!bone_remap_map.has(str), ERR_INVALID_DATA);
  986. bone_remap.write[i] = bone_remap_map[str];
  987. }
  988. }
  989. if (collada.state.morph_controller_data_map.has(ngsource)) {
  990. //it's a morph!!
  991. morph = &collada.state.morph_controller_data_map[ngsource];
  992. meshid = morph->mesh;
  993. if (morph->targets.has("MORPH_TARGET")) {
  994. String target = morph->targets["MORPH_TARGET"];
  995. bool valid = false;
  996. if (morph->sources.has(target)) {
  997. valid = true;
  998. Vector<String> names = morph->sources[target].sarray;
  999. for (int i = 0; i < names.size(); i++) {
  1000. const String &meshid2 = names[i];
  1001. if (collada.state.mesh_data_map.has(meshid2)) {
  1002. Ref<ImporterMesh> mesh = Ref<ImporterMesh>(memnew(ImporterMesh));
  1003. const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid2];
  1004. mesh->set_name(meshdata.name);
  1005. Error err = _create_mesh_surfaces(false, mesh, ng2->material_map, meshdata, apply_xform, bone_remap, skin, nullptr, Vector<Ref<ImporterMesh>>(), false);
  1006. ERR_FAIL_COND_V(err, err);
  1007. morphs.push_back(mesh);
  1008. } else {
  1009. valid = false;
  1010. }
  1011. }
  1012. }
  1013. if (!valid) {
  1014. morphs.clear();
  1015. }
  1016. ngsource = "";
  1017. }
  1018. }
  1019. ERR_FAIL_COND_V_MSG(!ngsource.is_empty(), ERR_INVALID_DATA, "Controller instance source '" + ngsource + "' is neither skin or morph!");
  1020. } else {
  1021. meshid = ng2->source;
  1022. }
  1023. Ref<ImporterMesh> mesh;
  1024. if (mesh_cache.has(meshid)) {
  1025. mesh = mesh_cache[meshid];
  1026. } else {
  1027. if (collada.state.mesh_data_map.has(meshid)) {
  1028. //bleh, must ignore invalid
  1029. ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(meshid), ERR_INVALID_DATA);
  1030. mesh.instantiate();
  1031. const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid];
  1032. String name = meshdata.name;
  1033. if (name.is_empty()) {
  1034. name = "Mesh";
  1035. }
  1036. int counter = 2;
  1037. while (mesh_unique_names.has(name)) {
  1038. name = meshdata.name;
  1039. if (name.is_empty()) {
  1040. name = "Mesh";
  1041. }
  1042. name += itos(counter++);
  1043. }
  1044. mesh_unique_names.insert(name);
  1045. mesh->set_name(name);
  1046. Error err = _create_mesh_surfaces(morphs.size() == 0, mesh, ng2->material_map, meshdata, apply_xform, bone_remap, skin, morph, morphs, p_use_compression, use_mesh_builtin_materials);
  1047. ERR_FAIL_COND_V_MSG(err, err, "Cannot create mesh surface.");
  1048. mesh_cache[meshid] = mesh;
  1049. } else {
  1050. WARN_PRINT("Collada: Will not import geometry: " + meshid);
  1051. }
  1052. }
  1053. if (mesh.is_valid()) {
  1054. mi->set_mesh(mesh);
  1055. if (!use_mesh_builtin_materials) {
  1056. const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid];
  1057. for (int i = 0; i < meshdata.primitives.size(); i++) {
  1058. String matname = meshdata.primitives[i].material;
  1059. if (ng2->material_map.has(matname)) {
  1060. String target = ng2->material_map[matname].target;
  1061. Ref<Material> material;
  1062. if (!material_cache.has(target)) {
  1063. Error err = _create_material(target);
  1064. if (!err) {
  1065. material = material_cache[target];
  1066. }
  1067. } else {
  1068. material = material_cache[target];
  1069. }
  1070. mi->set_surface_material(i, material);
  1071. } else if (!matname.is_empty()) {
  1072. WARN_PRINT("Collada: Unreferenced material in geometry instance: " + matname);
  1073. }
  1074. }
  1075. }
  1076. }
  1077. }
  1078. }
  1079. for (int i = 0; i < p_node->children.size(); i++) {
  1080. Error err = _create_resources(p_node->children[i], p_use_compression);
  1081. if (err) {
  1082. return err;
  1083. }
  1084. }
  1085. return OK;
  1086. }
  1087. Error ColladaImport::load(const String &p_path, int p_flags, bool p_force_make_tangents, bool p_use_compression) {
  1088. Error err = collada.load(p_path, p_flags);
  1089. ERR_FAIL_COND_V_MSG(err, err, "Cannot load file '" + p_path + "'.");
  1090. force_make_tangents = p_force_make_tangents;
  1091. ERR_FAIL_COND_V(!collada.state.visual_scene_map.has(collada.state.root_visual_scene), ERR_INVALID_DATA);
  1092. Collada::VisualScene &vs = collada.state.visual_scene_map[collada.state.root_visual_scene];
  1093. scene = memnew(Node3D); // root
  1094. //determine what's going on with the lights
  1095. for (int i = 0; i < vs.root_nodes.size(); i++) {
  1096. _pre_process_lights(vs.root_nodes[i]);
  1097. }
  1098. //import scene
  1099. for (int i = 0; i < vs.root_nodes.size(); i++) {
  1100. Error err2 = _create_scene_skeletons(vs.root_nodes[i]);
  1101. if (err2 != OK) {
  1102. memdelete(scene);
  1103. ERR_FAIL_COND_V(err2, err2);
  1104. }
  1105. }
  1106. for (int i = 0; i < vs.root_nodes.size(); i++) {
  1107. Error err2 = _create_scene(vs.root_nodes[i], scene);
  1108. if (err2 != OK) {
  1109. memdelete(scene);
  1110. ERR_FAIL_COND_V(err2, err2);
  1111. }
  1112. Error err3 = _create_resources(vs.root_nodes[i], p_use_compression);
  1113. if (err3 != OK) {
  1114. memdelete(scene);
  1115. ERR_FAIL_COND_V(err3, err3);
  1116. }
  1117. }
  1118. //optatively, set unit scale in the root
  1119. scene->set_transform(collada.get_root_transform());
  1120. return OK;
  1121. }
  1122. void ColladaImport::_fix_param_animation_tracks() {
  1123. for (KeyValue<String, Collada::Node *> &E : collada.state.scene_map) {
  1124. Collada::Node *n = E.value;
  1125. switch (n->type) {
  1126. case Collada::Node::TYPE_NODE: {
  1127. // ? do nothing
  1128. } break;
  1129. case Collada::Node::TYPE_JOINT: {
  1130. } break;
  1131. case Collada::Node::TYPE_SKELETON: {
  1132. } break;
  1133. case Collada::Node::TYPE_LIGHT: {
  1134. } break;
  1135. case Collada::Node::TYPE_CAMERA: {
  1136. } break;
  1137. case Collada::Node::TYPE_GEOMETRY: {
  1138. Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(n);
  1139. // test source(s)
  1140. String source = ng->source;
  1141. while (!source.is_empty()) {
  1142. if (collada.state.skin_controller_data_map.has(source)) {
  1143. const Collada::SkinControllerData &skin = collada.state.skin_controller_data_map[source];
  1144. //nothing to animate here i think
  1145. source = skin.base;
  1146. } else if (collada.state.morph_controller_data_map.has(source)) {
  1147. const Collada::MorphControllerData &morph = collada.state.morph_controller_data_map[source];
  1148. if (morph.targets.has("MORPH_WEIGHT") && morph.targets.has("MORPH_TARGET")) {
  1149. String weights = morph.targets["MORPH_WEIGHT"];
  1150. String targets = morph.targets["MORPH_TARGET"];
  1151. //fails here
  1152. if (morph.sources.has(targets) && morph.sources.has(weights)) {
  1153. const Collada::MorphControllerData::Source &weight_src = morph.sources[weights];
  1154. const Collada::MorphControllerData::Source &target_src = morph.sources[targets];
  1155. ERR_FAIL_COND(weight_src.array.size() != target_src.sarray.size());
  1156. for (int i = 0; i < weight_src.array.size(); i++) {
  1157. String track_name = weights + "(" + itos(i) + ")";
  1158. String mesh_name = target_src.sarray[i];
  1159. if (collada.state.mesh_name_map.has(mesh_name) && collada.state.referenced_tracks.has(track_name)) {
  1160. const Vector<int> &rt = collada.state.referenced_tracks[track_name];
  1161. for (int rti = 0; rti < rt.size(); rti++) {
  1162. Collada::AnimationTrack *at = &collada.state.animation_tracks.write[rt[rti]];
  1163. at->target = E.key;
  1164. at->param = "morph/" + collada.state.mesh_name_map[mesh_name];
  1165. at->property = true;
  1166. //at->param
  1167. }
  1168. }
  1169. }
  1170. }
  1171. }
  1172. source = morph.mesh;
  1173. } else {
  1174. source = ""; // for now nothing else supported
  1175. }
  1176. }
  1177. } break;
  1178. }
  1179. }
  1180. }
  1181. void ColladaImport::create_animations(bool p_import_value_tracks) {
  1182. _fix_param_animation_tracks();
  1183. for (int i = 0; i < collada.state.animation_clips.size(); i++) {
  1184. for (int j = 0; j < collada.state.animation_clips[i].tracks.size(); j++) {
  1185. tracks_in_clips.insert(collada.state.animation_clips[i].tracks[j]);
  1186. }
  1187. }
  1188. for (int i = 0; i < collada.state.animation_tracks.size(); i++) {
  1189. const Collada::AnimationTrack &at = collada.state.animation_tracks[i];
  1190. String node;
  1191. if (!node_map.has(at.target)) {
  1192. if (node_name_map.has(at.target)) {
  1193. node = node_name_map[at.target];
  1194. } else {
  1195. WARN_PRINT("Collada: Couldn't find node: " + at.target);
  1196. continue;
  1197. }
  1198. } else {
  1199. node = at.target;
  1200. }
  1201. if (at.property) {
  1202. valid_animated_properties.push_back(i);
  1203. } else {
  1204. node_map[node].anim_tracks.push_back(i);
  1205. valid_animated_nodes.insert(node);
  1206. }
  1207. }
  1208. create_animation(-1, p_import_value_tracks);
  1209. for (int i = 0; i < collada.state.animation_clips.size(); i++) {
  1210. create_animation(i, p_import_value_tracks);
  1211. }
  1212. }
  1213. void ColladaImport::create_animation(int p_clip, bool p_import_value_tracks) {
  1214. Ref<Animation> animation = Ref<Animation>(memnew(Animation));
  1215. if (p_clip == -1) {
  1216. animation->set_name("default");
  1217. } else {
  1218. animation->set_name(collada.state.animation_clips[p_clip].name);
  1219. }
  1220. for (const KeyValue<String, NodeMap> &E : node_map) {
  1221. if (E.value.bone < 0) {
  1222. continue;
  1223. }
  1224. bones_with_animation[E.key] = false;
  1225. }
  1226. //store and validate tracks
  1227. if (p_clip == -1) {
  1228. //main anim
  1229. }
  1230. HashSet<int> track_filter;
  1231. if (p_clip == -1) {
  1232. for (int i = 0; i < collada.state.animation_clips.size(); i++) {
  1233. int tc = collada.state.animation_clips[i].tracks.size();
  1234. for (int j = 0; j < tc; j++) {
  1235. String n = collada.state.animation_clips[i].tracks[j];
  1236. if (collada.state.by_id_tracks.has(n)) {
  1237. const Vector<int> &ti = collada.state.by_id_tracks[n];
  1238. for (int k = 0; k < ti.size(); k++) {
  1239. track_filter.insert(ti[k]);
  1240. }
  1241. }
  1242. }
  1243. }
  1244. } else {
  1245. int tc = collada.state.animation_clips[p_clip].tracks.size();
  1246. for (int j = 0; j < tc; j++) {
  1247. String n = collada.state.animation_clips[p_clip].tracks[j];
  1248. if (collada.state.by_id_tracks.has(n)) {
  1249. const Vector<int> &ti = collada.state.by_id_tracks[n];
  1250. for (int k = 0; k < ti.size(); k++) {
  1251. track_filter.insert(ti[k]);
  1252. }
  1253. }
  1254. }
  1255. }
  1256. //animation->set_loop(true);
  1257. //create animation tracks
  1258. Vector<real_t> base_snapshots;
  1259. float f = 0;
  1260. float snapshot_interval = 1.0 / bake_fps; //should be customizable somewhere...
  1261. float anim_length = collada.state.animation_length;
  1262. if (p_clip >= 0 && collada.state.animation_clips[p_clip].end) {
  1263. anim_length = collada.state.animation_clips[p_clip].end;
  1264. }
  1265. while (f < anim_length) {
  1266. base_snapshots.push_back(f);
  1267. f += snapshot_interval;
  1268. if (f >= anim_length) {
  1269. base_snapshots.push_back(anim_length);
  1270. }
  1271. }
  1272. animation->set_length(anim_length);
  1273. animation->set_step(snapshot_interval);
  1274. bool tracks_found = false;
  1275. for (const String &E : valid_animated_nodes) {
  1276. // take snapshots
  1277. if (!collada.state.scene_map.has(E)) {
  1278. continue;
  1279. }
  1280. NodeMap &nm = node_map[E];
  1281. String path = scene->get_path_to(nm.node);
  1282. if (nm.bone >= 0) {
  1283. Skeleton3D *sk = static_cast<Skeleton3D *>(nm.node);
  1284. String name = sk->get_bone_name(nm.bone);
  1285. path = path + ":" + name;
  1286. }
  1287. bool found_anim = false;
  1288. Collada::Node *cn = collada.state.scene_map[E];
  1289. if (cn->ignore_anim) {
  1290. continue;
  1291. }
  1292. bool has_position = false;
  1293. bool has_rotation = false;
  1294. bool has_scale = false;
  1295. for (int i = 0; i < cn->xform_list.size(); i++) {
  1296. switch (cn->xform_list[i].op) {
  1297. case Collada::Node::XForm::OP_ROTATE: {
  1298. has_rotation = true;
  1299. } break;
  1300. case Collada::Node::XForm::OP_SCALE: {
  1301. has_scale = true;
  1302. } break;
  1303. case Collada::Node::XForm::OP_TRANSLATE: {
  1304. has_position = true;
  1305. } break;
  1306. case Collada::Node::XForm::OP_MATRIX: {
  1307. has_position = true;
  1308. has_rotation = true;
  1309. has_scale = true;
  1310. } break;
  1311. case Collada::Node::XForm::OP_VISIBILITY: {
  1312. } break;
  1313. }
  1314. }
  1315. int base_track = animation->get_track_count();
  1316. int position_idx = -1;
  1317. if (has_position) {
  1318. position_idx = animation->get_track_count();
  1319. animation->add_track(Animation::TYPE_POSITION_3D);
  1320. animation->track_set_path(position_idx, path);
  1321. animation->track_set_imported(position_idx, true); //helps merging later
  1322. }
  1323. int rotation_idx = -1;
  1324. if (has_rotation) {
  1325. rotation_idx = animation->get_track_count();
  1326. animation->add_track(Animation::TYPE_ROTATION_3D);
  1327. animation->track_set_path(rotation_idx, path);
  1328. animation->track_set_imported(rotation_idx, true); //helps merging later
  1329. }
  1330. int scale_idx = -1;
  1331. if (has_scale) {
  1332. scale_idx = animation->get_track_count();
  1333. animation->add_track(Animation::TYPE_SCALE_3D);
  1334. animation->track_set_path(scale_idx, path);
  1335. animation->track_set_imported(scale_idx, true); //helps merging later
  1336. }
  1337. Vector<real_t> snapshots = base_snapshots;
  1338. if (nm.anim_tracks.size() == 1) {
  1339. //use snapshot keys from anim track instead, because this was most likely exported baked
  1340. const Collada::AnimationTrack &at = collada.state.animation_tracks[nm.anim_tracks.front()->get()];
  1341. snapshots.clear();
  1342. for (int i = 0; i < at.keys.size(); i++) {
  1343. snapshots.push_back(at.keys[i].time);
  1344. }
  1345. }
  1346. for (int i = 0; i < snapshots.size(); i++) {
  1347. for (const int track_id : nm.anim_tracks) {
  1348. //apply tracks
  1349. if (p_clip == -1) {
  1350. if (track_filter.has(track_id)) {
  1351. continue;
  1352. }
  1353. } else {
  1354. if (!track_filter.has(track_id)) {
  1355. continue;
  1356. }
  1357. }
  1358. found_anim = true;
  1359. const Collada::AnimationTrack &at = collada.state.animation_tracks[track_id];
  1360. int xform_idx = -1;
  1361. for (int j = 0; j < cn->xform_list.size(); j++) {
  1362. if (cn->xform_list[j].id == at.param) {
  1363. xform_idx = j;
  1364. break;
  1365. }
  1366. }
  1367. if (xform_idx == -1) {
  1368. WARN_PRINT("Collada: Couldn't find matching node " + at.target + " xform for track " + at.param + ".");
  1369. continue;
  1370. }
  1371. Vector<float> data = at.get_value_at_time(snapshots[i]);
  1372. ERR_CONTINUE(data.is_empty());
  1373. Collada::Node::XForm &xf = cn->xform_list.write[xform_idx];
  1374. if (at.component == "ANGLE") {
  1375. ERR_CONTINUE(data.size() != 1);
  1376. ERR_CONTINUE(xf.op != Collada::Node::XForm::OP_ROTATE);
  1377. ERR_CONTINUE(xf.data.size() < 4);
  1378. xf.data.write[3] = data[0];
  1379. } else if (at.component == "X" || at.component == "Y" || at.component == "Z") {
  1380. int cn2 = at.component[0] - 'X';
  1381. ERR_CONTINUE(cn2 >= xf.data.size());
  1382. ERR_CONTINUE(data.size() > 1);
  1383. xf.data.write[cn2] = data[0];
  1384. } else if (data.size() == xf.data.size()) {
  1385. xf.data = data;
  1386. } else {
  1387. ERR_CONTINUE_MSG(data.size() != xf.data.size(), "Component " + at.component + " has datasize " + itos(data.size()) + ", xfdatasize " + itos(xf.data.size()) + ".");
  1388. }
  1389. }
  1390. Transform3D xform = cn->compute_transform(collada);
  1391. xform = collada.fix_transform(xform) * cn->post_transform;
  1392. Vector3 s = xform.basis.get_scale();
  1393. bool singular_matrix = Math::is_zero_approx(s.x) || Math::is_zero_approx(s.y) || Math::is_zero_approx(s.z);
  1394. Quaternion q = singular_matrix ? Quaternion() : xform.basis.get_rotation_quaternion();
  1395. Vector3 l = xform.origin;
  1396. if (position_idx >= 0) {
  1397. animation->position_track_insert_key(position_idx, snapshots[i], l);
  1398. }
  1399. if (rotation_idx >= 0) {
  1400. animation->rotation_track_insert_key(rotation_idx, snapshots[i], q);
  1401. }
  1402. if (scale_idx >= 0) {
  1403. animation->scale_track_insert_key(scale_idx, snapshots[i], s);
  1404. }
  1405. }
  1406. if (nm.bone >= 0) {
  1407. if (found_anim) {
  1408. bones_with_animation[E] = true;
  1409. }
  1410. }
  1411. if (found_anim) {
  1412. tracks_found = true;
  1413. } else {
  1414. if (position_idx >= 0) {
  1415. animation->remove_track(base_track);
  1416. }
  1417. if (rotation_idx >= 0) {
  1418. animation->remove_track(base_track);
  1419. }
  1420. if (scale_idx >= 0) {
  1421. animation->remove_track(base_track);
  1422. }
  1423. }
  1424. }
  1425. if (p_import_value_tracks) {
  1426. for (int i = 0; i < valid_animated_properties.size(); i++) {
  1427. int ti = valid_animated_properties[i];
  1428. if (p_clip == -1) {
  1429. if (track_filter.has(ti)) {
  1430. continue;
  1431. }
  1432. } else {
  1433. if (!track_filter.has(ti)) {
  1434. continue;
  1435. }
  1436. }
  1437. const Collada::AnimationTrack &at = collada.state.animation_tracks[ti];
  1438. // take snapshots
  1439. if (!collada.state.scene_map.has(at.target)) {
  1440. continue;
  1441. }
  1442. NodeMap &nm = node_map[at.target];
  1443. String path = scene->get_path_to(nm.node);
  1444. animation->add_track(Animation::TYPE_BLEND_SHAPE);
  1445. int track = animation->get_track_count() - 1;
  1446. path = path + ":" + at.param;
  1447. animation->track_set_path(track, path);
  1448. animation->track_set_imported(track, true); //helps merging later
  1449. for (int j = 0; j < at.keys.size(); j++) {
  1450. float time = at.keys[j].time;
  1451. Variant value;
  1452. Vector<float> data = at.keys[j].data;
  1453. if (data.size() == 1) {
  1454. //push a float
  1455. value = data[0];
  1456. } else if (data.size() == 16) {
  1457. //matrix
  1458. WARN_PRINT("Collada: Value keys for matrices not supported.");
  1459. } else {
  1460. WARN_PRINT("Collada: Unexpected amount of value keys: " + itos(data.size()));
  1461. }
  1462. animation->blend_shape_track_insert_key(track, time, value);
  1463. }
  1464. tracks_found = true;
  1465. }
  1466. }
  1467. if (tracks_found) {
  1468. animations.push_back(animation);
  1469. }
  1470. }
  1471. /*********************************************************************************/
  1472. /*************************************** SCENE ***********************************/
  1473. /*********************************************************************************/
  1474. void EditorSceneFormatImporterCollada::get_extensions(List<String> *r_extensions) const {
  1475. r_extensions->push_back("dae");
  1476. }
  1477. Node *EditorSceneFormatImporterCollada::import_scene(const String &p_path, uint32_t p_flags, const HashMap<StringName, Variant> &p_options, List<String> *r_missing_deps, Error *r_err) {
  1478. if (r_err) {
  1479. *r_err = OK;
  1480. }
  1481. ColladaImport state;
  1482. uint32_t flags = Collada::IMPORT_FLAG_SCENE;
  1483. if (p_flags & IMPORT_ANIMATION) {
  1484. flags |= Collada::IMPORT_FLAG_ANIMATION;
  1485. }
  1486. state.use_mesh_builtin_materials = true;
  1487. state.bake_fps = (float)p_options["animation/fps"];
  1488. Error err = state.load(p_path, flags, p_flags & EditorSceneFormatImporter::IMPORT_GENERATE_TANGENT_ARRAYS, !bool(p_flags & EditorSceneFormatImporter::IMPORT_FORCE_DISABLE_MESH_COMPRESSION));
  1489. if (r_err) {
  1490. *r_err = err;
  1491. }
  1492. ERR_FAIL_COND_V_MSG(err != OK, nullptr, "Cannot load scene from file '" + p_path + "'.");
  1493. if (state.missing_textures.size()) {
  1494. if (r_missing_deps) {
  1495. for (int i = 0; i < state.missing_textures.size(); i++) {
  1496. r_missing_deps->push_back(state.missing_textures[i]);
  1497. }
  1498. }
  1499. }
  1500. if (p_flags & IMPORT_ANIMATION) {
  1501. state.create_animations(true);
  1502. AnimationPlayer *ap = memnew(AnimationPlayer);
  1503. for (int i = 0; i < state.animations.size(); i++) {
  1504. String name;
  1505. if (state.animations[i]->get_name().is_empty()) {
  1506. name = "default";
  1507. } else {
  1508. name = state.animations[i]->get_name();
  1509. }
  1510. Ref<AnimationLibrary> library;
  1511. if (!ap->has_animation_library("")) {
  1512. library.instantiate();
  1513. ap->add_animation_library("", library);
  1514. } else {
  1515. library = ap->get_animation_library("");
  1516. }
  1517. library->add_animation(name, state.animations[i]);
  1518. }
  1519. state.scene->add_child(ap, true);
  1520. ap->set_owner(state.scene);
  1521. }
  1522. return state.scene;
  1523. }