BsBinarySerializer.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. #pragma once
  2. #include <unordered_map>
  3. #include "BsPrerequisitesUtil.h"
  4. #include "BsSerializedObject.h"
  5. #include "BsRTTIField.h"
  6. namespace BansheeEngine
  7. {
  8. /** @addtogroup Serialization
  9. * @{
  10. */
  11. class IReflectable;
  12. struct RTTIReflectableFieldBase;
  13. struct RTTIReflectablePtrFieldBase;
  14. // TODO - Low priority. I will probably want to extract a generalized Serializer class so we can re-use the code
  15. // in text or other serializers
  16. // TODO - Low priority. Encode does a chunk-based encode so that we don't need to know the buffer size in advance,
  17. // and don't have to use a lot of memory for the buffer. Consider doing something similar for decode.
  18. // TODO - Low priority. Add a simple encode method that doesn't require a callback, instead it calls the callback internally
  19. // and creates the buffer internally.
  20. /**
  21. * Encodes all the fields of the provided object into a binary format. Fields are encoded using their unique IDs.
  22. * Encoded data will remain compatible for decoding even if you modify the encoded class, as long as you assign new
  23. * unique field IDs to added/modified fields.
  24. *
  25. * Like for any serializable class, fields are defined in RTTIType that each IReflectable class must be able to return.
  26. *
  27. * Any data the object or its children are pointing to will also be serialized (unless the pointer isn't registered in
  28. * RTTIType). Upon decoding the pointer addresses will be set to proper values.
  29. *
  30. * @note
  31. * Child elements are guaranteed to be fully deserialized before their parents, except for fields marked with WeakRef flag.
  32. */
  33. class BS_UTILITY_EXPORT BinarySerializer
  34. {
  35. public:
  36. BinarySerializer();
  37. /**
  38. * Encodes all serializable fields provided by @p object into a binary format. Data is written in chunks. Whenever a
  39. * chunk is filled a callback is triggered that gives the user opportunity to expand or empty the buffer (for
  40. * example write the chunk to disk)
  41. *
  42. * @param[in] object Object to encode into binary format.
  43. * @param[out] buffer Preallocated buffer where the data will be stored.
  44. * @param[in] bufferLength Length of the buffer, in bytes.
  45. * @param[out] bytesWritten Length of the data that was actually written to the buffer, in bytes.
  46. * @param[in] flushBufferCallback This callback will get called whenever the buffer gets full (Be careful to
  47. * check the provided @p bytesRead variable, as buffer might not be full
  48. * completely). User must then either create a new buffer or empty the existing
  49. * one, and then return it by the callback. If the returned buffer address is
  50. * NULL, encoding is aborted.
  51. * @param[in] shallow Determines how to handle referenced objects. If true then references will
  52. * not be encoded and will be set to null. If false then references will be
  53. * encoded as well and restored upon decoding.
  54. */
  55. void encode(IReflectable* object, UINT8* buffer, UINT32 bufferLength, UINT32* bytesWritten,
  56. std::function<UINT8*(UINT8* buffer, UINT32 bytesWritten, UINT32& newBufferSize)> flushBufferCallback,
  57. bool shallow = false);
  58. /**
  59. * Decodes an object from binary data.
  60. *
  61. * @param[in] data Binary data to decode.
  62. * @param[in] dataLength Length of the data in bytes.
  63. */
  64. SPtr<IReflectable> decode(UINT8* data, UINT32 dataLength);
  65. /**
  66. * Encodes an object into an intermediate representation.
  67. *
  68. * @param[in] object Object to encode.
  69. * @param[in] shallow Determines how to handle referenced objects. If true then references will not be encoded
  70. * and will be set to null. If false then references will be encoded as well and restored
  71. * upon decoding.
  72. */
  73. SPtr<SerializedObject> _encodeIntermediate(IReflectable* object, bool shallow = false);
  74. /**
  75. * Decodes an object in memory into an intermediate representation for easier parsing.
  76. *
  77. * @param[in] data Binary data to decode.
  78. * @param[in] dataLength Length of the data in bytes.
  79. * @param[in] copyData Determines should the data be copied or just referenced. If referenced then the returned
  80. * serialized object will be invalid as soon as the original data buffer is destroyed.
  81. * Referencing is faster than copying.
  82. *
  83. * @note
  84. * Internal method.
  85. * @note
  86. * References to field data will point to the original buffer and will become invalid when it is destroyed.
  87. */
  88. SPtr<SerializedObject> _decodeIntermediate(UINT8* data, UINT32 dataLength, bool copyData = false);
  89. /**
  90. * Decodes an intermediate representation of a serialized object into the actual object.
  91. *
  92. * @note Internal method.
  93. */
  94. SPtr<IReflectable> _decodeIntermediate(const SPtr<SerializedObject>& serializedObject);
  95. private:
  96. struct ObjectMetaData
  97. {
  98. UINT32 objectMeta;
  99. UINT32 typeId;
  100. };
  101. struct ObjectToEncode
  102. {
  103. ObjectToEncode(UINT32 _objectId, std::shared_ptr<IReflectable> _object)
  104. :objectId(_objectId), object(_object)
  105. { }
  106. UINT32 objectId;
  107. std::shared_ptr<IReflectable> object;
  108. };
  109. struct ObjectToDecode
  110. {
  111. ObjectToDecode(const SPtr<IReflectable>& _object, const SPtr<SerializedObject>& serializedObject)
  112. :object(_object), serializedObject(serializedObject), isDecoded(false)
  113. { }
  114. SPtr<IReflectable> object;
  115. SPtr<SerializedObject> serializedObject;
  116. bool isDecoded;
  117. };
  118. /** Encodes a single IReflectable object. */
  119. UINT8* encodeInternal(IReflectable* object, UINT32 objectId, UINT8* buffer, UINT32& bufferLength, UINT32* bytesWritten,
  120. std::function<UINT8*(UINT8* buffer, UINT32 bytesWritten, UINT32& newBufferSize)> flushBufferCallback, bool shallow);
  121. /** Decodes a single IReflectable object. */
  122. void decodeInternal(const SPtr<IReflectable>& object, const SPtr<SerializedObject>& serializableObject);
  123. /** Decodes an object in memory into an intermediate representation for easier parsing. */
  124. bool decodeIntermediateInternal(UINT8* data, UINT32 dataLength, UINT32& bytesRead, SPtr<SerializedObject>& output, bool copyData);
  125. /** Helper method for encoding a complex object and copying its data to a buffer. */
  126. UINT8* complexTypeToBuffer(IReflectable* object, UINT8* buffer, UINT32& bufferLength, UINT32* bytesWritten,
  127. std::function<UINT8*(UINT8* buffer, UINT32 bytesWritten, UINT32& newBufferSize)> flushBufferCallback, bool shallow);
  128. /** Helper method for encoding a data block to a buffer. */
  129. UINT8* dataBlockToBuffer(UINT8* data, UINT32 size, UINT8* buffer, UINT32& bufferLength, UINT32* bytesWritten,
  130. std::function<UINT8*(UINT8* buffer, UINT32 bytesWritten, UINT32& newBufferSize)> flushBufferCallback);
  131. /** Finds an existing, or creates a unique unique identifier for the specified object. */
  132. UINT32 findOrCreatePersistentId(IReflectable* object);
  133. /**
  134. * Finds or creates an id for the provided object and returns it. And it adds the object to a list of objects that
  135. * need to be encoded, if it's not already there.
  136. */
  137. UINT32 registerObjectPtr(std::shared_ptr<IReflectable> object);
  138. /** Encodes data required for representing a serialized field, into 4 bytes. */
  139. static UINT32 encodeFieldMetaData(UINT16 id, UINT8 size, bool array,
  140. SerializableFieldType type, bool hasDynamicSize, bool terminator);
  141. /** Decode meta field that was encoded using encodeFieldMetaData().*/
  142. static void decodeFieldMetaData(UINT32 encodedData, UINT16& id, UINT8& size, bool& array,
  143. SerializableFieldType& type, bool& hasDynamicSize, bool& terminator);
  144. /**
  145. * Encodes data required for representing an object identifier, into 8 bytes.
  146. *
  147. * @param[in] objId Unique ID of the object instance.
  148. * @param[in] objTypeId Unique ID of the object type.
  149. * @param[in] isBaseClass true if this object is base class (i.e. just a part of a larger object).
  150. *
  151. * @note Id can be a maximum of 30 bits, as two bits are reserved.
  152. */
  153. static ObjectMetaData encodeObjectMetaData(UINT32 objId, UINT32 objTypeId, bool isBaseClass);
  154. /** Decode meta field that was encoded using encodeObjectMetaData. */
  155. static void decodeObjectMetaData(ObjectMetaData encodedData, UINT32& objId, UINT32& objTypeId, bool& isBaseClass);
  156. /** Returns true if the provided encoded meta data represents object meta data. */
  157. static bool isObjectMetaData(UINT32 encodedData);
  158. UnorderedMap<void*, UINT32> mObjectAddrToId;
  159. UINT32 mLastUsedObjectId;
  160. Vector<ObjectToEncode> mObjectsToEncode;
  161. UINT32 mTotalBytesWritten;
  162. UnorderedMap<SPtr<SerializedObject>, ObjectToDecode> mObjectMap;
  163. UnorderedMap<UINT32, SPtr<SerializedObject>> mInterimObjectMap;
  164. static const int META_SIZE = 4; // Meta field size
  165. static const int NUM_ELEM_FIELD_SIZE = 4; // Size of the field storing number of array elements
  166. static const int COMPLEX_TYPE_FIELD_SIZE = 4; // Size of the field storing the size of a child complex type
  167. static const int DATA_BLOCK_TYPE_FIELD_SIZE = 4;
  168. };
  169. /** @} */
  170. }