editor_scene_importer_gltf.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  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 j = 0; j < children.size(); j++) {
  201. node->children.push_back(children[j]);
  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 primitives2[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 = primitives2[mode];
  712. }
  713. ERR_FAIL_COND_V(!a.has("POSITION"), ERR_PARSE_ERROR);
  714. if (a.has("POSITION")) {
  715. array[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(state, a["POSITION"], true);
  716. }
  717. if (a.has("NORMAL")) {
  718. array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(state, a["NORMAL"], true);
  719. }
  720. if (a.has("TANGENT")) {
  721. array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(state, a["TANGENT"], true);
  722. }
  723. if (a.has("TEXCOORD_0")) {
  724. array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(state, a["TEXCOORD_0"], true);
  725. }
  726. if (a.has("TEXCOORD_1")) {
  727. array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(state, a["TEXCOORD_1"], true);
  728. }
  729. if (a.has("COLOR_0")) {
  730. array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(state, a["COLOR_0"], true);
  731. }
  732. if (a.has("JOINTS_0")) {
  733. array[Mesh::ARRAY_BONES] = _decode_accessor_as_ints(state, a["JOINTS_0"], true);
  734. }
  735. if (a.has("WEIGHTS_0")) {
  736. PoolVector<float> weights = _decode_accessor_as_floats(state, a["WEIGHTS_0"], true);
  737. { //gltf does not seem to normalize the weights for some reason..
  738. int wc = weights.size();
  739. PoolVector<float>::Write w = weights.write();
  740. //PoolVector<int> v = array[Mesh::ARRAY_BONES];
  741. //PoolVector<int>::Read r = v.read();
  742. for (int k = 0; k < wc; k += 4) {
  743. float total = 0.0;
  744. total += w[k + 0];
  745. total += w[k + 1];
  746. total += w[k + 2];
  747. total += w[k + 3];
  748. if (total > 0.0) {
  749. w[k + 0] /= total;
  750. w[k + 1] /= total;
  751. w[k + 2] /= total;
  752. w[k + 3] /= total;
  753. }
  754. //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]));
  755. }
  756. }
  757. array[Mesh::ARRAY_WEIGHTS] = weights;
  758. }
  759. if (p.has("indices")) {
  760. PoolVector<int> indices = _decode_accessor_as_ints(state, p["indices"], false);
  761. if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  762. //swap around indices, convert ccw to cw for front face
  763. int is = indices.size();
  764. PoolVector<int>::Write w = indices.write();
  765. for (int k = 0; k < is; k += 3) {
  766. SWAP(w[k + 1], w[k + 2]);
  767. }
  768. }
  769. array[Mesh::ARRAY_INDEX] = indices;
  770. } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  771. //generate indices because they need to be swapped for CW/CCW
  772. PoolVector<Vector3> vertices = array[Mesh::ARRAY_VERTEX];
  773. ERR_FAIL_COND_V(vertices.size() == 0, ERR_PARSE_ERROR);
  774. PoolVector<int> indices;
  775. int vs = vertices.size();
  776. indices.resize(vs);
  777. {
  778. PoolVector<int>::Write w = indices.write();
  779. for (int k = 0; k < vs; k += 3) {
  780. w[k] = k;
  781. w[k + 1] = k + 2;
  782. w[k + 2] = k + 1;
  783. }
  784. }
  785. array[Mesh::ARRAY_INDEX] = indices;
  786. }
  787. bool generated_tangents = false;
  788. Variant erased_indices;
  789. if (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("TEXCOORD_0") && a.has("NORMAL")) {
  790. //must generate mikktspace tangents.. ergh..
  791. Ref<SurfaceTool> st;
  792. st.instance();
  793. st->create_from_triangle_arrays(array);
  794. if (p.has("targets")) {
  795. //morph targets should not be reindexed, as array size might differ
  796. //removing indices is the best bet here
  797. st->deindex();
  798. erased_indices = a[Mesh::ARRAY_INDEX];
  799. a[Mesh::ARRAY_INDEX] = Variant();
  800. }
  801. st->generate_tangents();
  802. array = st->commit_to_arrays();
  803. generated_tangents = true;
  804. }
  805. Array morphs;
  806. //blend shapes
  807. if (p.has("targets")) {
  808. print_verbose("glTF: Mesh has targets");
  809. Array targets = p["targets"];
  810. //ideally BLEND_SHAPE_MODE_RELATIVE since gltf2 stores in displacement
  811. //but it could require a larger refactor?
  812. mesh.mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  813. if (j == 0) {
  814. Array target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array();
  815. for (int k = 0; k < targets.size(); k++) {
  816. String name = k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k);
  817. mesh.mesh->add_blend_shape(name);
  818. }
  819. }
  820. for (int k = 0; k < targets.size(); k++) {
  821. Dictionary t = targets[k];
  822. Array array_copy;
  823. array_copy.resize(Mesh::ARRAY_MAX);
  824. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  825. array_copy[l] = array[l];
  826. }
  827. array_copy[Mesh::ARRAY_INDEX] = Variant();
  828. if (t.has("POSITION")) {
  829. PoolVector<Vector3> varr = _decode_accessor_as_vec3(state, t["POSITION"], true);
  830. PoolVector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  831. int size = src_varr.size();
  832. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  833. {
  834. int max_idx = varr.size();
  835. varr.resize(size);
  836. PoolVector<Vector3>::Write w_varr = varr.write();
  837. PoolVector<Vector3>::Read r_varr = varr.read();
  838. PoolVector<Vector3>::Read r_src_varr = src_varr.read();
  839. for (int l = 0; l < size; l++) {
  840. if (l < max_idx) {
  841. w_varr[l] = r_varr[l] + r_src_varr[l];
  842. } else {
  843. w_varr[l] = r_src_varr[l];
  844. }
  845. }
  846. }
  847. array_copy[Mesh::ARRAY_VERTEX] = varr;
  848. }
  849. if (t.has("NORMAL")) {
  850. PoolVector<Vector3> narr = _decode_accessor_as_vec3(state, t["NORMAL"], true);
  851. PoolVector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  852. int size = src_narr.size();
  853. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  854. {
  855. int max_idx = narr.size();
  856. narr.resize(size);
  857. PoolVector<Vector3>::Write w_narr = narr.write();
  858. PoolVector<Vector3>::Read r_narr = narr.read();
  859. PoolVector<Vector3>::Read r_src_narr = src_narr.read();
  860. for (int l = 0; l < size; l++) {
  861. if (l < max_idx) {
  862. w_narr[l] = r_narr[l] + r_src_narr[l];
  863. } else {
  864. w_narr[l] = r_src_narr[l];
  865. }
  866. }
  867. }
  868. array_copy[Mesh::ARRAY_NORMAL] = narr;
  869. }
  870. if (t.has("TANGENT")) {
  871. PoolVector<Vector3> tangents_v3 = _decode_accessor_as_vec3(state, t["TANGENT"], true);
  872. PoolVector<float> tangents_v4;
  873. PoolVector<float> src_tangents = array[Mesh::ARRAY_TANGENT];
  874. ERR_FAIL_COND_V(src_tangents.size() == 0, ERR_PARSE_ERROR);
  875. {
  876. int max_idx = tangents_v3.size();
  877. int size4 = src_tangents.size();
  878. tangents_v4.resize(size4);
  879. PoolVector<float>::Write w4 = tangents_v4.write();
  880. PoolVector<Vector3>::Read r3 = tangents_v3.read();
  881. PoolVector<float>::Read r4 = src_tangents.read();
  882. for (int l = 0; l < size4 / 4; l++) {
  883. if (l < max_idx) {
  884. w4[l * 4 + 0] = r3[l].x + r4[l * 4 + 0];
  885. w4[l * 4 + 1] = r3[l].y + r4[l * 4 + 1];
  886. w4[l * 4 + 2] = r3[l].z + r4[l * 4 + 2];
  887. } else {
  888. w4[l * 4 + 0] = r4[l * 4 + 0];
  889. w4[l * 4 + 1] = r4[l * 4 + 1];
  890. w4[l * 4 + 2] = r4[l * 4 + 2];
  891. }
  892. w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value
  893. }
  894. }
  895. array_copy[Mesh::ARRAY_TANGENT] = tangents_v4;
  896. }
  897. if (generated_tangents) {
  898. Ref<SurfaceTool> st;
  899. st.instance();
  900. array_copy[Mesh::ARRAY_INDEX] = erased_indices; //needed for tangent generation, erased by deindex
  901. st->create_from_triangle_arrays(array_copy);
  902. st->deindex();
  903. st->generate_tangents();
  904. array_copy = st->commit_to_arrays();
  905. }
  906. morphs.push_back(array_copy);
  907. }
  908. }
  909. //just add it
  910. mesh.mesh->add_surface_from_arrays(primitive, array, morphs);
  911. if (p.has("material")) {
  912. int material = p["material"];
  913. ERR_FAIL_INDEX_V(material, state.materials.size(), ERR_FILE_CORRUPT);
  914. Ref<Material> mat = state.materials[material];
  915. mesh.mesh->surface_set_material(mesh.mesh->get_surface_count() - 1, mat);
  916. }
  917. }
  918. if (d.has("weights")) {
  919. Array weights = d["weights"];
  920. ERR_FAIL_COND_V(mesh.mesh->get_blend_shape_count() != weights.size(), ERR_PARSE_ERROR);
  921. mesh.blend_weights.resize(weights.size());
  922. for (int j = 0; j < weights.size(); j++) {
  923. mesh.blend_weights.write[j] = weights[j];
  924. }
  925. }
  926. state.meshes.push_back(mesh);
  927. }
  928. print_verbose("glTF: Total meshes: " + itos(state.meshes.size()));
  929. return OK;
  930. }
  931. Error EditorSceneImporterGLTF::_parse_images(GLTFState &state, const String &p_base_path) {
  932. if (!state.json.has("images"))
  933. return OK;
  934. Array images = state.json["images"];
  935. for (int i = 0; i < images.size(); i++) {
  936. Dictionary d = images[i];
  937. String mimetype;
  938. if (d.has("mimeType")) {
  939. mimetype = d["mimeType"];
  940. }
  941. Vector<uint8_t> data;
  942. const uint8_t *data_ptr = NULL;
  943. int data_size = 0;
  944. if (d.has("uri")) {
  945. String uri = d["uri"];
  946. if (uri.findn("data:application/octet-stream;base64") == 0 ||
  947. uri.findn("data:" + mimetype + ";base64") == 0) {
  948. //embedded data
  949. data = _parse_base64_uri(uri);
  950. data_ptr = data.ptr();
  951. data_size = data.size();
  952. } else {
  953. uri = p_base_path.plus_file(uri).replace("\\", "/"); //fix for windows
  954. Ref<Texture> texture = ResourceLoader::load(uri);
  955. state.images.push_back(texture);
  956. continue;
  957. }
  958. }
  959. if (d.has("bufferView")) {
  960. int bvi = d["bufferView"];
  961. ERR_FAIL_INDEX_V(bvi, state.buffer_views.size(), ERR_PARAMETER_RANGE_ERROR);
  962. const GLTFBufferView &bv = state.buffer_views[bvi];
  963. int bi = bv.buffer;
  964. ERR_FAIL_INDEX_V(bi, state.buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  965. ERR_FAIL_COND_V(bv.byte_offset + bv.byte_length > state.buffers[bi].size(), ERR_FILE_CORRUPT);
  966. data_ptr = &state.buffers[bi][bv.byte_offset];
  967. data_size = bv.byte_length;
  968. }
  969. ERR_FAIL_COND_V(mimetype == "", ERR_FILE_CORRUPT);
  970. if (mimetype.findn("png") != -1) {
  971. //is a png
  972. Ref<Image> img = Image::_png_mem_loader_func(data_ptr, data_size);
  973. ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT);
  974. Ref<ImageTexture> t;
  975. t.instance();
  976. t->create_from_image(img);
  977. state.images.push_back(t);
  978. continue;
  979. }
  980. if (mimetype.findn("jpeg") != -1) {
  981. //is a jpg
  982. Ref<Image> img = Image::_jpg_mem_loader_func(data_ptr, data_size);
  983. ERR_FAIL_COND_V(img.is_null(), ERR_FILE_CORRUPT);
  984. Ref<ImageTexture> t;
  985. t.instance();
  986. t->create_from_image(img);
  987. state.images.push_back(t);
  988. continue;
  989. }
  990. ERR_FAIL_V(ERR_FILE_CORRUPT);
  991. }
  992. print_verbose("Total images: " + itos(state.images.size()));
  993. return OK;
  994. }
  995. Error EditorSceneImporterGLTF::_parse_textures(GLTFState &state) {
  996. if (!state.json.has("textures"))
  997. return OK;
  998. Array textures = state.json["textures"];
  999. for (int i = 0; i < textures.size(); i++) {
  1000. Dictionary d = textures[i];
  1001. ERR_FAIL_COND_V(!d.has("source"), ERR_PARSE_ERROR);
  1002. GLTFTexture t;
  1003. t.src_image = d["source"];
  1004. state.textures.push_back(t);
  1005. }
  1006. return OK;
  1007. }
  1008. Ref<Texture> EditorSceneImporterGLTF::_get_texture(GLTFState &state, int p_texture) {
  1009. ERR_FAIL_INDEX_V(p_texture, state.textures.size(), Ref<Texture>());
  1010. int image = state.textures[p_texture].src_image;
  1011. ERR_FAIL_INDEX_V(image, state.images.size(), Ref<Texture>());
  1012. return state.images[image];
  1013. }
  1014. Error EditorSceneImporterGLTF::_parse_materials(GLTFState &state) {
  1015. if (!state.json.has("materials"))
  1016. return OK;
  1017. Array materials = state.json["materials"];
  1018. for (int i = 0; i < materials.size(); i++) {
  1019. Dictionary d = materials[i];
  1020. Ref<SpatialMaterial> material;
  1021. material.instance();
  1022. if (d.has("name")) {
  1023. material->set_name(d["name"]);
  1024. }
  1025. if (d.has("pbrMetallicRoughness")) {
  1026. Dictionary mr = d["pbrMetallicRoughness"];
  1027. if (mr.has("baseColorFactor")) {
  1028. Array arr = mr["baseColorFactor"];
  1029. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  1030. Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb();
  1031. material->set_albedo(c);
  1032. }
  1033. if (mr.has("baseColorTexture")) {
  1034. Dictionary bct = mr["baseColorTexture"];
  1035. if (bct.has("index")) {
  1036. material->set_texture(SpatialMaterial::TEXTURE_ALBEDO, _get_texture(state, bct["index"]));
  1037. }
  1038. if (!mr.has("baseColorFactor")) {
  1039. material->set_albedo(Color(1, 1, 1));
  1040. }
  1041. }
  1042. if (mr.has("metallicFactor")) {
  1043. material->set_metallic(mr["metallicFactor"]);
  1044. } else {
  1045. material->set_metallic(1.0);
  1046. }
  1047. if (mr.has("roughnessFactor")) {
  1048. material->set_roughness(mr["roughnessFactor"]);
  1049. } else {
  1050. material->set_roughness(1.0);
  1051. }
  1052. if (mr.has("metallicRoughnessTexture")) {
  1053. Dictionary bct = mr["metallicRoughnessTexture"];
  1054. if (bct.has("index")) {
  1055. Ref<Texture> t = _get_texture(state, bct["index"]);
  1056. material->set_texture(SpatialMaterial::TEXTURE_METALLIC, t);
  1057. material->set_metallic_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_BLUE);
  1058. material->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, t);
  1059. material->set_roughness_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_GREEN);
  1060. if (!mr.has("metallicFactor")) {
  1061. material->set_metallic(1);
  1062. }
  1063. if (!mr.has("roughnessFactor")) {
  1064. material->set_roughness(1);
  1065. }
  1066. }
  1067. }
  1068. }
  1069. if (d.has("normalTexture")) {
  1070. Dictionary bct = d["normalTexture"];
  1071. if (bct.has("index")) {
  1072. material->set_texture(SpatialMaterial::TEXTURE_NORMAL, _get_texture(state, bct["index"]));
  1073. material->set_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING, true);
  1074. }
  1075. if (bct.has("scale")) {
  1076. material->set_normal_scale(bct["scale"]);
  1077. }
  1078. }
  1079. if (d.has("occlusionTexture")) {
  1080. Dictionary bct = d["occlusionTexture"];
  1081. if (bct.has("index")) {
  1082. material->set_texture(SpatialMaterial::TEXTURE_AMBIENT_OCCLUSION, _get_texture(state, bct["index"]));
  1083. material->set_ao_texture_channel(SpatialMaterial::TEXTURE_CHANNEL_RED);
  1084. material->set_feature(SpatialMaterial::FEATURE_AMBIENT_OCCLUSION, true);
  1085. }
  1086. }
  1087. if (d.has("emissiveFactor")) {
  1088. Array arr = d["emissiveFactor"];
  1089. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  1090. Color c = Color(arr[0], arr[1], arr[2]).to_srgb();
  1091. material->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  1092. material->set_emission(c);
  1093. }
  1094. if (d.has("emissiveTexture")) {
  1095. Dictionary bct = d["emissiveTexture"];
  1096. if (bct.has("index")) {
  1097. material->set_texture(SpatialMaterial::TEXTURE_EMISSION, _get_texture(state, bct["index"]));
  1098. material->set_feature(SpatialMaterial::FEATURE_EMISSION, true);
  1099. material->set_emission(Color(0, 0, 0));
  1100. }
  1101. }
  1102. if (d.has("doubleSided")) {
  1103. bool ds = d["doubleSided"];
  1104. if (ds) {
  1105. material->set_cull_mode(SpatialMaterial::CULL_DISABLED);
  1106. }
  1107. }
  1108. if (d.has("alphaMode")) {
  1109. String am = d["alphaMode"];
  1110. if (am != "OPAQUE") {
  1111. material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  1112. }
  1113. }
  1114. state.materials.push_back(material);
  1115. }
  1116. print_verbose("Total materials: " + itos(state.materials.size()));
  1117. return OK;
  1118. }
  1119. Error EditorSceneImporterGLTF::_parse_skins(GLTFState &state) {
  1120. if (!state.json.has("skins"))
  1121. return OK;
  1122. Array skins = state.json["skins"];
  1123. for (int i = 0; i < skins.size(); i++) {
  1124. Dictionary d = skins[i];
  1125. GLTFSkin skin;
  1126. ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR);
  1127. Array joints = d["joints"];
  1128. Vector<Transform> bind_matrices;
  1129. if (d.has("inverseBindMatrices")) {
  1130. bind_matrices = _decode_accessor_as_xform(state, d["inverseBindMatrices"], false);
  1131. ERR_FAIL_COND_V(bind_matrices.size() != joints.size(), ERR_PARSE_ERROR);
  1132. }
  1133. for (int j = 0; j < joints.size(); j++) {
  1134. int index = joints[j];
  1135. ERR_FAIL_INDEX_V(index, state.nodes.size(), ERR_PARSE_ERROR);
  1136. GLTFNode::Joint joint;
  1137. joint.skin = state.skins.size();
  1138. joint.bone = j;
  1139. state.nodes[index]->joints.push_back(joint);
  1140. GLTFSkin::Bone bone;
  1141. bone.node = index;
  1142. if (bind_matrices.size()) {
  1143. bone.inverse_bind = bind_matrices[j];
  1144. }
  1145. skin.bones.push_back(bone);
  1146. }
  1147. print_verbose("glTF: Skin has skeleton? " + itos(d.has("skeleton")));
  1148. if (d.has("skeleton")) {
  1149. int skeleton = d["skeleton"];
  1150. ERR_FAIL_INDEX_V(skeleton, state.nodes.size(), ERR_PARSE_ERROR);
  1151. print_verbose("glTF: Setting skeleton skin to" + itos(skeleton));
  1152. skin.skeleton = skeleton;
  1153. if (!state.skeleton_nodes.has(skeleton)) {
  1154. state.skeleton_nodes[skeleton] = Vector<int>();
  1155. }
  1156. state.skeleton_nodes[skeleton].push_back(i);
  1157. }
  1158. if (d.has("name")) {
  1159. skin.name = d["name"];
  1160. }
  1161. //locate the right place to put a Skeleton node
  1162. /*
  1163. if (state.skin_users.has(i)) {
  1164. Vector<int> users = state.skin_users[i];
  1165. int skin_node = -1;
  1166. for (int j = 0; j < users.size(); j++) {
  1167. int user = state.nodes[users[j]]->parent; //always go from parent
  1168. if (j == 0) {
  1169. skin_node = user;
  1170. } else if (skin_node != -1) {
  1171. bool found = false;
  1172. while (skin_node >= 0) {
  1173. int cuser = user;
  1174. while (cuser != -1) {
  1175. if (cuser == skin_node) {
  1176. found = true;
  1177. break;
  1178. }
  1179. cuser = state.nodes[skin_node]->parent;
  1180. }
  1181. if (found)
  1182. break;
  1183. skin_node = state.nodes[skin_node]->parent;
  1184. }
  1185. if (!found) {
  1186. skin_node = -1; //just leave where it is
  1187. }
  1188. //find a common parent
  1189. }
  1190. }
  1191. if (skin_node != -1) {
  1192. for (int j = 0; j < users.size(); j++) {
  1193. state.nodes[users[j]]->child_of_skeleton = i;
  1194. }
  1195. state.nodes[skin_node]->skeleton_children.push_back(i);
  1196. }
  1197. }
  1198. */
  1199. state.skins.push_back(skin);
  1200. }
  1201. print_verbose("glTF: Total skins: " + itos(state.skins.size()));
  1202. //now
  1203. return OK;
  1204. }
  1205. Error EditorSceneImporterGLTF::_parse_cameras(GLTFState &state) {
  1206. if (!state.json.has("cameras"))
  1207. return OK;
  1208. Array cameras = state.json["cameras"];
  1209. for (int i = 0; i < cameras.size(); i++) {
  1210. Dictionary d = cameras[i];
  1211. GLTFCamera camera;
  1212. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  1213. String type = d["type"];
  1214. if (type == "orthographic") {
  1215. camera.perspective = false;
  1216. if (d.has("orthographic")) {
  1217. Dictionary og = d["orthographic"];
  1218. camera.fov_size = og["ymag"];
  1219. camera.zfar = og["zfar"];
  1220. camera.znear = og["znear"];
  1221. } else {
  1222. camera.fov_size = 10;
  1223. }
  1224. } else if (type == "perspective") {
  1225. camera.perspective = true;
  1226. if (d.has("perspective")) {
  1227. Dictionary ppt = d["perspective"];
  1228. // GLTF spec is in radians, Godot's camera is in degrees.
  1229. camera.fov_size = (double)ppt["yfov"] * 180.0 / Math_PI;
  1230. camera.zfar = ppt["zfar"];
  1231. camera.znear = ppt["znear"];
  1232. } else {
  1233. camera.fov_size = 10;
  1234. }
  1235. } else {
  1236. ERR_EXPLAIN("Camera should be in 'orthographic' or 'perspective'");
  1237. ERR_FAIL_V(ERR_PARSE_ERROR);
  1238. }
  1239. state.cameras.push_back(camera);
  1240. }
  1241. print_verbose("glTF: Total cameras: " + itos(state.cameras.size()));
  1242. return OK;
  1243. }
  1244. Error EditorSceneImporterGLTF::_parse_animations(GLTFState &state) {
  1245. if (!state.json.has("animations"))
  1246. return OK;
  1247. Array animations = state.json["animations"];
  1248. for (int i = 0; i < animations.size(); i++) {
  1249. Dictionary d = animations[i];
  1250. GLTFAnimation animation;
  1251. if (!d.has("channels") || !d.has("samplers"))
  1252. continue;
  1253. Array channels = d["channels"];
  1254. Array samplers = d["samplers"];
  1255. if (d.has("name")) {
  1256. animation.name = d["name"];
  1257. }
  1258. for (int j = 0; j < channels.size(); j++) {
  1259. Dictionary c = channels[j];
  1260. if (!c.has("target"))
  1261. continue;
  1262. Dictionary t = c["target"];
  1263. if (!t.has("node") || !t.has("path")) {
  1264. continue;
  1265. }
  1266. ERR_FAIL_COND_V(!c.has("sampler"), ERR_PARSE_ERROR);
  1267. int sampler = c["sampler"];
  1268. ERR_FAIL_INDEX_V(sampler, samplers.size(), ERR_PARSE_ERROR);
  1269. int node = t["node"];
  1270. String path = t["path"];
  1271. ERR_FAIL_INDEX_V(node, state.nodes.size(), ERR_PARSE_ERROR);
  1272. GLTFAnimation::Track *track = NULL;
  1273. if (!animation.tracks.has(node)) {
  1274. animation.tracks[node] = GLTFAnimation::Track();
  1275. }
  1276. track = &animation.tracks[node];
  1277. Dictionary s = samplers[sampler];
  1278. ERR_FAIL_COND_V(!s.has("input"), ERR_PARSE_ERROR);
  1279. ERR_FAIL_COND_V(!s.has("output"), ERR_PARSE_ERROR);
  1280. int input = s["input"];
  1281. int output = s["output"];
  1282. GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR;
  1283. if (s.has("interpolation")) {
  1284. String in = s["interpolation"];
  1285. if (in == "STEP") {
  1286. interp = GLTFAnimation::INTERP_STEP;
  1287. } else if (in == "LINEAR") {
  1288. interp = GLTFAnimation::INTERP_LINEAR;
  1289. } else if (in == "CATMULLROMSPLINE") {
  1290. interp = GLTFAnimation::INTERP_CATMULLROMSPLINE;
  1291. } else if (in == "CUBICSPLINE") {
  1292. interp = GLTFAnimation::INTERP_CUBIC_SPLINE;
  1293. }
  1294. }
  1295. PoolVector<float> times = _decode_accessor_as_floats(state, input, false);
  1296. if (path == "translation") {
  1297. PoolVector<Vector3> translations = _decode_accessor_as_vec3(state, output, false);
  1298. track->translation_track.interpolation = interp;
  1299. track->translation_track.times = Variant(times); //convert via variant
  1300. track->translation_track.values = Variant(translations); //convert via variant
  1301. } else if (path == "rotation") {
  1302. Vector<Quat> rotations = _decode_accessor_as_quat(state, output, false);
  1303. track->rotation_track.interpolation = interp;
  1304. track->rotation_track.times = Variant(times); //convert via variant
  1305. track->rotation_track.values = rotations; //convert via variant
  1306. } else if (path == "scale") {
  1307. PoolVector<Vector3> scales = _decode_accessor_as_vec3(state, output, false);
  1308. track->scale_track.interpolation = interp;
  1309. track->scale_track.times = Variant(times); //convert via variant
  1310. track->scale_track.values = Variant(scales); //convert via variant
  1311. } else if (path == "weights") {
  1312. PoolVector<float> weights = _decode_accessor_as_floats(state, output, false);
  1313. ERR_FAIL_INDEX_V(state.nodes[node]->mesh, state.meshes.size(), ERR_PARSE_ERROR);
  1314. const GLTFMesh *mesh = &state.meshes[state.nodes[node]->mesh];
  1315. ERR_FAIL_COND_V(mesh->blend_weights.size() == 0, ERR_PARSE_ERROR);
  1316. int wc = mesh->blend_weights.size();
  1317. track->weight_tracks.resize(wc);
  1318. int wlen = weights.size() / wc;
  1319. PoolVector<float>::Read r = weights.read();
  1320. for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea
  1321. GLTFAnimation::Channel<float> cf;
  1322. cf.interpolation = interp;
  1323. cf.times = Variant(times);
  1324. Vector<float> wdata;
  1325. wdata.resize(wlen);
  1326. for (int l = 0; l < wlen; l++) {
  1327. wdata.write[l] = r[l * wc + k];
  1328. }
  1329. cf.values = wdata;
  1330. track->weight_tracks.write[k] = cf;
  1331. }
  1332. } else {
  1333. WARN_PRINTS("Invalid path: " + path);
  1334. }
  1335. }
  1336. state.animations.push_back(animation);
  1337. }
  1338. print_verbose("glTF: Total animations: " + itos(state.animations.size()));
  1339. return OK;
  1340. }
  1341. void EditorSceneImporterGLTF::_assign_scene_names(GLTFState &state) {
  1342. for (int i = 0; i < state.nodes.size(); i++) {
  1343. GLTFNode *n = state.nodes[i];
  1344. if (n->name == "") {
  1345. if (n->mesh >= 0) {
  1346. n->name = "Mesh";
  1347. } else if (n->joints.size()) {
  1348. n->name = "Bone";
  1349. } else {
  1350. n->name = "Node";
  1351. }
  1352. }
  1353. n->name = _gen_unique_name(state, n->name);
  1354. }
  1355. }
  1356. void EditorSceneImporterGLTF::_generate_node(GLTFState &state, int p_node, Node *p_parent, Node *p_owner, Vector<Skeleton *> &skeletons) {
  1357. ERR_FAIL_INDEX(p_node, state.nodes.size());
  1358. GLTFNode *n = state.nodes[p_node];
  1359. Spatial *node;
  1360. if (n->mesh >= 0) {
  1361. ERR_FAIL_INDEX(n->mesh, state.meshes.size());
  1362. MeshInstance *mi = memnew(MeshInstance);
  1363. print_verbose("glTF: Creating mesh for: " + n->name);
  1364. GLTFMesh &mesh = state.meshes.write[n->mesh];
  1365. mi->set_mesh(mesh.mesh);
  1366. if (mesh.mesh->get_name() == "") {
  1367. mesh.mesh->set_name(n->name);
  1368. }
  1369. for (int i = 0; i < mesh.blend_weights.size(); i++) {
  1370. mi->set("blend_shapes/" + mesh.mesh->get_blend_shape_name(i), mesh.blend_weights[i]);
  1371. }
  1372. node = mi;
  1373. } else if (n->camera >= 0) {
  1374. ERR_FAIL_INDEX(n->camera, state.cameras.size());
  1375. Camera *camera = memnew(Camera);
  1376. const GLTFCamera &c = state.cameras[n->camera];
  1377. if (c.perspective) {
  1378. camera->set_perspective(c.fov_size, c.znear, c.znear);
  1379. } else {
  1380. camera->set_orthogonal(c.fov_size, c.znear, c.znear);
  1381. }
  1382. node = camera;
  1383. } else {
  1384. node = memnew(Spatial);
  1385. }
  1386. node->set_name(n->name);
  1387. n->godot_nodes.push_back(node);
  1388. if (n->skin >= 0 && n->skin < skeletons.size() && Object::cast_to<MeshInstance>(node)) {
  1389. MeshInstance *mi = Object::cast_to<MeshInstance>(node);
  1390. Skeleton *s = skeletons[n->skin];
  1391. s->add_child(node); //According to spec, mesh should actually act as a child of the skeleton, as it inherits its transform
  1392. mi->set_skeleton_path(String(".."));
  1393. } else {
  1394. p_parent->add_child(node);
  1395. node->set_transform(n->xform);
  1396. }
  1397. node->set_owner(p_owner);
  1398. #if 0
  1399. for (int i = 0; i < n->skeleton_children.size(); i++) {
  1400. Skeleton *s = skeletons[n->skeleton_children[i]];
  1401. s->get_parent()->remove_child(s);
  1402. node->add_child(s);
  1403. s->set_owner(p_owner);
  1404. }
  1405. #endif
  1406. for (int i = 0; i < n->children.size(); i++) {
  1407. if (state.nodes[n->children[i]]->joints.size()) {
  1408. _generate_bone(state, n->children[i], skeletons, node);
  1409. } else {
  1410. _generate_node(state, n->children[i], node, p_owner, skeletons);
  1411. }
  1412. }
  1413. }
  1414. void EditorSceneImporterGLTF::_generate_bone(GLTFState &state, int p_node, Vector<Skeleton *> &skeletons, Node *p_parent_node) {
  1415. ERR_FAIL_INDEX(p_node, state.nodes.size());
  1416. if (state.skeleton_nodes.has(p_node)) {
  1417. //reparent skeletons to proper place
  1418. Vector<int> nodes = state.skeleton_nodes[p_node];
  1419. for (int i = 0; i < nodes.size(); i++) {
  1420. Node *owner = skeletons[i]->get_owner();
  1421. skeletons[i]->get_parent()->remove_child(skeletons[i]);
  1422. p_parent_node->add_child(skeletons[i]);
  1423. skeletons[i]->set_owner(owner);
  1424. //may have meshes as children, set owner in them too
  1425. for (int j = 0; j < skeletons[i]->get_child_count(); j++) {
  1426. skeletons[i]->get_child(j)->set_owner(owner);
  1427. }
  1428. }
  1429. }
  1430. GLTFNode *n = state.nodes[p_node];
  1431. for (int i = 0; i < n->joints.size(); i++) {
  1432. const int skin = n->joints[i].skin;
  1433. ERR_FAIL_COND(skin < 0);
  1434. Skeleton *s = skeletons[skin];
  1435. const GLTFNode *gltf_bone_node = state.nodes[state.skins[skin].bones[n->joints[i].bone].node];
  1436. const String bone_name = gltf_bone_node->name;
  1437. const int parent = gltf_bone_node->parent;
  1438. const int parent_index = s->find_bone(state.nodes[parent]->name);
  1439. const int bone_index = s->find_bone(bone_name);
  1440. s->set_bone_parent(bone_index, parent_index);
  1441. n->godot_nodes.push_back(s);
  1442. n->joints.write[i].godot_bone_index = bone_index;
  1443. }
  1444. for (int i = 0; i < n->children.size(); i++) {
  1445. _generate_bone(state, n->children[i], skeletons, p_parent_node);
  1446. }
  1447. }
  1448. template <class T>
  1449. struct EditorSceneImporterGLTFInterpolate {
  1450. T lerp(const T &a, const T &b, float c) const {
  1451. return a + (b - a) * c;
  1452. }
  1453. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  1454. float t2 = t * t;
  1455. float t3 = t2 * t;
  1456. 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);
  1457. }
  1458. T bezier(T start, T control_1, T control_2, T end, float t) {
  1459. /* Formula from Wikipedia article on Bezier curves. */
  1460. real_t omt = (1.0 - t);
  1461. real_t omt2 = omt * omt;
  1462. real_t omt3 = omt2 * omt;
  1463. real_t t2 = t * t;
  1464. real_t t3 = t2 * t;
  1465. return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
  1466. }
  1467. };
  1468. //thank you for existing, partial specialization
  1469. template <>
  1470. struct EditorSceneImporterGLTFInterpolate<Quat> {
  1471. Quat lerp(const Quat &a, const Quat &b, float c) const {
  1472. ERR_FAIL_COND_V(!a.is_normalized(), Quat());
  1473. ERR_FAIL_COND_V(!b.is_normalized(), Quat());
  1474. return a.slerp(b, c).normalized();
  1475. }
  1476. Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) {
  1477. ERR_FAIL_COND_V(!p1.is_normalized(), Quat());
  1478. ERR_FAIL_COND_V(!p2.is_normalized(), Quat());
  1479. return p1.slerp(p2, c).normalized();
  1480. }
  1481. Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) {
  1482. ERR_FAIL_COND_V(!start.is_normalized(), Quat());
  1483. ERR_FAIL_COND_V(!end.is_normalized(), Quat());
  1484. return start.slerp(end, t).normalized();
  1485. }
  1486. };
  1487. template <class T>
  1488. T EditorSceneImporterGLTF::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time, GLTFAnimation::Interpolation p_interp) {
  1489. //could use binary search, worth it?
  1490. int idx = -1;
  1491. for (int i = 0; i < p_times.size(); i++) {
  1492. if (p_times[i] > p_time)
  1493. break;
  1494. idx++;
  1495. }
  1496. EditorSceneImporterGLTFInterpolate<T> interp;
  1497. switch (p_interp) {
  1498. case GLTFAnimation::INTERP_LINEAR: {
  1499. if (idx == -1) {
  1500. return p_values[0];
  1501. } else if (idx >= p_times.size() - 1) {
  1502. return p_values[p_times.size() - 1];
  1503. }
  1504. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1505. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  1506. } break;
  1507. case GLTFAnimation::INTERP_STEP: {
  1508. if (idx == -1) {
  1509. return p_values[0];
  1510. } else if (idx >= p_times.size() - 1) {
  1511. return p_values[p_times.size() - 1];
  1512. }
  1513. return p_values[idx];
  1514. } break;
  1515. case GLTFAnimation::INTERP_CATMULLROMSPLINE: {
  1516. if (idx == -1) {
  1517. return p_values[1];
  1518. } else if (idx >= p_times.size() - 1) {
  1519. return p_values[1 + p_times.size() - 1];
  1520. }
  1521. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1522. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  1523. } break;
  1524. case GLTFAnimation::INTERP_CUBIC_SPLINE: {
  1525. if (idx == -1) {
  1526. return p_values[1];
  1527. } else if (idx >= p_times.size() - 1) {
  1528. return p_values[(p_times.size() - 1) * 3 + 1];
  1529. }
  1530. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  1531. T from = p_values[idx * 3 + 1];
  1532. T c1 = from + p_values[idx * 3 + 2];
  1533. T to = p_values[idx * 3 + 4];
  1534. T c2 = to + p_values[idx * 3 + 3];
  1535. return interp.bezier(from, c1, c2, to, c);
  1536. } break;
  1537. }
  1538. ERR_FAIL_V(p_values[0]);
  1539. }
  1540. void EditorSceneImporterGLTF::_import_animation(GLTFState &state, AnimationPlayer *ap, int index, int bake_fps, Vector<Skeleton *> skeletons) {
  1541. const GLTFAnimation &anim = state.animations[index];
  1542. String name = anim.name;
  1543. if (name == "") {
  1544. name = _gen_unique_name(state, "Animation");
  1545. }
  1546. Ref<Animation> animation;
  1547. animation.instance();
  1548. animation->set_name(name);
  1549. float length = 0;
  1550. for (Map<int, GLTFAnimation::Track>::Element *E = anim.tracks.front(); E; E = E->next()) {
  1551. const GLTFAnimation::Track &track = E->get();
  1552. //need to find the path
  1553. NodePath node_path;
  1554. GLTFNode *node = state.nodes[E->key()];
  1555. for (int n = 0; n < node->godot_nodes.size(); n++) {
  1556. if (node->joints.size()) {
  1557. Skeleton *sk = (Skeleton *)node->godot_nodes[n];
  1558. String path = ap->get_parent()->get_path_to(sk);
  1559. String bone = sk->get_bone_name(node->joints[n].godot_bone_index);
  1560. node_path = path + ":" + bone;
  1561. } else {
  1562. node_path = ap->get_parent()->get_path_to(node->godot_nodes[n]);
  1563. }
  1564. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  1565. length = MAX(length, track.rotation_track.times[i]);
  1566. }
  1567. for (int i = 0; i < track.translation_track.times.size(); i++) {
  1568. length = MAX(length, track.translation_track.times[i]);
  1569. }
  1570. for (int i = 0; i < track.scale_track.times.size(); i++) {
  1571. length = MAX(length, track.scale_track.times[i]);
  1572. }
  1573. for (int i = 0; i < track.weight_tracks.size(); i++) {
  1574. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  1575. length = MAX(length, track.weight_tracks[i].times[j]);
  1576. }
  1577. }
  1578. if (track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) {
  1579. //make transform track
  1580. int track_idx = animation->get_track_count();
  1581. animation->add_track(Animation::TYPE_TRANSFORM);
  1582. animation->track_set_path(track_idx, node_path);
  1583. //first determine animation length
  1584. float increment = 1.0 / float(bake_fps);
  1585. float time = 0.0;
  1586. Vector3 base_pos;
  1587. Quat base_rot;
  1588. Vector3 base_scale = Vector3(1, 1, 1);
  1589. if (!track.rotation_track.values.size()) {
  1590. base_rot = state.nodes[E->key()]->rotation.normalized();
  1591. }
  1592. if (!track.translation_track.values.size()) {
  1593. base_pos = state.nodes[E->key()]->translation;
  1594. }
  1595. if (!track.scale_track.values.size()) {
  1596. base_scale = state.nodes[E->key()]->scale;
  1597. }
  1598. bool last = false;
  1599. while (true) {
  1600. Vector3 pos = base_pos;
  1601. Quat rot = base_rot;
  1602. Vector3 scale = base_scale;
  1603. if (track.translation_track.times.size()) {
  1604. pos = _interpolate_track<Vector3>(track.translation_track.times, track.translation_track.values, time, track.translation_track.interpolation);
  1605. }
  1606. if (track.rotation_track.times.size()) {
  1607. rot = _interpolate_track<Quat>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation);
  1608. }
  1609. if (track.scale_track.times.size()) {
  1610. scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation);
  1611. }
  1612. if (node->joints.size()) {
  1613. Transform xform;
  1614. //xform.basis = Basis(rot);
  1615. //xform.basis.scale(scale);
  1616. xform.basis.set_quat_scale(rot, scale);
  1617. xform.origin = pos;
  1618. Skeleton *skeleton = skeletons[node->joints[n].skin];
  1619. int bone = node->joints[n].godot_bone_index;
  1620. xform = skeleton->get_bone_rest(bone).affine_inverse() * xform;
  1621. rot = xform.basis.get_rotation_quat();
  1622. rot.normalize();
  1623. scale = xform.basis.get_scale();
  1624. pos = xform.origin;
  1625. }
  1626. animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
  1627. if (last) {
  1628. break;
  1629. }
  1630. time += increment;
  1631. if (time >= length) {
  1632. last = true;
  1633. time = length;
  1634. }
  1635. }
  1636. }
  1637. for (int i = 0; i < track.weight_tracks.size(); i++) {
  1638. ERR_CONTINUE(node->mesh < 0 || node->mesh >= state.meshes.size());
  1639. const GLTFMesh &mesh = state.meshes[node->mesh];
  1640. String prop = "blend_shapes/" + mesh.mesh->get_blend_shape_name(i);
  1641. node_path = String(node_path) + ":" + prop;
  1642. int track_idx = animation->get_track_count();
  1643. animation->add_track(Animation::TYPE_VALUE);
  1644. animation->track_set_path(track_idx, node_path);
  1645. if (track.weight_tracks[i].interpolation <= GLTFAnimation::INTERP_STEP) {
  1646. animation->track_set_interpolation_type(track_idx, track.weight_tracks[i].interpolation == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_NEAREST);
  1647. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  1648. float t = track.weight_tracks[i].times[j];
  1649. float w = track.weight_tracks[i].values[j];
  1650. animation->track_insert_key(track_idx, t, w);
  1651. }
  1652. } else {
  1653. //must bake, apologies.
  1654. float increment = 1.0 / float(bake_fps);
  1655. float time = 0.0;
  1656. bool last = false;
  1657. while (true) {
  1658. _interpolate_track<float>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, track.weight_tracks[i].interpolation);
  1659. if (last) {
  1660. break;
  1661. }
  1662. time += increment;
  1663. if (time >= length) {
  1664. last = true;
  1665. time = length;
  1666. }
  1667. }
  1668. }
  1669. }
  1670. }
  1671. }
  1672. animation->set_length(length);
  1673. ap->add_animation(name, animation);
  1674. }
  1675. Spatial *EditorSceneImporterGLTF::_generate_scene(GLTFState &state, int p_bake_fps) {
  1676. Spatial *root = memnew(Spatial);
  1677. root->set_name(state.scene_name);
  1678. //generate skeletons
  1679. Vector<Skeleton *> skeletons;
  1680. for (int i = 0; i < state.skins.size(); i++) {
  1681. Skeleton *s = memnew(Skeleton);
  1682. s->set_use_bones_in_world_transform(false); //GLTF does not need this since meshes are always local
  1683. String name = state.skins[i].name;
  1684. if (name == "") {
  1685. name = _gen_unique_name(state, "Skeleton");
  1686. }
  1687. for (int j = 0; j < state.skins[i].bones.size(); j++) {
  1688. s->add_bone(state.nodes[state.skins[i].bones[j].node]->name);
  1689. s->set_bone_rest(j, state.skins[i].bones[j].inverse_bind.affine_inverse());
  1690. }
  1691. s->set_name(name);
  1692. root->add_child(s);
  1693. s->set_owner(root);
  1694. skeletons.push_back(s);
  1695. }
  1696. for (int i = 0; i < state.root_nodes.size(); i++) {
  1697. if (state.nodes[state.root_nodes[i]]->joints.size()) {
  1698. _generate_bone(state, state.root_nodes[i], skeletons, root);
  1699. } else {
  1700. _generate_node(state, state.root_nodes[i], root, root, skeletons);
  1701. }
  1702. }
  1703. for (int i = 0; i < skeletons.size(); i++) {
  1704. skeletons[i]->localize_rests();
  1705. }
  1706. if (state.animations.size()) {
  1707. AnimationPlayer *ap = memnew(AnimationPlayer);
  1708. ap->set_name("AnimationPlayer");
  1709. root->add_child(ap);
  1710. ap->set_owner(root);
  1711. for (int i = 0; i < state.animations.size(); i++) {
  1712. _import_animation(state, ap, i, p_bake_fps, skeletons);
  1713. }
  1714. }
  1715. return root;
  1716. }
  1717. Node *EditorSceneImporterGLTF::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
  1718. GLTFState state;
  1719. if (p_path.to_lower().ends_with("glb")) {
  1720. //binary file
  1721. //text file
  1722. Error err = _parse_glb(p_path, state);
  1723. if (err)
  1724. return NULL;
  1725. } else {
  1726. //text file
  1727. Error err = _parse_json(p_path, state);
  1728. if (err)
  1729. return NULL;
  1730. }
  1731. ERR_FAIL_COND_V(!state.json.has("asset"), NULL);
  1732. Dictionary asset = state.json["asset"];
  1733. ERR_FAIL_COND_V(!asset.has("version"), NULL);
  1734. String version = asset["version"];
  1735. state.major_version = version.get_slice(".", 0).to_int();
  1736. state.minor_version = version.get_slice(".", 1).to_int();
  1737. /* STEP 0 PARSE SCENE */
  1738. Error err = _parse_scenes(state);
  1739. if (err != OK)
  1740. return NULL;
  1741. /* STEP 1 PARSE NODES */
  1742. err = _parse_nodes(state);
  1743. if (err != OK)
  1744. return NULL;
  1745. /* STEP 2 PARSE BUFFERS */
  1746. err = _parse_buffers(state, p_path.get_base_dir());
  1747. if (err != OK)
  1748. return NULL;
  1749. /* STEP 3 PARSE BUFFER VIEWS */
  1750. err = _parse_buffer_views(state);
  1751. if (err != OK)
  1752. return NULL;
  1753. /* STEP 4 PARSE ACCESSORS */
  1754. err = _parse_accessors(state);
  1755. if (err != OK)
  1756. return NULL;
  1757. /* STEP 5 PARSE IMAGES */
  1758. err = _parse_images(state, p_path.get_base_dir());
  1759. if (err != OK)
  1760. return NULL;
  1761. /* STEP 6 PARSE TEXTURES */
  1762. err = _parse_textures(state);
  1763. if (err != OK)
  1764. return NULL;
  1765. /* STEP 7 PARSE TEXTURES */
  1766. err = _parse_materials(state);
  1767. if (err != OK)
  1768. return NULL;
  1769. /* STEP 8 PARSE MESHES (we have enough info now) */
  1770. err = _parse_meshes(state);
  1771. if (err != OK)
  1772. return NULL;
  1773. /* STEP 9 PARSE SKINS */
  1774. err = _parse_skins(state);
  1775. if (err != OK)
  1776. return NULL;
  1777. /* STEP 10 PARSE CAMERAS */
  1778. err = _parse_cameras(state);
  1779. if (err != OK)
  1780. return NULL;
  1781. /* STEP 11 PARSE ANIMATIONS */
  1782. err = _parse_animations(state);
  1783. if (err != OK)
  1784. return NULL;
  1785. /* STEP 12 ASSIGN SCENE NAMES */
  1786. _assign_scene_names(state);
  1787. /* STEP 13 MAKE SCENE! */
  1788. Spatial *scene = _generate_scene(state, p_bake_fps);
  1789. return scene;
  1790. }
  1791. Ref<Animation> EditorSceneImporterGLTF::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  1792. return Ref<Animation>();
  1793. }
  1794. EditorSceneImporterGLTF::EditorSceneImporterGLTF() {
  1795. }