b3Serializer.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #ifndef B3_SERIALIZER_H
  14. #define B3_SERIALIZER_H
  15. #include "Bullet3Common/b3Scalar.h" // has definitions like B3_FORCE_INLINE
  16. #include "Bullet3Common/b3StackAlloc.h"
  17. #include "Bullet3Common/b3HashMap.h"
  18. #if !defined(__CELLOS_LV2__) && !defined(__MWERKS__)
  19. #include <memory.h>
  20. #endif
  21. #include <string.h>
  22. extern char b3s_bulletDNAstr[];
  23. extern int b3s_bulletDNAlen;
  24. extern char b3s_bulletDNAstr64[];
  25. extern int b3s_bulletDNAlen64;
  26. B3_FORCE_INLINE int b3StrLen(const char* str)
  27. {
  28. if (!str)
  29. return (0);
  30. int len = 0;
  31. while (*str != 0)
  32. {
  33. str++;
  34. len++;
  35. }
  36. return len;
  37. }
  38. class b3Chunk
  39. {
  40. public:
  41. int m_chunkCode;
  42. int m_length;
  43. void* m_oldPtr;
  44. int m_dna_nr;
  45. int m_number;
  46. };
  47. enum b3SerializationFlags
  48. {
  49. B3_SERIALIZE_NO_BVH = 1,
  50. B3_SERIALIZE_NO_TRIANGLEINFOMAP = 2,
  51. B3_SERIALIZE_NO_DUPLICATE_ASSERT = 4
  52. };
  53. class b3Serializer
  54. {
  55. public:
  56. virtual ~b3Serializer() {}
  57. virtual const unsigned char* getBufferPointer() const = 0;
  58. virtual int getCurrentBufferSize() const = 0;
  59. virtual b3Chunk* allocate(size_t size, int numElements) = 0;
  60. virtual void finalizeChunk(b3Chunk* chunk, const char* structType, int chunkCode, void* oldPtr) = 0;
  61. virtual void* findPointer(void* oldPtr) = 0;
  62. virtual void* getUniquePointer(void* oldPtr) = 0;
  63. virtual void startSerialization() = 0;
  64. virtual void finishSerialization() = 0;
  65. virtual const char* findNameForPointer(const void* ptr) const = 0;
  66. virtual void registerNameForPointer(const void* ptr, const char* name) = 0;
  67. virtual void serializeName(const char* ptr) = 0;
  68. virtual int getSerializationFlags() const = 0;
  69. virtual void setSerializationFlags(int flags) = 0;
  70. };
  71. #define B3_HEADER_LENGTH 12
  72. #if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined(__PPC__) || defined(__ppc__) || defined(__BIG_ENDIAN__)
  73. #define B3_MAKE_ID(a, b, c, d) ((int)(a) << 24 | (int)(b) << 16 | (c) << 8 | (d))
  74. #else
  75. #define B3_MAKE_ID(a, b, c, d) ((int)(d) << 24 | (int)(c) << 16 | (b) << 8 | (a))
  76. #endif
  77. #define B3_SOFTBODY_CODE B3_MAKE_ID('S', 'B', 'D', 'Y')
  78. #define B3_COLLISIONOBJECT_CODE B3_MAKE_ID('C', 'O', 'B', 'J')
  79. #define B3_RIGIDBODY_CODE B3_MAKE_ID('R', 'B', 'D', 'Y')
  80. #define B3_CONSTRAINT_CODE B3_MAKE_ID('C', 'O', 'N', 'S')
  81. #define B3_BOXSHAPE_CODE B3_MAKE_ID('B', 'O', 'X', 'S')
  82. #define B3_QUANTIZED_BVH_CODE B3_MAKE_ID('Q', 'B', 'V', 'H')
  83. #define B3_TRIANLGE_INFO_MAP B3_MAKE_ID('T', 'M', 'A', 'P')
  84. #define B3_SHAPE_CODE B3_MAKE_ID('S', 'H', 'A', 'P')
  85. #define B3_ARRAY_CODE B3_MAKE_ID('A', 'R', 'A', 'Y')
  86. #define B3_SBMATERIAL_CODE B3_MAKE_ID('S', 'B', 'M', 'T')
  87. #define B3_SBNODE_CODE B3_MAKE_ID('S', 'B', 'N', 'D')
  88. #define B3_DYNAMICSWORLD_CODE B3_MAKE_ID('D', 'W', 'L', 'D')
  89. #define B3_DNA_CODE B3_MAKE_ID('D', 'N', 'A', '1')
  90. struct b3PointerUid
  91. {
  92. union {
  93. void* m_ptr;
  94. int m_uniqueIds[2];
  95. };
  96. };
  97. ///The b3DefaultSerializer is the main Bullet serialization class.
  98. ///The constructor takes an optional argument for backwards compatibility, it is recommended to leave this empty/zero.
  99. class b3DefaultSerializer : public b3Serializer
  100. {
  101. b3AlignedObjectArray<char*> mTypes;
  102. b3AlignedObjectArray<short*> mStructs;
  103. b3AlignedObjectArray<short> mTlens;
  104. b3HashMap<b3HashInt, int> mStructReverse;
  105. b3HashMap<b3HashString, int> mTypeLookup;
  106. b3HashMap<b3HashPtr, void*> m_chunkP;
  107. b3HashMap<b3HashPtr, const char*> m_nameMap;
  108. b3HashMap<b3HashPtr, b3PointerUid> m_uniquePointers;
  109. int m_uniqueIdGenerator;
  110. int m_totalSize;
  111. unsigned char* m_buffer;
  112. int m_currentSize;
  113. void* m_dna;
  114. int m_dnaLength;
  115. int m_serializationFlags;
  116. b3AlignedObjectArray<b3Chunk*> m_chunkPtrs;
  117. protected:
  118. virtual void* findPointer(void* oldPtr)
  119. {
  120. void** ptr = m_chunkP.find(oldPtr);
  121. if (ptr && *ptr)
  122. return *ptr;
  123. return 0;
  124. }
  125. void writeDNA()
  126. {
  127. b3Chunk* dnaChunk = allocate(m_dnaLength, 1);
  128. memcpy(dnaChunk->m_oldPtr, m_dna, m_dnaLength);
  129. finalizeChunk(dnaChunk, "DNA1", B3_DNA_CODE, m_dna);
  130. }
  131. int getReverseType(const char* type) const
  132. {
  133. b3HashString key(type);
  134. const int* valuePtr = mTypeLookup.find(key);
  135. if (valuePtr)
  136. return *valuePtr;
  137. return -1;
  138. }
  139. void initDNA(const char* bdnaOrg, int dnalen)
  140. {
  141. ///was already initialized
  142. if (m_dna)
  143. return;
  144. int littleEndian = 1;
  145. littleEndian = ((char*)&littleEndian)[0];
  146. m_dna = b3AlignedAlloc(dnalen, 16);
  147. memcpy(m_dna, bdnaOrg, dnalen);
  148. m_dnaLength = dnalen;
  149. int* intPtr = 0;
  150. short* shtPtr = 0;
  151. char* cp = 0;
  152. int dataLen = 0;
  153. intPtr = (int*)m_dna;
  154. /*
  155. SDNA (4 bytes) (magic number)
  156. NAME (4 bytes)
  157. <nr> (4 bytes) amount of names (int)
  158. <string>
  159. <string>
  160. */
  161. if (strncmp((const char*)m_dna, "SDNA", 4) == 0)
  162. {
  163. // skip ++ NAME
  164. intPtr++;
  165. intPtr++;
  166. }
  167. // Parse names
  168. if (!littleEndian)
  169. *intPtr = b3SwapEndian(*intPtr);
  170. dataLen = *intPtr;
  171. intPtr++;
  172. cp = (char*)intPtr;
  173. int i;
  174. for (i = 0; i < dataLen; i++)
  175. {
  176. while (*cp) cp++;
  177. cp++;
  178. }
  179. cp = b3AlignPointer(cp, 4);
  180. /*
  181. TYPE (4 bytes)
  182. <nr> amount of types (int)
  183. <string>
  184. <string>
  185. */
  186. intPtr = (int*)cp;
  187. b3Assert(strncmp(cp, "TYPE", 4) == 0);
  188. intPtr++;
  189. if (!littleEndian)
  190. *intPtr = b3SwapEndian(*intPtr);
  191. dataLen = *intPtr;
  192. intPtr++;
  193. cp = (char*)intPtr;
  194. for (i = 0; i < dataLen; i++)
  195. {
  196. mTypes.push_back(cp);
  197. while (*cp) cp++;
  198. cp++;
  199. }
  200. cp = b3AlignPointer(cp, 4);
  201. /*
  202. TLEN (4 bytes)
  203. <len> (short) the lengths of types
  204. <len>
  205. */
  206. // Parse type lens
  207. intPtr = (int*)cp;
  208. b3Assert(strncmp(cp, "TLEN", 4) == 0);
  209. intPtr++;
  210. dataLen = (int)mTypes.size();
  211. shtPtr = (short*)intPtr;
  212. for (i = 0; i < dataLen; i++, shtPtr++)
  213. {
  214. if (!littleEndian)
  215. shtPtr[0] = b3SwapEndian(shtPtr[0]);
  216. mTlens.push_back(shtPtr[0]);
  217. }
  218. if (dataLen & 1) shtPtr++;
  219. /*
  220. STRC (4 bytes)
  221. <nr> amount of structs (int)
  222. <typenr>
  223. <nr_of_elems>
  224. <typenr>
  225. <namenr>
  226. <typenr>
  227. <namenr>
  228. */
  229. intPtr = (int*)shtPtr;
  230. cp = (char*)intPtr;
  231. b3Assert(strncmp(cp, "STRC", 4) == 0);
  232. intPtr++;
  233. if (!littleEndian)
  234. *intPtr = b3SwapEndian(*intPtr);
  235. dataLen = *intPtr;
  236. intPtr++;
  237. shtPtr = (short*)intPtr;
  238. for (i = 0; i < dataLen; i++)
  239. {
  240. mStructs.push_back(shtPtr);
  241. if (!littleEndian)
  242. {
  243. shtPtr[0] = b3SwapEndian(shtPtr[0]);
  244. shtPtr[1] = b3SwapEndian(shtPtr[1]);
  245. int len = shtPtr[1];
  246. shtPtr += 2;
  247. for (int a = 0; a < len; a++, shtPtr += 2)
  248. {
  249. shtPtr[0] = b3SwapEndian(shtPtr[0]);
  250. shtPtr[1] = b3SwapEndian(shtPtr[1]);
  251. }
  252. }
  253. else
  254. {
  255. shtPtr += (2 * shtPtr[1]) + 2;
  256. }
  257. }
  258. // build reverse lookups
  259. for (i = 0; i < (int)mStructs.size(); i++)
  260. {
  261. short* strc = mStructs.at(i);
  262. mStructReverse.insert(strc[0], i);
  263. mTypeLookup.insert(b3HashString(mTypes[strc[0]]), i);
  264. }
  265. }
  266. public:
  267. b3DefaultSerializer(int totalSize = 0)
  268. : m_totalSize(totalSize),
  269. m_currentSize(0),
  270. m_dna(0),
  271. m_dnaLength(0),
  272. m_serializationFlags(0)
  273. {
  274. m_buffer = m_totalSize ? (unsigned char*)b3AlignedAlloc(totalSize, 16) : 0;
  275. const bool VOID_IS_8 = ((sizeof(void*) == 8));
  276. #ifdef B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
  277. if (VOID_IS_8)
  278. {
  279. #if _WIN64
  280. initDNA((const char*)b3s_bulletDNAstr64, b3s_bulletDNAlen64);
  281. #else
  282. b3Assert(0);
  283. #endif
  284. }
  285. else
  286. {
  287. #ifndef _WIN64
  288. initDNA((const char*)b3s_bulletDNAstr, b3s_bulletDNAlen);
  289. #else
  290. b3Assert(0);
  291. #endif
  292. }
  293. #else //B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
  294. if (VOID_IS_8)
  295. {
  296. initDNA((const char*)b3s_bulletDNAstr64, b3s_bulletDNAlen64);
  297. }
  298. else
  299. {
  300. initDNA((const char*)b3s_bulletDNAstr, b3s_bulletDNAlen);
  301. }
  302. #endif //B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
  303. }
  304. virtual ~b3DefaultSerializer()
  305. {
  306. if (m_buffer)
  307. b3AlignedFree(m_buffer);
  308. if (m_dna)
  309. b3AlignedFree(m_dna);
  310. }
  311. void writeHeader(unsigned char* buffer) const
  312. {
  313. #ifdef B3_USE_DOUBLE_PRECISION
  314. memcpy(buffer, "BULLETd", 7);
  315. #else
  316. memcpy(buffer, "BULLETf", 7);
  317. #endif //B3_USE_DOUBLE_PRECISION
  318. int littleEndian = 1;
  319. littleEndian = ((char*)&littleEndian)[0];
  320. if (sizeof(void*) == 8)
  321. {
  322. buffer[7] = '-';
  323. }
  324. else
  325. {
  326. buffer[7] = '_';
  327. }
  328. if (littleEndian)
  329. {
  330. buffer[8] = 'v';
  331. }
  332. else
  333. {
  334. buffer[8] = 'V';
  335. }
  336. buffer[9] = '2';
  337. buffer[10] = '8';
  338. buffer[11] = '1';
  339. }
  340. virtual void startSerialization()
  341. {
  342. m_uniqueIdGenerator = 1;
  343. if (m_totalSize)
  344. {
  345. unsigned char* buffer = internalAlloc(B3_HEADER_LENGTH);
  346. writeHeader(buffer);
  347. }
  348. }
  349. virtual void finishSerialization()
  350. {
  351. writeDNA();
  352. //if we didn't pre-allocate a buffer, we need to create a contiguous buffer now
  353. int mysize = 0;
  354. if (!m_totalSize)
  355. {
  356. if (m_buffer)
  357. b3AlignedFree(m_buffer);
  358. m_currentSize += B3_HEADER_LENGTH;
  359. m_buffer = (unsigned char*)b3AlignedAlloc(m_currentSize, 16);
  360. unsigned char* currentPtr = m_buffer;
  361. writeHeader(m_buffer);
  362. currentPtr += B3_HEADER_LENGTH;
  363. mysize += B3_HEADER_LENGTH;
  364. for (int i = 0; i < m_chunkPtrs.size(); i++)
  365. {
  366. int curLength = sizeof(b3Chunk) + m_chunkPtrs[i]->m_length;
  367. memcpy(currentPtr, m_chunkPtrs[i], curLength);
  368. b3AlignedFree(m_chunkPtrs[i]);
  369. currentPtr += curLength;
  370. mysize += curLength;
  371. }
  372. }
  373. mTypes.clear();
  374. mStructs.clear();
  375. mTlens.clear();
  376. mStructReverse.clear();
  377. mTypeLookup.clear();
  378. m_chunkP.clear();
  379. m_nameMap.clear();
  380. m_uniquePointers.clear();
  381. m_chunkPtrs.clear();
  382. }
  383. virtual void* getUniquePointer(void* oldPtr)
  384. {
  385. if (!oldPtr)
  386. return 0;
  387. b3PointerUid* uptr = (b3PointerUid*)m_uniquePointers.find(oldPtr);
  388. if (uptr)
  389. {
  390. return uptr->m_ptr;
  391. }
  392. m_uniqueIdGenerator++;
  393. b3PointerUid uid;
  394. uid.m_uniqueIds[0] = m_uniqueIdGenerator;
  395. uid.m_uniqueIds[1] = m_uniqueIdGenerator;
  396. m_uniquePointers.insert(oldPtr, uid);
  397. return uid.m_ptr;
  398. }
  399. virtual const unsigned char* getBufferPointer() const
  400. {
  401. return m_buffer;
  402. }
  403. virtual int getCurrentBufferSize() const
  404. {
  405. return m_currentSize;
  406. }
  407. virtual void finalizeChunk(b3Chunk* chunk, const char* structType, int chunkCode, void* oldPtr)
  408. {
  409. if (!(m_serializationFlags & B3_SERIALIZE_NO_DUPLICATE_ASSERT))
  410. {
  411. b3Assert(!findPointer(oldPtr));
  412. }
  413. chunk->m_dna_nr = getReverseType(structType);
  414. chunk->m_chunkCode = chunkCode;
  415. void* uniquePtr = getUniquePointer(oldPtr);
  416. m_chunkP.insert(oldPtr, uniquePtr); //chunk->m_oldPtr);
  417. chunk->m_oldPtr = uniquePtr; //oldPtr;
  418. }
  419. virtual unsigned char* internalAlloc(size_t size)
  420. {
  421. unsigned char* ptr = 0;
  422. if (m_totalSize)
  423. {
  424. ptr = m_buffer + m_currentSize;
  425. m_currentSize += int(size);
  426. b3Assert(m_currentSize < m_totalSize);
  427. }
  428. else
  429. {
  430. ptr = (unsigned char*)b3AlignedAlloc(size, 16);
  431. m_currentSize += int(size);
  432. }
  433. return ptr;
  434. }
  435. virtual b3Chunk* allocate(size_t size, int numElements)
  436. {
  437. unsigned char* ptr = internalAlloc(int(size) * numElements + sizeof(b3Chunk));
  438. unsigned char* data = ptr + sizeof(b3Chunk);
  439. b3Chunk* chunk = (b3Chunk*)ptr;
  440. chunk->m_chunkCode = 0;
  441. chunk->m_oldPtr = data;
  442. chunk->m_length = int(size) * numElements;
  443. chunk->m_number = numElements;
  444. m_chunkPtrs.push_back(chunk);
  445. return chunk;
  446. }
  447. virtual const char* findNameForPointer(const void* ptr) const
  448. {
  449. const char* const* namePtr = m_nameMap.find(ptr);
  450. if (namePtr && *namePtr)
  451. return *namePtr;
  452. return 0;
  453. }
  454. virtual void registerNameForPointer(const void* ptr, const char* name)
  455. {
  456. m_nameMap.insert(ptr, name);
  457. }
  458. virtual void serializeName(const char* name)
  459. {
  460. if (name)
  461. {
  462. //don't serialize name twice
  463. if (findPointer((void*)name))
  464. return;
  465. int len = b3StrLen(name);
  466. if (len)
  467. {
  468. int newLen = len + 1;
  469. int padding = ((newLen + 3) & ~3) - newLen;
  470. newLen += padding;
  471. //serialize name string now
  472. b3Chunk* chunk = allocate(sizeof(char), newLen);
  473. char* destinationName = (char*)chunk->m_oldPtr;
  474. for (int i = 0; i < len; i++)
  475. {
  476. destinationName[i] = name[i];
  477. }
  478. destinationName[len] = 0;
  479. finalizeChunk(chunk, "char", B3_ARRAY_CODE, (void*)name);
  480. }
  481. }
  482. }
  483. virtual int getSerializationFlags() const
  484. {
  485. return m_serializationFlags;
  486. }
  487. virtual void setSerializationFlags(int flags)
  488. {
  489. m_serializationFlags = flags;
  490. }
  491. };
  492. #endif //B3_SERIALIZER_H