GltfImporter.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Importer/GltfImporter.h>
  6. #include <AnKi/Util/System.h>
  7. #include <AnKi/Util/ThreadJobManager.h>
  8. #include <AnKi/Util/StringList.h>
  9. #include <AnKi/Util/Xml.h>
  10. #if ANKI_COMPILER_GCC_COMPATIBLE
  11. # pragma GCC diagnostic push
  12. # pragma GCC diagnostic ignored "-Wconversion"
  13. #endif
  14. #define CGLTF_IMPLEMENTATION
  15. #include <Cgltf/cgltf.h>
  16. #if ANKI_COMPILER_GCC_COMPATIBLE
  17. # pragma GCC diagnostic pop
  18. #endif
  19. namespace anki {
  20. static F32 computeLightRadius(const Vec3 color)
  21. {
  22. // Based on the attenuation equation: att = 1 - fragLightDist^2 / lightRadius^2
  23. const F32 minAtt = 0.01f;
  24. const F32 maxIntensity = max(max(color.x(), color.y()), color.z());
  25. return sqrt(maxIntensity / minAtt);
  26. }
  27. #if 0
  28. static Error getUniformScale(const Mat4& m, F32& out)
  29. {
  30. const F32 SCALE_THRESHOLD = 0.01f; // 1 cm
  31. Vec3 xAxis = m.getColumn(0).xyz();
  32. Vec3 yAxis = m.getColumn(1).xyz();
  33. Vec3 zAxis = m.getColumn(2).xyz();
  34. const F32 scale = xAxis.getLength();
  35. if(absolute(scale - yAxis.getLength()) > SCALE_THRESHOLD || absolute(scale - zAxis.getLength()) > SCALE_THRESHOLD)
  36. {
  37. ANKI_IMPORTER_LOGE("No uniform scale in the matrix");
  38. return Error::kUserData;
  39. }
  40. out = scale;
  41. return Error::kNone;
  42. }
  43. #endif
  44. static void removeScale(Mat4& m)
  45. {
  46. Vec3 xAxis = m.getColumn(0).xyz();
  47. Vec3 yAxis = m.getColumn(1).xyz();
  48. Vec3 zAxis = m.getColumn(2).xyz();
  49. xAxis = xAxis.normalize();
  50. yAxis = yAxis.normalize();
  51. zAxis = zAxis.normalize();
  52. Mat3 rot;
  53. rot.setColumns(xAxis, yAxis, zAxis);
  54. m.setRotationPart(rot);
  55. }
  56. static void getNodeTransform(const cgltf_node& node, Vec3& tsl, Mat3& rot, Vec3& scale)
  57. {
  58. if(node.has_matrix)
  59. {
  60. Mat4 trf = Mat4(node.matrix);
  61. Vec3 xAxis = trf.getColumn(0).xyz();
  62. Vec3 yAxis = trf.getColumn(1).xyz();
  63. Vec3 zAxis = trf.getColumn(2).xyz();
  64. scale = Vec3(xAxis.length(), yAxis.length(), zAxis.length());
  65. removeScale(trf);
  66. rot = trf.getRotationPart();
  67. tsl = trf.getTranslationPart().xyz();
  68. }
  69. else
  70. {
  71. if(node.has_translation)
  72. {
  73. tsl = Vec3(node.translation[0], node.translation[1], node.translation[2]);
  74. }
  75. else
  76. {
  77. tsl = Vec3(0.0f);
  78. }
  79. if(node.has_rotation)
  80. {
  81. rot = Mat3(Quat(node.rotation[0], node.rotation[1], node.rotation[2], node.rotation[3]));
  82. }
  83. else
  84. {
  85. rot = Mat3::getIdentity();
  86. }
  87. if(node.has_scale)
  88. {
  89. ANKI_ASSERT(node.scale[0] > 0.0f);
  90. ANKI_ASSERT(node.scale[1] > 0.0f);
  91. ANKI_ASSERT(node.scale[2] > 0.0f);
  92. scale = Vec3(node.scale[0], node.scale[1], node.scale[2]);
  93. }
  94. else
  95. {
  96. scale = Vec3(1.0f);
  97. }
  98. }
  99. }
  100. static Error getNodeTransform(const cgltf_node& node, Transform& trf)
  101. {
  102. Vec3 tsl;
  103. Mat3 rot;
  104. Vec3 scale;
  105. getNodeTransform(node, tsl, rot, scale);
  106. trf.setOrigin(tsl.xyz0());
  107. trf.setRotation(Mat3x4(Vec3(0.0f), rot));
  108. trf.setScale(scale);
  109. return Error::kNone;
  110. }
  111. static Bool stringsExist(const ImporterHashMap<CString, ImporterString>& map, const std::initializer_list<CString>& list)
  112. {
  113. for(CString item : list)
  114. {
  115. if(map.find(item) != map.getEnd())
  116. {
  117. return true;
  118. }
  119. }
  120. return false;
  121. }
  122. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, F32& val, Bool& found)
  123. {
  124. found = false;
  125. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  126. if(it != extras.getEnd())
  127. {
  128. const Error err = it->toNumber(val);
  129. if(err)
  130. {
  131. ANKI_IMPORTER_LOGE("Failed to parse %s with value: %s", name.cstr(), it->cstr());
  132. return err;
  133. }
  134. found = true;
  135. }
  136. return Error::kNone;
  137. }
  138. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, ImporterString& val, Bool& found)
  139. {
  140. found = false;
  141. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  142. if(it != extras.getEnd())
  143. {
  144. val = *it;
  145. found = true;
  146. }
  147. return Error::kNone;
  148. }
  149. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, Bool& val, Bool& found)
  150. {
  151. found = false;
  152. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  153. if(it != extras.getEnd())
  154. {
  155. if(*it == "true" || *it == "1")
  156. {
  157. val = true;
  158. }
  159. else if(*it == "false" || *it == "0")
  160. {
  161. val = false;
  162. }
  163. else
  164. {
  165. U32 valu;
  166. const Error err = it->toNumber(valu);
  167. if(err || valu != 0 || valu != 1)
  168. {
  169. ANKI_IMPORTER_LOGE("Failed to parse %s with value: %s", name.cstr(), it->cstr());
  170. return err;
  171. }
  172. val = valu != 0;
  173. }
  174. found = true;
  175. }
  176. return Error::kNone;
  177. }
  178. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, Vec3& val, Bool& found)
  179. {
  180. found = false;
  181. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  182. if(it != extras.getEnd())
  183. {
  184. ImporterStringList tokens;
  185. tokens.splitString(*it, ' ');
  186. if(tokens.getSize() != 3)
  187. {
  188. ANKI_IMPORTER_LOGE("Error parsing %s with value: %s", name.cstr(), it->cstr());
  189. return Error::kUserData;
  190. }
  191. U count = 0;
  192. for(auto& token : tokens)
  193. {
  194. F32 f;
  195. const Error err = token.toNumber(f);
  196. if(err)
  197. {
  198. ANKI_IMPORTER_LOGE("Error parsing %s with value: %s", name.cstr(), it->cstr());
  199. return Error::kUserData;
  200. }
  201. val[count++] = f;
  202. }
  203. found = true;
  204. }
  205. return Error::kNone;
  206. }
  207. GltfImporter::GltfImporter()
  208. {
  209. }
  210. GltfImporter::~GltfImporter()
  211. {
  212. if(m_gltf)
  213. {
  214. cgltf_free(m_gltf);
  215. m_gltf = nullptr;
  216. }
  217. deleteInstance(ImporterMemoryPool::getSingleton(), m_jobManager);
  218. }
  219. Error GltfImporter::init(const GltfImporterInitInfo& initInfo)
  220. {
  221. m_inputFname = initInfo.m_inputFilename;
  222. m_outDir = initInfo.m_outDirectory;
  223. m_rpath = initInfo.m_rpath;
  224. m_texrpath = initInfo.m_texrpath;
  225. m_optimizeMeshes = initInfo.m_optimizeMeshes;
  226. m_optimizeAnimations = initInfo.m_optimizeAnimations;
  227. m_comment = initInfo.m_comment;
  228. m_lightIntensityScale = max(initInfo.m_lightIntensityScale, kEpsilonf);
  229. m_lodCount = clamp(initInfo.m_lodCount, 1u, 3u);
  230. m_lodFactor = clamp(initInfo.m_lodFactor, 0.0f, 1.0f);
  231. if(m_lodFactor * F32(m_lodCount - 1) > 0.7f)
  232. {
  233. ANKI_IMPORTER_LOGE("LOD factor is too high %f", m_lodFactor);
  234. return Error::kUserData;
  235. }
  236. if(m_lodFactor < kEpsilonf || m_lodCount == 1)
  237. {
  238. m_lodCount = 1;
  239. m_lodFactor = 0.0f;
  240. }
  241. ANKI_IMPORTER_LOGV("Having %u LODs with LOD factor %f", m_lodCount, m_lodFactor);
  242. cgltf_options options = {};
  243. cgltf_result res = cgltf_parse_file(&options, m_inputFname.cstr(), &m_gltf);
  244. if(res != cgltf_result_success)
  245. {
  246. ANKI_IMPORTER_LOGE("Failed to open the GLTF file. Code: %d", res);
  247. return Error::kFunctionFailed;
  248. }
  249. res = cgltf_load_buffers(&options, m_gltf, m_inputFname.cstr());
  250. if(res != cgltf_result_success)
  251. {
  252. ANKI_IMPORTER_LOGE("Failed to load GLTF data. Code: %d", res);
  253. return Error::kFunctionFailed;
  254. }
  255. if(initInfo.m_threadCount > 0)
  256. {
  257. const U32 threadCount = min(getCpuCoresCount(), initInfo.m_threadCount);
  258. m_jobManager = newInstance<ThreadJobManager>(ImporterMemoryPool::getSingleton(), threadCount, true);
  259. }
  260. m_importTextures = initInfo.m_importTextures;
  261. return Error::kNone;
  262. }
  263. Error GltfImporter::writeAll()
  264. {
  265. populateNodePtrToIdx();
  266. ImporterString sceneFname;
  267. sceneFname.sprintf("%sScene.lua", m_outDir.cstr());
  268. ANKI_CHECK(m_sceneFile.open(sceneFname.toCString(), FileOpenFlag::kWrite));
  269. ANKI_CHECK(m_sceneFile.writeTextf("-- Generated by: %s\n", m_comment.cstr()));
  270. ANKI_CHECK(m_sceneFile.writeText("local scene = getSceneGraph()\nlocal events = getEventManager()\n"));
  271. // Nodes
  272. for(const cgltf_scene* scene = m_gltf->scenes; scene < m_gltf->scenes + m_gltf->scenes_count; ++scene)
  273. {
  274. for(cgltf_node* const* node = scene->nodes; node < scene->nodes + scene->nodes_count; ++node)
  275. {
  276. ANKI_CHECK(visitNode(*(*node), Transform::getIdentity(), ImporterHashMap<CString, ImporterString>()));
  277. }
  278. }
  279. // Fire up all requests
  280. for(auto& req : m_meshImportRequests)
  281. {
  282. if(m_jobManager)
  283. {
  284. m_jobManager->dispatchTask([&req]([[maybe_unused]] U32 threadId) {
  285. Error err = req.m_importer->m_errorInThread.load();
  286. if(!err)
  287. {
  288. err = req.m_importer->writeMesh(*req.m_value);
  289. }
  290. if(err)
  291. {
  292. req.m_importer->m_errorInThread.store(err._getCode());
  293. }
  294. });
  295. }
  296. else
  297. {
  298. ANKI_CHECK(writeMesh(*req.m_value));
  299. }
  300. }
  301. for(auto& req : m_materialImportRequests)
  302. {
  303. if(m_jobManager)
  304. {
  305. m_jobManager->dispatchTask([&req]([[maybe_unused]] U32 threadId) {
  306. Error err = req.m_importer->m_errorInThread.load();
  307. if(!err)
  308. {
  309. err = req.m_importer->writeMaterial(*req.m_value.m_cgltfMaterial, req.m_value.m_writeRt);
  310. }
  311. if(err)
  312. {
  313. req.m_importer->m_errorInThread.store(err._getCode());
  314. }
  315. });
  316. }
  317. else
  318. {
  319. ANKI_CHECK(writeMaterial(*req.m_value.m_cgltfMaterial, req.m_value.m_writeRt));
  320. }
  321. }
  322. for(auto& req : m_skinImportRequests)
  323. {
  324. if(m_jobManager)
  325. {
  326. m_jobManager->dispatchTask([&req]([[maybe_unused]] U32 threadId) {
  327. Error err = req.m_importer->m_errorInThread.load();
  328. if(!err)
  329. {
  330. err = req.m_importer->writeSkeleton(*req.m_value);
  331. }
  332. if(err)
  333. {
  334. req.m_importer->m_errorInThread.store(err._getCode());
  335. }
  336. });
  337. }
  338. else
  339. {
  340. ANKI_CHECK(writeSkeleton(*req.m_value));
  341. }
  342. }
  343. for(auto& req : m_modelImportRequests)
  344. {
  345. if(m_jobManager)
  346. {
  347. m_jobManager->dispatchTask([&req]([[maybe_unused]] U32 threadId) {
  348. Error err = req.m_importer->m_errorInThread.load();
  349. if(!err)
  350. {
  351. err = req.m_importer->writeModel(*req.m_value);
  352. }
  353. if(err)
  354. {
  355. req.m_importer->m_errorInThread.store(err._getCode());
  356. }
  357. });
  358. }
  359. else
  360. {
  361. ANKI_CHECK(writeModel(*req.m_value));
  362. }
  363. }
  364. if(m_jobManager)
  365. {
  366. m_jobManager->waitForAllTasksToFinish();
  367. const Error threadErr = m_errorInThread.load();
  368. if(threadErr)
  369. {
  370. ANKI_IMPORTER_LOGE("Error happened in a thread");
  371. return threadErr;
  372. }
  373. }
  374. // Animations
  375. for(const cgltf_animation* anim = m_gltf->animations; anim < m_gltf->animations + m_gltf->animations_count; ++anim)
  376. {
  377. ANKI_CHECK(writeAnimation(*anim));
  378. }
  379. ANKI_IMPORTER_LOGV("Importing GLTF has completed");
  380. return Error::kNone;
  381. }
  382. Error GltfImporter::appendExtras(const cgltf_extras& extras, ImporterHashMap<CString, ImporterString>& out) const
  383. {
  384. cgltf_size extrasSize;
  385. cgltf_copy_extras_json(m_gltf, &extras, nullptr, &extrasSize);
  386. if(extrasSize == 0)
  387. {
  388. return Error::kNone;
  389. }
  390. ImporterDynamicArrayLarge<char> json;
  391. json.resize(extrasSize + 1);
  392. cgltf_result res = cgltf_copy_extras_json(m_gltf, &extras, &json[0], &extrasSize);
  393. if(res != cgltf_result_success)
  394. {
  395. ANKI_IMPORTER_LOGE("cgltf_copy_extras_json failed: %d", res);
  396. return Error::kFunctionFailed;
  397. }
  398. json[json.getSize() - 1] = '\0';
  399. // Get token count
  400. CString jsonTxt(&json[0]);
  401. jsmn_parser parser;
  402. jsmn_init(&parser);
  403. const I tokenCount = jsmn_parse(&parser, jsonTxt.cstr(), jsonTxt.getLength(), nullptr, 0);
  404. if(tokenCount < 1)
  405. {
  406. return Error::kNone;
  407. }
  408. ImporterDynamicArray<jsmntok_t> tokens;
  409. tokens.resize(U32(tokenCount));
  410. // Get tokens
  411. jsmn_init(&parser);
  412. jsmn_parse(&parser, jsonTxt.cstr(), jsonTxt.getLength(), &tokens[0], tokens.getSize());
  413. ImporterStringList tokenStrings;
  414. for(const jsmntok_t& token : tokens)
  415. {
  416. if(token.type != JSMN_STRING && token.type != JSMN_PRIMITIVE)
  417. {
  418. continue;
  419. }
  420. ImporterString tokenStr(&jsonTxt[token.start], &jsonTxt[token.end]);
  421. tokenStrings.pushBack(tokenStr.toCString());
  422. }
  423. if((tokenStrings.getSize() % 2) != 0)
  424. {
  425. ANKI_IMPORTER_LOGV("Ignoring: %s", jsonTxt.cstr());
  426. return Error::kNone;
  427. }
  428. // Write them to the map
  429. auto it = tokenStrings.getBegin();
  430. while(it != tokenStrings.getEnd())
  431. {
  432. auto it2 = it;
  433. ++it2;
  434. out.emplace(it->toCString(), ImporterString(it2->toCString()));
  435. ++it;
  436. ++it;
  437. }
  438. return Error::kNone;
  439. }
  440. static void appendExtrasMap(const ImporterHashMap<CString, ImporterString>& in, ImporterHashMap<CString, ImporterString>& out)
  441. {
  442. auto& outs = out.getSparseArray();
  443. for(auto it = in.getBegin(); it != in.getEnd(); ++it)
  444. {
  445. outs.emplace(it.getKey(), *it);
  446. }
  447. }
  448. void GltfImporter::populateNodePtrToIdxInternal(const cgltf_node& node, U32& idx)
  449. {
  450. m_nodePtrToIdx.emplace(&node, idx++);
  451. for(cgltf_node* const* c = node.children; c < node.children + node.children_count; ++c)
  452. {
  453. populateNodePtrToIdxInternal(**c, idx);
  454. }
  455. }
  456. void GltfImporter::populateNodePtrToIdx()
  457. {
  458. U32 idx = 0;
  459. for(const cgltf_scene* scene = m_gltf->scenes; scene < m_gltf->scenes + m_gltf->scenes_count; ++scene)
  460. {
  461. for(cgltf_node* const* node = scene->nodes; node < scene->nodes + scene->nodes_count; ++node)
  462. {
  463. populateNodePtrToIdxInternal(**node, idx);
  464. }
  465. }
  466. }
  467. ImporterString GltfImporter::getNodeName(const cgltf_node& node) const
  468. {
  469. ImporterString out;
  470. if(node.name)
  471. {
  472. out = node.name;
  473. }
  474. else
  475. {
  476. auto it = m_nodePtrToIdx.find(&node);
  477. ANKI_ASSERT(it != m_nodePtrToIdx.getEnd());
  478. out.sprintf("unnamed_node_%u", *it);
  479. }
  480. return out;
  481. }
  482. Error GltfImporter::parseArrayOfNumbers(CString str, ImporterDynamicArray<F64>& out, const U32* expectedArraySize)
  483. {
  484. ImporterStringList list;
  485. list.splitString(str, ' ');
  486. out.resize(U32(list.getSize()));
  487. Error err = Error::kNone;
  488. auto it = list.getBegin();
  489. auto end = list.getEnd();
  490. U32 i = 0;
  491. while(it != end && !err)
  492. {
  493. err = it->toNumber(out[i++]);
  494. ++it;
  495. }
  496. if(err)
  497. {
  498. ANKI_IMPORTER_LOGE("Failed to parse floats: %s", str.cstr());
  499. }
  500. if(expectedArraySize && *expectedArraySize != out.getSize())
  501. {
  502. ANKI_IMPORTER_LOGE("Failed to parse floats. Expecting %u floats got %u: %s", *expectedArraySize, out.getSize(), str.cstr());
  503. }
  504. return Error::kNone;
  505. }
  506. Error GltfImporter::visitNode(const cgltf_node& node, const Transform& parentTrf, const ImporterHashMap<CString, ImporterString>& parentExtras)
  507. {
  508. // Check error from a thread
  509. const Error threadErr = m_errorInThread.load();
  510. if(threadErr)
  511. {
  512. ANKI_IMPORTER_LOGE("Error happened in a thread");
  513. return threadErr;
  514. }
  515. ImporterHashMap<CString, ImporterString> outExtras;
  516. if(node.light)
  517. {
  518. ImporterHashMap<CString, ImporterString> extras;
  519. ANKI_CHECK(appendExtras(node.light->extras, extras));
  520. ANKI_CHECK(appendExtras(node.extras, extras));
  521. appendExtrasMap(parentExtras, extras);
  522. ANKI_CHECK(writeLight(node, extras));
  523. Transform localTrf;
  524. ANKI_CHECK(getNodeTransform(node, localTrf));
  525. localTrf.setScale(Vec4(1.0f, 1.0f, 1.0f, 0.0f)); // Remove scale
  526. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  527. }
  528. else if(node.camera)
  529. {
  530. ImporterHashMap<CString, ImporterString> extras;
  531. ANKI_CHECK(appendExtras(node.camera->extras, extras));
  532. ANKI_CHECK(appendExtras(node.extras, extras));
  533. appendExtrasMap(parentExtras, extras);
  534. ANKI_CHECK(writeCamera(node, extras));
  535. Transform localTrf;
  536. ANKI_CHECK(getNodeTransform(node, localTrf));
  537. localTrf.setScale(Vec4(1.0f, 1.0f, 1.0f, 0.0f)); // Remove scale
  538. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  539. }
  540. else if(node.mesh)
  541. {
  542. // Handle special nodes
  543. ImporterHashMap<CString, ImporterString> extras;
  544. ANKI_CHECK(appendExtras(node.mesh->extras, extras));
  545. ANKI_CHECK(appendExtras(node.extras, extras));
  546. appendExtrasMap(parentExtras, extras);
  547. ImporterString extraValueStr;
  548. Bool extraValueBool = false;
  549. Vec3 extraValueVec3;
  550. F32 extraValuef = 0.0f;
  551. Bool extraFound = false;
  552. ANKI_CHECK(getExtra(extras, "particles", extraValueStr, extraFound));
  553. if(extraFound)
  554. {
  555. Bool gpuParticles = false;
  556. ANKI_CHECK(getExtra(extras, "gpu_particles", extraValueBool, extraFound));
  557. if(extraFound)
  558. {
  559. gpuParticles = extraValueBool;
  560. }
  561. if(!gpuParticles) // TODO Re-enable GPU particles
  562. {
  563. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  564. ANKI_CHECK(m_sceneFile.writeTextf("comp = node:newParticleEmitterComponent()\n"));
  565. ANKI_CHECK(m_sceneFile.writeTextf("comp:loadParticleEmitterResource(\"%s\")\n", extraValueStr.cstr()));
  566. Transform localTrf;
  567. ANKI_CHECK(getNodeTransform(node, localTrf));
  568. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  569. }
  570. }
  571. else if(stringsExist(extras, {"skybox_solid_color", "skybox_image", "fog_min_density", "fog_max_density", "fog_height_of_min_density",
  572. "fog_height_of_max_density", "fog_diffuse_color", "skybox_generated"}))
  573. {
  574. // Atmosphere
  575. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  576. ANKI_CHECK(m_sceneFile.writeText("comp = node:newSkyboxComponent()\n"));
  577. ANKI_CHECK(getExtra(extras, "skybox_solid_color", extraValueVec3, extraFound));
  578. if(extraFound)
  579. {
  580. ANKI_CHECK(
  581. m_sceneFile.writeTextf("comp:setSolidColor(Vec3.new(%f, %f, %f))\n", extraValueVec3.x(), extraValueVec3.y(), extraValueVec3.z()));
  582. }
  583. ANKI_CHECK(getExtra(extras, "skybox_image", extraValueStr, extraFound));
  584. if(extraFound)
  585. {
  586. ANKI_CHECK(m_sceneFile.writeTextf("comp:loadImageResource(\"%s\")\n", extraValueStr.cstr()));
  587. }
  588. ANKI_CHECK(getExtra(extras, "skybox_image_scale", extraValueVec3, extraFound));
  589. if(extraFound)
  590. {
  591. ANKI_CHECK(
  592. m_sceneFile.writeTextf("comp:setImageScale(Vec3.new(%f, %f, %f))\n", extraValueVec3.x(), extraValueVec3.y(), extraValueVec3.z()));
  593. }
  594. ANKI_CHECK(getExtra(extras, "fog_min_density", extraValuef, extraFound));
  595. if(extraFound)
  596. {
  597. ANKI_CHECK(m_sceneFile.writeTextf("comp:setMinFogDensity(%f)\n", extraValuef));
  598. }
  599. ANKI_CHECK(getExtra(extras, "fog_max_density", extraValuef, extraFound));
  600. if(extraFound)
  601. {
  602. ANKI_CHECK(m_sceneFile.writeTextf("comp:setMaxFogDensity(%f)\n", extraValuef));
  603. }
  604. ANKI_CHECK(getExtra(extras, "fog_height_of_min_density", extraValuef, extraFound));
  605. if(extraFound)
  606. {
  607. ANKI_CHECK(m_sceneFile.writeTextf("comp:setHeightOfMinFogDensity(%f)\n", extraValuef));
  608. }
  609. ANKI_CHECK(getExtra(extras, "fog_height_of_max_density", extraValuef, extraFound));
  610. if(extraFound)
  611. {
  612. ANKI_CHECK(m_sceneFile.writeTextf("comp:setHeightOfMaxFogDensity(%f)\n", extraValuef));
  613. }
  614. ANKI_CHECK(getExtra(extras, "fog_diffuse_color", extraValueVec3, extraFound));
  615. if(extraFound)
  616. {
  617. ANKI_CHECK(m_sceneFile.writeTextf("comp:setFogDiffuseColor(Vec3.new(%f, %f, %f))\n", extraValueVec3.x(), extraValueVec3.y(),
  618. extraValueVec3.z()));
  619. }
  620. ANKI_CHECK(getExtra(extras, "skybox_generated", extraValueBool, extraFound));
  621. if(extraFound && extraValueBool)
  622. {
  623. ANKI_CHECK(m_sceneFile.writeTextf("comp:setGeneratedSky()\n"));
  624. }
  625. Transform localTrf;
  626. ANKI_CHECK(getNodeTransform(node, localTrf));
  627. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  628. }
  629. else if(stringsExist(extras, {"collision"}))
  630. {
  631. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  632. ANKI_CHECK(m_sceneFile.writeText("comp = scene:newBodyComponent()\n"));
  633. const ImporterString meshFname = computeMeshResourceFilename(*node.mesh);
  634. ANKI_CHECK(m_sceneFile.writeTextf("comp:loadMeshResource(\"%s%s\")\n", m_rpath.cstr(), meshFname.cstr()));
  635. Transform localTrf;
  636. ANKI_CHECK(getNodeTransform(node, localTrf));
  637. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  638. }
  639. else if(stringsExist(extras, {"reflection_probe"}))
  640. {
  641. Vec3 tsl;
  642. Mat3 rot;
  643. Vec3 scale;
  644. getNodeTransform(node, tsl, rot, scale);
  645. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  646. ANKI_CHECK(m_sceneFile.writeText("comp = node:newReflectionProbeComponent()\n"));
  647. const Transform localTrf = Transform(tsl, rot, scale);
  648. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  649. }
  650. else if(stringsExist(extras, {"gi_probe"}))
  651. {
  652. Vec3 tsl;
  653. Mat3 rot;
  654. Vec3 scale;
  655. getNodeTransform(node, tsl, rot, scale);
  656. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  657. ANKI_CHECK(m_sceneFile.writeText("comp = node:newGlobalIlluminationProbeComponent()\n"));
  658. ANKI_CHECK(getExtra(extras, "gi_probe_fade_distance", extraValuef, extraFound));
  659. if(extraFound && extraValuef > 0.0f)
  660. {
  661. ANKI_CHECK(m_sceneFile.writeTextf("comp:setFadeDistance(%f)\n", extraValuef));
  662. }
  663. ANKI_CHECK(getExtra(extras, "gi_probe_cell_size", extraValuef, extraFound));
  664. if(extraFound && extraValuef > 0.0f)
  665. {
  666. ANKI_CHECK(m_sceneFile.writeTextf("comp:setCellSize(%f)\n", extraValuef));
  667. }
  668. const Transform localTrf = Transform(tsl, rot, scale);
  669. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  670. }
  671. else if(stringsExist(extras, {"decal"}))
  672. {
  673. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  674. ANKI_CHECK(m_sceneFile.writeText("comp = node:newDecalComponent()\n"));
  675. ANKI_CHECK(getExtra(extras, "decal_diffuse", extraValueStr, extraFound));
  676. if(extraFound)
  677. {
  678. ANKI_CHECK(getExtra(extras, "decal_diffuse_factor", extraValuef, extraFound));
  679. ANKI_CHECK(
  680. m_sceneFile.writeTextf("comp:loadDiffuseImageResource(\"%s\", %f)\n", extraValueStr.cstr(), (extraFound) ? extraValuef : 1.0f));
  681. }
  682. ANKI_CHECK(getExtra(extras, "decal_metal_roughness", extraValueStr, extraFound));
  683. if(extraFound)
  684. {
  685. ANKI_CHECK(getExtra(extras, "decal_metal_roughness_factor", extraValuef, extraFound));
  686. ANKI_CHECK(m_sceneFile.writeTextf("comp:loadMetalRoughnessImageResource(\"%s\", %f)\n", extraValueStr.cstr(),
  687. (extraFound) ? extraValuef : 1.0f));
  688. }
  689. Vec3 tsl;
  690. Mat3 rot;
  691. Vec3 scale;
  692. getNodeTransform(node, tsl, rot, scale);
  693. const Transform localTrf = Transform(tsl, rot, scale);
  694. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  695. }
  696. else
  697. {
  698. // Model node
  699. ANKI_CHECK(getExtra(extras, "no_rt", extraValueBool, extraFound));
  700. const Bool skipRt = (extraFound) ? extraValueBool : false;
  701. Transform localTrf;
  702. const Error err = getNodeTransform(node, localTrf);
  703. if(err)
  704. {
  705. ANKI_IMPORTER_LOGE("Will skip node: %s", getNodeName(node).cstr());
  706. }
  707. else
  708. {
  709. addRequest<const cgltf_mesh*>(node.mesh, m_meshImportRequests);
  710. for(U32 i = 0; i < node.mesh->primitives_count; ++i)
  711. {
  712. const MaterialImportRequest req = {node.mesh->primitives[i].material, !skipRt};
  713. addRequest<MaterialImportRequest>(req, m_materialImportRequests);
  714. }
  715. if(node.skin)
  716. {
  717. addRequest<const cgltf_skin*>(node.skin, m_skinImportRequests);
  718. }
  719. addRequest<const cgltf_mesh*>(node.mesh, m_modelImportRequests);
  720. ImporterHashMap<CString, ImporterString>::Iterator it2;
  721. const Bool selfCollision = (it2 = extras.find("collision_mesh")) != extras.getEnd() && *it2 == "self";
  722. ANKI_CHECK(writeModelNode(node, parentExtras));
  723. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  724. if(selfCollision)
  725. {
  726. ANKI_CHECK(m_sceneFile.writeText("comp = node:newBodyComponent()\n"));
  727. const ImporterString meshFname = computeMeshResourceFilename(*node.mesh);
  728. ANKI_CHECK(m_sceneFile.writeText("comp:setCollisionShapeType(BodyComponentCollisionShapeType.kFromModelComponent)\n"));
  729. ANKI_CHECK(m_sceneFile.writeText("comp:teleportTo(trf:getOrigin(), trf:getRotation())\n"));
  730. }
  731. }
  732. }
  733. }
  734. else
  735. {
  736. ANKI_IMPORTER_LOGV("Ignoring node %s. Assuming transform node", getNodeName(node).cstr());
  737. ANKI_CHECK(appendExtras(node.extras, outExtras));
  738. }
  739. // Visit children
  740. Transform nodeTrf;
  741. {
  742. Vec3 tsl;
  743. Mat3 rot;
  744. Vec3 scale;
  745. getNodeTransform(node, tsl, rot, scale);
  746. nodeTrf = Transform(tsl.xyz0(), Mat3x4(Vec3(0.0f), rot), scale.xyz0());
  747. }
  748. for(cgltf_node* const* c = node.children; c < node.children + node.children_count; ++c)
  749. {
  750. ANKI_CHECK(visitNode(*(*c), nodeTrf, outExtras));
  751. }
  752. return Error::kNone;
  753. }
  754. Error GltfImporter::writeTransform(const Transform& trf)
  755. {
  756. ANKI_CHECK(m_sceneFile.writeText("trf = Transform.new()\n"));
  757. ANKI_CHECK(m_sceneFile.writeTextf("trf:setOrigin(Vec3.new(%f, %f, %f))\n", trf.getOrigin().x(), trf.getOrigin().y(), trf.getOrigin().z()));
  758. ANKI_CHECK(m_sceneFile.writeText("rot = Mat3.new()\n"));
  759. ANKI_CHECK(m_sceneFile.writeText("rot:setAll("));
  760. for(U i = 0; i < 9; i++)
  761. {
  762. ANKI_CHECK(m_sceneFile.writeTextf((i != 8) ? "%f, " : "%f)\n", trf.getRotation().getRotationPart()[i]));
  763. }
  764. ANKI_CHECK(m_sceneFile.writeText("trf:setRotation(rot)\n"));
  765. ANKI_CHECK(m_sceneFile.writeTextf("trf:setScale(Vec3.new(%f, %f, %f))\n", trf.getScale().x(), trf.getScale().y(), trf.getScale().z()));
  766. ANKI_CHECK(m_sceneFile.writeText("node:setLocalTransform(trf)\n"));
  767. return Error::kNone;
  768. }
  769. Error GltfImporter::writeModel(const cgltf_mesh& mesh) const
  770. {
  771. const ImporterString modelFname = computeModelResourceFilename(mesh);
  772. ANKI_IMPORTER_LOGV("Importing model %s", modelFname.cstr());
  773. ImporterHashMap<CString, ImporterString> extras;
  774. ANKI_CHECK(appendExtras(mesh.extras, extras));
  775. File file;
  776. ImporterString modelFullFname;
  777. modelFullFname.sprintf("%s/%s", m_outDir.cstr(), modelFname.cstr());
  778. ANKI_CHECK(file.open(modelFullFname, FileOpenFlag::kWrite));
  779. ANKI_CHECK(file.writeText("<model>\n"));
  780. ANKI_CHECK(file.writeText("\t<modelPatches>\n"));
  781. for(U32 primIdx = 0; primIdx < mesh.primitives_count; ++primIdx)
  782. {
  783. ANKI_CHECK(file.writeText("\t\t<modelPatch>\n"));
  784. const ImporterString meshFname = computeMeshResourceFilename(mesh);
  785. if(mesh.primitives_count == 1)
  786. {
  787. ANKI_CHECK(file.writeTextf("\t\t\t<mesh>%s%s</mesh>\n", m_rpath.cstr(), meshFname.cstr()));
  788. }
  789. else
  790. {
  791. ANKI_CHECK(file.writeTextf("\t\t\t<mesh subMeshIndex=\"%u\">%s%s</mesh>\n", primIdx, m_rpath.cstr(), meshFname.cstr()));
  792. }
  793. ImporterHashMap<CString, ImporterString> materialExtras;
  794. ANKI_CHECK(appendExtras(mesh.primitives[primIdx].material->extras, materialExtras));
  795. auto mtlOverride = materialExtras.find("material_override");
  796. if(mtlOverride != materialExtras.getEnd())
  797. {
  798. ANKI_CHECK(file.writeTextf("\t\t\t<material>%s</material>\n", mtlOverride->cstr()));
  799. }
  800. else
  801. {
  802. const ImporterString mtlFname = computeMaterialResourceFilename(*mesh.primitives[primIdx].material);
  803. ANKI_CHECK(file.writeTextf("\t\t\t<material>%s%s</material>\n", m_rpath.cstr(), mtlFname.cstr()));
  804. }
  805. ANKI_CHECK(file.writeText("\t\t</modelPatch>\n"));
  806. }
  807. ANKI_CHECK(file.writeText("\t</modelPatches>\n"));
  808. ANKI_CHECK(file.writeText("</model>\n"));
  809. return Error::kNone;
  810. }
  811. Error GltfImporter::writeSkeleton(const cgltf_skin& skin) const
  812. {
  813. ImporterString fname;
  814. fname.sprintf("%s%s", m_outDir.cstr(), computeSkeletonResourceFilename(skin).cstr());
  815. ANKI_IMPORTER_LOGV("Importing skeleton %s", fname.cstr());
  816. // Get matrices
  817. ImporterDynamicArray<Mat4> boneMats;
  818. readAccessor(*skin.inverse_bind_matrices, boneMats);
  819. if(boneMats.getSize() != skin.joints_count)
  820. {
  821. ANKI_IMPORTER_LOGE("Bone matrices should match the joint count");
  822. return Error::kUserData;
  823. }
  824. // Write file
  825. File file;
  826. ANKI_CHECK(file.open(fname.toCString(), FileOpenFlag::kWrite));
  827. ANKI_CHECK(file.writeTextf("%s\n<skeleton>\n", XmlDocument<MemoryPoolPtrWrapper<BaseMemoryPool>>::kXmlHeader.cstr()));
  828. ANKI_CHECK(file.writeTextf("\t<bones>\n"));
  829. for(U32 i = 0; i < skin.joints_count; ++i)
  830. {
  831. const cgltf_node& boneNode = *skin.joints[i];
  832. ImporterString parent;
  833. // Name & parent
  834. ANKI_CHECK(file.writeTextf("\t\t<bone name=\"%s\" ", getNodeName(boneNode).cstr()));
  835. if(boneNode.parent && getNodeName(*boneNode.parent) != skin.name)
  836. {
  837. ANKI_CHECK(file.writeTextf("parent=\"%s\" ", getNodeName(*boneNode.parent).cstr()));
  838. }
  839. // Bone transform
  840. ANKI_CHECK(file.writeText("boneTransform=\""));
  841. Mat4 btrf(&boneMats[i][0]);
  842. btrf = btrf.transpose();
  843. const Mat3x4 btrf3x4(btrf);
  844. for(U32 j = 0; j < 12; j++)
  845. {
  846. ANKI_CHECK(file.writeTextf("%f ", btrf3x4[j]));
  847. }
  848. ANKI_CHECK(file.writeText("\" "));
  849. // Transform
  850. Transform trf;
  851. ANKI_CHECK(getNodeTransform(boneNode, trf));
  852. Mat3x4 mat(trf);
  853. ANKI_CHECK(file.writeText("transform=\""));
  854. for(U j = 0; j < 12; j++)
  855. {
  856. ANKI_CHECK(file.writeTextf("%f ", mat[j]));
  857. }
  858. ANKI_CHECK(file.writeText("\" "));
  859. ANKI_CHECK(file.writeText("/>\n"));
  860. }
  861. ANKI_CHECK(file.writeText("\t</bones>\n"));
  862. ANKI_CHECK(file.writeText("</skeleton>\n"));
  863. return Error::kNone;
  864. }
  865. Error GltfImporter::writeLight(const cgltf_node& node, const ImporterHashMap<CString, ImporterString>& parentExtras)
  866. {
  867. const cgltf_light& light = *node.light;
  868. ImporterString nodeName = getNodeName(node);
  869. ANKI_IMPORTER_LOGV("Importing light %s", nodeName.cstr());
  870. ImporterHashMap<CString, ImporterString> extras(parentExtras);
  871. ANKI_CHECK(appendExtras(light.extras, extras));
  872. ANKI_CHECK(appendExtras(node.extras, extras));
  873. CString lightTypeStr;
  874. switch(light.type)
  875. {
  876. case cgltf_light_type_point:
  877. lightTypeStr = "Point";
  878. break;
  879. case cgltf_light_type_spot:
  880. lightTypeStr = "Spot";
  881. break;
  882. case cgltf_light_type_directional:
  883. lightTypeStr = "Directional";
  884. break;
  885. default:
  886. ANKI_IMPORTER_LOGE("Unsupporter light type %d", light.type);
  887. return Error::kUserData;
  888. }
  889. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", nodeName.cstr()));
  890. ANKI_CHECK(m_sceneFile.writeText("lcomp = node:newLightComponent()\n"));
  891. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setLightComponentType(LightComponentType.k%s)\n", lightTypeStr.cstr()));
  892. Vec3 color(light.color[0], light.color[1], light.color[2]);
  893. color *= light.intensity;
  894. color *= m_lightIntensityScale;
  895. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setDiffuseColor(Vec4.new(%f, %f, %f, 1))\n", color.x(), color.y(), color.z()));
  896. auto shadow = extras.find("shadow");
  897. if(shadow != extras.getEnd())
  898. {
  899. if(*shadow == "true" || *shadow == "1")
  900. {
  901. ANKI_CHECK(m_sceneFile.writeText("lcomp:setShadowEnabled(1)\n"));
  902. }
  903. else
  904. {
  905. ANKI_CHECK(m_sceneFile.writeText("lcomp:setShadowEnabled(0)\n"));
  906. }
  907. }
  908. if(light.type == cgltf_light_type_point)
  909. {
  910. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setRadius(%f)\n", (light.range > 0.0f) ? light.range : computeLightRadius(color)));
  911. }
  912. else if(light.type == cgltf_light_type_spot)
  913. {
  914. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setDistance(%f)\n", (light.range > 0.0f) ? light.range : computeLightRadius(color)));
  915. const F32 outer = light.spot_outer_cone_angle * 2.0f;
  916. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setOuterAngle(%f)\n", outer));
  917. auto angStr = extras.find("inner_cone_angle_factor");
  918. F32 inner;
  919. if(angStr != extras.getEnd())
  920. {
  921. F32 factor;
  922. ANKI_CHECK(angStr->toNumber(factor));
  923. inner = light.spot_inner_cone_angle * 2.0f * min(1.0f, factor);
  924. }
  925. else
  926. {
  927. inner = light.spot_inner_cone_angle * 2.0f;
  928. }
  929. if(inner >= 0.95f * outer)
  930. {
  931. inner = 0.75f * outer;
  932. }
  933. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setInnerAngle(%f)\n", inner));
  934. }
  935. auto lensFlaresFname = extras.find("lens_flare");
  936. if(lensFlaresFname != extras.getEnd())
  937. {
  938. ANKI_CHECK(m_sceneFile.writeTextf("lfcomp = node:newLensFlareComponent()\n"));
  939. ANKI_CHECK(m_sceneFile.writeTextf("lfcomp:loadImageResource(\"%s\")\n", lensFlaresFname->cstr()));
  940. auto lsSpriteSize = extras.find("lens_flare_first_sprite_size");
  941. auto lsColor = extras.find("lens_flare_color");
  942. if(lsSpriteSize != extras.getEnd())
  943. {
  944. ImporterDynamicArray<F64> numbers;
  945. const U32 count = 2;
  946. ANKI_CHECK(parseArrayOfNumbers(lsSpriteSize->toCString(), numbers, &count));
  947. ANKI_CHECK(m_sceneFile.writeTextf("lfcomp:setFirstFlareSize(Vec2.new(%f, %f))\n", numbers[0], numbers[1]));
  948. }
  949. if(lsColor != extras.getEnd())
  950. {
  951. ImporterDynamicArray<F64> numbers;
  952. const U32 count = 4;
  953. ANKI_CHECK(parseArrayOfNumbers(lsColor->toCString(), numbers, &count));
  954. ANKI_CHECK(
  955. m_sceneFile.writeTextf("lfcomp:setColorMultiplier(Vec4.new(%f, %f, %f, %f))\n", numbers[0], numbers[1], numbers[2], numbers[3]));
  956. }
  957. }
  958. auto lightEventIntensity = extras.find("light_event_intensity");
  959. auto lightEventFrequency = extras.find("light_event_frequency");
  960. if(lightEventIntensity != extras.getEnd() || lightEventFrequency != extras.getEnd())
  961. {
  962. ANKI_CHECK(m_sceneFile.writeText("event = events:newLightEvent(0.0, -1.0, node)\n"));
  963. if(lightEventIntensity != extras.getEnd())
  964. {
  965. ImporterDynamicArray<F64> numbers;
  966. const U32 count = 4;
  967. ANKI_CHECK(parseArrayOfNumbers(lightEventIntensity->toCString(), numbers, &count));
  968. ANKI_CHECK(
  969. m_sceneFile.writeTextf("event:setIntensityMultiplier(Vec4.new(%f, %f, %f, %f))\n", numbers[0], numbers[1], numbers[2], numbers[3]));
  970. }
  971. if(lightEventFrequency != extras.getEnd())
  972. {
  973. ImporterDynamicArray<F64> numbers;
  974. const U32 count = 2;
  975. ANKI_CHECK(parseArrayOfNumbers(lightEventFrequency->toCString(), numbers, &count));
  976. ANKI_CHECK(m_sceneFile.writeTextf("event:setFrequency(%f, %f)\n", numbers[0], numbers[1]));
  977. }
  978. }
  979. return Error::kNone;
  980. }
  981. Error GltfImporter::writeCamera(const cgltf_node& node, [[maybe_unused]] const ImporterHashMap<CString, ImporterString>& parentExtras)
  982. {
  983. if(node.camera->type != cgltf_camera_type_perspective)
  984. {
  985. ANKI_IMPORTER_LOGV("Unsupported camera type: %s", getNodeName(node).cstr());
  986. return Error::kNone;
  987. }
  988. const cgltf_camera_perspective& cam = node.camera->data.perspective;
  989. ANKI_IMPORTER_LOGV("Importing camera %s", getNodeName(node).cstr());
  990. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  991. ANKI_CHECK(m_sceneFile.writeText("scene:setActiveCameraNode(node)\n"));
  992. ANKI_CHECK(m_sceneFile.writeText("comp = node:newCameraComponent()\n"));
  993. ANKI_CHECK(
  994. m_sceneFile.writeTextf("comp:setPerspective(%f, %f, getRenderer():getAspectRatio() * %f, %f)\n", cam.znear, cam.zfar, cam.yfov, cam.yfov));
  995. return Error::kNone;
  996. }
  997. Error GltfImporter::writeModelNode(const cgltf_node& node, const ImporterHashMap<CString, ImporterString>& parentExtras)
  998. {
  999. ANKI_IMPORTER_LOGV("Importing model node %s", getNodeName(node).cstr());
  1000. ImporterHashMap<CString, ImporterString> extras(parentExtras);
  1001. ANKI_CHECK(appendExtras(node.extras, extras));
  1002. const ImporterString modelFname = computeModelResourceFilename(*node.mesh);
  1003. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  1004. ANKI_CHECK(m_sceneFile.writeTextf("node:newModelComponent():loadModelResource(\"%s%s\")\n", m_rpath.cstr(), modelFname.cstr()));
  1005. if(node.skin)
  1006. {
  1007. ANKI_CHECK(m_sceneFile.writeTextf("node:newSkinComponent():loadSkeletonResource(\"%s%s\")\n", m_rpath.cstr(),
  1008. computeSkeletonResourceFilename(*node.skin).cstr()));
  1009. }
  1010. return Error::kNone;
  1011. }
  1012. ImporterString GltfImporter::computeModelResourceFilename(const cgltf_mesh& mesh) const
  1013. {
  1014. ImporterStringList list;
  1015. list.pushBack(mesh.name);
  1016. for(U i = 0; i < mesh.primitives_count; ++i)
  1017. {
  1018. const Char* mtlName = (mesh.primitives[i].material) ? mesh.primitives[i].material->name : "UnamedMtl";
  1019. list.pushBackSprintf("_%s", mtlName);
  1020. }
  1021. ImporterString joined;
  1022. list.join("", joined);
  1023. const U64 hash = computeHash(joined.getBegin(), joined.getLength());
  1024. ImporterString out;
  1025. out.sprintf("%.64s_%" PRIx64 ".ankimdl", joined.cstr(), hash); // Limit the filename size
  1026. return out;
  1027. }
  1028. ImporterString GltfImporter::computeMeshResourceFilename(const cgltf_mesh& mesh) const
  1029. {
  1030. const U64 hash = computeHash(mesh.name, strlen(mesh.name));
  1031. ImporterString out;
  1032. out.sprintf("%.64s_%" PRIx64 ".ankimesh", mesh.name, hash); // Limit the filename size
  1033. return out;
  1034. }
  1035. ImporterString GltfImporter::computeMaterialResourceFilename(const cgltf_material& mtl) const
  1036. {
  1037. const U64 hash = computeHash(mtl.name, strlen(mtl.name));
  1038. ImporterString out;
  1039. out.sprintf("%.64s_%" PRIx64 ".ankimtl", mtl.name, hash); // Limit the filename size
  1040. return out;
  1041. }
  1042. ImporterString GltfImporter::computeAnimationResourceFilename(const cgltf_animation& anim) const
  1043. {
  1044. const U64 hash = computeHash(anim.name, strlen(anim.name));
  1045. ImporterString out;
  1046. out.sprintf("%.64s_%" PRIx64 ".ankianim", anim.name, hash); // Limit the filename size
  1047. return out;
  1048. }
  1049. ImporterString GltfImporter::computeSkeletonResourceFilename(const cgltf_skin& skin) const
  1050. {
  1051. const U64 hash = computeHash(skin.name, strlen(skin.name));
  1052. ImporterString out;
  1053. out.sprintf("%.64s_%" PRIx64 ".ankiskel", skin.name, hash); // Limit the filename size
  1054. return out;
  1055. }
  1056. } // end namespace anki