AssbinFileWriter.cpp 29 KB

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