AssbinFileWriter.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2022, 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. /** @file AssbinFileWriter.cpp
  34. * @brief Implementation of Assbin file writer.
  35. */
  36. #include "AssbinFileWriter.h"
  37. #include "Common/assbin_chunks.h"
  38. #include "PostProcessing/ProcessHelper.h"
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/version.h>
  41. #include <assimp/IOStream.hpp>
  42. #ifdef ASSIMP_BUILD_NO_OWN_ZLIB
  43. #include <zlib.h>
  44. #else
  45. #include "../contrib/zlib/zlib.h"
  46. #endif
  47. #include <ctime>
  48. #if _MSC_VER
  49. #pragma warning(push)
  50. #pragma warning(disable : 4706)
  51. #endif // _MSC_VER
  52. namespace Assimp {
  53. template <typename T>
  54. size_t Write(IOStream *stream, const T &v) {
  55. return stream->Write(&v, sizeof(T), 1);
  56. }
  57. // -----------------------------------------------------------------------------------
  58. // Serialize an aiString
  59. template <>
  60. inline size_t Write<aiString>(IOStream *stream, const aiString &s) {
  61. const size_t s2 = (uint32_t)s.length;
  62. stream->Write(&s, 4, 1);
  63. stream->Write(s.data, s2, 1);
  64. return s2 + 4;
  65. }
  66. // -----------------------------------------------------------------------------------
  67. // Serialize an unsigned int as uint32_t
  68. template <>
  69. inline size_t Write<unsigned int>(IOStream *stream, const unsigned int &w) {
  70. const uint32_t t = (uint32_t)w;
  71. if (w > t) {
  72. // this shouldn't happen, integers in Assimp data structures never exceed 2^32
  73. throw DeadlyExportError("loss of data due to 64 -> 32 bit integer conversion");
  74. }
  75. stream->Write(&t, 4, 1);
  76. return 4;
  77. }
  78. // -----------------------------------------------------------------------------------
  79. // Serialize an unsigned int as uint16_t
  80. template <>
  81. inline size_t Write<uint16_t>(IOStream *stream, const uint16_t &w) {
  82. static_assert(sizeof(uint16_t) == 2, "sizeof(uint16_t)==2");
  83. stream->Write(&w, 2, 1);
  84. return 2;
  85. }
  86. // -----------------------------------------------------------------------------------
  87. // Serialize a float
  88. template <>
  89. inline size_t Write<float>(IOStream *stream, const float &f) {
  90. static_assert(sizeof(float) == 4, "sizeof(float)==4");
  91. stream->Write(&f, 4, 1);
  92. return 4;
  93. }
  94. // -----------------------------------------------------------------------------------
  95. // Serialize a double
  96. template <>
  97. inline size_t Write<double>(IOStream *stream, const double &f) {
  98. static_assert(sizeof(double) == 8, "sizeof(double)==8");
  99. stream->Write(&f, 8, 1);
  100. return 8;
  101. }
  102. // -----------------------------------------------------------------------------------
  103. // Serialize a vec3
  104. template <>
  105. inline size_t Write<aiVector3D>(IOStream *stream, const aiVector3D &v) {
  106. size_t t = Write<float>(stream, v.x);
  107. t += Write<float>(stream, v.y);
  108. t += Write<float>(stream, v.z);
  109. return t;
  110. }
  111. // -----------------------------------------------------------------------------------
  112. // Serialize a color value
  113. template <>
  114. inline size_t Write<aiColor3D>(IOStream *stream, const aiColor3D &v) {
  115. size_t t = Write<float>(stream, v.r);
  116. t += Write<float>(stream, v.g);
  117. t += Write<float>(stream, v.b);
  118. return t;
  119. }
  120. // -----------------------------------------------------------------------------------
  121. // Serialize a color value
  122. template <>
  123. inline size_t Write<aiColor4D>(IOStream *stream, const aiColor4D &v) {
  124. size_t t = Write<float>(stream, v.r);
  125. t += Write<float>(stream, v.g);
  126. t += Write<float>(stream, v.b);
  127. t += Write<float>(stream, v.a);
  128. return t;
  129. }
  130. // -----------------------------------------------------------------------------------
  131. // Serialize a quaternion
  132. template <>
  133. inline size_t Write<aiQuaternion>(IOStream *stream, const aiQuaternion &v) {
  134. size_t t = Write<float>(stream, v.w);
  135. t += Write<float>(stream, v.x);
  136. t += Write<float>(stream, v.y);
  137. t += Write<float>(stream, v.z);
  138. ai_assert(t == 16);
  139. return t;
  140. }
  141. // -----------------------------------------------------------------------------------
  142. // Serialize a vertex weight
  143. template <>
  144. inline size_t Write<aiVertexWeight>(IOStream *stream, const aiVertexWeight &v) {
  145. size_t t = Write<unsigned int>(stream, v.mVertexId);
  146. return t + Write<float>(stream, v.mWeight);
  147. }
  148. // -----------------------------------------------------------------------------------
  149. // Serialize a mat4x4
  150. template <>
  151. inline size_t Write<aiMatrix4x4>(IOStream *stream, const aiMatrix4x4 &m) {
  152. for (unsigned int i = 0; i < 4; ++i) {
  153. for (unsigned int i2 = 0; i2 < 4; ++i2) {
  154. Write<float>(stream, m[i][i2]);
  155. }
  156. }
  157. return 64;
  158. }
  159. // -----------------------------------------------------------------------------------
  160. // Serialize an aiVectorKey
  161. template <>
  162. inline size_t Write<aiVectorKey>(IOStream *stream, const aiVectorKey &v) {
  163. const size_t t = Write<double>(stream, v.mTime);
  164. return t + Write<aiVector3D>(stream, v.mValue);
  165. }
  166. // -----------------------------------------------------------------------------------
  167. // Serialize an aiQuatKey
  168. template <>
  169. inline size_t Write<aiQuatKey>(IOStream *stream, const aiQuatKey &v) {
  170. const size_t t = Write<double>(stream, v.mTime);
  171. return t + Write<aiQuaternion>(stream, v.mValue);
  172. }
  173. template <typename T>
  174. inline size_t WriteBounds(IOStream *stream, const T *in, unsigned int size) {
  175. T minc, maxc;
  176. ArrayBounds(in, size, minc, maxc);
  177. const size_t t = Write<T>(stream, minc);
  178. return t + Write<T>(stream, maxc);
  179. }
  180. // We use this to write out non-byte arrays so that we write using the specializations.
  181. // This way we avoid writing out extra bytes that potentially come from struct alignment.
  182. template <typename T>
  183. inline size_t WriteArray(IOStream *stream, const T *in, unsigned int size) {
  184. size_t n = 0;
  185. for (unsigned int i = 0; i < size; i++)
  186. n += Write<T>(stream, in[i]);
  187. return n;
  188. }
  189. // ----------------------------------------------------------------------------------
  190. /** @class AssbinChunkWriter
  191. * @brief Chunk writer mechanism for the .assbin file structure
  192. *
  193. * This is a standard in-memory IOStream (most of the code is based on BlobIOStream),
  194. * the difference being that this takes another IOStream as a "container" in the
  195. * constructor, and when it is destroyed, it appends the magic number, the chunk size,
  196. * and the chunk contents to the container stream. This allows relatively easy chunk
  197. * chunk construction, even recursively.
  198. */
  199. class AssbinChunkWriter : public IOStream {
  200. private:
  201. uint8_t *buffer;
  202. uint32_t magic;
  203. IOStream *container;
  204. size_t cur_size, cursor, initial;
  205. private:
  206. // -------------------------------------------------------------------
  207. void Grow(size_t need = 0) {
  208. size_t new_size = std::max(initial, std::max(need, cur_size + (cur_size >> 1)));
  209. const uint8_t *const old = buffer;
  210. buffer = new uint8_t[new_size];
  211. if (old) {
  212. memcpy(buffer, old, cur_size);
  213. delete[] old;
  214. }
  215. cur_size = new_size;
  216. }
  217. public:
  218. AssbinChunkWriter(IOStream *container, uint32_t magic, size_t initial = 4096) :
  219. buffer(nullptr),
  220. magic(magic),
  221. container(container),
  222. cur_size(0),
  223. cursor(0),
  224. initial(initial) {
  225. // empty
  226. }
  227. ~AssbinChunkWriter() override {
  228. if (container) {
  229. container->Write(&magic, sizeof(uint32_t), 1);
  230. container->Write(&cursor, sizeof(uint32_t), 1);
  231. container->Write(buffer, 1, cursor);
  232. }
  233. if (buffer) delete[] buffer;
  234. }
  235. void *GetBufferPointer() { return buffer; }
  236. size_t Read(void * /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/) override {
  237. return 0;
  238. }
  239. aiReturn Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/) override {
  240. return aiReturn_FAILURE;
  241. }
  242. size_t Tell() const override {
  243. return cursor;
  244. }
  245. void Flush() override {
  246. // not implemented
  247. }
  248. size_t FileSize() const override {
  249. return cursor;
  250. }
  251. size_t Write(const void *pvBuffer, size_t pSize, size_t pCount) override {
  252. pSize *= pCount;
  253. if (cursor + pSize > cur_size) {
  254. Grow(cursor + pSize);
  255. }
  256. memcpy(buffer + cursor, pvBuffer, pSize);
  257. cursor += pSize;
  258. return pCount;
  259. }
  260. };
  261. // ----------------------------------------------------------------------------------
  262. /** @class AssbinFileWriter
  263. * @brief Assbin file writer class
  264. *
  265. * This class writes an .assbin file, and is responsible for the file layout.
  266. */
  267. class AssbinFileWriter {
  268. private:
  269. bool shortened;
  270. bool compressed;
  271. protected:
  272. // -----------------------------------------------------------------------------------
  273. void WriteBinaryNode(IOStream *container, const aiNode *node) {
  274. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AINODE);
  275. unsigned int nb_metadata = (node->mMetaData != nullptr ? node->mMetaData->mNumProperties : 0);
  276. Write<aiString>(&chunk, node->mName);
  277. Write<aiMatrix4x4>(&chunk, node->mTransformation);
  278. Write<unsigned int>(&chunk, node->mNumChildren);
  279. Write<unsigned int>(&chunk, node->mNumMeshes);
  280. Write<unsigned int>(&chunk, nb_metadata);
  281. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  282. Write<unsigned int>(&chunk, node->mMeshes[i]);
  283. }
  284. for (unsigned int i = 0; i < node->mNumChildren; ++i) {
  285. WriteBinaryNode(&chunk, node->mChildren[i]);
  286. }
  287. for (unsigned int i = 0; i < nb_metadata; ++i) {
  288. const aiString &key = node->mMetaData->mKeys[i];
  289. aiMetadataType type = node->mMetaData->mValues[i].mType;
  290. void *value = node->mMetaData->mValues[i].mData;
  291. Write<aiString>(&chunk, key);
  292. Write<uint16_t>(&chunk, (uint16_t)type);
  293. switch (type) {
  294. case AI_BOOL:
  295. Write<bool>(&chunk, *((bool *)value));
  296. break;
  297. case AI_INT32:
  298. Write<int32_t>(&chunk, *((int32_t *)value));
  299. break;
  300. case AI_UINT64:
  301. Write<uint64_t>(&chunk, *((uint64_t *)value));
  302. break;
  303. case AI_FLOAT:
  304. Write<float>(&chunk, *((float *)value));
  305. break;
  306. case AI_DOUBLE:
  307. Write<double>(&chunk, *((double *)value));
  308. break;
  309. case AI_AISTRING:
  310. Write<aiString>(&chunk, *((aiString *)value));
  311. break;
  312. case AI_AIVECTOR3D:
  313. Write<aiVector3D>(&chunk, *((aiVector3D *)value));
  314. break;
  315. #ifdef SWIG
  316. case FORCE_32BIT:
  317. #endif // SWIG
  318. default:
  319. break;
  320. }
  321. }
  322. }
  323. // -----------------------------------------------------------------------------------
  324. void WriteBinaryTexture(IOStream *container, const aiTexture *tex) {
  325. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AITEXTURE);
  326. Write<unsigned int>(&chunk, tex->mWidth);
  327. Write<unsigned int>(&chunk, tex->mHeight);
  328. // Write the texture format, but don't include the null terminator.
  329. chunk.Write(tex->achFormatHint, sizeof(char), HINTMAXTEXTURELEN - 1);
  330. if (!shortened) {
  331. if (!tex->mHeight) {
  332. chunk.Write(tex->pcData, 1, tex->mWidth);
  333. } else {
  334. chunk.Write(tex->pcData, 1, tex->mWidth * tex->mHeight * 4);
  335. }
  336. }
  337. }
  338. // -----------------------------------------------------------------------------------
  339. void WriteBinaryBone(IOStream *container, const aiBone *b) {
  340. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIBONE);
  341. Write<aiString>(&chunk, b->mName);
  342. Write<unsigned int>(&chunk, b->mNumWeights);
  343. Write<aiMatrix4x4>(&chunk, b->mOffsetMatrix);
  344. // for the moment we write dumb min/max values for the bones, too.
  345. // maybe I'll add a better, hash-like solution later
  346. if (shortened) {
  347. WriteBounds(&chunk, b->mWeights, b->mNumWeights);
  348. } // else write as usual
  349. else
  350. WriteArray<aiVertexWeight>(&chunk, b->mWeights, b->mNumWeights);
  351. }
  352. // -----------------------------------------------------------------------------------
  353. void WriteBinaryMesh(IOStream *container, const aiMesh *mesh) {
  354. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMESH);
  355. Write<unsigned int>(&chunk, mesh->mPrimitiveTypes);
  356. Write<unsigned int>(&chunk, mesh->mNumVertices);
  357. Write<unsigned int>(&chunk, mesh->mNumFaces);
  358. Write<unsigned int>(&chunk, mesh->mNumBones);
  359. Write<unsigned int>(&chunk, mesh->mMaterialIndex);
  360. // first of all, write bits for all existent vertex components
  361. unsigned int c = 0;
  362. if (mesh->mVertices) {
  363. c |= ASSBIN_MESH_HAS_POSITIONS;
  364. }
  365. if (mesh->mNormals) {
  366. c |= ASSBIN_MESH_HAS_NORMALS;
  367. }
  368. if (mesh->mTangents && mesh->mBitangents) {
  369. c |= ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS;
  370. }
  371. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) {
  372. if (!mesh->mTextureCoords[n]) {
  373. break;
  374. }
  375. c |= ASSBIN_MESH_HAS_TEXCOORD(n);
  376. }
  377. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) {
  378. if (!mesh->mColors[n]) {
  379. break;
  380. }
  381. c |= ASSBIN_MESH_HAS_COLOR(n);
  382. }
  383. Write<unsigned int>(&chunk, c);
  384. aiVector3D minVec, maxVec;
  385. if (mesh->mVertices) {
  386. if (shortened) {
  387. WriteBounds(&chunk, mesh->mVertices, mesh->mNumVertices);
  388. } // else write as usual
  389. else
  390. WriteArray<aiVector3D>(&chunk, mesh->mVertices, mesh->mNumVertices);
  391. }
  392. if (mesh->mNormals) {
  393. if (shortened) {
  394. WriteBounds(&chunk, mesh->mNormals, mesh->mNumVertices);
  395. } // else write as usual
  396. else
  397. WriteArray<aiVector3D>(&chunk, mesh->mNormals, mesh->mNumVertices);
  398. }
  399. if (mesh->mTangents && mesh->mBitangents) {
  400. if (shortened) {
  401. WriteBounds(&chunk, mesh->mTangents, mesh->mNumVertices);
  402. WriteBounds(&chunk, mesh->mBitangents, mesh->mNumVertices);
  403. } // else write as usual
  404. else {
  405. WriteArray<aiVector3D>(&chunk, mesh->mTangents, mesh->mNumVertices);
  406. WriteArray<aiVector3D>(&chunk, mesh->mBitangents, mesh->mNumVertices);
  407. }
  408. }
  409. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) {
  410. if (!mesh->mColors[n])
  411. break;
  412. if (shortened) {
  413. WriteBounds(&chunk, mesh->mColors[n], mesh->mNumVertices);
  414. } // else write as usual
  415. else
  416. WriteArray<aiColor4D>(&chunk, mesh->mColors[n], mesh->mNumVertices);
  417. }
  418. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) {
  419. if (!mesh->mTextureCoords[n])
  420. break;
  421. // write number of UV components
  422. Write<unsigned int>(&chunk, mesh->mNumUVComponents[n]);
  423. if (shortened) {
  424. WriteBounds(&chunk, mesh->mTextureCoords[n], mesh->mNumVertices);
  425. } // else write as usual
  426. else
  427. WriteArray<aiVector3D>(&chunk, mesh->mTextureCoords[n], mesh->mNumVertices);
  428. }
  429. // write faces. There are no floating-point calculations involved
  430. // in these, so we can write a simple hash over the face data
  431. // to the dump file. We generate a single 32 Bit hash for 512 faces
  432. // using Assimp's standard hashing function.
  433. if (shortened) {
  434. unsigned int processed = 0;
  435. for (unsigned int job; (job = std::min(mesh->mNumFaces - processed, 512u)); processed += job) {
  436. uint32_t hash = 0;
  437. for (unsigned int a = 0; a < job; ++a) {
  438. const aiFace &f = mesh->mFaces[processed + a];
  439. uint32_t tmp = f.mNumIndices;
  440. hash = SuperFastHash(reinterpret_cast<const char *>(&tmp), sizeof tmp, hash);
  441. for (unsigned int i = 0; i < f.mNumIndices; ++i) {
  442. static_assert(AI_MAX_VERTICES <= 0xffffffff, "AI_MAX_VERTICES <= 0xffffffff");
  443. tmp = static_cast<uint32_t>(f.mIndices[i]);
  444. hash = SuperFastHash(reinterpret_cast<const char *>(&tmp), sizeof tmp, hash);
  445. }
  446. }
  447. Write<unsigned int>(&chunk, hash);
  448. }
  449. } else // else write as usual
  450. {
  451. // if there are less than 2^16 vertices, we can simply use 16 bit integers ...
  452. for (unsigned int i = 0; i < mesh->mNumFaces; ++i) {
  453. const aiFace &f = mesh->mFaces[i];
  454. static_assert(AI_MAX_FACE_INDICES <= 0xffff, "AI_MAX_FACE_INDICES <= 0xffff");
  455. Write<uint16_t>(&chunk, static_cast<uint16_t>(f.mNumIndices));
  456. for (unsigned int a = 0; a < f.mNumIndices; ++a) {
  457. if (mesh->mNumVertices < (1u << 16)) {
  458. Write<uint16_t>(&chunk, static_cast<uint16_t>(f.mIndices[a]));
  459. } else {
  460. Write<unsigned int>(&chunk, f.mIndices[a]);
  461. }
  462. }
  463. }
  464. }
  465. // write bones
  466. if (mesh->mNumBones) {
  467. for (unsigned int a = 0; a < mesh->mNumBones; ++a) {
  468. const aiBone *b = mesh->mBones[a];
  469. WriteBinaryBone(&chunk, b);
  470. }
  471. }
  472. }
  473. // -----------------------------------------------------------------------------------
  474. void WriteBinaryMaterialProperty(IOStream *container, const aiMaterialProperty *prop) {
  475. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMATERIALPROPERTY);
  476. Write<aiString>(&chunk, prop->mKey);
  477. Write<unsigned int>(&chunk, prop->mSemantic);
  478. Write<unsigned int>(&chunk, prop->mIndex);
  479. Write<unsigned int>(&chunk, prop->mDataLength);
  480. Write<unsigned int>(&chunk, (unsigned int)prop->mType);
  481. chunk.Write(prop->mData, 1, prop->mDataLength);
  482. }
  483. // -----------------------------------------------------------------------------------
  484. void WriteBinaryMaterial(IOStream *container, const aiMaterial *mat) {
  485. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMATERIAL);
  486. Write<unsigned int>(&chunk, mat->mNumProperties);
  487. for (unsigned int i = 0; i < mat->mNumProperties; ++i) {
  488. WriteBinaryMaterialProperty(&chunk, mat->mProperties[i]);
  489. }
  490. }
  491. // -----------------------------------------------------------------------------------
  492. void WriteBinaryNodeAnim(IOStream *container, const aiNodeAnim *nd) {
  493. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AINODEANIM);
  494. Write<aiString>(&chunk, nd->mNodeName);
  495. Write<unsigned int>(&chunk, nd->mNumPositionKeys);
  496. Write<unsigned int>(&chunk, nd->mNumRotationKeys);
  497. Write<unsigned int>(&chunk, nd->mNumScalingKeys);
  498. Write<unsigned int>(&chunk, nd->mPreState);
  499. Write<unsigned int>(&chunk, nd->mPostState);
  500. if (nd->mPositionKeys) {
  501. if (shortened) {
  502. WriteBounds(&chunk, nd->mPositionKeys, nd->mNumPositionKeys);
  503. } // else write as usual
  504. else
  505. WriteArray<aiVectorKey>(&chunk, nd->mPositionKeys, nd->mNumPositionKeys);
  506. }
  507. if (nd->mRotationKeys) {
  508. if (shortened) {
  509. WriteBounds(&chunk, nd->mRotationKeys, nd->mNumRotationKeys);
  510. } // else write as usual
  511. else
  512. WriteArray<aiQuatKey>(&chunk, nd->mRotationKeys, nd->mNumRotationKeys);
  513. }
  514. if (nd->mScalingKeys) {
  515. if (shortened) {
  516. WriteBounds(&chunk, nd->mScalingKeys, nd->mNumScalingKeys);
  517. } // else write as usual
  518. else
  519. WriteArray<aiVectorKey>(&chunk, nd->mScalingKeys, nd->mNumScalingKeys);
  520. }
  521. }
  522. // -----------------------------------------------------------------------------------
  523. void WriteBinaryAnim(IOStream *container, const aiAnimation *anim) {
  524. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIANIMATION);
  525. Write<aiString>(&chunk, anim->mName);
  526. Write<double>(&chunk, anim->mDuration);
  527. Write<double>(&chunk, anim->mTicksPerSecond);
  528. Write<unsigned int>(&chunk, anim->mNumChannels);
  529. for (unsigned int a = 0; a < anim->mNumChannels; ++a) {
  530. const aiNodeAnim *nd = anim->mChannels[a];
  531. WriteBinaryNodeAnim(&chunk, nd);
  532. }
  533. }
  534. // -----------------------------------------------------------------------------------
  535. void WriteBinaryLight(IOStream *container, const aiLight *l) {
  536. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AILIGHT);
  537. Write<aiString>(&chunk, l->mName);
  538. Write<unsigned int>(&chunk, l->mType);
  539. if (l->mType != aiLightSource_DIRECTIONAL) {
  540. Write<float>(&chunk, l->mAttenuationConstant);
  541. Write<float>(&chunk, l->mAttenuationLinear);
  542. Write<float>(&chunk, l->mAttenuationQuadratic);
  543. }
  544. Write<aiColor3D>(&chunk, l->mColorDiffuse);
  545. Write<aiColor3D>(&chunk, l->mColorSpecular);
  546. Write<aiColor3D>(&chunk, l->mColorAmbient);
  547. if (l->mType == aiLightSource_SPOT) {
  548. Write<float>(&chunk, l->mAngleInnerCone);
  549. Write<float>(&chunk, l->mAngleOuterCone);
  550. }
  551. }
  552. // -----------------------------------------------------------------------------------
  553. void WriteBinaryCamera(IOStream *container, const aiCamera *cam) {
  554. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AICAMERA);
  555. Write<aiString>(&chunk, cam->mName);
  556. Write<aiVector3D>(&chunk, cam->mPosition);
  557. Write<aiVector3D>(&chunk, cam->mLookAt);
  558. Write<aiVector3D>(&chunk, cam->mUp);
  559. Write<float>(&chunk, cam->mHorizontalFOV);
  560. Write<float>(&chunk, cam->mClipPlaneNear);
  561. Write<float>(&chunk, cam->mClipPlaneFar);
  562. Write<float>(&chunk, cam->mAspect);
  563. }
  564. // -----------------------------------------------------------------------------------
  565. void WriteBinaryScene(IOStream *container, const aiScene *scene) {
  566. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AISCENE);
  567. // basic scene information
  568. Write<unsigned int>(&chunk, scene->mFlags);
  569. Write<unsigned int>(&chunk, scene->mNumMeshes);
  570. Write<unsigned int>(&chunk, scene->mNumMaterials);
  571. Write<unsigned int>(&chunk, scene->mNumAnimations);
  572. Write<unsigned int>(&chunk, scene->mNumTextures);
  573. Write<unsigned int>(&chunk, scene->mNumLights);
  574. Write<unsigned int>(&chunk, scene->mNumCameras);
  575. // write node graph
  576. WriteBinaryNode(&chunk, scene->mRootNode);
  577. // write all meshes
  578. for (unsigned int i = 0; i < scene->mNumMeshes; ++i) {
  579. const aiMesh *mesh = scene->mMeshes[i];
  580. WriteBinaryMesh(&chunk, mesh);
  581. }
  582. // write materials
  583. for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
  584. const aiMaterial *mat = scene->mMaterials[i];
  585. WriteBinaryMaterial(&chunk, mat);
  586. }
  587. // write all animations
  588. for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
  589. const aiAnimation *anim = scene->mAnimations[i];
  590. WriteBinaryAnim(&chunk, anim);
  591. }
  592. // write all textures
  593. for (unsigned int i = 0; i < scene->mNumTextures; ++i) {
  594. const aiTexture *mesh = scene->mTextures[i];
  595. WriteBinaryTexture(&chunk, mesh);
  596. }
  597. // write lights
  598. for (unsigned int i = 0; i < scene->mNumLights; ++i) {
  599. const aiLight *l = scene->mLights[i];
  600. WriteBinaryLight(&chunk, l);
  601. }
  602. // write cameras
  603. for (unsigned int i = 0; i < scene->mNumCameras; ++i) {
  604. const aiCamera *cam = scene->mCameras[i];
  605. WriteBinaryCamera(&chunk, cam);
  606. }
  607. }
  608. public:
  609. AssbinFileWriter(bool shortened, bool compressed) :
  610. shortened(shortened), compressed(compressed) {
  611. }
  612. // -----------------------------------------------------------------------------------
  613. // Write a binary model dump
  614. void WriteBinaryDump(const char *pFile, const char *cmd, IOSystem *pIOSystem, const aiScene *pScene) {
  615. IOStream *out = pIOSystem->Open(pFile, "wb");
  616. if (!out)
  617. throw std::runtime_error("Unable to open output file " + std::string(pFile) + '\n');
  618. auto CloseIOStream = [&]() {
  619. if (out) {
  620. pIOSystem->Close(out);
  621. out = nullptr; // Ensure this is only done once.
  622. }
  623. };
  624. try {
  625. time_t tt = time(nullptr);
  626. #if _WIN32
  627. tm *p = gmtime(&tt);
  628. #else
  629. struct tm now;
  630. tm *p = gmtime_r(&tt, &now);
  631. #endif
  632. // header
  633. char s[64];
  634. memset(s, 0, 64);
  635. #if _MSC_VER >= 1400
  636. sprintf_s(s, "ASSIMP.binary-dump.%s", asctime(p));
  637. #else
  638. ai_snprintf(s, 64, "ASSIMP.binary-dump.%s", asctime(p));
  639. #endif
  640. out->Write(s, 44, 1);
  641. // == 44 bytes
  642. Write<unsigned int>(out, ASSBIN_VERSION_MAJOR);
  643. Write<unsigned int>(out, ASSBIN_VERSION_MINOR);
  644. Write<unsigned int>(out, aiGetVersionRevision());
  645. Write<unsigned int>(out, aiGetCompileFlags());
  646. Write<uint16_t>(out, shortened);
  647. Write<uint16_t>(out, compressed);
  648. // == 20 bytes
  649. char buff[256] = { 0 };
  650. ai_snprintf(buff, 256, "%s", pFile);
  651. out->Write(buff, sizeof(char), 256);
  652. memset(buff, 0, sizeof(buff));
  653. ai_snprintf(buff, 128, "%s", cmd);
  654. out->Write(buff, sizeof(char), 128);
  655. // leave 64 bytes free for future extensions
  656. memset(buff, 0xcd, 64);
  657. out->Write(buff, sizeof(char), 64);
  658. // == 435 bytes
  659. // ==== total header size: 512 bytes
  660. ai_assert(out->Tell() == ASSBIN_HEADER_LENGTH);
  661. // Up to here the data is uncompressed. For compressed files, the rest
  662. // is compressed using standard DEFLATE from zlib.
  663. if (compressed) {
  664. AssbinChunkWriter uncompressedStream(nullptr, 0);
  665. WriteBinaryScene(&uncompressedStream, pScene);
  666. uLongf uncompressedSize = static_cast<uLongf>(uncompressedStream.Tell());
  667. uLongf compressedSize = (uLongf)compressBound(uncompressedSize);
  668. uint8_t *compressedBuffer = new uint8_t[compressedSize];
  669. int res = compress2(compressedBuffer, &compressedSize, (const Bytef *)uncompressedStream.GetBufferPointer(), uncompressedSize, 9);
  670. if (res != Z_OK) {
  671. delete[] compressedBuffer;
  672. throw DeadlyExportError("Compression failed.");
  673. }
  674. out->Write(&uncompressedSize, sizeof(uint32_t), 1);
  675. out->Write(compressedBuffer, sizeof(char), compressedSize);
  676. delete[] compressedBuffer;
  677. } else {
  678. WriteBinaryScene(out, pScene);
  679. }
  680. CloseIOStream();
  681. } catch (...) {
  682. CloseIOStream();
  683. throw;
  684. }
  685. }
  686. };
  687. void DumpSceneToAssbin(
  688. const char *pFile, const char *cmd, IOSystem *pIOSystem,
  689. const aiScene *pScene, bool shortened, bool compressed) {
  690. AssbinFileWriter fileWriter(shortened, compressed);
  691. fileWriter.WriteBinaryDump(pFile, cmd, pIOSystem, pScene);
  692. }
  693. #if _MSC_VER
  694. #pragma warning(pop)
  695. #endif // _MSC_VER
  696. } // end of namespace Assimp