glTF2Exporter.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2024, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER
  35. #include "AssetLib/glTF2/glTF2Exporter.h"
  36. #include "AssetLib/glTF2/glTF2AssetWriter.h"
  37. #include "PostProcessing/SplitLargeMeshes.h"
  38. #include <assimp/ByteSwapper.h>
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/SceneCombiner.h>
  41. #include <assimp/StringComparison.h>
  42. #include <assimp/commonMetaData.h>
  43. #include <assimp/material.h>
  44. #include <assimp/scene.h>
  45. #include <assimp/version.h>
  46. #include <assimp/Exporter.hpp>
  47. #include <assimp/IOSystem.hpp>
  48. #include <assimp/config.h>
  49. // Header files, standard library.
  50. #include <cinttypes>
  51. #include <limits>
  52. #include <memory>
  53. #include <iostream>
  54. using namespace rapidjson;
  55. using namespace Assimp;
  56. using namespace glTF2;
  57. namespace Assimp {
  58. // ------------------------------------------------------------------------------------------------
  59. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  60. void ExportSceneGLTF2(const char *pFile, IOSystem *pIOSystem, const aiScene *pScene, const ExportProperties *pProperties) {
  61. // invoke the exporter
  62. glTF2Exporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  66. void ExportSceneGLB2(const char *pFile, IOSystem *pIOSystem, const aiScene *pScene, const ExportProperties *pProperties) {
  67. // invoke the exporter
  68. glTF2Exporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  69. }
  70. } // end of namespace Assimp
  71. glTF2Exporter::glTF2Exporter(const char *filename, IOSystem *pIOSystem, const aiScene *pScene,
  72. const ExportProperties *pProperties, bool isBinary) :
  73. mFilename(filename), mIOSystem(pIOSystem), mScene(pScene), mProperties(pProperties), mAsset(new Asset(pIOSystem)) {
  74. // Always on as our triangulation process is aware of this type of encoding
  75. mAsset->extensionsUsed.FB_ngon_encoding = true;
  76. configEpsilon = mProperties->GetPropertyFloat(
  77. AI_CONFIG_CHECK_IDENTITY_MATRIX_EPSILON,
  78. (ai_real)AI_CONFIG_CHECK_IDENTITY_MATRIX_EPSILON_DEFAULT);
  79. if (isBinary) {
  80. mAsset->SetAsBinary();
  81. }
  82. ExportMetadata();
  83. ExportMaterials();
  84. if (mScene->mRootNode) {
  85. ExportNodeHierarchy(mScene->mRootNode);
  86. }
  87. ExportMeshes();
  88. MergeMeshes();
  89. ExportScene();
  90. ExportAnimations();
  91. // export extras
  92. if (mProperties->HasPropertyCallback("extras")) {
  93. std::function<void *(void *)> ExportExtras = mProperties->GetPropertyCallback("extras");
  94. mAsset->extras = (rapidjson::Value *)ExportExtras(0);
  95. }
  96. AssetWriter writer(*mAsset);
  97. if (isBinary) {
  98. writer.WriteGLBFile(filename);
  99. } else {
  100. writer.WriteFile(filename);
  101. }
  102. }
  103. glTF2Exporter::~glTF2Exporter() = default;
  104. /*
  105. * Copy a 4x4 matrix from struct aiMatrix to typedef mat4.
  106. * Also converts from row-major to column-major storage.
  107. */
  108. static void CopyValue(const aiMatrix4x4 &v, mat4 &o) {
  109. o[0] = v.a1;
  110. o[1] = v.b1;
  111. o[2] = v.c1;
  112. o[3] = v.d1;
  113. o[4] = v.a2;
  114. o[5] = v.b2;
  115. o[6] = v.c2;
  116. o[7] = v.d2;
  117. o[8] = v.a3;
  118. o[9] = v.b3;
  119. o[10] = v.c3;
  120. o[11] = v.d3;
  121. o[12] = v.a4;
  122. o[13] = v.b4;
  123. o[14] = v.c4;
  124. o[15] = v.d4;
  125. }
  126. static void CopyValue(const aiMatrix4x4 &v, aiMatrix4x4 &o) {
  127. memcpy(&o, &v, sizeof(aiMatrix4x4));
  128. }
  129. static void IdentityMatrix4(mat4 &o) {
  130. o[0] = 1;
  131. o[1] = 0;
  132. o[2] = 0;
  133. o[3] = 0;
  134. o[4] = 0;
  135. o[5] = 1;
  136. o[6] = 0;
  137. o[7] = 0;
  138. o[8] = 0;
  139. o[9] = 0;
  140. o[10] = 1;
  141. o[11] = 0;
  142. o[12] = 0;
  143. o[13] = 0;
  144. o[14] = 0;
  145. o[15] = 1;
  146. }
  147. template <typename T>
  148. void SetAccessorRange(Ref<Accessor> acc, void *data, size_t count,
  149. unsigned int numCompsIn, unsigned int numCompsOut) {
  150. ai_assert(numCompsOut <= numCompsIn);
  151. // Allocate and initialize with large values.
  152. for (unsigned int i = 0; i < numCompsOut; i++) {
  153. acc->min.push_back(std::numeric_limits<double>::max());
  154. acc->max.push_back(-std::numeric_limits<double>::max());
  155. }
  156. size_t totalComps = count * numCompsIn;
  157. T *buffer_ptr = static_cast<T *>(data);
  158. T *buffer_end = buffer_ptr + totalComps;
  159. // Search and set extreme values.
  160. for (; buffer_ptr < buffer_end; buffer_ptr += numCompsIn) {
  161. for (unsigned int j = 0; j < numCompsOut; j++) {
  162. double valueTmp = buffer_ptr[j];
  163. // Gracefully tolerate rogue NaN's in buffer data
  164. // Any NaNs/Infs introduced in accessor bounds will end up in
  165. // document and prevent rapidjson from writing out valid JSON
  166. if (!std::isfinite(valueTmp)) {
  167. continue;
  168. }
  169. if (valueTmp < acc->min[j]) {
  170. acc->min[j] = valueTmp;
  171. }
  172. if (valueTmp > acc->max[j]) {
  173. acc->max[j] = valueTmp;
  174. }
  175. }
  176. }
  177. }
  178. inline void SetAccessorRange(ComponentType compType, Ref<Accessor> acc, void *data,
  179. size_t count, unsigned int numCompsIn, unsigned int numCompsOut) {
  180. switch (compType) {
  181. case ComponentType_SHORT:
  182. SetAccessorRange<short>(acc, data, count, numCompsIn, numCompsOut);
  183. return;
  184. case ComponentType_UNSIGNED_SHORT:
  185. SetAccessorRange<unsigned short>(acc, data, count, numCompsIn, numCompsOut);
  186. return;
  187. case ComponentType_UNSIGNED_INT:
  188. SetAccessorRange<unsigned int>(acc, data, count, numCompsIn, numCompsOut);
  189. return;
  190. case ComponentType_FLOAT:
  191. SetAccessorRange<float>(acc, data, count, numCompsIn, numCompsOut);
  192. return;
  193. case ComponentType_BYTE:
  194. SetAccessorRange<int8_t>(acc, data, count, numCompsIn, numCompsOut);
  195. return;
  196. case ComponentType_UNSIGNED_BYTE:
  197. SetAccessorRange<uint8_t>(acc, data, count, numCompsIn, numCompsOut);
  198. return;
  199. }
  200. }
  201. // compute the (data-dataBase), store the non-zero data items
  202. template <typename T>
  203. size_t NZDiff(void *data, void *dataBase, size_t count, unsigned int numCompsIn, unsigned int numCompsOut, void *&outputNZDiff, void *&outputNZIdx) {
  204. std::vector<T> vNZDiff;
  205. std::vector<unsigned short> vNZIdx;
  206. size_t totalComps = count * numCompsIn;
  207. T *bufferData_ptr = static_cast<T *>(data);
  208. T *bufferData_end = bufferData_ptr + totalComps;
  209. T *bufferBase_ptr = static_cast<T *>(dataBase);
  210. // Search and set extreme values.
  211. for (short idx = 0; bufferData_ptr < bufferData_end; idx += 1, bufferData_ptr += numCompsIn) {
  212. bool bNonZero = false;
  213. // for the data, check any component Non Zero
  214. for (unsigned int j = 0; j < numCompsOut; j++) {
  215. double valueData = bufferData_ptr[j];
  216. double valueBase = bufferBase_ptr ? bufferBase_ptr[j] : 0;
  217. if ((valueData - valueBase) != 0) {
  218. bNonZero = true;
  219. break;
  220. }
  221. }
  222. // all zeros, continue
  223. if (!bNonZero)
  224. continue;
  225. // non zero, store the data
  226. for (unsigned int j = 0; j < numCompsOut; j++) {
  227. T valueData = bufferData_ptr[j];
  228. T valueBase = bufferBase_ptr ? bufferBase_ptr[j] : 0;
  229. vNZDiff.push_back(valueData - valueBase);
  230. }
  231. vNZIdx.push_back(idx);
  232. }
  233. // avoid all-0, put 1 item
  234. if (vNZDiff.size() == 0) {
  235. for (unsigned int j = 0; j < numCompsOut; j++)
  236. vNZDiff.push_back(0);
  237. vNZIdx.push_back(0);
  238. }
  239. // process data
  240. outputNZDiff = new T[vNZDiff.size()];
  241. memcpy(outputNZDiff, vNZDiff.data(), vNZDiff.size() * sizeof(T));
  242. outputNZIdx = new unsigned short[vNZIdx.size()];
  243. memcpy(outputNZIdx, vNZIdx.data(), vNZIdx.size() * sizeof(unsigned short));
  244. return vNZIdx.size();
  245. }
  246. inline size_t NZDiff(ComponentType compType, void *data, void *dataBase, size_t count, unsigned int numCompsIn, unsigned int numCompsOut, void *&nzDiff, void *&nzIdx) {
  247. switch (compType) {
  248. case ComponentType_SHORT:
  249. return NZDiff<short>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  250. case ComponentType_UNSIGNED_SHORT:
  251. return NZDiff<unsigned short>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  252. case ComponentType_UNSIGNED_INT:
  253. return NZDiff<unsigned int>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  254. case ComponentType_FLOAT:
  255. return NZDiff<float>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  256. case ComponentType_BYTE:
  257. return NZDiff<int8_t>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  258. case ComponentType_UNSIGNED_BYTE:
  259. return NZDiff<uint8_t>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  260. }
  261. return 0;
  262. }
  263. inline Ref<Accessor> ExportDataSparse(Asset &a, std::string &meshName, Ref<Buffer> &buffer,
  264. size_t count, void *data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, BufferViewTarget target = BufferViewTarget_NONE, void *dataBase = nullptr) {
  265. if (!count || !data) {
  266. return Ref<Accessor>();
  267. }
  268. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  269. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  270. unsigned int bytesPerComp = ComponentTypeSize(compType);
  271. // accessor
  272. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  273. // if there is a basic data vector
  274. if (dataBase) {
  275. size_t base_offset = buffer->byteLength;
  276. size_t base_padding = base_offset % bytesPerComp;
  277. base_offset += base_padding;
  278. size_t base_length = count * numCompsOut * bytesPerComp;
  279. buffer->Grow(base_length + base_padding);
  280. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  281. bv->buffer = buffer;
  282. bv->byteOffset = base_offset;
  283. bv->byteLength = base_length; //! The target that the WebGL buffer should be bound to.
  284. bv->byteStride = 0;
  285. bv->target = target;
  286. acc->bufferView = bv;
  287. acc->WriteData(count, dataBase, numCompsIn * bytesPerComp);
  288. }
  289. acc->byteOffset = 0;
  290. acc->componentType = compType;
  291. acc->count = count;
  292. acc->type = typeOut;
  293. if (data) {
  294. void *nzDiff = nullptr, *nzIdx = nullptr;
  295. size_t nzCount = NZDiff(compType, data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  296. acc->sparse.reset(new Accessor::Sparse);
  297. acc->sparse->count = nzCount;
  298. // indices
  299. unsigned int bytesPerIdx = sizeof(unsigned short);
  300. size_t indices_offset = buffer->byteLength;
  301. size_t indices_padding = indices_offset % bytesPerIdx;
  302. indices_offset += indices_padding;
  303. size_t indices_length = nzCount * 1 * bytesPerIdx;
  304. buffer->Grow(indices_length + indices_padding);
  305. Ref<BufferView> indicesBV = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  306. indicesBV->buffer = buffer;
  307. indicesBV->byteOffset = indices_offset;
  308. indicesBV->byteLength = indices_length;
  309. indicesBV->byteStride = 0;
  310. acc->sparse->indices = indicesBV;
  311. acc->sparse->indicesType = ComponentType_UNSIGNED_SHORT;
  312. acc->sparse->indicesByteOffset = 0;
  313. acc->WriteSparseIndices(nzCount, nzIdx, 1 * bytesPerIdx);
  314. // values
  315. size_t values_offset = buffer->byteLength;
  316. size_t values_padding = values_offset % bytesPerComp;
  317. values_offset += values_padding;
  318. size_t values_length = nzCount * numCompsOut * bytesPerComp;
  319. buffer->Grow(values_length + values_padding);
  320. Ref<BufferView> valuesBV = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  321. valuesBV->buffer = buffer;
  322. valuesBV->byteOffset = values_offset;
  323. valuesBV->byteLength = values_length;
  324. valuesBV->byteStride = 0;
  325. acc->sparse->values = valuesBV;
  326. acc->sparse->valuesByteOffset = 0;
  327. acc->WriteSparseValues(nzCount, nzDiff, numCompsIn * bytesPerComp);
  328. // clear
  329. delete[] (char *)nzDiff;
  330. delete[] (char *)nzIdx;
  331. }
  332. return acc;
  333. }
  334. inline Ref<Accessor> ExportData(Asset &a, std::string &meshName, Ref<Buffer> &buffer,
  335. size_t count, void *data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, BufferViewTarget target = BufferViewTarget_NONE) {
  336. if (!count || !data) {
  337. return Ref<Accessor>();
  338. }
  339. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  340. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  341. unsigned int bytesPerComp = ComponentTypeSize(compType);
  342. size_t offset = buffer->byteLength;
  343. // make sure offset is correctly byte-aligned, as required by spec
  344. size_t padding = offset % bytesPerComp;
  345. offset += padding;
  346. size_t length = count * numCompsOut * bytesPerComp;
  347. buffer->Grow(length + padding);
  348. // bufferView
  349. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  350. bv->buffer = buffer;
  351. bv->byteOffset = offset;
  352. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  353. bv->byteStride = 0;
  354. bv->target = target;
  355. // accessor
  356. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  357. acc->bufferView = bv;
  358. acc->byteOffset = 0;
  359. acc->componentType = compType;
  360. acc->count = count;
  361. acc->type = typeOut;
  362. // calculate min and max values
  363. SetAccessorRange(compType, acc, data, count, numCompsIn, numCompsOut);
  364. // copy the data
  365. acc->WriteData(count, data, numCompsIn * bytesPerComp);
  366. return acc;
  367. }
  368. inline void ExportNodeExtras(const aiMetadataEntry &metadataEntry, aiString name, CustomExtension &value) {
  369. value.name = name.C_Str();
  370. switch (metadataEntry.mType) {
  371. case AI_BOOL:
  372. value.mBoolValue.value = *static_cast<bool *>(metadataEntry.mData);
  373. value.mBoolValue.isPresent = true;
  374. break;
  375. case AI_INT32:
  376. value.mInt64Value.value = *static_cast<int32_t *>(metadataEntry.mData);
  377. value.mInt64Value.isPresent = true;
  378. break;
  379. case AI_UINT64:
  380. value.mUint64Value.value = *static_cast<uint64_t *>(metadataEntry.mData);
  381. value.mUint64Value.isPresent = true;
  382. break;
  383. case AI_FLOAT:
  384. value.mDoubleValue.value = *static_cast<float *>(metadataEntry.mData);
  385. value.mDoubleValue.isPresent = true;
  386. break;
  387. case AI_DOUBLE:
  388. value.mDoubleValue.value = *static_cast<double *>(metadataEntry.mData);
  389. value.mDoubleValue.isPresent = true;
  390. break;
  391. case AI_AISTRING:
  392. value.mStringValue.value = static_cast<aiString *>(metadataEntry.mData)->C_Str();
  393. value.mStringValue.isPresent = true;
  394. break;
  395. case AI_AIMETADATA: {
  396. const aiMetadata *subMetadata = static_cast<aiMetadata *>(metadataEntry.mData);
  397. value.mValues.value.resize(subMetadata->mNumProperties);
  398. value.mValues.isPresent = true;
  399. for (unsigned i = 0; i < subMetadata->mNumProperties; ++i) {
  400. ExportNodeExtras(subMetadata->mValues[i], subMetadata->mKeys[i], value.mValues.value.at(i));
  401. }
  402. break;
  403. }
  404. default:
  405. // AI_AIVECTOR3D not handled
  406. break;
  407. }
  408. }
  409. inline void ExportNodeExtras(const aiMetadata *metadata, Extras &extras) {
  410. if (metadata == nullptr || metadata->mNumProperties == 0) {
  411. return;
  412. }
  413. extras.mValues.resize(metadata->mNumProperties);
  414. for (unsigned int i = 0; i < metadata->mNumProperties; ++i) {
  415. ExportNodeExtras(metadata->mValues[i], metadata->mKeys[i], extras.mValues.at(i));
  416. }
  417. }
  418. inline void SetSamplerWrap(SamplerWrap &wrap, aiTextureMapMode map) {
  419. switch (map) {
  420. case aiTextureMapMode_Clamp:
  421. wrap = SamplerWrap::Clamp_To_Edge;
  422. break;
  423. case aiTextureMapMode_Mirror:
  424. wrap = SamplerWrap::Mirrored_Repeat;
  425. break;
  426. case aiTextureMapMode_Wrap:
  427. case aiTextureMapMode_Decal:
  428. default:
  429. wrap = SamplerWrap::Repeat;
  430. break;
  431. };
  432. }
  433. void glTF2Exporter::GetTexSampler(const aiMaterial &mat, Ref<Texture> texture, aiTextureType tt, unsigned int slot) {
  434. aiString aId;
  435. std::string id;
  436. if (aiGetMaterialString(&mat, AI_MATKEY_GLTF_MAPPINGID(tt, slot), &aId) == AI_SUCCESS) {
  437. id = aId.C_Str();
  438. }
  439. if (Ref<Sampler> ref = mAsset->samplers.Get(id.c_str())) {
  440. texture->sampler = ref;
  441. } else {
  442. id = mAsset->FindUniqueID(id, "sampler");
  443. texture->sampler = mAsset->samplers.Create(id.c_str());
  444. aiTextureMapMode mapU, mapV;
  445. SamplerMagFilter filterMag;
  446. SamplerMinFilter filterMin;
  447. if (aiGetMaterialInteger(&mat, AI_MATKEY_MAPPINGMODE_U(tt, slot), (int *)&mapU) == AI_SUCCESS) {
  448. SetSamplerWrap(texture->sampler->wrapS, mapU);
  449. }
  450. if (aiGetMaterialInteger(&mat, AI_MATKEY_MAPPINGMODE_V(tt, slot), (int *)&mapV) == AI_SUCCESS) {
  451. SetSamplerWrap(texture->sampler->wrapT, mapV);
  452. }
  453. if (aiGetMaterialInteger(&mat, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(tt, slot), (int *)&filterMag) == AI_SUCCESS) {
  454. texture->sampler->magFilter = filterMag;
  455. }
  456. if (aiGetMaterialInteger(&mat, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(tt, slot), (int *)&filterMin) == AI_SUCCESS) {
  457. texture->sampler->minFilter = filterMin;
  458. }
  459. aiString name;
  460. if (aiGetMaterialString(&mat, AI_MATKEY_GLTF_MAPPINGNAME(tt, slot), &name) == AI_SUCCESS) {
  461. texture->sampler->name = name.C_Str();
  462. }
  463. }
  464. }
  465. void glTF2Exporter::GetMatTexProp(const aiMaterial &mat, unsigned int &prop, const char *propName, aiTextureType tt, unsigned int slot) {
  466. std::string textureKey = std::string(_AI_MATKEY_TEXTURE_BASE) + "." + propName;
  467. mat.Get(textureKey.c_str(), tt, slot, prop);
  468. }
  469. void glTF2Exporter::GetMatTexProp(const aiMaterial &mat, float &prop, const char *propName, aiTextureType tt, unsigned int slot) {
  470. std::string textureKey = std::string(_AI_MATKEY_TEXTURE_BASE) + "." + propName;
  471. mat.Get(textureKey.c_str(), tt, slot, prop);
  472. }
  473. void glTF2Exporter::GetMatTex(const aiMaterial &mat, Ref<Texture> &texture, unsigned int &texCoord, aiTextureType tt, unsigned int slot = 0) {
  474. if (mat.GetTextureCount(tt) == 0) {
  475. return;
  476. }
  477. aiString tex;
  478. // Read texcoord (UV map index)
  479. // Note: must be an int to be successful.
  480. int tmp = 0;
  481. const auto ok = mat.Get(AI_MATKEY_UVWSRC(tt, slot), tmp);
  482. if (ok == aiReturn_SUCCESS) texCoord = tmp;
  483. if (mat.Get(AI_MATKEY_TEXTURE(tt, slot), tex) == AI_SUCCESS) {
  484. std::string path = tex.C_Str();
  485. if (path.size() > 0) {
  486. std::map<std::string, unsigned int>::iterator it = mTexturesByPath.find(path);
  487. if (it != mTexturesByPath.end()) {
  488. texture = mAsset->textures.Get(it->second);
  489. }
  490. bool useBasisUniversal = false;
  491. if (!texture) {
  492. std::string texId = mAsset->FindUniqueID("", "texture");
  493. texture = mAsset->textures.Create(texId);
  494. mTexturesByPath[path] = texture.GetIndex();
  495. std::string imgId = mAsset->FindUniqueID("", "image");
  496. texture->source = mAsset->images.Create(imgId);
  497. const aiTexture *curTex = mScene->GetEmbeddedTexture(path.c_str());
  498. if (curTex != nullptr) { // embedded
  499. texture->source->name = curTex->mFilename.C_Str();
  500. // basisu: embedded ktx2, bu
  501. if (curTex->achFormatHint[0]) {
  502. std::string mimeType = "image/";
  503. if (memcmp(curTex->achFormatHint, "jpg", 3) == 0)
  504. mimeType += "jpeg";
  505. else if (memcmp(curTex->achFormatHint, "ktx", 3) == 0) {
  506. useBasisUniversal = true;
  507. mimeType += "ktx";
  508. } else if (memcmp(curTex->achFormatHint, "kx2", 3) == 0) {
  509. useBasisUniversal = true;
  510. mimeType += "ktx2";
  511. } else if (memcmp(curTex->achFormatHint, "bu", 2) == 0) {
  512. useBasisUniversal = true;
  513. mimeType += "basis";
  514. } else
  515. mimeType += curTex->achFormatHint;
  516. texture->source->mimeType = mimeType;
  517. }
  518. // The asset has its own buffer, see Image::SetData
  519. // basisu: "image/ktx2", "image/basis" as is
  520. texture->source->SetData(reinterpret_cast<uint8_t *>(curTex->pcData), curTex->mWidth, *mAsset);
  521. } else {
  522. texture->source->uri = path;
  523. if (texture->source->uri.find(".ktx") != std::string::npos ||
  524. texture->source->uri.find(".basis") != std::string::npos) {
  525. useBasisUniversal = true;
  526. }
  527. }
  528. // basisu
  529. if (useBasisUniversal) {
  530. mAsset->extensionsUsed.KHR_texture_basisu = true;
  531. mAsset->extensionsRequired.KHR_texture_basisu = true;
  532. }
  533. GetTexSampler(mat, texture, tt, slot);
  534. }
  535. }
  536. }
  537. }
  538. void glTF2Exporter::GetMatTex(const aiMaterial &mat, TextureInfo &prop, aiTextureType tt, unsigned int slot = 0) {
  539. Ref<Texture> &texture = prop.texture;
  540. GetMatTex(mat, texture, prop.texCoord, tt, slot);
  541. }
  542. void glTF2Exporter::GetMatTex(const aiMaterial &mat, NormalTextureInfo &prop, aiTextureType tt, unsigned int slot = 0) {
  543. Ref<Texture> &texture = prop.texture;
  544. GetMatTex(mat, texture, prop.texCoord, tt, slot);
  545. if (texture) {
  546. // GetMatTexProp(mat, prop.texCoord, "texCoord", tt, slot);
  547. GetMatTexProp(mat, prop.scale, "scale", tt, slot);
  548. }
  549. }
  550. void glTF2Exporter::GetMatTex(const aiMaterial &mat, OcclusionTextureInfo &prop, aiTextureType tt, unsigned int slot = 0) {
  551. Ref<Texture> &texture = prop.texture;
  552. GetMatTex(mat, texture, prop.texCoord, tt, slot);
  553. if (texture) {
  554. // GetMatTexProp(mat, prop.texCoord, "texCoord", tt, slot);
  555. GetMatTexProp(mat, prop.strength, "strength", tt, slot);
  556. }
  557. }
  558. aiReturn glTF2Exporter::GetMatColor(const aiMaterial &mat, vec4 &prop, const char *propName, int type, int idx) const {
  559. aiColor4D col;
  560. aiReturn result = mat.Get(propName, type, idx, col);
  561. if (result == AI_SUCCESS) {
  562. prop[0] = col.r;
  563. prop[1] = col.g;
  564. prop[2] = col.b;
  565. prop[3] = col.a;
  566. }
  567. return result;
  568. }
  569. aiReturn glTF2Exporter::GetMatColor(const aiMaterial &mat, vec3 &prop, const char *propName, int type, int idx) const {
  570. aiColor3D col;
  571. aiReturn result = mat.Get(propName, type, idx, col);
  572. if (result == AI_SUCCESS) {
  573. prop[0] = col.r;
  574. prop[1] = col.g;
  575. prop[2] = col.b;
  576. }
  577. return result;
  578. }
  579. // This extension has been deprecated, only export with the specific flag enabled, defaults to false. Uses KHR_material_specular default.
  580. bool glTF2Exporter::GetMatSpecGloss(const aiMaterial &mat, glTF2::PbrSpecularGlossiness &pbrSG) {
  581. bool result = false;
  582. // If has Glossiness, a Specular Color or Specular Texture, use the KHR_materials_pbrSpecularGlossiness extension
  583. if (mat.Get(AI_MATKEY_GLOSSINESS_FACTOR, pbrSG.glossinessFactor) == AI_SUCCESS) {
  584. result = true;
  585. } else {
  586. // Don't have explicit glossiness, convert from pbr roughness or legacy shininess
  587. float shininess;
  588. if (mat.Get(AI_MATKEY_ROUGHNESS_FACTOR, shininess) == AI_SUCCESS) {
  589. pbrSG.glossinessFactor = 1.0f - shininess; // Extension defines this way
  590. } else if (mat.Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS) {
  591. pbrSG.glossinessFactor = shininess / 1000;
  592. }
  593. }
  594. if (GetMatColor(mat, pbrSG.specularFactor, AI_MATKEY_COLOR_SPECULAR) == AI_SUCCESS) {
  595. result = true;
  596. }
  597. // Add any appropriate textures
  598. GetMatTex(mat, pbrSG.specularGlossinessTexture, aiTextureType_SPECULAR);
  599. result = result || pbrSG.specularGlossinessTexture.texture;
  600. if (result) {
  601. // Likely to always have diffuse
  602. GetMatTex(mat, pbrSG.diffuseTexture, aiTextureType_DIFFUSE);
  603. GetMatColor(mat, pbrSG.diffuseFactor, AI_MATKEY_COLOR_DIFFUSE);
  604. }
  605. return result;
  606. }
  607. bool glTF2Exporter::GetMatSpecular(const aiMaterial &mat, glTF2::MaterialSpecular &specular) {
  608. // Specular requires either/or, default factors of zero disables specular, so do not export
  609. if (GetMatColor(mat, specular.specularColorFactor, AI_MATKEY_COLOR_SPECULAR) != AI_SUCCESS && mat.Get(AI_MATKEY_SPECULAR_FACTOR, specular.specularFactor) != AI_SUCCESS) {
  610. return false;
  611. }
  612. // The spec states that the default is 1.0 and [1.0, 1.0, 1.0]. We if both are 0, which should disable specular. Otherwise, if one is 0, set to 1.0
  613. const bool colorFactorIsZero = specular.specularColorFactor[0] == defaultSpecularColorFactor[0] && specular.specularColorFactor[1] == defaultSpecularColorFactor[1] && specular.specularColorFactor[2] == defaultSpecularColorFactor[2];
  614. if (specular.specularFactor == 0.0f && colorFactorIsZero) {
  615. return false;
  616. } else if (specular.specularFactor == 0.0f) {
  617. specular.specularFactor = 1.0f;
  618. } else if (colorFactorIsZero) {
  619. specular.specularColorFactor[0] = specular.specularColorFactor[1] = specular.specularColorFactor[2] = 1.0f;
  620. }
  621. GetMatTex(mat, specular.specularTexture, aiTextureType_SPECULAR, 0);
  622. GetMatTex(mat, specular.specularColorTexture, aiTextureType_SPECULAR, 1);
  623. return true;
  624. }
  625. bool glTF2Exporter::GetMatSheen(const aiMaterial &mat, glTF2::MaterialSheen &sheen) {
  626. // Return true if got any valid Sheen properties or textures
  627. if (GetMatColor(mat, sheen.sheenColorFactor, AI_MATKEY_SHEEN_COLOR_FACTOR) != aiReturn_SUCCESS) {
  628. return false;
  629. }
  630. // Default Sheen color factor {0,0,0} disables Sheen, so do not export
  631. if (sheen.sheenColorFactor[0] == defaultSheenFactor[0] && sheen.sheenColorFactor[1] == defaultSheenFactor[1] && sheen.sheenColorFactor[2] == defaultSheenFactor[2]) {
  632. return false;
  633. }
  634. mat.Get(AI_MATKEY_SHEEN_ROUGHNESS_FACTOR, sheen.sheenRoughnessFactor);
  635. GetMatTex(mat, sheen.sheenColorTexture, AI_MATKEY_SHEEN_COLOR_TEXTURE);
  636. GetMatTex(mat, sheen.sheenRoughnessTexture, AI_MATKEY_SHEEN_ROUGHNESS_TEXTURE);
  637. return true;
  638. }
  639. bool glTF2Exporter::GetMatClearcoat(const aiMaterial &mat, glTF2::MaterialClearcoat &clearcoat) {
  640. if (mat.Get(AI_MATKEY_CLEARCOAT_FACTOR, clearcoat.clearcoatFactor) != aiReturn_SUCCESS) {
  641. return false;
  642. }
  643. // Clearcoat factor of zero disables Clearcoat, so do not export
  644. if (clearcoat.clearcoatFactor == 0.0f)
  645. return false;
  646. mat.Get(AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR, clearcoat.clearcoatRoughnessFactor);
  647. GetMatTex(mat, clearcoat.clearcoatTexture, AI_MATKEY_CLEARCOAT_TEXTURE);
  648. GetMatTex(mat, clearcoat.clearcoatRoughnessTexture, AI_MATKEY_CLEARCOAT_ROUGHNESS_TEXTURE);
  649. GetMatTex(mat, clearcoat.clearcoatNormalTexture, AI_MATKEY_CLEARCOAT_NORMAL_TEXTURE);
  650. return true;
  651. }
  652. bool glTF2Exporter::GetMatTransmission(const aiMaterial &mat, glTF2::MaterialTransmission &transmission) {
  653. bool result = mat.Get(AI_MATKEY_TRANSMISSION_FACTOR, transmission.transmissionFactor) == aiReturn_SUCCESS;
  654. GetMatTex(mat, transmission.transmissionTexture, AI_MATKEY_TRANSMISSION_TEXTURE);
  655. return result || transmission.transmissionTexture.texture;
  656. }
  657. bool glTF2Exporter::GetMatVolume(const aiMaterial &mat, glTF2::MaterialVolume &volume) {
  658. bool result = mat.Get(AI_MATKEY_VOLUME_THICKNESS_FACTOR, volume.thicknessFactor) != aiReturn_SUCCESS;
  659. GetMatTex(mat, volume.thicknessTexture, AI_MATKEY_VOLUME_THICKNESS_TEXTURE);
  660. result = result || mat.Get(AI_MATKEY_VOLUME_ATTENUATION_DISTANCE, volume.attenuationDistance);
  661. result = result || GetMatColor(mat, volume.attenuationColor, AI_MATKEY_VOLUME_ATTENUATION_COLOR) != aiReturn_SUCCESS;
  662. // Valid if any of these properties are available
  663. return result || volume.thicknessTexture.texture;
  664. }
  665. bool glTF2Exporter::GetMatIOR(const aiMaterial &mat, glTF2::MaterialIOR &ior) {
  666. return mat.Get(AI_MATKEY_REFRACTI, ior.ior) == aiReturn_SUCCESS;
  667. }
  668. bool glTF2Exporter::GetMatEmissiveStrength(const aiMaterial &mat, glTF2::MaterialEmissiveStrength &emissiveStrength) {
  669. return mat.Get(AI_MATKEY_EMISSIVE_INTENSITY, emissiveStrength.emissiveStrength) == aiReturn_SUCCESS;
  670. }
  671. void glTF2Exporter::ExportMaterials() {
  672. aiString aiName;
  673. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  674. ai_assert(mScene->mMaterials[i] != nullptr);
  675. const aiMaterial &mat = *(mScene->mMaterials[i]);
  676. std::string id = "material_" + ai_to_string(i);
  677. Ref<Material> m = mAsset->materials.Create(id);
  678. std::string name;
  679. if (mat.Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  680. name = aiName.C_Str();
  681. }
  682. name = mAsset->FindUniqueID(name, "material");
  683. m->name = name;
  684. GetMatTex(mat, m->pbrMetallicRoughness.baseColorTexture, aiTextureType_BASE_COLOR);
  685. if (!m->pbrMetallicRoughness.baseColorTexture.texture) {
  686. // if there wasn't a baseColorTexture defined in the source, fallback to any diffuse texture
  687. GetMatTex(mat, m->pbrMetallicRoughness.baseColorTexture, aiTextureType_DIFFUSE);
  688. }
  689. GetMatTex(mat, m->pbrMetallicRoughness.metallicRoughnessTexture, aiTextureType_DIFFUSE_ROUGHNESS);
  690. if (!m->pbrMetallicRoughness.metallicRoughnessTexture.texture) {
  691. // if there wasn't a aiTextureType_DIFFUSE_ROUGHNESS defined in the source, fallback to aiTextureType_METALNESS
  692. GetMatTex(mat, m->pbrMetallicRoughness.metallicRoughnessTexture, aiTextureType_METALNESS);
  693. }
  694. if (!m->pbrMetallicRoughness.metallicRoughnessTexture.texture) {
  695. // if there still wasn't a aiTextureType_METALNESS defined in the source, fallback to AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE
  696. GetMatTex(mat, m->pbrMetallicRoughness.metallicRoughnessTexture, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  697. }
  698. if (GetMatColor(mat, m->pbrMetallicRoughness.baseColorFactor, AI_MATKEY_BASE_COLOR) != AI_SUCCESS) {
  699. // if baseColorFactor wasn't defined, then the source is likely not a metallic roughness material.
  700. // a fallback to any diffuse color should be used instead
  701. GetMatColor(mat, m->pbrMetallicRoughness.baseColorFactor, AI_MATKEY_COLOR_DIFFUSE);
  702. }
  703. if (mat.Get(AI_MATKEY_METALLIC_FACTOR, m->pbrMetallicRoughness.metallicFactor) != AI_SUCCESS) {
  704. // if metallicFactor wasn't defined, then the source is likely not a PBR file, and the metallicFactor should be 0
  705. m->pbrMetallicRoughness.metallicFactor = 0;
  706. }
  707. // get roughness if source is gltf2 file
  708. if (mat.Get(AI_MATKEY_ROUGHNESS_FACTOR, m->pbrMetallicRoughness.roughnessFactor) != AI_SUCCESS) {
  709. // otherwise, try to derive and convert from specular + shininess values
  710. aiColor4D specularColor;
  711. ai_real shininess;
  712. if (mat.Get(AI_MATKEY_COLOR_SPECULAR, specularColor) == AI_SUCCESS && mat.Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS) {
  713. // convert specular color to luminance
  714. float specularIntensity = specularColor[0] * 0.2125f + specularColor[1] * 0.7154f + specularColor[2] * 0.0721f;
  715. // normalize shininess (assuming max is 1000) with an inverse exponentional curve
  716. float normalizedShininess = std::sqrt(shininess / 1000);
  717. // clamp the shininess value between 0 and 1
  718. normalizedShininess = std::min(std::max(normalizedShininess, 0.0f), 1.0f);
  719. // low specular intensity values should produce a rough material even if shininess is high.
  720. normalizedShininess = normalizedShininess * specularIntensity;
  721. m->pbrMetallicRoughness.roughnessFactor = 1 - normalizedShininess;
  722. }
  723. }
  724. GetMatTex(mat, m->normalTexture, aiTextureType_NORMALS);
  725. GetMatTex(mat, m->occlusionTexture, aiTextureType_LIGHTMAP);
  726. GetMatTex(mat, m->emissiveTexture, aiTextureType_EMISSIVE);
  727. GetMatColor(mat, m->emissiveFactor, AI_MATKEY_COLOR_EMISSIVE);
  728. mat.Get(AI_MATKEY_TWOSIDED, m->doubleSided);
  729. mat.Get(AI_MATKEY_GLTF_ALPHACUTOFF, m->alphaCutoff);
  730. float opacity;
  731. aiString alphaMode;
  732. if (mat.Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS) {
  733. if (opacity < 1) {
  734. m->alphaMode = "BLEND";
  735. m->pbrMetallicRoughness.baseColorFactor[3] *= opacity;
  736. }
  737. }
  738. if (mat.Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode) == AI_SUCCESS) {
  739. m->alphaMode = alphaMode.C_Str();
  740. }
  741. // This extension has been deprecated, only export with the specific flag enabled, defaults to false. Uses KHR_material_specular default.
  742. if (mProperties->GetPropertyBool(AI_CONFIG_USE_GLTF_PBR_SPECULAR_GLOSSINESS)) {
  743. // KHR_materials_pbrSpecularGlossiness extension
  744. PbrSpecularGlossiness pbrSG;
  745. if (GetMatSpecGloss(mat, pbrSG)) {
  746. mAsset->extensionsUsed.KHR_materials_pbrSpecularGlossiness = true;
  747. m->pbrSpecularGlossiness = Nullable<PbrSpecularGlossiness>(pbrSG);
  748. }
  749. }
  750. // glTFv2 is either PBR or Unlit
  751. aiShadingMode shadingMode = aiShadingMode_PBR_BRDF;
  752. mat.Get(AI_MATKEY_SHADING_MODEL, shadingMode);
  753. if (shadingMode == aiShadingMode_Unlit) {
  754. mAsset->extensionsUsed.KHR_materials_unlit = true;
  755. m->unlit = true;
  756. } else {
  757. // These extensions are not compatible with KHR_materials_unlit or KHR_materials_pbrSpecularGlossiness
  758. if (!m->pbrSpecularGlossiness.isPresent) {
  759. MaterialSpecular specular;
  760. if (GetMatSpecular(mat, specular)) {
  761. mAsset->extensionsUsed.KHR_materials_specular = true;
  762. m->materialSpecular = Nullable<MaterialSpecular>(specular);
  763. GetMatColor(mat, m->pbrMetallicRoughness.baseColorFactor, AI_MATKEY_COLOR_DIFFUSE);
  764. }
  765. MaterialSheen sheen;
  766. if (GetMatSheen(mat, sheen)) {
  767. mAsset->extensionsUsed.KHR_materials_sheen = true;
  768. m->materialSheen = Nullable<MaterialSheen>(sheen);
  769. }
  770. MaterialClearcoat clearcoat;
  771. if (GetMatClearcoat(mat, clearcoat)) {
  772. mAsset->extensionsUsed.KHR_materials_clearcoat = true;
  773. m->materialClearcoat = Nullable<MaterialClearcoat>(clearcoat);
  774. }
  775. MaterialTransmission transmission;
  776. if (GetMatTransmission(mat, transmission)) {
  777. mAsset->extensionsUsed.KHR_materials_transmission = true;
  778. m->materialTransmission = Nullable<MaterialTransmission>(transmission);
  779. }
  780. MaterialVolume volume;
  781. if (GetMatVolume(mat, volume)) {
  782. mAsset->extensionsUsed.KHR_materials_volume = true;
  783. m->materialVolume = Nullable<MaterialVolume>(volume);
  784. }
  785. MaterialIOR ior;
  786. if (GetMatIOR(mat, ior)) {
  787. mAsset->extensionsUsed.KHR_materials_ior = true;
  788. m->materialIOR = Nullable<MaterialIOR>(ior);
  789. }
  790. MaterialEmissiveStrength emissiveStrength;
  791. if (GetMatEmissiveStrength(mat, emissiveStrength)) {
  792. mAsset->extensionsUsed.KHR_materials_emissive_strength = true;
  793. m->materialEmissiveStrength = Nullable<MaterialEmissiveStrength>(emissiveStrength);
  794. }
  795. }
  796. }
  797. }
  798. }
  799. /*
  800. * Search through node hierarchy and find the node containing the given meshID.
  801. * Returns true on success, and false otherwise.
  802. */
  803. bool FindMeshNode(Ref<Node> &nodeIn, Ref<Node> &meshNode, const std::string &meshID) {
  804. for (unsigned int i = 0; i < nodeIn->meshes.size(); ++i) {
  805. if (meshID.compare(nodeIn->meshes[i]->id) == 0) {
  806. meshNode = nodeIn;
  807. return true;
  808. }
  809. }
  810. for (unsigned int i = 0; i < nodeIn->children.size(); ++i) {
  811. if (FindMeshNode(nodeIn->children[i], meshNode, meshID)) {
  812. return true;
  813. }
  814. }
  815. return false;
  816. }
  817. /*
  818. * Find the root joint of the skeleton.
  819. * Starts will any joint node and traces up the tree,
  820. * until a parent is found that does not have a jointName.
  821. * Returns the first parent Ref<Node> found that does not have a jointName.
  822. */
  823. Ref<Node> FindSkeletonRootJoint(Ref<Skin> &skinRef) {
  824. Ref<Node> startNodeRef;
  825. Ref<Node> parentNodeRef;
  826. // Arbitrarily use the first joint to start the search.
  827. startNodeRef = skinRef->jointNames[0];
  828. parentNodeRef = skinRef->jointNames[0];
  829. do {
  830. startNodeRef = parentNodeRef;
  831. parentNodeRef = startNodeRef->parent;
  832. } while (parentNodeRef && !parentNodeRef->jointName.empty());
  833. return parentNodeRef;
  834. }
  835. struct boneIndexWeightPair {
  836. unsigned int indexJoint;
  837. float weight;
  838. bool operator()(boneIndexWeightPair &a, boneIndexWeightPair &b) {
  839. return a.weight > b.weight;
  840. }
  841. };
  842. void ExportSkin(Asset &mAsset, const aiMesh *aimesh, Ref<Mesh> &meshRef, Ref<Buffer> &bufferRef, Ref<Skin> &skinRef,
  843. std::vector<aiMatrix4x4> &inverseBindMatricesData, bool unlimitedBonesPerVertex) {
  844. if (aimesh->mNumBones < 1) {
  845. return;
  846. }
  847. // Store the vertex joint and weight data.
  848. const size_t NumVerts(aimesh->mNumVertices);
  849. int *jointsPerVertex = new int[NumVerts];
  850. std::vector<std::vector<boneIndexWeightPair>> allVerticesPairs;
  851. int maxJointsPerVertex = 0;
  852. for (size_t i = 0; i < NumVerts; ++i) {
  853. jointsPerVertex[i] = 0;
  854. std::vector<boneIndexWeightPair> vertexPair;
  855. allVerticesPairs.push_back(vertexPair);
  856. }
  857. for (unsigned int idx_bone = 0; idx_bone < aimesh->mNumBones; ++idx_bone) {
  858. const aiBone *aib = aimesh->mBones[idx_bone];
  859. // aib->mName =====> skinRef->jointNames
  860. // Find the node with id = mName.
  861. Ref<Node> nodeRef = mAsset.nodes.Get(aib->mName.C_Str());
  862. nodeRef->jointName = nodeRef->name;
  863. unsigned int jointNamesIndex = 0;
  864. bool addJointToJointNames = true;
  865. for (unsigned int idx_joint = 0; idx_joint < skinRef->jointNames.size(); ++idx_joint) {
  866. if (skinRef->jointNames[idx_joint]->jointName.compare(nodeRef->jointName) == 0) {
  867. addJointToJointNames = false;
  868. jointNamesIndex = idx_joint;
  869. }
  870. }
  871. if (addJointToJointNames) {
  872. skinRef->jointNames.push_back(nodeRef);
  873. // aib->mOffsetMatrix =====> skinRef->inverseBindMatrices
  874. aiMatrix4x4 tmpMatrix4;
  875. CopyValue(aib->mOffsetMatrix, tmpMatrix4);
  876. inverseBindMatricesData.push_back(tmpMatrix4);
  877. jointNamesIndex = static_cast<unsigned int>(inverseBindMatricesData.size() - 1);
  878. }
  879. // aib->mWeights =====> temp pairs data
  880. for (unsigned int idx_weights = 0; idx_weights < aib->mNumWeights;
  881. ++idx_weights) {
  882. unsigned int vertexId = aib->mWeights[idx_weights].mVertexId;
  883. float vertWeight = aib->mWeights[idx_weights].mWeight;
  884. allVerticesPairs[vertexId].push_back({jointNamesIndex, vertWeight});
  885. jointsPerVertex[vertexId] += 1;
  886. maxJointsPerVertex =
  887. std::max(maxJointsPerVertex, jointsPerVertex[vertexId]);
  888. }
  889. } // End: for-loop mNumMeshes
  890. if (!unlimitedBonesPerVertex){
  891. // skinning limited only for 4 bones per vertex, default
  892. maxJointsPerVertex = 4;
  893. }
  894. // temp pairs data =====> vertexWeightData
  895. size_t numGroups = (maxJointsPerVertex - 1) / 4 + 1;
  896. vec4 *vertexJointData = new vec4[NumVerts * numGroups];
  897. vec4 *vertexWeightData = new vec4[NumVerts * numGroups];
  898. for (size_t indexVertex = 0; indexVertex < NumVerts; ++indexVertex) {
  899. // order pairs by weight for each vertex
  900. std::sort(allVerticesPairs[indexVertex].begin(),
  901. allVerticesPairs[indexVertex].end(),
  902. boneIndexWeightPair());
  903. for (size_t indexGroup = 0; indexGroup < numGroups; ++indexGroup) {
  904. for (size_t indexJoint = 0; indexJoint < 4; ++indexJoint) {
  905. size_t indexBone = indexGroup * 4 + indexJoint;
  906. size_t indexData = indexVertex + NumVerts * indexGroup;
  907. if (indexBone >= allVerticesPairs[indexVertex].size()) {
  908. vertexJointData[indexData][indexJoint] = 0.f;
  909. vertexWeightData[indexData][indexJoint] = 0.f;
  910. } else {
  911. vertexJointData[indexData][indexJoint] =
  912. static_cast<float>(
  913. allVerticesPairs[indexVertex][indexBone].indexJoint);
  914. vertexWeightData[indexData][indexJoint] =
  915. allVerticesPairs[indexVertex][indexBone].weight;
  916. }
  917. }
  918. }
  919. }
  920. for (size_t idx_group = 0; idx_group < numGroups; ++idx_group) {
  921. Mesh::Primitive &p = meshRef->primitives.back();
  922. Ref<Accessor> vertexJointAccessor = ExportData(
  923. mAsset, skinRef->id, bufferRef, aimesh->mNumVertices,
  924. vertexJointData + idx_group * NumVerts,
  925. AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  926. if (vertexJointAccessor) {
  927. size_t offset = vertexJointAccessor->bufferView->byteOffset;
  928. size_t bytesLen = vertexJointAccessor->bufferView->byteLength;
  929. unsigned int s_bytesPerComp =
  930. ComponentTypeSize(ComponentType_UNSIGNED_SHORT);
  931. unsigned int bytesPerComp =
  932. ComponentTypeSize(vertexJointAccessor->componentType);
  933. size_t s_bytesLen = bytesLen * s_bytesPerComp / bytesPerComp;
  934. Ref<Buffer> buf = vertexJointAccessor->bufferView->buffer;
  935. uint8_t *arrys = new uint8_t[bytesLen];
  936. unsigned int i = 0;
  937. for (unsigned int j = 0; j < bytesLen; j += bytesPerComp) {
  938. size_t len_p = offset + j;
  939. float f_value = *(float *)&buf->GetPointer()[len_p];
  940. unsigned short c = static_cast<unsigned short>(f_value);
  941. memcpy(&arrys[i * s_bytesPerComp], &c, s_bytesPerComp);
  942. ++i;
  943. }
  944. buf->ReplaceData_joint(offset, bytesLen, arrys, bytesLen);
  945. vertexJointAccessor->componentType = ComponentType_UNSIGNED_SHORT;
  946. vertexJointAccessor->bufferView->byteLength = s_bytesLen;
  947. p.attributes.joint.push_back(vertexJointAccessor);
  948. delete[] arrys;
  949. }
  950. Ref<Accessor> vertexWeightAccessor = ExportData(
  951. mAsset, skinRef->id, bufferRef, aimesh->mNumVertices,
  952. vertexWeightData + idx_group * NumVerts,
  953. AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  954. if (vertexWeightAccessor) {
  955. p.attributes.weight.push_back(vertexWeightAccessor);
  956. }
  957. }
  958. delete[] jointsPerVertex;
  959. delete[] vertexWeightData;
  960. delete[] vertexJointData;
  961. }
  962. void glTF2Exporter::ExportMeshes() {
  963. typedef decltype(aiFace::mNumIndices) IndicesType;
  964. std::string fname = std::string(mFilename);
  965. std::string bufferIdPrefix = fname.substr(0, fname.rfind(".gltf"));
  966. std::string bufferId = mAsset->FindUniqueID("", bufferIdPrefix.c_str());
  967. Ref<Buffer> b = mAsset->GetBodyBuffer();
  968. if (!b) {
  969. b = mAsset->buffers.Create(bufferId);
  970. }
  971. //----------------------------------------
  972. // Initialize variables for the skin
  973. bool createSkin = false;
  974. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  975. const aiMesh *aim = mScene->mMeshes[idx_mesh];
  976. if (aim->HasBones()) {
  977. createSkin = true;
  978. break;
  979. }
  980. }
  981. Ref<Skin> skinRef;
  982. std::string skinName = mAsset->FindUniqueID("skin", "skin");
  983. std::vector<aiMatrix4x4> inverseBindMatricesData;
  984. if (createSkin) {
  985. skinRef = mAsset->skins.Create(skinName);
  986. skinRef->name = skinName;
  987. }
  988. //----------------------------------------
  989. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  990. const aiMesh *aim = mScene->mMeshes[idx_mesh];
  991. if (aim->mNumFaces == 0) {
  992. continue;
  993. }
  994. std::string name = aim->mName.C_Str();
  995. std::string meshId = mAsset->FindUniqueID(name, "mesh");
  996. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  997. m->primitives.resize(1);
  998. Mesh::Primitive &p = m->primitives.back();
  999. m->name = name;
  1000. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  1001. p.ngonEncoded = (aim->mPrimitiveTypes & aiPrimitiveType_NGONEncodingFlag) != 0;
  1002. /******************* Vertices ********************/
  1003. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3,
  1004. AttribType::VEC3, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  1005. if (v) {
  1006. p.attributes.position.push_back(v);
  1007. }
  1008. /******************** Normals ********************/
  1009. // Normalize all normals as the validator can emit a warning otherwise
  1010. if (nullptr != aim->mNormals) {
  1011. for (auto i = 0u; i < aim->mNumVertices; ++i) {
  1012. aim->mNormals[i].NormalizeSafe();
  1013. }
  1014. }
  1015. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3,
  1016. AttribType::VEC3, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  1017. if (n) {
  1018. p.attributes.normal.push_back(n);
  1019. }
  1020. /******************** Tangents ********************/
  1021. if (nullptr != aim->mTangents) {
  1022. for (uint32_t i = 0; i < aim->mNumVertices; ++i) {
  1023. aim->mTangents[i].NormalizeSafe();
  1024. }
  1025. Ref<Accessor> t = ExportData(
  1026. *mAsset, meshId, b, aim->mNumVertices, aim->mTangents, AttribType::VEC3,
  1027. AttribType::VEC3, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER
  1028. );
  1029. if (t) {
  1030. p.attributes.tangent.push_back(t);
  1031. }
  1032. }
  1033. /************** Texture coordinates **************/
  1034. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  1035. if (!aim->HasTextureCoords(i)) {
  1036. continue;
  1037. }
  1038. // Flip UV y coords
  1039. if (aim->mNumUVComponents[i] > 1) {
  1040. for (unsigned int j = 0; j < aim->mNumVertices; ++j) {
  1041. aim->mTextureCoords[i][j].y = 1 - aim->mTextureCoords[i][j].y;
  1042. }
  1043. }
  1044. if (aim->mNumUVComponents[i] > 0) {
  1045. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  1046. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i],
  1047. AttribType::VEC3, type, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  1048. if (tc) {
  1049. p.attributes.texcoord.push_back(tc);
  1050. }
  1051. }
  1052. }
  1053. /*************** Vertex colors ****************/
  1054. for (unsigned int indexColorChannel = 0; indexColorChannel < aim->GetNumColorChannels(); ++indexColorChannel) {
  1055. Ref<Accessor> c = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mColors[indexColorChannel],
  1056. AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  1057. if (c) {
  1058. p.attributes.color.push_back(c);
  1059. }
  1060. }
  1061. /*************** Vertices indices ****************/
  1062. if (aim->mNumFaces > 0) {
  1063. std::vector<IndicesType> indices;
  1064. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  1065. indices.resize(aim->mNumFaces * nIndicesPerFace);
  1066. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  1067. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  1068. indices[i * nIndicesPerFace + j] = IndicesType(aim->mFaces[i].mIndices[j]);
  1069. }
  1070. }
  1071. p.indices = ExportData(*mAsset, meshId, b, indices.size(), &indices[0], AttribType::SCALAR, AttribType::SCALAR,
  1072. ComponentType_UNSIGNED_INT, BufferViewTarget_ELEMENT_ARRAY_BUFFER);
  1073. }
  1074. switch (aim->mPrimitiveTypes) {
  1075. case aiPrimitiveType_POLYGON:
  1076. p.mode = PrimitiveMode_TRIANGLES;
  1077. break; // TODO implement this
  1078. case aiPrimitiveType_LINE:
  1079. p.mode = PrimitiveMode_LINES;
  1080. break;
  1081. case aiPrimitiveType_POINT:
  1082. p.mode = PrimitiveMode_POINTS;
  1083. break;
  1084. default: // aiPrimitiveType_TRIANGLE
  1085. p.mode = PrimitiveMode_TRIANGLES;
  1086. break;
  1087. }
  1088. // /*************** Skins ****************/
  1089. // if (aim->HasBones()) {
  1090. // ExportSkin(*mAsset, aim, m, b, skinRef, inverseBindMatricesData);
  1091. // }
  1092. /*************** Skins ****************/
  1093. if (aim->HasBones()) {
  1094. bool unlimitedBonesPerVertex =
  1095. this->mProperties->HasPropertyBool(
  1096. AI_CONFIG_EXPORT_GLTF_UNLIMITED_SKINNING_BONES_PER_VERTEX) &&
  1097. this->mProperties->GetPropertyBool(
  1098. AI_CONFIG_EXPORT_GLTF_UNLIMITED_SKINNING_BONES_PER_VERTEX);
  1099. ExportSkin(*mAsset, aim, m, b, skinRef, inverseBindMatricesData,
  1100. unlimitedBonesPerVertex);
  1101. }
  1102. /*************** Targets for blendshapes ****************/
  1103. if (aim->mNumAnimMeshes > 0) {
  1104. bool bUseSparse = this->mProperties->HasPropertyBool("GLTF2_SPARSE_ACCESSOR_EXP") &&
  1105. this->mProperties->GetPropertyBool("GLTF2_SPARSE_ACCESSOR_EXP");
  1106. bool bIncludeNormal = this->mProperties->HasPropertyBool("GLTF2_TARGET_NORMAL_EXP") &&
  1107. this->mProperties->GetPropertyBool("GLTF2_TARGET_NORMAL_EXP");
  1108. bool bExportTargetNames = this->mProperties->HasPropertyBool("GLTF2_TARGETNAMES_EXP") &&
  1109. this->mProperties->GetPropertyBool("GLTF2_TARGETNAMES_EXP");
  1110. p.targets.resize(aim->mNumAnimMeshes);
  1111. for (unsigned int am = 0; am < aim->mNumAnimMeshes; ++am) {
  1112. aiAnimMesh *pAnimMesh = aim->mAnimMeshes[am];
  1113. if (bExportTargetNames) {
  1114. m->targetNames.emplace_back(pAnimMesh->mName.data);
  1115. }
  1116. // position
  1117. if (pAnimMesh->HasPositions()) {
  1118. // NOTE: in gltf it is the diff stored
  1119. aiVector3D *pPositionDiff = new aiVector3D[pAnimMesh->mNumVertices];
  1120. for (unsigned int vt = 0; vt < pAnimMesh->mNumVertices; ++vt) {
  1121. pPositionDiff[vt] = pAnimMesh->mVertices[vt] - aim->mVertices[vt];
  1122. }
  1123. Ref<Accessor> vec;
  1124. if (bUseSparse) {
  1125. vec = ExportDataSparse(*mAsset, meshId, b,
  1126. pAnimMesh->mNumVertices, pPositionDiff,
  1127. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1128. } else {
  1129. vec = ExportData(*mAsset, meshId, b,
  1130. pAnimMesh->mNumVertices, pPositionDiff,
  1131. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1132. }
  1133. if (vec) {
  1134. p.targets[am].position.push_back(vec);
  1135. }
  1136. delete[] pPositionDiff;
  1137. }
  1138. // normal
  1139. if (pAnimMesh->HasNormals() && bIncludeNormal) {
  1140. aiVector3D *pNormalDiff = new aiVector3D[pAnimMesh->mNumVertices];
  1141. for (unsigned int vt = 0; vt < pAnimMesh->mNumVertices; ++vt) {
  1142. pNormalDiff[vt] = pAnimMesh->mNormals[vt] - aim->mNormals[vt];
  1143. }
  1144. Ref<Accessor> vec;
  1145. if (bUseSparse) {
  1146. vec = ExportDataSparse(*mAsset, meshId, b,
  1147. pAnimMesh->mNumVertices, pNormalDiff,
  1148. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1149. } else {
  1150. vec = ExportData(*mAsset, meshId, b,
  1151. pAnimMesh->mNumVertices, pNormalDiff,
  1152. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1153. }
  1154. if (vec) {
  1155. p.targets[am].normal.push_back(vec);
  1156. }
  1157. delete[] pNormalDiff;
  1158. }
  1159. // tangent?
  1160. }
  1161. }
  1162. }
  1163. //----------------------------------------
  1164. // Finish the skin
  1165. // Create the Accessor for skinRef->inverseBindMatrices
  1166. bool bAddCustomizedProperty = this->mProperties->HasPropertyBool("GLTF2_CUSTOMIZE_PROPERTY");
  1167. if (createSkin) {
  1168. mat4 *invBindMatrixData = new mat4[inverseBindMatricesData.size()];
  1169. for (unsigned int idx_joint = 0; idx_joint < inverseBindMatricesData.size(); ++idx_joint) {
  1170. CopyValue(inverseBindMatricesData[idx_joint], invBindMatrixData[idx_joint]);
  1171. }
  1172. Ref<Accessor> invBindMatrixAccessor = ExportData(*mAsset, skinName, b,
  1173. static_cast<unsigned int>(inverseBindMatricesData.size()),
  1174. invBindMatrixData, AttribType::MAT4, AttribType::MAT4, ComponentType_FLOAT);
  1175. if (invBindMatrixAccessor) {
  1176. skinRef->inverseBindMatrices = invBindMatrixAccessor;
  1177. }
  1178. // Identity Matrix =====> skinRef->bindShapeMatrix
  1179. // Temporary. Hard-coded identity matrix here
  1180. skinRef->bindShapeMatrix.isPresent = bAddCustomizedProperty;
  1181. IdentityMatrix4(skinRef->bindShapeMatrix.value);
  1182. // Find nodes that contain a mesh with bones and add "skeletons" and "skin" attributes to those nodes.
  1183. Ref<Node> rootNode = mAsset->nodes.Get(unsigned(0));
  1184. Ref<Node> meshNode;
  1185. for (unsigned int meshIndex = 0; meshIndex < mAsset->meshes.Size(); ++meshIndex) {
  1186. Ref<Mesh> mesh = mAsset->meshes.Get(meshIndex);
  1187. bool hasBones = false;
  1188. for (unsigned int i = 0; i < mesh->primitives.size(); ++i) {
  1189. if (!mesh->primitives[i].attributes.weight.empty()) {
  1190. hasBones = true;
  1191. break;
  1192. }
  1193. }
  1194. if (!hasBones) {
  1195. continue;
  1196. }
  1197. std::string meshID = mesh->id;
  1198. FindMeshNode(rootNode, meshNode, meshID);
  1199. Ref<Node> rootJoint = FindSkeletonRootJoint(skinRef);
  1200. if (bAddCustomizedProperty)
  1201. meshNode->skeletons.push_back(rootJoint);
  1202. meshNode->skin = skinRef;
  1203. }
  1204. delete[] invBindMatrixData;
  1205. }
  1206. }
  1207. // Merges a node's multiple meshes (with one primitive each) into one mesh with multiple primitives
  1208. void glTF2Exporter::MergeMeshes() {
  1209. for (unsigned int n = 0; n < mAsset->nodes.Size(); ++n) {
  1210. Ref<Node> node = mAsset->nodes.Get(n);
  1211. unsigned int nMeshes = static_cast<unsigned int>(node->meshes.size());
  1212. // skip if it's 1 or less meshes per node
  1213. if (nMeshes > 1) {
  1214. Ref<Mesh> firstMesh = node->meshes.at(0);
  1215. // loop backwards to allow easy removal of a mesh from a node once it's merged
  1216. for (unsigned int m = nMeshes - 1; m >= 1; --m) {
  1217. Ref<Mesh> mesh = node->meshes.at(m);
  1218. // append this mesh's primitives to the first mesh's primitives
  1219. firstMesh->primitives.insert(
  1220. firstMesh->primitives.end(),
  1221. mesh->primitives.begin(),
  1222. mesh->primitives.end());
  1223. // remove the mesh from the list of meshes
  1224. unsigned int removedIndex = mAsset->meshes.Remove(mesh->id.c_str());
  1225. // find the presence of the removed mesh in other nodes
  1226. for (unsigned int nn = 0; nn < mAsset->nodes.Size(); ++nn) {
  1227. Ref<Node> curNode = mAsset->nodes.Get(nn);
  1228. for (unsigned int mm = 0; mm < curNode->meshes.size(); ++mm) {
  1229. Ref<Mesh> &meshRef = curNode->meshes.at(mm);
  1230. unsigned int meshIndex = meshRef.GetIndex();
  1231. if (meshIndex == removedIndex) {
  1232. curNode->meshes.erase(curNode->meshes.begin() + mm);
  1233. } else if (meshIndex > removedIndex) {
  1234. Ref<Mesh> newMeshRef = mAsset->meshes.Get(meshIndex - 1);
  1235. meshRef = newMeshRef;
  1236. }
  1237. }
  1238. }
  1239. }
  1240. // since we were looping backwards, reverse the order of merged primitives to their original order
  1241. std::reverse(firstMesh->primitives.begin() + 1, firstMesh->primitives.end());
  1242. }
  1243. }
  1244. }
  1245. /*
  1246. * Export the root node of the node hierarchy.
  1247. * Calls ExportNode for all children.
  1248. */
  1249. unsigned int glTF2Exporter::ExportNodeHierarchy(const aiNode *n) {
  1250. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  1251. node->name = n->mName.C_Str();
  1252. if (!n->mTransformation.IsIdentity(configEpsilon)) {
  1253. node->matrix.isPresent = true;
  1254. CopyValue(n->mTransformation, node->matrix.value);
  1255. }
  1256. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  1257. node->meshes.emplace_back(mAsset->meshes.Get(n->mMeshes[i]));
  1258. }
  1259. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  1260. unsigned int idx = ExportNode(n->mChildren[i], node);
  1261. node->children.emplace_back(mAsset->nodes.Get(idx));
  1262. }
  1263. return node.GetIndex();
  1264. }
  1265. /*
  1266. * Export node and recursively calls ExportNode for all children.
  1267. * Since these nodes are not the root node, we also export the parent Ref<Node>
  1268. */
  1269. unsigned int glTF2Exporter::ExportNode(const aiNode *n, Ref<Node> &parent) {
  1270. std::string name = mAsset->FindUniqueID(n->mName.C_Str(), "node");
  1271. Ref<Node> node = mAsset->nodes.Create(name);
  1272. node->parent = parent;
  1273. node->name = name;
  1274. ExportNodeExtras(n->mMetaData, node->extras);
  1275. if (!n->mTransformation.IsIdentity(configEpsilon)) {
  1276. if (mScene->mNumAnimations > 0 || (mProperties && mProperties->HasPropertyBool("GLTF2_NODE_IN_TRS"))) {
  1277. aiQuaternion quaternion;
  1278. n->mTransformation.Decompose(*reinterpret_cast<aiVector3D *>(&node->scale.value), quaternion, *reinterpret_cast<aiVector3D *>(&node->translation.value));
  1279. aiVector3D vector(static_cast<ai_real>(1.0f), static_cast<ai_real>(1.0f), static_cast<ai_real>(1.0f));
  1280. if (!reinterpret_cast<aiVector3D *>(&node->scale.value)->Equal(vector)) {
  1281. node->scale.isPresent = true;
  1282. }
  1283. if (!reinterpret_cast<aiVector3D *>(&node->translation.value)->Equal(vector)) {
  1284. node->translation.isPresent = true;
  1285. }
  1286. node->rotation.isPresent = true;
  1287. node->rotation.value[0] = quaternion.x;
  1288. node->rotation.value[1] = quaternion.y;
  1289. node->rotation.value[2] = quaternion.z;
  1290. node->rotation.value[3] = quaternion.w;
  1291. node->matrix.isPresent = false;
  1292. } else {
  1293. node->matrix.isPresent = true;
  1294. CopyValue(n->mTransformation, node->matrix.value);
  1295. }
  1296. }
  1297. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  1298. node->meshes.emplace_back(mAsset->meshes.Get(n->mMeshes[i]));
  1299. }
  1300. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  1301. unsigned int idx = ExportNode(n->mChildren[i], node);
  1302. node->children.emplace_back(mAsset->nodes.Get(idx));
  1303. }
  1304. return node.GetIndex();
  1305. }
  1306. void glTF2Exporter::ExportScene() {
  1307. // Use the name of the scene if specified
  1308. const std::string sceneName = (mScene->mName.length > 0) ? mScene->mName.C_Str() : "defaultScene";
  1309. // Ensure unique
  1310. Ref<Scene> scene = mAsset->scenes.Create(mAsset->FindUniqueID(sceneName, ""));
  1311. // root node will be the first one exported (idx 0)
  1312. if (mAsset->nodes.Size() > 0) {
  1313. scene->nodes.emplace_back(mAsset->nodes.Get(0u));
  1314. }
  1315. // set as the default scene
  1316. mAsset->scene = scene;
  1317. }
  1318. void glTF2Exporter::ExportMetadata() {
  1319. AssetMetadata &asset = mAsset->asset;
  1320. asset.version = "2.0";
  1321. char buffer[256];
  1322. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%x)",
  1323. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  1324. asset.generator = buffer;
  1325. // Copyright
  1326. aiString copyright_str;
  1327. if (mScene->mMetaData != nullptr && mScene->mMetaData->Get(AI_METADATA_SOURCE_COPYRIGHT, copyright_str)) {
  1328. asset.copyright = copyright_str.C_Str();
  1329. }
  1330. }
  1331. inline Ref<Accessor> GetSamplerInputRef(Asset &asset, std::string &animId, Ref<Buffer> &buffer, std::vector<ai_real> &times) {
  1332. return ExportData(asset, animId, buffer, (unsigned int)times.size(), &times[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_FLOAT);
  1333. }
  1334. inline void ExtractTranslationSampler(Asset &asset, std::string &animId, Ref<Buffer> &buffer, const aiNodeAnim *nodeChannel, float ticksPerSecond, Animation::Sampler &sampler) {
  1335. const unsigned int numKeyframes = nodeChannel->mNumPositionKeys;
  1336. std::vector<ai_real> times(numKeyframes);
  1337. std::vector<ai_real> values(numKeyframes * 3);
  1338. for (unsigned int i = 0; i < numKeyframes; ++i) {
  1339. const aiVectorKey &key = nodeChannel->mPositionKeys[i];
  1340. // mTime is measured in ticks, but GLTF time is measured in seconds, so convert.
  1341. times[i] = static_cast<float>(key.mTime / ticksPerSecond);
  1342. values[(i * 3) + 0] = (ai_real)key.mValue.x;
  1343. values[(i * 3) + 1] = (ai_real)key.mValue.y;
  1344. values[(i * 3) + 2] = (ai_real)key.mValue.z;
  1345. }
  1346. sampler.input = GetSamplerInputRef(asset, animId, buffer, times);
  1347. sampler.output = ExportData(asset, animId, buffer, numKeyframes, &values[0], AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1348. sampler.interpolation = Interpolation_LINEAR;
  1349. }
  1350. inline void ExtractScaleSampler(Asset &asset, std::string &animId, Ref<Buffer> &buffer, const aiNodeAnim *nodeChannel, float ticksPerSecond, Animation::Sampler &sampler) {
  1351. const unsigned int numKeyframes = nodeChannel->mNumScalingKeys;
  1352. std::vector<ai_real> times(numKeyframes);
  1353. std::vector<ai_real> values(numKeyframes * 3);
  1354. for (unsigned int i = 0; i < numKeyframes; ++i) {
  1355. const aiVectorKey &key = nodeChannel->mScalingKeys[i];
  1356. // mTime is measured in ticks, but GLTF time is measured in seconds, so convert.
  1357. times[i] = static_cast<float>(key.mTime / ticksPerSecond);
  1358. values[(i * 3) + 0] = (ai_real)key.mValue.x;
  1359. values[(i * 3) + 1] = (ai_real)key.mValue.y;
  1360. values[(i * 3) + 2] = (ai_real)key.mValue.z;
  1361. }
  1362. sampler.input = GetSamplerInputRef(asset, animId, buffer, times);
  1363. sampler.output = ExportData(asset, animId, buffer, numKeyframes, &values[0], AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1364. sampler.interpolation = Interpolation_LINEAR;
  1365. }
  1366. inline void ExtractRotationSampler(Asset &asset, std::string &animId, Ref<Buffer> &buffer, const aiNodeAnim *nodeChannel, float ticksPerSecond, Animation::Sampler &sampler) {
  1367. const unsigned int numKeyframes = nodeChannel->mNumRotationKeys;
  1368. std::vector<ai_real> times(numKeyframes);
  1369. std::vector<ai_real> values(numKeyframes * 4);
  1370. for (unsigned int i = 0; i < numKeyframes; ++i) {
  1371. const aiQuatKey &key = nodeChannel->mRotationKeys[i];
  1372. // mTime is measured in ticks, but GLTF time is measured in seconds, so convert.
  1373. times[i] = static_cast<float>(key.mTime / ticksPerSecond);
  1374. values[(i * 4) + 0] = (ai_real)key.mValue.x;
  1375. values[(i * 4) + 1] = (ai_real)key.mValue.y;
  1376. values[(i * 4) + 2] = (ai_real)key.mValue.z;
  1377. values[(i * 4) + 3] = (ai_real)key.mValue.w;
  1378. }
  1379. sampler.input = GetSamplerInputRef(asset, animId, buffer, times);
  1380. sampler.output = ExportData(asset, animId, buffer, numKeyframes, &values[0], AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  1381. sampler.interpolation = Interpolation_LINEAR;
  1382. }
  1383. static void AddSampler(Ref<Animation> &animRef, Ref<Node> &nodeRef, Animation::Sampler &sampler, AnimationPath path) {
  1384. Animation::Channel channel;
  1385. channel.sampler = static_cast<int>(animRef->samplers.size());
  1386. channel.target.path = path;
  1387. channel.target.node = nodeRef;
  1388. animRef->channels.push_back(channel);
  1389. animRef->samplers.push_back(sampler);
  1390. }
  1391. void glTF2Exporter::ExportAnimations() {
  1392. Ref<Buffer> bufferRef = mAsset->buffers.Get(unsigned(0));
  1393. for (unsigned int i = 0; i < mScene->mNumAnimations; ++i) {
  1394. const aiAnimation *anim = mScene->mAnimations[i];
  1395. const float ticksPerSecond = static_cast<float>(anim->mTicksPerSecond);
  1396. std::string nameAnim = "anim";
  1397. if (anim->mName.length > 0) {
  1398. nameAnim = anim->mName.C_Str();
  1399. }
  1400. Ref<Animation> animRef = mAsset->animations.Create(nameAnim);
  1401. animRef->name = nameAnim;
  1402. for (unsigned int channelIndex = 0; channelIndex < anim->mNumChannels; ++channelIndex) {
  1403. const aiNodeAnim *nodeChannel = anim->mChannels[channelIndex];
  1404. std::string name = nameAnim + "_" + ai_to_string(channelIndex);
  1405. name = mAsset->FindUniqueID(name, "animation");
  1406. Ref<Node> animNode = mAsset->nodes.Get(nodeChannel->mNodeName.C_Str());
  1407. if (nodeChannel->mNumPositionKeys > 0) {
  1408. Animation::Sampler translationSampler;
  1409. ExtractTranslationSampler(*mAsset, name, bufferRef, nodeChannel, ticksPerSecond, translationSampler);
  1410. AddSampler(animRef, animNode, translationSampler, AnimationPath_TRANSLATION);
  1411. }
  1412. if (nodeChannel->mNumRotationKeys > 0) {
  1413. Animation::Sampler rotationSampler;
  1414. ExtractRotationSampler(*mAsset, name, bufferRef, nodeChannel, ticksPerSecond, rotationSampler);
  1415. AddSampler(animRef, animNode, rotationSampler, AnimationPath_ROTATION);
  1416. }
  1417. if (nodeChannel->mNumScalingKeys > 0) {
  1418. Animation::Sampler scaleSampler;
  1419. ExtractScaleSampler(*mAsset, name, bufferRef, nodeChannel, ticksPerSecond, scaleSampler);
  1420. AddSampler(animRef, animNode, scaleSampler, AnimationPath_SCALE);
  1421. }
  1422. }
  1423. } // End: for-loop mNumAnimations
  1424. }
  1425. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  1426. #endif // ASSIMP_BUILD_NO_EXPORT