editor_scene_importer_gltf.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. /*************************************************************************/
  2. /* editor_scene_importer_gltf.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 "editor_scene_importer_gltf.h"
  31. #include "core/io/json.h"
  32. #include "core/math/math_defs.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/os.h"
  35. #include "scene/3d/camera.h"
  36. #include "scene/3d/mesh_instance.h"
  37. #include "scene/animation/animation_player.h"
  38. #include "scene/resources/surface_tool.h"
  39. #include "thirdparty/misc/base64.h"
  40. uint32_t EditorSceneImporterGLTF::get_import_flags() const {
  41. return IMPORT_SCENE | IMPORT_ANIMATION;
  42. }
  43. void EditorSceneImporterGLTF::get_extensions(List<String> *r_extensions) const {
  44. r_extensions->push_back("gltf");
  45. r_extensions->push_back("glb");
  46. }
  47. Error EditorSceneImporterGLTF::_parse_json(const String &p_path, GLTFState &state) {
  48. Error err;
  49. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
  50. if (!f) {
  51. return err;
  52. }
  53. Vector<uint8_t> array;
  54. array.resize(f->get_len());
  55. f->get_buffer(array.ptrw(), array.size());
  56. String text;
  57. text.parse_utf8((const char *)array.ptr(), array.size());
  58. String err_txt;
  59. int err_line;
  60. Variant v;
  61. err = JSON::parse(text, v, err_txt, err_line);
  62. if (err != OK) {
  63. _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
  64. return err;
  65. }
  66. state.json = v;
  67. return OK;
  68. }
  69. Error EditorSceneImporterGLTF::_parse_glb(const String &p_path, GLTFState &state) {
  70. Error err;
  71. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ, &err);
  72. if (!f) {
  73. return err;
  74. }
  75. uint32_t magic = f->get_32();
  76. ERR_FAIL_COND_V(magic != 0x46546C67, ERR_FILE_UNRECOGNIZED); //glTF
  77. f->get_32(); // version
  78. f->get_32(); // length
  79. uint32_t chunk_length = f->get_32();
  80. uint32_t chunk_type = f->get_32();
  81. ERR_FAIL_COND_V(chunk_type != 0x4E4F534A, ERR_PARSE_ERROR); //JSON
  82. Vector<uint8_t> json_data;
  83. json_data.resize(chunk_length);
  84. uint32_t len = f->get_buffer(json_data.ptrw(), chunk_length);
  85. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  86. String text;
  87. text.parse_utf8((const char *)json_data.ptr(), json_data.size());
  88. String err_txt;
  89. int err_line;
  90. Variant v;
  91. err = JSON::parse(text, v, err_txt, err_line);
  92. if (err != OK) {
  93. _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
  94. return err;
  95. }
  96. state.json = v;
  97. //data?
  98. chunk_length = f->get_32();
  99. chunk_type = f->get_32();
  100. if (f->eof_reached()) {
  101. return OK; //all good
  102. }
  103. ERR_FAIL_COND_V(chunk_type != 0x004E4942, ERR_PARSE_ERROR); //BIN
  104. state.glb_data.resize(chunk_length);
  105. len = f->get_buffer(state.glb_data.ptrw(), chunk_length);
  106. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  107. return OK;
  108. }
  109. static Vector3 _arr_to_vec3(const Array &p_array) {
  110. ERR_FAIL_COND_V(p_array.size() != 3, Vector3());
  111. return Vector3(p_array[0], p_array[1], p_array[2]);
  112. }
  113. static Quat _arr_to_quat(const Array &p_array) {
  114. ERR_FAIL_COND_V(p_array.size() != 4, Quat());
  115. return Quat(p_array[0], p_array[1], p_array[2], p_array[3]);
  116. }
  117. static Transform _arr_to_xform(const Array &p_array) {
  118. ERR_FAIL_COND_V(p_array.size() != 16, Transform());
  119. Transform xform;
  120. xform.basis.set_axis(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2]));
  121. xform.basis.set_axis(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6]));
  122. xform.basis.set_axis(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10]));
  123. xform.set_origin(Vector3(p_array[12], p_array[13], p_array[14]));
  124. return xform;
  125. }
  126. String EditorSceneImporterGLTF::_gen_unique_name(GLTFState &state, const String &p_name) {
  127. int index = 1;
  128. String name;
  129. while (true) {
  130. name = p_name;
  131. if (index > 1) {
  132. name += " " + itos(index);
  133. }
  134. if (!state.unique_names.has(name)) {
  135. break;
  136. }
  137. index++;
  138. }
  139. state.unique_names.insert(name);
  140. return name;
  141. }
  142. Error EditorSceneImporterGLTF::_parse_scenes(GLTFState &state) {
  143. ERR_FAIL_COND_V(!state.json.has("scenes"), ERR_FILE_CORRUPT);
  144. Array scenes = state.json["scenes"];
  145. for (int i = 0; i < 1; i++) { //only first scene is imported
  146. Dictionary s = scenes[i];
  147. ERR_FAIL_COND_V(!s.has("nodes"), ERR_UNAVAILABLE);
  148. Array nodes = s["nodes"];
  149. for (int j = 0; j < nodes.size(); j++) {
  150. state.root_nodes.push_back(nodes[j]);
  151. }
  152. if (s.has("name")) {
  153. state.scene_name = s["name"];
  154. }
  155. }
  156. return OK;
  157. }
  158. Error EditorSceneImporterGLTF::_parse_nodes(GLTFState &state) {
  159. ERR_FAIL_COND_V(!state.json.has("nodes"), ERR_FILE_CORRUPT);
  160. Array nodes = state.json["nodes"];
  161. for (int i = 0; i < nodes.size(); i++) {
  162. GLTFNode *node = memnew(GLTFNode);
  163. Dictionary n = nodes[i];
  164. if (n.has("name")) {
  165. node->name = n["name"];
  166. }
  167. if (n.has("camera")) {
  168. node->camera = n["camera"];
  169. }
  170. if (n.has("mesh")) {
  171. node->mesh = n["mesh"];
  172. }
  173. if (n.has("skin")) {
  174. node->skin = n["skin"];
  175. /*
  176. if (!state.skin_users.has(node->skin)) {
  177. state.skin_users[node->skin] = Vector<int>();
  178. }
  179. state.skin_users[node->skin].push_back(i);
  180. */
  181. }
  182. if (n.has("matrix")) {
  183. node->xform = _arr_to_xform(n["matrix"]);
  184. } else {
  185. if (n.has("translation")) {
  186. node->translation = _arr_to_vec3(n["translation"]);
  187. }
  188. if (n.has("rotation")) {
  189. node->rotation = _arr_to_quat(n["rotation"]);
  190. }
  191. if (n.has("scale")) {
  192. node->scale = _arr_to_vec3(n["scale"]);
  193. }
  194. node->xform.basis = Basis(node->rotation);
  195. node->xform.basis.scale(node->scale);
  196. node->xform.origin = node->translation;
  197. }
  198. if (n.has("children")) {
  199. Array children = n["children"];
  200. for (int i = 0; i < children.size(); i++) {
  201. node->children.push_back(children[i]);
  202. }
  203. }
  204. state.nodes.push_back(node);
  205. }
  206. //build the hierarchy
  207. for (int i = 0; i < state.nodes.size(); i++) {
  208. for (int j = 0; j < state.nodes[i]->children.size(); j++) {
  209. int child = state.nodes[i]->children[j];
  210. ERR_FAIL_INDEX_V(child, state.nodes.size(), ERR_FILE_CORRUPT);
  211. ERR_CONTINUE(state.nodes[child]->parent != -1); //node already has a parent, wtf.
  212. state.nodes[child]->parent = i;
  213. }
  214. }
  215. return OK;
  216. }
  217. static Vector<uint8_t> _parse_base64_uri(const String &uri) {
  218. int start = uri.find(",");
  219. ERR_FAIL_COND_V(start == -1, Vector<uint8_t>());
  220. CharString substr = uri.right(start + 1).ascii();
  221. int strlen = substr.length();
  222. Vector<uint8_t> buf;
  223. buf.resize(strlen / 4 * 3 + 1 + 1);
  224. int len = base64_decode((char *)buf.ptr(), (char *)substr.get_data(), strlen);
  225. buf.resize(len);
  226. return buf;
  227. }
  228. Error EditorSceneImporterGLTF::_parse_buffers(GLTFState &state, const String &p_base_path) {
  229. if (!state.json.has("buffers"))
  230. return OK;
  231. Array buffers = state.json["buffers"];
  232. for (int i = 0; i < buffers.size(); i++) {
  233. if (i == 0 && state.glb_data.size()) {
  234. state.buffers.push_back(state.glb_data);
  235. } else {
  236. Dictionary buffer = buffers[i];
  237. if (buffer.has("uri")) {
  238. Vector<uint8_t> buffer_data;
  239. String uri = buffer["uri"];
  240. if (uri.findn("data:application/octet-stream;base64") == 0) {
  241. //embedded data
  242. buffer_data = _parse_base64_uri(uri);
  243. } else {
  244. uri = p_base_path.plus_file(uri).replace("\\", "/"); //fix for windows
  245. buffer_data = FileAccess::get_file_as_array(uri);
  246. ERR_FAIL_COND_V(buffer.size() == 0, ERR_PARSE_ERROR);
  247. }
  248. ERR_FAIL_COND_V(!buffer.has("byteLength"), ERR_PARSE_ERROR);
  249. int byteLength = buffer["byteLength"];
  250. ERR_FAIL_COND_V(byteLength < buffer_data.size(), ERR_PARSE_ERROR);
  251. state.buffers.push_back(buffer_data);
  252. }
  253. }
  254. }
  255. print_verbose("glTF: Total buffers: " + itos(state.buffers.size()));
  256. return OK;
  257. }
  258. Error EditorSceneImporterGLTF::_parse_buffer_views(GLTFState &state) {
  259. ERR_FAIL_COND_V(!state.json.has("bufferViews"), ERR_FILE_CORRUPT);
  260. Array buffers = state.json["bufferViews"];
  261. for (int i = 0; i < buffers.size(); i++) {
  262. Dictionary d = buffers[i];
  263. GLTFBufferView buffer_view;
  264. ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR);
  265. buffer_view.buffer = d["buffer"];
  266. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_PARSE_ERROR);
  267. buffer_view.byte_length = d["byteLength"];
  268. if (d.has("byteOffset")) {
  269. buffer_view.byte_offset = d["byteOffset"];
  270. }
  271. if (d.has("byteStride")) {
  272. buffer_view.byte_stride = d["byteStride"];
  273. }
  274. if (d.has("target")) {
  275. int target = d["target"];
  276. buffer_view.indices = target == ELEMENT_ARRAY_BUFFER;
  277. }
  278. state.buffer_views.push_back(buffer_view);
  279. }
  280. print_verbose("glTF: Total buffer views: " + itos(state.buffer_views.size()));
  281. return OK;
  282. }
  283. EditorSceneImporterGLTF::GLTFType EditorSceneImporterGLTF::_get_type_from_str(const String &p_string) {
  284. if (p_string == "SCALAR")
  285. return TYPE_SCALAR;
  286. if (p_string == "VEC2")
  287. return TYPE_VEC2;
  288. if (p_string == "VEC3")
  289. return TYPE_VEC3;
  290. if (p_string == "VEC4")
  291. return TYPE_VEC4;
  292. if (p_string == "MAT2")
  293. return TYPE_MAT2;
  294. if (p_string == "MAT3")
  295. return TYPE_MAT3;
  296. if (p_string == "MAT4")
  297. return TYPE_MAT4;
  298. ERR_FAIL_V(TYPE_SCALAR);
  299. }
  300. Error EditorSceneImporterGLTF::_parse_accessors(GLTFState &state) {
  301. ERR_FAIL_COND_V(!state.json.has("accessors"), ERR_FILE_CORRUPT);
  302. Array accessors = state.json["accessors"];
  303. for (int i = 0; i < accessors.size(); i++) {
  304. Dictionary d = accessors[i];
  305. GLTFAccessor accessor;
  306. ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR);
  307. accessor.component_type = d["componentType"];
  308. ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
  309. accessor.count = d["count"];
  310. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  311. accessor.type = _get_type_from_str(d["type"]);
  312. if (d.has("bufferView")) {
  313. accessor.buffer_view = d["bufferView"]; //optional because it may be sparse...
  314. }
  315. if (d.has("byteOffset")) {
  316. accessor.byte_offset = d["byteOffset"];
  317. }
  318. if (d.has("max")) {
  319. accessor.max = d["max"];
  320. }
  321. if (d.has("min")) {
  322. accessor.min = d["min"];
  323. }
  324. if (d.has("sparse")) {
  325. //eeh..
  326. Dictionary s = d["sparse"];
  327. ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
  328. accessor.sparse_count = d["count"];
  329. ERR_FAIL_COND_V(!d.has("indices"), ERR_PARSE_ERROR);
  330. Dictionary si = d["indices"];
  331. ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
  332. accessor.sparse_indices_buffer_view = si["bufferView"];
  333. ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
  334. accessor.sparse_indices_component_type = si["componentType"];
  335. if (si.has("byteOffset")) {
  336. accessor.sparse_indices_byte_offset = si["byteOffset"];
  337. }
  338. ERR_FAIL_COND_V(!d.has("values"), ERR_PARSE_ERROR);
  339. Dictionary sv = d["values"];
  340. ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  341. accessor.sparse_values_buffer_view = sv["bufferView"];
  342. if (sv.has("byteOffset")) {
  343. accessor.sparse_values_byte_offset = sv["byteOffset"];
  344. }
  345. }
  346. state.accessors.push_back(accessor);
  347. }
  348. print_verbose("glTF: Total accessors: " + itos(state.accessors.size()));
  349. return OK;
  350. }
  351. String EditorSceneImporterGLTF::_get_component_type_name(uint32_t p_component) {
  352. switch (p_component) {
  353. case COMPONENT_TYPE_BYTE: return "Byte";
  354. case COMPONENT_TYPE_UNSIGNED_BYTE: return "UByte";
  355. case COMPONENT_TYPE_SHORT: return "Short";
  356. case COMPONENT_TYPE_UNSIGNED_SHORT: return "UShort";
  357. case COMPONENT_TYPE_INT: return "Int";
  358. case COMPONENT_TYPE_FLOAT: return "Float";
  359. }
  360. return "<Error>";
  361. }
  362. String EditorSceneImporterGLTF::_get_type_name(GLTFType p_component) {
  363. static const char *names[] = {
  364. "float",
  365. "vec2",
  366. "vec3",
  367. "vec4",
  368. "mat2",
  369. "mat3",
  370. "mat4"
  371. };
  372. return names[p_component];
  373. }
  374. Error EditorSceneImporterGLTF::_decode_buffer_view(GLTFState &state, int p_buffer_view, double *dst, int skip_every, int skip_bytes, int element_size, int count, GLTFType type, int component_count, int component_type, int component_size, bool normalized, int byte_offset, bool for_vertex) {
  375. const GLTFBufferView &bv = state.buffer_views[p_buffer_view];
  376. int stride = bv.byte_stride ? bv.byte_stride : element_size;
  377. if (for_vertex && stride % 4) {
  378. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  379. }
  380. ERR_FAIL_INDEX_V(bv.buffer, state.buffers.size(), ERR_PARSE_ERROR);
  381. uint32_t offset = bv.byte_offset + byte_offset;
  382. Vector<uint8_t> buffer = state.buffers[bv.buffer]; //copy on write, so no performance hit
  383. const uint8_t *bufptr = buffer.ptr();
  384. //use to debug
  385. print_verbose("glTF: type " + _get_type_name(type) + " component type: " + _get_component_type_name(component_type) + " stride: " + itos(stride) + " amount " + itos(count));
  386. print_verbose("glTF: accessor offset" + itos(byte_offset) + " view offset: " + itos(bv.byte_offset) + " total buffer len: " + itos(buffer.size()) + " view len " + itos(bv.byte_length));
  387. int buffer_end = (stride * (count - 1)) + element_size;
  388. ERR_FAIL_COND_V(buffer_end > bv.byte_length, ERR_PARSE_ERROR);
  389. ERR_FAIL_COND_V((int)(offset + buffer_end) > buffer.size(), ERR_PARSE_ERROR);
  390. //fill everything as doubles
  391. for (int i = 0; i < count; i++) {
  392. const uint8_t *src = &bufptr[offset + i * stride];
  393. for (int j = 0; j < component_count; j++) {
  394. if (skip_every && j > 0 && (j % skip_every) == 0) {
  395. src += skip_bytes;
  396. }
  397. double d = 0;
  398. switch (component_type) {
  399. case COMPONENT_TYPE_BYTE: {
  400. int8_t b = int8_t(*src);
  401. if (normalized) {
  402. d = (double(b) / 128.0);
  403. } else {
  404. d = double(b);
  405. }
  406. } break;
  407. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  408. uint8_t b = *src;
  409. if (normalized) {
  410. d = (double(b) / 255.0);
  411. } else {
  412. d = double(b);
  413. }
  414. } break;
  415. case COMPONENT_TYPE_SHORT: {
  416. int16_t s = *(int16_t *)src;
  417. if (normalized) {
  418. d = (double(s) / 32768.0);
  419. } else {
  420. d = double(s);
  421. }
  422. } break;
  423. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  424. uint16_t s = *(uint16_t *)src;
  425. if (normalized) {
  426. d = (double(s) / 65535.0);
  427. } else {
  428. d = double(s);
  429. }
  430. } break;
  431. case COMPONENT_TYPE_INT: {
  432. d = *(int *)src;
  433. } break;
  434. case COMPONENT_TYPE_FLOAT: {
  435. d = *(float *)src;
  436. } break;
  437. }
  438. *dst++ = d;
  439. src += component_size;
  440. }
  441. }
  442. return OK;
  443. }
  444. int EditorSceneImporterGLTF::_get_component_type_size(int component_type) {
  445. switch (component_type) {
  446. case COMPONENT_TYPE_BYTE: return 1; break;
  447. case COMPONENT_TYPE_UNSIGNED_BYTE: return 1; break;
  448. case COMPONENT_TYPE_SHORT: return 2; break;
  449. case COMPONENT_TYPE_UNSIGNED_SHORT: return 2; break;
  450. case COMPONENT_TYPE_INT: return 4; break;
  451. case COMPONENT_TYPE_FLOAT: return 4; break;
  452. default: { ERR_FAIL_V(0); }
  453. }
  454. return 0;
  455. }
  456. Vector<double> EditorSceneImporterGLTF::_decode_accessor(GLTFState &state, int p_accessor, bool p_for_vertex) {
  457. //spec, for reference:
  458. //https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  459. ERR_FAIL_INDEX_V(p_accessor, state.accessors.size(), Vector<double>());
  460. const GLTFAccessor &a = state.accessors[p_accessor];
  461. int component_count_for_type[7] = {
  462. 1, 2, 3, 4, 4, 9, 16
  463. };
  464. int component_count = component_count_for_type[a.type];
  465. int component_size = _get_component_type_size(a.component_type);
  466. ERR_FAIL_COND_V(component_size == 0, Vector<double>());
  467. int element_size = component_count * component_size;
  468. int skip_every = 0;
  469. int skip_bytes = 0;
  470. //special case of alignments, as described in spec
  471. switch (a.component_type) {
  472. case COMPONENT_TYPE_BYTE:
  473. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  474. if (a.type == TYPE_MAT2) {
  475. skip_every = 2;
  476. skip_bytes = 2;
  477. element_size = 8; //override for this case
  478. }
  479. if (a.type == TYPE_MAT3) {
  480. skip_every = 3;
  481. skip_bytes = 1;
  482. element_size = 12; //override for this case
  483. }
  484. } break;
  485. case COMPONENT_TYPE_SHORT:
  486. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  487. if (a.type == TYPE_MAT3) {
  488. skip_every = 6;
  489. skip_bytes = 4;
  490. element_size = 16; //override for this case
  491. }
  492. } break;
  493. default: {}
  494. }
  495. Vector<double> dst_buffer;
  496. dst_buffer.resize(component_count * a.count);
  497. double *dst = dst_buffer.ptrw();
  498. if (a.buffer_view >= 0) {
  499. ERR_FAIL_INDEX_V(a.buffer_view, state.buffer_views.size(), Vector<double>());
  500. Error err = _decode_buffer_view(state, a.buffer_view, dst, skip_every, skip_bytes, element_size, a.count, a.type, component_count, a.component_type, component_size, a.normalized, a.byte_offset, p_for_vertex);
  501. if (err != OK)
  502. return Vector<double>();
  503. } else {
  504. //fill with zeros, as bufferview is not defined.
  505. for (int i = 0; i < (a.count * component_count); i++) {
  506. dst_buffer.write[i] = 0;
  507. }
  508. }
  509. if (a.sparse_count > 0) {
  510. // I could not find any file using this, so this code is so far untested
  511. Vector<double> indices;
  512. indices.resize(a.sparse_count);
  513. int indices_component_size = _get_component_type_size(a.sparse_indices_component_type);
  514. Error err = _decode_buffer_view(state, a.sparse_indices_buffer_view, indices.ptrw(), 0, 0, indices_component_size, a.sparse_count, TYPE_SCALAR, 1, a.sparse_indices_component_type, indices_component_size, false, a.sparse_indices_byte_offset, false);
  515. if (err != OK)
  516. return Vector<double>();
  517. Vector<double> data;
  518. data.resize(component_count * a.sparse_count);
  519. err = _decode_buffer_view(state, a.sparse_values_buffer_view, data.ptrw(), skip_every, skip_bytes, element_size, a.sparse_count, a.type, component_count, a.component_type, component_size, a.normalized, a.sparse_values_byte_offset, p_for_vertex);
  520. if (err != OK)
  521. return Vector<double>();
  522. for (int i = 0; i < indices.size(); i++) {
  523. int write_offset = int(indices[i]) * component_count;
  524. for (int j = 0; j < component_count; j++) {
  525. dst[write_offset + j] = data[i * component_count + j];
  526. }
  527. }
  528. }
  529. return dst_buffer;
  530. }
  531. PoolVector<int> EditorSceneImporterGLTF::_decode_accessor_as_ints(GLTFState &state, int p_accessor, bool p_for_vertex) {
  532. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  533. PoolVector<int> ret;
  534. if (attribs.size() == 0)
  535. return ret;
  536. const double *attribs_ptr = attribs.ptr();
  537. int ret_size = attribs.size();
  538. ret.resize(ret_size);
  539. {
  540. PoolVector<int>::Write w = ret.write();
  541. for (int i = 0; i < ret_size; i++) {
  542. w[i] = int(attribs_ptr[i]);
  543. }
  544. }
  545. return ret;
  546. }
  547. PoolVector<float> EditorSceneImporterGLTF::_decode_accessor_as_floats(GLTFState &state, int p_accessor, bool p_for_vertex) {
  548. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  549. PoolVector<float> ret;
  550. if (attribs.size() == 0)
  551. return ret;
  552. const double *attribs_ptr = attribs.ptr();
  553. int ret_size = attribs.size();
  554. ret.resize(ret_size);
  555. {
  556. PoolVector<float>::Write w = ret.write();
  557. for (int i = 0; i < ret_size; i++) {
  558. w[i] = float(attribs_ptr[i]);
  559. }
  560. }
  561. return ret;
  562. }
  563. PoolVector<Vector2> EditorSceneImporterGLTF::_decode_accessor_as_vec2(GLTFState &state, int p_accessor, bool p_for_vertex) {
  564. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  565. PoolVector<Vector2> ret;
  566. if (attribs.size() == 0)
  567. return ret;
  568. ERR_FAIL_COND_V(attribs.size() % 2 != 0, ret);
  569. const double *attribs_ptr = attribs.ptr();
  570. int ret_size = attribs.size() / 2;
  571. ret.resize(ret_size);
  572. {
  573. PoolVector<Vector2>::Write w = ret.write();
  574. for (int i = 0; i < ret_size; i++) {
  575. w[i] = Vector2(attribs_ptr[i * 2 + 0], attribs_ptr[i * 2 + 1]);
  576. }
  577. }
  578. return ret;
  579. }
  580. PoolVector<Vector3> EditorSceneImporterGLTF::_decode_accessor_as_vec3(GLTFState &state, int p_accessor, bool p_for_vertex) {
  581. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  582. PoolVector<Vector3> ret;
  583. if (attribs.size() == 0)
  584. return ret;
  585. ERR_FAIL_COND_V(attribs.size() % 3 != 0, ret);
  586. const double *attribs_ptr = attribs.ptr();
  587. int ret_size = attribs.size() / 3;
  588. ret.resize(ret_size);
  589. {
  590. PoolVector<Vector3>::Write w = ret.write();
  591. for (int i = 0; i < ret_size; i++) {
  592. w[i] = Vector3(attribs_ptr[i * 3 + 0], attribs_ptr[i * 3 + 1], attribs_ptr[i * 3 + 2]);
  593. }
  594. }
  595. return ret;
  596. }
  597. PoolVector<Color> EditorSceneImporterGLTF::_decode_accessor_as_color(GLTFState &state, int p_accessor, bool p_for_vertex) {
  598. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  599. PoolVector<Color> ret;
  600. if (attribs.size() == 0)
  601. return ret;
  602. int type = state.accessors[p_accessor].type;
  603. ERR_FAIL_COND_V(!(type == TYPE_VEC3 || type == TYPE_VEC4), ret);
  604. int components;
  605. if (type == TYPE_VEC3) {
  606. components = 3;
  607. } else { // TYPE_VEC4
  608. components = 4;
  609. }
  610. ERR_FAIL_COND_V(attribs.size() % components != 0, ret);
  611. const double *attribs_ptr = attribs.ptr();
  612. int ret_size = attribs.size() / components;
  613. ret.resize(ret_size);
  614. {
  615. PoolVector<Color>::Write w = ret.write();
  616. for (int i = 0; i < ret_size; i++) {
  617. w[i] = Color(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], components == 4 ? attribs_ptr[i * 4 + 3] : 1.0);
  618. }
  619. }
  620. return ret;
  621. }
  622. Vector<Quat> EditorSceneImporterGLTF::_decode_accessor_as_quat(GLTFState &state, int p_accessor, bool p_for_vertex) {
  623. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  624. Vector<Quat> ret;
  625. if (attribs.size() == 0)
  626. return ret;
  627. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  628. const double *attribs_ptr = attribs.ptr();
  629. int ret_size = attribs.size() / 4;
  630. ret.resize(ret_size);
  631. {
  632. for (int i = 0; i < ret_size; i++) {
  633. ret.write[i] = Quat(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized();
  634. }
  635. }
  636. return ret;
  637. }
  638. Vector<Transform2D> EditorSceneImporterGLTF::_decode_accessor_as_xform2d(GLTFState &state, int p_accessor, bool p_for_vertex) {
  639. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  640. Vector<Transform2D> ret;
  641. if (attribs.size() == 0)
  642. return ret;
  643. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  644. ret.resize(attribs.size() / 4);
  645. for (int i = 0; i < ret.size(); i++) {
  646. ret.write[i][0] = Vector2(attribs[i * 4 + 0], attribs[i * 4 + 1]);
  647. ret.write[i][1] = Vector2(attribs[i * 4 + 2], attribs[i * 4 + 3]);
  648. }
  649. return ret;
  650. }
  651. Vector<Basis> EditorSceneImporterGLTF::_decode_accessor_as_basis(GLTFState &state, int p_accessor, bool p_for_vertex) {
  652. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  653. Vector<Basis> ret;
  654. if (attribs.size() == 0)
  655. return ret;
  656. ERR_FAIL_COND_V(attribs.size() % 9 != 0, ret);
  657. ret.resize(attribs.size() / 9);
  658. for (int i = 0; i < ret.size(); i++) {
  659. ret.write[i].set_axis(0, Vector3(attribs[i * 9 + 0], attribs[i * 9 + 1], attribs[i * 9 + 2]));
  660. ret.write[i].set_axis(1, Vector3(attribs[i * 9 + 3], attribs[i * 9 + 4], attribs[i * 9 + 5]));
  661. ret.write[i].set_axis(2, Vector3(attribs[i * 9 + 6], attribs[i * 9 + 7], attribs[i * 9 + 8]));
  662. }
  663. return ret;
  664. }
  665. Vector<Transform> EditorSceneImporterGLTF::_decode_accessor_as_xform(GLTFState &state, int p_accessor, bool p_for_vertex) {
  666. Vector<double> attribs = _decode_accessor(state, p_accessor, p_for_vertex);
  667. Vector<Transform> ret;
  668. if (attribs.size() == 0)
  669. return ret;
  670. ERR_FAIL_COND_V(attribs.size() % 16 != 0, ret);
  671. ret.resize(attribs.size() / 16);
  672. for (int i = 0; i < ret.size(); i++) {
  673. ret.write[i].basis.set_axis(0, Vector3(attribs[i * 16 + 0], attribs[i * 16 + 1], attribs[i * 16 + 2]));
  674. ret.write[i].basis.set_axis(1, Vector3(attribs[i * 16 + 4], attribs[i * 16 + 5], attribs[i * 16 + 6]));
  675. ret.write[i].basis.set_axis(2, Vector3(attribs[i * 16 + 8], attribs[i * 16 + 9], attribs[i * 16 + 10]));
  676. ret.write[i].set_origin(Vector3(attribs[i * 16 + 12], attribs[i * 16 + 13], attribs[i * 16 + 14]));
  677. }
  678. return ret;
  679. }
  680. Error EditorSceneImporterGLTF::_parse_meshes(GLTFState &state) {
  681. if (!state.json.has("meshes"))
  682. return OK;
  683. Array meshes = state.json["meshes"];
  684. for (int i = 0; i < meshes.size(); i++) {
  685. print_verbose("glTF: Parsing mesh: " + itos(i));
  686. Dictionary d = meshes[i];
  687. GLTFMesh mesh;
  688. mesh.mesh.instance();
  689. ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR);
  690. Array primitives = d["primitives"];
  691. Dictionary extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary();
  692. for (int j = 0; j < primitives.size(); j++) {
  693. Dictionary p = primitives[j];
  694. Array array;
  695. array.resize(Mesh::ARRAY_MAX);
  696. ERR_FAIL_COND_V(!p.has("attributes"), ERR_PARSE_ERROR);
  697. Dictionary a = p["attributes"];
  698. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  699. if (p.has("mode")) {
  700. int mode = p["mode"];
  701. ERR_FAIL_INDEX_V(mode, 7, ERR_FILE_CORRUPT);
  702. static const Mesh::PrimitiveType primitives[7] = {
  703. Mesh::PRIMITIVE_POINTS,
  704. Mesh::PRIMITIVE_LINES,
  705. Mesh::PRIMITIVE_LINE_LOOP,
  706. Mesh::PRIMITIVE_LINE_STRIP,
  707. Mesh::PRIMITIVE_TRIANGLES,
  708. Mesh::PRIMITIVE_TRIANGLE_STRIP,
  709. Mesh::PRIMITIVE_TRIANGLE_FAN,
  710. };
  711. primitive = primitives[mode];
  712. }
  713. if (a.has("POSITION")) {
  714. array[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(state, a["POSITION"], true);
  715. }
  716. if (a.has("NORMAL")) {
  717. array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(state, a["NORMAL"], true);
  718. }
  719. if (a.has("TANGENT")) {
  720. array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(state, a["TANGENT"], true);
  721. }
  722. if (a.has("TEXCOORD_0")) {
  723. array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(state, a["TEXCOORD_0"], true);
  724. }
  725. if (a.has("TEXCOORD_1")) {
  726. array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(state, a["TEXCOORD_1"], true);
  727. }
  728. if (a.has("COLOR_0")) {
  729. array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(state, a["COLOR_0"], true);
  730. }
  731. if (a.has("JOINTS_0")) {
  732. array[Mesh::ARRAY_BONES] = _decode_accessor_as_ints(state, a["JOINTS_0"], true);
  733. }
  734. if (a.has("WEIGHTS_0")) {
  735. PoolVector<float> weights = _decode_accessor_as_floats(state, a["WEIGHTS_0"], true);
  736. { //gltf does not seem to normalize the weights for some reason..
  737. int wc = weights.size();
  738. PoolVector<float>::Write w = weights.write();
  739. //PoolVector<int> v = array[Mesh::ARRAY_BONES];
  740. //PoolVector<int>::Read r = v.read();
  741. for (int j = 0; j < wc; j += 4) {
  742. float total = 0.0;
  743. total += w[j + 0];
  744. total += w[j + 1];
  745. total += w[j + 2];
  746. total += w[j + 3];
  747. if (total > 0.0) {
  748. w[j + 0] /= total;
  749. w[j + 1] /= total;
  750. w[j + 2] /= total;
  751. w[j + 3] /= total;
  752. }
  753. //print_verbose(itos(j / 4) + ": " + itos(r[j + 0]) + ":" + rtos(w[j + 0]) + ", " + itos(r[j + 1]) + ":" + rtos(w[j + 1]) + ", " + itos(r[j + 2]) + ":" + rtos(w[j + 2]) + ", " + itos(r[j + 3]) + ":" + rtos(w[j + 3]));
  754. }
  755. }
  756. array[Mesh::ARRAY_WEIGHTS] = weights;
  757. }
  758. if (p.has("indices")) {
  759. PoolVector<int> indices = _decode_accessor_as_ints(state, p["indices"], false);
  760. if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  761. //swap around indices, convert ccw to cw for front face
  762. int is = indices.size();
  763. PoolVector<int>::Write w = indices.write();
  764. for (int i = 0; i < is; i += 3) {
  765. SWAP(w[i + 1], w[i + 2]);
  766. }
  767. }
  768. array[Mesh::ARRAY_INDEX] = indices;
  769. } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  770. //generate indices because they need to be swapped for CW/CCW
  771. PoolVector<Vector3> vertices = array[Mesh::ARRAY_VERTEX];
  772. ERR_FAIL_COND_V(vertices.size() == 0, ERR_PARSE_ERROR);
  773. PoolVector<int> indices;
  774. int vs = vertices.size();
  775. indices.resize(vs);
  776. {
  777. PoolVector<int>::Write w = indices.write();
  778. for (int i = 0; i < vs; i += 3) {
  779. w[i] = i;
  780. w[i + 1] = i + 2;
  781. w[i + 2] = i + 1;
  782. }
  783. }
  784. array[Mesh::ARRAY_INDEX] = indices;
  785. }
  786. bool generated_tangents = false;
  787. Variant erased_indices;
  788. if (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("TEXCOORD_0") && a.has("NORMAL")) {
  789. //must generate mikktspace tangents.. ergh..
  790. Ref<SurfaceTool> st;
  791. st.instance();
  792. st->create_from_triangle_arrays(array);
  793. if (p.has("targets")) {
  794. //morph targets should not be reindexed, as array size might differ
  795. //removing indices is the best bet here
  796. st->deindex();
  797. erased_indices = a[Mesh::ARRAY_INDEX];
  798. a[Mesh::ARRAY_INDEX] = Variant();
  799. }
  800. st->generate_tangents();
  801. array = st->commit_to_arrays();
  802. generated_tangents = true;
  803. }
  804. Array morphs;
  805. //blend shapes
  806. if (p.has("targets")) {
  807. print_verbose("glTF: Mesh has targets");
  808. Array targets = p["targets"];
  809. //ideally BLEND_SHAPE_MODE_RELATIVE since gltf2 stores in displacement
  810. //but it could require a larger refactor?
  811. mesh.mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  812. if (j == 0) {
  813. Array target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array();
  814. for (int k = 0; k < targets.size(); k++) {
  815. String name = k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k);
  816. mesh.mesh->add_blend_shape(name);
  817. }
  818. }
  819. for (int k = 0; k < targets.size(); k++) {
  820. Dictionary t = targets[k];
  821. Array array_copy;
  822. array_copy.resize(Mesh::ARRAY_MAX);
  823. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  824. array_copy[l] = array[l];
  825. }
  826. array_copy[Mesh::ARRAY_INDEX] = Variant();
  827. if (t.has("POSITION")) {
  828. PoolVector<Vector3> varr = _decode_accessor_as_vec3(state, t["POSITION"], true);
  829. PoolVector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  830. int size = src_varr.size();
  831. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  832. {
  833. PoolVector<Vector3>::Write w_varr = varr.write();
  834. PoolVector<Vector3>::Read r_varr = varr.read();
  835. PoolVector<Vector3>::Read r_src_varr = src_varr.read();
  836. for (int l = 0; l < size; l++) {
  837. w_varr[l] = r_varr[l] + r_src_varr[l];
  838. }
  839. }
  840. array_copy[Mesh::ARRAY_VERTEX] = varr;
  841. }
  842. if (t.has("NORMAL")) {
  843. PoolVector<Vector3> narr = _decode_accessor_as_vec3(state, t["NORMAL"], true);
  844. PoolVector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  845. int size = src_narr.size();
  846. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  847. {
  848. PoolVector<Vector3>::Write w_narr = narr.write();
  849. PoolVector<Vector3>::Read r_narr = narr.read();
  850. PoolVector<Vector3>::Read r_src_narr = src_narr.read();
  851. for (int l = 0; l < size; l++) {
  852. w_narr[l] = r_narr[l] + r_src_narr[l];
  853. }
  854. }
  855. array_copy[Mesh::ARRAY_NORMAL] = narr;
  856. }
  857. if (t.has("TANGENT")) {
  858. PoolVector<Vector3> tangents_v3 = _decode_accessor_as_vec3(state, t["TANGENT"], true);
  859. PoolVector<float> tangents_v4;
  860. PoolVector<float> src_tangents = array[Mesh::ARRAY_TANGENT];
  861. ERR_FAIL_COND_V(src_tangents.size() == 0, ERR_PARSE_ERROR);
  862. {
  863. int size4 = src_tangents.size();
  864. tangents_v4.resize(size4);
  865. PoolVector<float>::Write w4 = tangents_v4.write();
  866. PoolVector<Vector3>::Read r3 = tangents_v3.read();
  867. PoolVector<float>::Read r4 = src_tangents.read();
  868. for (int l = 0; l < size4 / 4; l++) {
  869. w4[l * 4 + 0] = r3[l].x + r4[l * 4 + 0];
  870. w4[l * 4 + 1] = r3[l].y + r4[l * 4 + 1];
  871. w4[l * 4 + 2] = r3[l].z + r4[l * 4 + 2];
  872. w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value
  873. }
  874. }
  875. array_copy[Mesh::ARRAY_TANGENT] = tangents_v4;
  876. }
  877. if (generated_tangents) {
  878. Ref<SurfaceTool> st;
  879. st.instance();
  880. array_copy[Mesh::ARRAY_INDEX] = erased_indices; //needed for tangent generation, erased by deindex
  881. st->create_from_triangle_arrays(array_copy);
  882. st->deindex();
  883. st->generate_tangents();
  884. array_copy = st->commit_to_arrays();
  885. }
  886. morphs.push_back(array_copy);
  887. }
  888. }
  889. //just add it
  890. mesh.mesh->add_surface_from_arrays(primitive, array, morphs);
  891. if (p.has("material")) {
  892. int material = p["material"];
  893. ERR_FAIL_INDEX_V(material, state.materials.size(), ERR_FILE_CORRUPT);
  894. Ref<Material> mat = state.materials[material];
  895. mesh.mesh->surface_set_material(mesh.mesh->get_surface_count() - 1, mat);
  896. }
  897. }
  898. if (d.has("weights")) {
  899. Array weights = d["weights"];
  900. ERR_FAIL_COND_V(mesh.mesh->get_blend_shape_count() != weights.size(), ERR_PARSE_ERROR);
  901. mesh.blend_weights.resize(weights.size());
  902. for (int j = 0; j < weights.size(); j++) {
  903. mesh.blend_weights.write[j] = weights[j];
  904. }
  905. }
  906. state.meshes.push_back(mesh);
  907. }
  908. print_verbose("glTF: Total meshes: " + itos(state.meshes.size()));
  909. return OK;
  910. }
  911. Error EditorSceneImporterGLTF::_parse_images(GLTFState &state, const String &p_base_path) {
  912. if (!state.json.has("images"))
  913. return OK;
  914. Array images = state.json["images"];
  915. for (int i = 0; i < images.size(); i++) {
  916. Dictionary d = images[i];
  917. String mimetype;
  918. if (d.has("mimeType")) {
  919. mimetype = d["mimeType"];
  920. }
  921. Vector<uint8_t> data;
  922. const uint8_t *data_ptr = NULL;
  923. int data_size = 0;
  924. if (d.has("uri")) {
  925. String uri = d["uri"];
  926. if (uri.findn("data:application/octet-stream;base64") == 0 ||
  927. uri.findn("data:" + mimetype + ";base64") == 0) {
  928. //embedded data
  929. data = _parse_base64_uri(uri);
  930. data_ptr = data.ptr();
  931. data_size = data.size();
  932. } else {
  933. uri = p_base_path.plus_file(uri).replace("\\", "/"); //fix for windows
  934. Ref<Texture> texture = ResourceLoader::load(uri);
  935. state.images.push_back(texture);
  936. continue;
  937. }
  938. }
  939. if (d.has("bufferView")) {
  940. int bvi = d["bufferView"];
  941. ERR_FAIL_INDEX_V(bvi, state.buffer_views.size(), ERR_PARAMETER_RANGE_ERROR);
  942. const GLTFBufferView &bv = state.buffer_views[bvi];
  943. int bi = bv.buffer;
  944. ERR_FAIL_INDEX_V(bi, state.buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  945. ERR_FAIL_COND_V(bv.byte_offset + bv.byte_length > state.buffers[bi].size(), ERR_FILE_CORRUPT);
  946. data_ptr = &state.buffers[bi][bv.byte_offset];
  947. data_size = bv.byte_length;
  948. }
  949. ERR_FAIL_COND_V(mimetype == "", ERR_FILE_CORRUPT);
  950. if (mimetype.findn("png") != -1) {
  951. //is a png
  952. Ref<Image> img = Image::_png_mem_loader_func(data_ptr, data_size);
  953. ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT);
  954. Ref<ImageTexture> t;
  955. t.instance();
  956. t->create_from_image(img);
  957. state.images.push_back(t);
  958. continue;
  959. }
  960. if (mimetype.findn("jpeg") != -1) {
  961. //is a jpg
  962. Ref<Image> img = Image::_jpg_mem_loader_func(data_ptr, data_size);
  963. ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT);
  964. Ref<ImageTexture> t;
  965. t.instance();
  966. t->create_from_image(img);
  967. state.images.push_back(t);
  968. continue;
  969. }
  970. ERR_FAIL_V(ERR_FILE_CORRUPT);
  971. }
  972. print_verbose("Total images: " + itos(state.images.size()));
  973. return OK;
  974. }
  975. Error EditorSceneImporterGLTF::_parse_textures(GLTFState &state) {
  976. if (!state.json.has("textures"))
  977. return OK;
  978. Array textures = state.json["textures"];
  979. for (int i = 0; i < textures.size(); i++) {
  980. Dictionary d = textures[i];
  981. ERR_FAIL_COND_V(!d.has("source"), ERR_PARSE_ERROR);
  982. GLTFTexture t;
  983. t.src_image = d["source"];
  984. state.textures.push_back(t);
  985. }
  986. return OK;
  987. }
  988. Ref<Texture> EditorSceneImporterGLTF::_get_texture(GLTFState &state, int p_texture) {
  989. ERR_FAIL_INDEX_V(p_texture, state.textures.size(), Ref<Texture>());
  990. int image = state.textures[p_texture].src_image;
  991. ERR_FAIL_INDEX_V(image, state.images.size(), Ref<Texture>());
  992. return state.images[image];
  993. }
  994. Error EditorSceneImporterGLTF::_parse_materials(GLTFState &state) {
  995. if (!state.json.has("materials"))
  996. return OK;
  997. Array materials = state.json["materials"];
  998. for (int i = 0; i < materials.size(); i++) {
  999. Dictionary d = materials[i];
  1000. Ref<SpatialMaterial> material;
  1001. material.instance();
  1002. if (d.has("name")) {
  1003. material->set_name(d["name"]);
  1004. }
  1005. if (d.has("pbrMetallicRoughness")) {
  1006. Dictionary mr = d["pbrMetallicRoughness"];
  1007. if (mr.has("baseColorFactor")) {
  1008. Array arr = mr["baseColorFactor"];
  1009. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  1010. Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb();
  1011. material->set_albedo(c);
  1012. }
  1013. if (mr.has("baseColorTexture")) {
  1014. Dictionary bct = mr["baseColorTexture"];
  1015. if (bct.has("index")) {
  1016. material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, _get_texture(state, bct["index"]));
  1017. }
  1018. if (!mr.has("baseColorFactor")) {
  1019. material->set_albedo(Color(1, 1, 1));
  1020. }
  1021. }
  1022. if (mr.has("metallicFactor")) {
  1023. material->set_metallic(mr["metallicFactor"]);
  1024. } else {
  1025. material->set_metallic(1.0);
  1026. }
  1027. if (mr.has("roughnessFactor")) {
  1028. material->set_roughness(mr["roughnessFactor"]);
  1029. } else {
  1030. material->set_roughness(1.0);
  1031. }
  1032. if (mr.has("metallicRoughnessTexture")) {
  1033. Dictionary bct = mr["metallicRoughnessTexture"];
  1034. if (bct.has("index")) {
  1035. Ref<Texture> t = _get_texture(state, bct["index"]);
  1036. material->set_texture(SpatialMaterial::TEXTURE_METALLIC, t);
  1037. material->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_BLUE);
  1038. material->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, t);
  1039. material->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GREEN);
  1040. if (!mr.has("metallicFactor")) {
  1041. material->set_metallic(1);
  1042. }
  1043. if (!mr.has("roughnessFactor")) {
  1044. material->set_roughness(1);
  1045. }
  1046. }
  1047. }
  1048. }
  1049. if (d.has("normalTexture")) {
  1050. Dictionary bct = d["normalTexture"];
  1051. if (bct.has("index")) {
  1052. material->set_texture(SpatialMaterial::TEXTURE_NORMAL, _get_texture(state, bct["index"]));
  1053. material->set_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING, true);
  1054. }
  1055. if (bct.has("scale")) {
  1056. material->set_normal_scale(bct["scale"]);
  1057. }
  1058. }
  1059. if (d.has("occlusionTexture")) {
  1060. Dictionary bct = d["occlusionTexture"];
  1061. if (bct.has("index")) {
  1062. material->set_texture(SpatialMaterial::TEXTURE_AMBIENT_OCCLUSION, _get_texture(state, bct["index"]));
  1063. material->set_ao_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_RED);
  1064. material->set_feature(SpatialMaterial::FEATURE_AMBIENT_OCCLUSION, true);
  1065. }
  1066. }
  1067. if (d.has("emissiveFactor")) {
  1068. Array arr = d["emissiveFactor"];
  1069. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  1070. Color c = Color(arr[0], arr[1], arr[2]).to_srgb();
  1071. material->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  1072. material->set_emission(c);
  1073. }
  1074. if (d.has("emissiveTexture")) {
  1075. Dictionary bct = d["emissiveTexture"];
  1076. if (bct.has("index")) {
  1077. material->set_texture(SpatialMaterial::TEXTURE_EMISSION, _get_texture(state, bct["index"]));
  1078. material->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  1079. material->set_emission(Color(0, 0, 0));
  1080. }
  1081. }
  1082. if (d.has("doubleSided")) {
  1083. bool ds = d["doubleSided"];
  1084. if (ds) {
  1085. material->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  1086. }
  1087. }
  1088. if (d.has("alphaMode")) {
  1089. String am = d["alphaMode"];
  1090. if (am != "OPAQUE") {
  1091. material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  1092. }
  1093. }
  1094. state.materials.push_back(material);
  1095. }
  1096. print_verbose("Total materials: " + itos(state.materials.size()));
  1097. return OK;
  1098. }
  1099. Error EditorSceneImporterGLTF::_parse_skins(GLTFState &state) {
  1100. if (!state.json.has("skins"))
  1101. return OK;
  1102. Array skins = state.json["skins"];
  1103. for (int i = 0; i < skins.size(); i++) {
  1104. Dictionary d = skins[i];
  1105. GLTFSkin skin;
  1106. ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR);
  1107. Array joints = d["joints"];
  1108. Vector<Transform> bind_matrices;
  1109. if (d.has("inverseBindMatrices")) {
  1110. bind_matrices = _decode_accessor_as_xform(state, d["inverseBindMatrices"], false);
  1111. ERR_FAIL_COND_V(bind_matrices.size() != joints.size(), ERR_PARSE_ERROR);
  1112. }
  1113. for (int j = 0; j < joints.size(); j++) {
  1114. int index = joints[j];
  1115. ERR_FAIL_INDEX_V(index, state.nodes.size(), ERR_PARSE_ERROR);
  1116. GLTFNode::Joint joint;
  1117. joint.skin = state.skins.size();
  1118. joint.bone = j;
  1119. state.nodes[index]->joints.push_back(joint);
  1120. GLTFSkin::Bone bone;
  1121. bone.node = index;
  1122. if (bind_matrices.size()) {
  1123. bone.inverse_bind = bind_matrices[j];
  1124. }
  1125. skin.bones.push_back(bone);
  1126. }
  1127. print_verbose("glTF: Skin has skeleton? " + itos(d.has("skeleton")));
  1128. if (d.has("skeleton")) {
  1129. int skeleton = d["skeleton"];
  1130. ERR_FAIL_INDEX_V(skeleton, state.nodes.size(), ERR_PARSE_ERROR);
  1131. print_verbose("glTF: Setting skeleton skin to" + itos(skeleton));
  1132. skin.skeleton = skeleton;
  1133. if (!state.skeleton_nodes.has(skeleton)) {
  1134. state.skeleton_nodes[skeleton] = Vector<int>();
  1135. }
  1136. state.skeleton_nodes[skeleton].push_back(i);
  1137. }
  1138. if (d.has("name")) {
  1139. skin.name = d["name"];
  1140. }
  1141. //locate the right place to put a Skeleton node
  1142. /*
  1143. if (state.skin_users.has(i)) {
  1144. Vector<int> users = state.skin_users[i];
  1145. int skin_node = -1;
  1146. for (int j = 0; j < users.size(); j++) {
  1147. int user = state.nodes[users[j]]->parent; //always go from parent
  1148. if (j == 0) {
  1149. skin_node = user;
  1150. } else if (skin_node != -1) {
  1151. bool found = false;
  1152. while (skin_node >= 0) {
  1153. int cuser = user;
  1154. while (cuser != -1) {
  1155. if (cuser == skin_node) {
  1156. found = true;
  1157. break;
  1158. }
  1159. cuser = state.nodes[skin_node]->parent;
  1160. }
  1161. if (found)
  1162. break;
  1163. skin_node = state.nodes[skin_node]->parent;
  1164. }
  1165. if (!found) {
  1166. skin_node = -1; //just leave where it is
  1167. }
  1168. //find a common parent
  1169. }
  1170. }
  1171. if (skin_node != -1) {
  1172. for (int j = 0; j < users.size(); j++) {
  1173. state.nodes[users[j]]->child_of_skeleton = i;
  1174. }
  1175. state.nodes[skin_node]->skeleton_children.push_back(i);
  1176. }
  1177. }
  1178. */
  1179. state.skins.push_back(skin);
  1180. }
  1181. print_verbose("glTF: Total skins: " + itos(state.skins.size()));
  1182. //now
  1183. return OK;
  1184. }
  1185. Error EditorSceneImporterGLTF::_parse_cameras(GLTFState &state) {
  1186. if (!state.json.has("cameras"))
  1187. return OK;
  1188. Array cameras = state.json["cameras"];
  1189. for (int i = 0; i < cameras.size(); i++) {
  1190. Dictionary d = cameras[i];
  1191. GLTFCamera camera;
  1192. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  1193. String type = d["type"];
  1194. if (type == "orthographic") {
  1195. camera.perspective = false;
  1196. if (d.has("orthographic")) {
  1197. Dictionary og = d["orthographic"];
  1198. camera.fov_size = og["ymag"];
  1199. camera.zfar = og["zfar"];
  1200. camera.znear = og["znear"];
  1201. } else {
  1202. camera.fov_size = 10;
  1203. }
  1204. } else if (type == "perspective") {
  1205. camera.perspective = true;
  1206. if (d.has("perspective")) {
  1207. Dictionary ppt = d["perspective"];
  1208. // GLTF spec is in radians, Godot's camera is in degrees.
  1209. camera.fov_size = (double)ppt["yfov"] * 180.0 / Math_PI;
  1210. camera.zfar = ppt["zfar"];
  1211. camera.znear = ppt["znear"];
  1212. } else {
  1213. camera.fov_size = 10;
  1214. }
  1215. } else {
  1216. ERR_EXPLAIN("Camera should be in 'orthographic' or 'perspective'");
  1217. ERR_FAIL_V(ERR_PARSE_ERROR);
  1218. }
  1219. state.cameras.push_back(camera);
  1220. }
  1221. print_verbose("glTF: Total cameras: " + itos(state.cameras.size()));
  1222. return OK;
  1223. }
  1224. Error EditorSceneImporterGLTF::_parse_animations(GLTFState &state) {
  1225. if (!state.json.has("animations"))
  1226. return OK;
  1227. Array animations = state.json["animations"];
  1228. for (int i = 0; i < animations.size(); i++) {
  1229. Dictionary d = animations[i];
  1230. GLTFAnimation animation;
  1231. if (!d.has("channels") || !d.has("samplers"))
  1232. continue;
  1233. Array channels = d["channels"];
  1234. Array samplers = d["samplers"];
  1235. if (d.has("name")) {
  1236. animation.name = d["name"];
  1237. }
  1238. for (int j = 0; j < channels.size(); j++) {
  1239. Dictionary c = channels[j];
  1240. if (!c.has("target"))
  1241. continue;
  1242. Dictionary t = c["target"];
  1243. if (!t.has("node") || !t.has("path")) {
  1244. continue;
  1245. }
  1246. ERR_FAIL_COND_V(!c.has("sampler"), ERR_PARSE_ERROR);
  1247. int sampler = c["sampler"];
  1248. ERR_FAIL_INDEX_V(sampler, samplers.size(), ERR_PARSE_ERROR);
  1249. int node = t["node"];
  1250. String path = t["path"];
  1251. ERR_FAIL_INDEX_V(node, state.nodes.size(), ERR_PARSE_ERROR);
  1252. GLTFAnimation::Track *track = NULL;
  1253. if (!animation.tracks.has(node)) {
  1254. animation.tracks[node] = GLTFAnimation::Track();
  1255. }
  1256. track = &animation.tracks[node];
  1257. Dictionary s = samplers[sampler];
  1258. ERR_FAIL_COND_V(!s.has("input"), ERR_PARSE_ERROR);
  1259. ERR_FAIL_COND_V(!s.has("output"), ERR_PARSE_ERROR);
  1260. int input = s["input"];
  1261. int output = s["output"];
  1262. GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR;
  1263. if (s.has("interpolation")) {
  1264. String in = s["interpolation"];
  1265. if (in == "STEP") {
  1266. interp = GLTFAnimation::INTERP_STEP;
  1267. } else if (in == "LINEAR") {
  1268. interp = GLTFAnimation::INTERP_LINEAR;
  1269. } else if (in == "CATMULLROMSPLINE") {
  1270. interp = GLTFAnimation::INTERP_CATMULLROMSPLINE;
  1271. } else if (in == "CUBICSPLINE") {
  1272. interp = GLTFAnimation::INTERP_CUBIC_SPLINE;
  1273. }
  1274. }
  1275. PoolVector<float> times = _decode_accessor_as_floats(state, input, false);
  1276. if (path == "translation") {
  1277. PoolVector<Vector3> translations = _decode_accessor_as_vec3(state, output, false);
  1278. track->translation_track.interpolation = interp;
  1279. track->translation_track.times = Variant(times); //convert via variant
  1280. track->translation_track.values = Variant(translations); //convert via variant
  1281. } else if (path == "rotation") {
  1282. Vector<Quat> rotations = _decode_accessor_as_quat(state, output, false);
  1283. track->rotation_track.interpolation = interp;
  1284. track->rotation_track.times = Variant(times); //convert via variant
  1285. track->rotation_track.values = rotations; //convert via variant
  1286. } else if (path == "scale") {
  1287. PoolVector<Vector3> scales = _decode_accessor_as_vec3(state, output, false);
  1288. track->scale_track.interpolation = interp;
  1289. track->scale_track.times = Variant(times); //convert via variant
  1290. track->scale_track.values = Variant(scales); //convert via variant
  1291. } else if (path == "weights") {
  1292. PoolVector<float> weights = _decode_accessor_as_floats(state, output, false);
  1293. ERR_FAIL_INDEX_V(state.nodes[node]->mesh, state.meshes.size(), ERR_PARSE_ERROR);
  1294. const GLTFMesh *mesh = &state.meshes[state.nodes[node]->mesh];
  1295. ERR_FAIL_COND_V(mesh->blend_weights.size() == 0, ERR_PARSE_ERROR);
  1296. int wc = mesh->blend_weights.size();
  1297. track->weight_tracks.resize(wc);
  1298. int wlen = weights.size() / wc;
  1299. PoolVector<float>::Read r = weights.read();
  1300. for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea
  1301. GLTFAnimation::Channel<float> cf;
  1302. cf.interpolation = interp;
  1303. cf.times = Variant(times);
  1304. Vector<float> wdata;
  1305. wdata.resize(wlen);
  1306. for (int l = 0; l < wlen; l++) {
  1307. wdata.write[l] = r[l * wc + k];
  1308. }
  1309. cf.values = wdata;
  1310. track->weight_tracks.write[k] = cf;
  1311. }
  1312. } else {
  1313. WARN_PRINTS("Invalid path: " + path);
  1314. }
  1315. }
  1316. state.animations.push_back(animation);
  1317. }
  1318. print_verbose("glTF: Total animations: " + itos(state.animations.size()));
  1319. return OK;
  1320. }
  1321. void EditorSceneImporterGLTF::_assign_scene_names(GLTFState &state) {
  1322. for (int i = 0; i < state.nodes.size(); i++) {
  1323. GLTFNode *n = state.nodes[i];
  1324. if (n->name == "") {
  1325. if (n->mesh >= 0) {
  1326. n->name = "Mesh";
  1327. } else if (n->joints.size()) {
  1328. n->name = "Bone";
  1329. } else {
  1330. n->name = "Node";
  1331. }
  1332. }
  1333. n->name = _gen_unique_name(state, n->name);
  1334. }
  1335. }
  1336. void EditorSceneImporterGLTF::_generate_node(GLTFState &state, int p_node, Node *p_parent, Node *p_owner, Vector<Skeleton *> &skeletons) {
  1337. ERR_FAIL_INDEX(p_node, state.nodes.size());
  1338. GLTFNode *n = state.nodes[p_node];
  1339. Spatial *node;
  1340. if (n->mesh >= 0) {
  1341. ERR_FAIL_INDEX(n->mesh, state.meshes.size());
  1342. MeshInstance *mi = memnew(MeshInstance);
  1343. print_verbose("glTF: Creating mesh for: " + n->name);
  1344. GLTFMesh &mesh = state.meshes.write[n->mesh];
  1345. mi->set_mesh(mesh.mesh);
  1346. if (mesh.mesh->get_name() == "") {
  1347. mesh.mesh->set_name(n->name);
  1348. }
  1349. for (int i = 0; i < mesh.blend_weights.size(); i++) {
  1350. mi->set("blend_shapes/" + mesh.mesh->get_blend_shape_name(i), mesh.blend_weights[i]);
  1351. }
  1352. node = mi;
  1353. } else if (n->camera >= 0) {
  1354. ERR_FAIL_INDEX(n->camera, state.cameras.size());
  1355. Camera *camera = memnew(Camera);
  1356. const GLTFCamera &c = state.cameras[n->camera];
  1357. if (c.perspective) {
  1358. camera->set_perspective(c.fov_size, c.znear, c.znear);
  1359. } else {
  1360. camera->set_orthogonal(c.fov_size, c.znear, c.znear);
  1361. }
  1362. node = camera;
  1363. } else {
  1364. node = memnew(Spatial);
  1365. }
  1366. node->set_name(n->name);
  1367. n->godot_nodes.push_back(node);
  1368. if (n->skin >= 0 && n->skin < skeletons.size() && Object::cast_to<MeshInstance>(node)) {
  1369. MeshInstance *mi = Object::cast_to<MeshInstance>(node);
  1370. Skeleton *s = skeletons[n->skin];
  1371. s->add_child(node); //According to spec, mesh should actually act as a child of the skeleton, as it inherits its transform
  1372. mi->set_skeleton_path(String(".."));
  1373. } else {
  1374. p_parent->add_child(node);
  1375. node->set_transform(n->xform);
  1376. }
  1377. node->set_owner(p_owner);
  1378. #if 0
  1379. for (int i = 0; i < n->skeleton_children.size(); i++) {
  1380. Skeleton *s = skeletons[n->skeleton_children[i]];
  1381. s->get_parent()->remove_child(s);
  1382. node->add_child(s);
  1383. s->set_owner(p_owner);
  1384. }
  1385. #endif
  1386. for (int i = 0; i < n->children.size(); i++) {
  1387. if (state.nodes[n->children[i]]->joints.size()) {
  1388. _generate_bone(state, n->children[i], skeletons, node);
  1389. } else {
  1390. _generate_node(state, n->children[i], node, p_owner, skeletons);
  1391. }
  1392. }
  1393. }
  1394. void EditorSceneImporterGLTF::_generate_bone(GLTFState &state, int p_node, Vector<Skeleton *> &skeletons, Node *p_parent_node) {
  1395. ERR_FAIL_INDEX(p_node, state.nodes.size());
  1396. if (state.skeleton_nodes.has(p_node)) {
  1397. //reparent skeletons to proper place
  1398. Vector<int> nodes = state.skeleton_nodes[p_node];
  1399. for (int i = 0; i < nodes.size(); i++) {
  1400. Node *owner = skeletons[i]->get_owner();
  1401. skeletons[i]->get_parent()->remove_child(skeletons[i]);
  1402. p_parent_node->add_child(skeletons[i]);
  1403. skeletons[i]->set_owner(owner);
  1404. //may have meshes as children, set owner in them too
  1405. for (int j = 0; j < skeletons[i]->get_child_count(); j++) {
  1406. skeletons[i]->get_child(j)->set_owner(owner);
  1407. }
  1408. }
  1409. }
  1410. GLTFNode *n = state.nodes[p_node];
  1411. for (int i = 0; i < n->joints.size(); i++) {
  1412. const int skin = n->joints[i].skin;
  1413. ERR_FAIL_COND(skin < 0);
  1414. Skeleton *s = skeletons[skin];
  1415. const GLTFNode *gltf_bone_node = state.nodes[state.skins[skin].bones[n->joints[i].bone].node];
  1416. const String bone_name = gltf_bone_node->name;
  1417. const int parent = gltf_bone_node->parent;
  1418. const int parent_index = s->find_bone(state.nodes[parent]->name);
  1419. const int bone_index = s->find_bone(bone_name);
  1420. s->set_bone_parent(bone_index, parent_index);
  1421. n->godot_nodes.push_back(s);
  1422. n->joints.write[i].godot_bone_index = bone_index;
  1423. }
  1424. for (int i = 0; i < n->children.size(); i++) {
  1425. _generate_bone(state, n->children[i], skeletons, p_parent_node);
  1426. }
  1427. }
  1428. template <class T>
  1429. struct EditorSceneImporterGLTFInterpolate {
  1430. T lerp(const T &a, const T &b, float c) const {
  1431. return a + (b - a) * c;
  1432. }
  1433. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  1434. float t2 = t * t;
  1435. float t3 = t2 * t;
  1436. return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
  1437. }
  1438. T bezier(T start, T control_1, T control_2, T end, float t) {
  1439. /* Formula from Wikipedia article on Bezier curves. */
  1440. real_t omt = (1.0 - t);
  1441. real_t omt2 = omt * omt;
  1442. real_t omt3 = omt2 * omt;
  1443. real_t t2 = t * t;
  1444. real_t t3 = t2 * t;
  1445. return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
  1446. }
  1447. };
  1448. //thank you for existing, partial specialization
  1449. template <>
  1450. struct EditorSceneImporterGLTFInterpolate<Quat> {
  1451. Quat lerp(const Quat &a, const Quat &b, float c) const {
  1452. ERR_FAIL_COND_V(!a.is_normalized(), Quat());
  1453. ERR_FAIL_COND_V(!b.is_normalized(), Quat());
  1454. return a.slerp(b, c).normalized();
  1455. }
  1456. Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) {
  1457. ERR_FAIL_COND_V(!p1.is_normalized(), Quat());
  1458. ERR_FAIL_COND_V(!p2.is_normalized(), Quat());
  1459. return p1.slerp(p2, c).normalized();
  1460. }
  1461. Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) {
  1462. ERR_FAIL_COND_V(!start.is_normalized(), Quat());
  1463. ERR_FAIL_COND_V(!end.is_normalized(), Quat());
  1464. return start.slerp(end, t).normalized();
  1465. }
  1466. };
  1467. template <class T>
  1468. T EditorSceneImporterGLTF::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, GLTFAnimation::Interpolation p_interp) {
  1469. //could use binary search, worth it?
  1470. int idx = -1;
  1471. for (int i = 0; i < p_times.size(); i++) {
  1472. if (p_times[i] > p_time)
  1473. break;
  1474. idx++;
  1475. }
  1476. EditorSceneImporterGLTFInterpolate<T> interp;
  1477. switch (p_interp) {
  1478. case GLTFAnimation::INTERP_LINEAR: {
  1479. if (idx == -1) {
  1480. return p_values[0];
  1481. } else if (idx >= p_times.size() - 1) {
  1482. return p_values[p_times.size() - 1];
  1483. }
  1484. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1485. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  1486. } break;
  1487. case GLTFAnimation::INTERP_STEP: {
  1488. if (idx == -1) {
  1489. return p_values[0];
  1490. } else if (idx >= p_times.size() - 1) {
  1491. return p_values[p_times.size() - 1];
  1492. }
  1493. return p_values[idx];
  1494. } break;
  1495. case GLTFAnimation::INTERP_CATMULLROMSPLINE: {
  1496. if (idx == -1) {
  1497. return p_values[1];
  1498. } else if (idx >= p_times.size() - 1) {
  1499. return p_values[1 + p_times.size() - 1];
  1500. }
  1501. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1502. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  1503. } break;
  1504. case GLTFAnimation::INTERP_CUBIC_SPLINE: {
  1505. if (idx == -1) {
  1506. return p_values[1];
  1507. } else if (idx >= p_times.size() - 1) {
  1508. return p_values[(p_times.size() - 1) * 3 + 1];
  1509. }
  1510. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1511. T from = p_values[idx * 3 + 1];
  1512. T c1 = from + p_values[idx * 3 + 2];
  1513. T to = p_values[idx * 3 + 4];
  1514. T c2 = to + p_values[idx * 3 + 3];
  1515. return interp.bezier(from, c1, c2, to, c);
  1516. } break;
  1517. }
  1518. ERR_FAIL_V(p_values[0]);
  1519. }
  1520. void EditorSceneImporterGLTF::_import_animation(GLTFState &state, AnimationPlayer *ap, int index, int bake_fps, Vector<Skeleton *> skeletons) {
  1521. const GLTFAnimation &anim = state.animations[index];
  1522. String name = anim.name;
  1523. if (name == "") {
  1524. name = _gen_unique_name(state, "Animation");
  1525. }
  1526. Ref<Animation> animation;
  1527. animation.instance();
  1528. animation->set_name(name);
  1529. float length = 0;
  1530. for (Map<int, GLTFAnimation::Track>::Element *E = anim.tracks.front(); E; E = E->next()) {
  1531. const GLTFAnimation::Track &track = E->get();
  1532. //need to find the path
  1533. NodePath node_path;
  1534. GLTFNode *node = state.nodes[E->key()];
  1535. for (int n = 0; n < node->godot_nodes.size(); n++) {
  1536. if (node->joints.size()) {
  1537. Skeleton *sk = (Skeleton *)node->godot_nodes[n];
  1538. String path = ap->get_parent()->get_path_to(sk);
  1539. String bone = sk->get_bone_name(node->joints[n].godot_bone_index);
  1540. node_path = path + ":" + bone;
  1541. } else {
  1542. node_path = ap->get_parent()->get_path_to(node->godot_nodes[n]);
  1543. }
  1544. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  1545. length = MAX(length, track.rotation_track.times[i]);
  1546. }
  1547. for (int i = 0; i < track.translation_track.times.size(); i++) {
  1548. length = MAX(length, track.translation_track.times[i]);
  1549. }
  1550. for (int i = 0; i < track.scale_track.times.size(); i++) {
  1551. length = MAX(length, track.scale_track.times[i]);
  1552. }
  1553. for (int i = 0; i < track.weight_tracks.size(); i++) {
  1554. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  1555. length = MAX(length, track.weight_tracks[i].times[j]);
  1556. }
  1557. }
  1558. if (track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) {
  1559. //make transform track
  1560. int track_idx = animation->get_track_count();
  1561. animation->add_track(Animation::TYPE_TRANSFORM);
  1562. animation->track_set_path(track_idx, node_path);
  1563. //first determine animation length
  1564. float increment = 1.0 / float(bake_fps);
  1565. float time = 0.0;
  1566. Vector3 base_pos;
  1567. Quat base_rot;
  1568. Vector3 base_scale = Vector3(1, 1, 1);
  1569. if (!track.rotation_track.values.size()) {
  1570. base_rot = state.nodes[E->key()]->rotation.normalized();
  1571. }
  1572. if (!track.translation_track.values.size()) {
  1573. base_pos = state.nodes[E->key()]->translation;
  1574. }
  1575. if (!track.scale_track.values.size()) {
  1576. base_scale = state.nodes[E->key()]->scale;
  1577. }
  1578. bool last = false;
  1579. while (true) {
  1580. Vector3 pos = base_pos;
  1581. Quat rot = base_rot;
  1582. Vector3 scale = base_scale;
  1583. if (track.translation_track.times.size()) {
  1584. pos = _interpolate_track<Vector3>(track.translation_track.times, track.translation_track.values, time, track.translation_track.interpolation);
  1585. }
  1586. if (track.rotation_track.times.size()) {
  1587. rot = _interpolate_track<Quat>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation);
  1588. }
  1589. if (track.scale_track.times.size()) {
  1590. scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation);
  1591. }
  1592. if (node->joints.size()) {
  1593. Transform xform;
  1594. //xform.basis = Basis(rot);
  1595. //xform.basis.scale(scale);
  1596. xform.basis.set_quat_scale(rot, scale);
  1597. xform.origin = pos;
  1598. Skeleton *skeleton = skeletons[node->joints[n].skin];
  1599. int bone = node->joints[n].godot_bone_index;
  1600. xform = skeleton->get_bone_rest(bone).affine_inverse() * xform;
  1601. rot = xform.basis.get_rotation_quat();
  1602. rot.normalize();
  1603. scale = xform.basis.get_scale();
  1604. pos = xform.origin;
  1605. }
  1606. animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
  1607. if (last) {
  1608. break;
  1609. }
  1610. time += increment;
  1611. if (time >= length) {
  1612. last = true;
  1613. time = length;
  1614. }
  1615. }
  1616. }
  1617. for (int i = 0; i < track.weight_tracks.size(); i++) {
  1618. ERR_CONTINUE(node->mesh < 0 || node->mesh >= state.meshes.size());
  1619. const GLTFMesh &mesh = state.meshes[node->mesh];
  1620. String prop = "blend_shapes/" + mesh.mesh->get_blend_shape_name(i);
  1621. node_path = String(node_path) + ":" + prop;
  1622. int track_idx = animation->get_track_count();
  1623. animation->add_track(Animation::TYPE_VALUE);
  1624. animation->track_set_path(track_idx, node_path);
  1625. if (track.weight_tracks[i].interpolation <= GLTFAnimation::INTERP_STEP) {
  1626. animation->track_set_interpolation_type(track_idx, track.weight_tracks[i].interpolation == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_NEAREST);
  1627. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  1628. float t = track.weight_tracks[i].times[j];
  1629. float w = track.weight_tracks[i].values[j];
  1630. animation->track_insert_key(track_idx, t, w);
  1631. }
  1632. } else {
  1633. //must bake, apologies.
  1634. float increment = 1.0 / float(bake_fps);
  1635. float time = 0.0;
  1636. bool last = false;
  1637. while (true) {
  1638. _interpolate_track<float>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, track.weight_tracks[i].interpolation);
  1639. if (last) {
  1640. break;
  1641. }
  1642. time += increment;
  1643. if (time >= length) {
  1644. last = true;
  1645. time = length;
  1646. }
  1647. }
  1648. }
  1649. }
  1650. }
  1651. }
  1652. animation->set_length(length);
  1653. ap->add_animation(name, animation);
  1654. }
  1655. Spatial *EditorSceneImporterGLTF::_generate_scene(GLTFState &state, int p_bake_fps) {
  1656. Spatial *root = memnew(Spatial);
  1657. root->set_name(state.scene_name);
  1658. //generate skeletons
  1659. Vector<Skeleton *> skeletons;
  1660. for (int i = 0; i < state.skins.size(); i++) {
  1661. Skeleton *s = memnew(Skeleton);
  1662. String name = state.skins[i].name;
  1663. if (name == "") {
  1664. name = _gen_unique_name(state, "Skeleton");
  1665. }
  1666. for (int j = 0; j < state.skins[i].bones.size(); j++) {
  1667. s->add_bone(state.nodes[state.skins[i].bones[j].node]->name);
  1668. s->set_bone_rest(j, state.skins[i].bones[j].inverse_bind.affine_inverse());
  1669. }
  1670. s->set_name(name);
  1671. root->add_child(s);
  1672. s->set_owner(root);
  1673. skeletons.push_back(s);
  1674. }
  1675. for (int i = 0; i < state.root_nodes.size(); i++) {
  1676. if (state.nodes[state.root_nodes[i]]->joints.size()) {
  1677. _generate_bone(state, state.root_nodes[i], skeletons, root);
  1678. } else {
  1679. _generate_node(state, state.root_nodes[i], root, root, skeletons);
  1680. }
  1681. }
  1682. for (int i = 0; i < skeletons.size(); i++) {
  1683. skeletons[i]->localize_rests();
  1684. }
  1685. if (state.animations.size()) {
  1686. AnimationPlayer *ap = memnew(AnimationPlayer);
  1687. ap->set_name("AnimationPlayer");
  1688. root->add_child(ap);
  1689. ap->set_owner(root);
  1690. for (int i = 0; i < state.animations.size(); i++) {
  1691. _import_animation(state, ap, i, p_bake_fps, skeletons);
  1692. }
  1693. }
  1694. return root;
  1695. }
  1696. Node *EditorSceneImporterGLTF::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
  1697. GLTFState state;
  1698. if (p_path.to_lower().ends_with("glb")) {
  1699. //binary file
  1700. //text file
  1701. Error err = _parse_glb(p_path, state);
  1702. if (err)
  1703. return NULL;
  1704. } else {
  1705. //text file
  1706. Error err = _parse_json(p_path, state);
  1707. if (err)
  1708. return NULL;
  1709. }
  1710. ERR_FAIL_COND_V(!state.json.has("asset"), NULL);
  1711. Dictionary asset = state.json["asset"];
  1712. ERR_FAIL_COND_V(!asset.has("version"), NULL);
  1713. String version = asset["version"];
  1714. state.major_version = version.get_slice(".", 0).to_int();
  1715. state.minor_version = version.get_slice(".", 1).to_int();
  1716. /* STEP 0 PARSE SCENE */
  1717. Error err = _parse_scenes(state);
  1718. if (err != OK)
  1719. return NULL;
  1720. /* STEP 1 PARSE NODES */
  1721. err = _parse_nodes(state);
  1722. if (err != OK)
  1723. return NULL;
  1724. /* STEP 2 PARSE BUFFERS */
  1725. err = _parse_buffers(state, p_path.get_base_dir());
  1726. if (err != OK)
  1727. return NULL;
  1728. /* STEP 3 PARSE BUFFER VIEWS */
  1729. err = _parse_buffer_views(state);
  1730. if (err != OK)
  1731. return NULL;
  1732. /* STEP 4 PARSE ACCESSORS */
  1733. err = _parse_accessors(state);
  1734. if (err != OK)
  1735. return NULL;
  1736. /* STEP 5 PARSE IMAGES */
  1737. err = _parse_images(state, p_path.get_base_dir());
  1738. if (err != OK)
  1739. return NULL;
  1740. /* STEP 6 PARSE TEXTURES */
  1741. err = _parse_textures(state);
  1742. if (err != OK)
  1743. return NULL;
  1744. /* STEP 7 PARSE TEXTURES */
  1745. err = _parse_materials(state);
  1746. if (err != OK)
  1747. return NULL;
  1748. /* STEP 8 PARSE MESHES (we have enough info now) */
  1749. err = _parse_meshes(state);
  1750. if (err != OK)
  1751. return NULL;
  1752. /* STEP 9 PARSE SKINS */
  1753. err = _parse_skins(state);
  1754. if (err != OK)
  1755. return NULL;
  1756. /* STEP 10 PARSE CAMERAS */
  1757. err = _parse_cameras(state);
  1758. if (err != OK)
  1759. return NULL;
  1760. /* STEP 11 PARSE ANIMATIONS */
  1761. err = _parse_animations(state);
  1762. if (err != OK)
  1763. return NULL;
  1764. /* STEP 12 ASSIGN SCENE NAMES */
  1765. _assign_scene_names(state);
  1766. /* STEP 13 MAKE SCENE! */
  1767. Spatial *scene = _generate_scene(state, p_bake_fps);
  1768. return scene;
  1769. }
  1770. Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  1771. return Ref<Animation>();
  1772. }
  1773. EditorSceneImporterGLTF::EditorSceneImporterGLTF() {
  1774. }