AssbinFileWriter.cpp 29 KB

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