BitStream.h 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. /// \file BitStream.h
  11. /// \brief This class allows you to write and read native types as a string of bits.
  12. /// \details BitStream is used extensively throughout RakNet and is designed to be used by users as well.
  13. ///
  14. #if defined(_MSC_VER) && _MSC_VER < 1299 // VC6 doesn't support template specialization
  15. #include "BitStream_NoTemplate.h"
  16. #else
  17. #ifndef __BITSTREAM_H
  18. #define __BITSTREAM_H
  19. #include "RakMemoryOverride.h"
  20. #include "RakNetDefines.h"
  21. #include "Export.h"
  22. #include "RakNetTypes.h"
  23. #include "RakString.h"
  24. #include "RakWString.h"
  25. #include "RakAssert.h"
  26. #include <math.h>
  27. #include <float.h>
  28. #ifdef _MSC_VER
  29. #pragma warning( push )
  30. #endif
  31. // MSWin uses _copysign, others use copysign...
  32. #ifndef _WIN32
  33. #define _copysign copysign
  34. #endif
  35. namespace RakNet
  36. {
  37. /// This class allows you to write and read native types as a string of bits. BitStream is used extensively throughout RakNet and is designed to be used by users as well.
  38. /// \sa BitStreamSample.txt
  39. class RAK_DLL_EXPORT BitStream
  40. {
  41. public:
  42. // GetInstance() and DestroyInstance(instance*)
  43. STATIC_FACTORY_DECLARATIONS(BitStream)
  44. /// Default Constructor
  45. BitStream();
  46. /// \brief Create the bitstream, with some number of bytes to immediately allocate.
  47. /// \details There is no benefit to calling this, unless you know exactly how many bytes you need and it is greater than BITSTREAM_STACK_ALLOCATION_SIZE.
  48. /// In that case all it does is save you one or more realloc calls.
  49. /// \param[in] initialBytesToAllocate the number of bytes to pre-allocate.
  50. BitStream( const unsigned int initialBytesToAllocate );
  51. /// \brief Initialize the BitStream, immediately setting the data it contains to a predefined pointer.
  52. /// \details Set \a _copyData to true if you want to make an internal copy of the data you are passing. Set it to false to just save a pointer to the data.
  53. /// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory
  54. /// 99% of the time you will use this function to cast Packet::data to a bitstream for reading, in which case you should write something as follows:
  55. /// \code
  56. /// RakNet::BitStream bs(packet->data, packet->length, false);
  57. /// \endcode
  58. /// \param[in] _data An array of bytes.
  59. /// \param[in] lengthInBytes Size of the \a _data.
  60. /// \param[in] _copyData true or false to make a copy of \a _data or not.
  61. BitStream( unsigned char* _data, const unsigned int lengthInBytes, bool _copyData );
  62. // Destructor
  63. ~BitStream();
  64. /// Resets the bitstream for reuse.
  65. void Reset( void );
  66. /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream.
  67. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  68. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  69. /// \param[in] inOutTemplateVar The value to write
  70. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  71. template <class templateType>
  72. bool Serialize(bool writeToBitstream, templateType &inOutTemplateVar);
  73. /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream.
  74. /// \details If the current value is different from the last value
  75. /// the current value will be written. Otherwise, a single bit will be written
  76. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  77. /// \param[in] inOutCurrentValue The current value to write
  78. /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true.
  79. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  80. template <class templateType>
  81. bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue);
  82. /// \brief Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value.
  83. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  84. /// \param[in] inOutCurrentValue The current value to write
  85. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  86. template <class templateType>
  87. bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue);
  88. /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream.
  89. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  90. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  91. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  92. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  93. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  94. /// \param[in] inOutTemplateVar The value to write
  95. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  96. template <class templateType>
  97. bool SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar);
  98. /// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream.
  99. /// \details If the current value is different from the last value
  100. /// the current value will be written. Otherwise, a single bit will be written
  101. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  102. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  103. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  104. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  105. /// \param[in] inOutCurrentValue The current value to write
  106. /// \param[in] lastValue The last value to compare against. Only used if \a writeToBitstream is true.
  107. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  108. template <class templateType>
  109. bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue);
  110. /// \brief Save as SerializeCompressedDelta(templateType &currentValue, const templateType &lastValue) when we have an unknown second parameter
  111. /// \return true on data read. False on insufficient data in bitstream
  112. template <class templateType>
  113. bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutTemplateVar);
  114. /// \brief Bidirectional serialize/deserialize an array or casted stream or raw data. This does NOT do endian swapping.
  115. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  116. /// \param[in] inOutByteArray a byte buffer
  117. /// \param[in] numberOfBytes the size of \a input in bytes
  118. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  119. bool Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes );
  120. /// \brief Serialize a float into 2 bytes, spanning the range between \a floatMin and \a floatMax
  121. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  122. /// \param[in] inOutFloat The float to write
  123. /// \param[in] floatMin Predetermined minimum value of f
  124. /// \param[in] floatMax Predetermined maximum value of f
  125. bool SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax);
  126. /// Serialize one type casted to another (smaller) type, to save bandwidth
  127. /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t
  128. /// Example: int num=53; SerializeCasted<uint8_t>(true, num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes)
  129. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  130. /// \param[in] value The value to serialize
  131. template <class serializationType, class sourceType >
  132. bool SerializeCasted( bool writeToBitstream, sourceType &value );
  133. /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range
  134. /// Then serialize only those bits
  135. /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program
  136. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  137. /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum
  138. /// \param[in] minimum Minimum value of \a value
  139. /// \param[in] maximum Maximum value of \a value
  140. /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates
  141. template <class templateType>
  142. bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false );
  143. /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum
  144. template <class templateType>
  145. bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false );
  146. /// \brief Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.
  147. /// \details Will further compress y or z axis aligned vectors.
  148. /// Accurate to 1/32767.5.
  149. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  150. /// \param[in] x x
  151. /// \param[in] y y
  152. /// \param[in] z z
  153. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  154. template <class templateType> // templateType for this function must be a float or double
  155. bool SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z );
  156. /// \brief Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12.
  157. /// \details Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.
  158. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  159. /// \param[in] x x
  160. /// \param[in] y y
  161. /// \param[in] z z
  162. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  163. template <class templateType> // templateType for this function must be a float or double
  164. bool SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z );
  165. /// \brief Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.
  166. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  167. /// \param[in] w w
  168. /// \param[in] x x
  169. /// \param[in] y y
  170. /// \param[in] z z
  171. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  172. template <class templateType> // templateType for this function must be a float or double
  173. bool SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z);
  174. /// \brief Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each.
  175. /// \details Use 6 bytes instead of 36
  176. /// Lossy, although the result is renormalized
  177. /// \return true on success, false on failure.
  178. template <class templateType> // templateType for this function must be a float or double
  179. bool SerializeOrthMatrix(
  180. bool writeToBitstream,
  181. templateType &m00, templateType &m01, templateType &m02,
  182. templateType &m10, templateType &m11, templateType &m12,
  183. templateType &m20, templateType &m21, templateType &m22 );
  184. /// \brief Bidirectional serialize/deserialize numberToSerialize bits to/from the input.
  185. /// \details Right aligned data means in the case of a partial byte, the bits are aligned
  186. /// from the right (bit 0) rather than the left (as in the normal
  187. /// internal representation) You would set this to true when
  188. /// writing user data, and false when copying bitstream data, such
  189. /// as writing one bitstream to another
  190. /// \param[in] writeToBitstream true to write from your data to this bitstream. False to read from this bitstream and write to your data
  191. /// \param[in] inOutByteArray The data
  192. /// \param[in] numberOfBitsToSerialize The number of bits to write
  193. /// \param[in] rightAlignedBits if true data will be right aligned
  194. /// \return true if \a writeToBitstream is true. true if \a writeToBitstream is false and the read was successful. false if \a writeToBitstream is false and the read was not successful.
  195. bool SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits = true );
  196. /// \brief Write any integral type to a bitstream.
  197. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  198. /// \param[in] inTemplateVar The value to write
  199. template <class templateType>
  200. void Write(const templateType &inTemplateVar);
  201. /// \brief Write the dereferenced pointer to any integral type to a bitstream.
  202. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  203. /// \param[in] inTemplateVar The value to write
  204. template <class templateType>
  205. void WritePtr(templateType *inTemplateVar);
  206. /// \brief Write any integral type to a bitstream.
  207. /// \details If the current value is different from the last value
  208. /// the current value will be written. Otherwise, a single bit will be written
  209. /// \param[in] currentValue The current value to write
  210. /// \param[in] lastValue The last value to compare against
  211. template <class templateType>
  212. void WriteDelta(const templateType &currentValue, const templateType &lastValue);
  213. /// \brief WriteDelta when you don't know what the last value is, or there is no last value.
  214. /// \param[in] currentValue The current value to write
  215. template <class templateType>
  216. void WriteDelta(const templateType &currentValue);
  217. /// \brief Write any integral type to a bitstream.
  218. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  219. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  220. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  221. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  222. /// \param[in] inTemplateVar The value to write
  223. template <class templateType>
  224. void WriteCompressed(const templateType &inTemplateVar);
  225. /// \brief Write any integral type to a bitstream.
  226. /// \details If the current value is different from the last value
  227. /// the current value will be written. Otherwise, a single bit will be written
  228. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  229. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  230. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  231. /// \param[in] currentValue The current value to write
  232. /// \param[in] lastValue The last value to compare against
  233. template <class templateType>
  234. void WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue);
  235. /// \brief Save as WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue) when we have an unknown second parameter
  236. template <class templateType>
  237. void WriteCompressedDelta(const templateType &currentValue);
  238. /// \brief Read any integral type from a bitstream.
  239. /// \details Define __BITSTREAM_NATIVE_END if you need endian swapping.
  240. /// \param[in] outTemplateVar The value to read
  241. /// \return true on success, false on failure.
  242. template <class templateType>
  243. bool Read(templateType &outTemplateVar);
  244. /// \brief Read any integral type from a bitstream.
  245. /// \details If the written value differed from the value compared against in the write function,
  246. /// var will be updated. Otherwise it will retain the current value.
  247. /// ReadDelta is only valid from a previous call to WriteDelta
  248. /// \param[in] outTemplateVar The value to read
  249. /// \return true on success, false on failure.
  250. template <class templateType>
  251. bool ReadDelta(templateType &outTemplateVar);
  252. /// \brief Read any integral type from a bitstream.
  253. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  254. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  255. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  256. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  257. /// \param[in] outTemplateVar The value to read
  258. /// \return true on success, false on failure.
  259. template <class templateType>
  260. bool ReadCompressed(templateType &outTemplateVar);
  261. /// \brief Read any integral type from a bitstream.
  262. /// \details If the written value differed from the value compared against in the write function,
  263. /// var will be updated. Otherwise it will retain the current value.
  264. /// the current value will be updated.
  265. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  266. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  267. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  268. /// ReadCompressedDelta is only valid from a previous call to WriteDelta
  269. /// \param[in] outTemplateVar The value to read
  270. /// \return true on success, false on failure.
  271. template <class templateType>
  272. bool ReadCompressedDelta(templateType &outTemplateVar);
  273. /// \brief Read one bitstream to another.
  274. /// \param[in] numberOfBits bits to read
  275. /// \param bitStream the bitstream to read into from
  276. /// \return true on success, false on failure.
  277. bool Read( BitStream *bitStream, BitSize_t numberOfBits );
  278. bool Read( BitStream *bitStream );
  279. bool Read( BitStream &bitStream, BitSize_t numberOfBits );
  280. bool Read( BitStream &bitStream );
  281. /// \brief Write an array or casted stream or raw data. This does NOT do endian swapping.
  282. /// \param[in] inputByteArray a byte buffer
  283. /// \param[in] numberOfBytes the size of \a input in bytes
  284. void Write( const char* inputByteArray, const unsigned int numberOfBytes );
  285. /// \brief Write one bitstream to another.
  286. /// \param[in] numberOfBits bits to write
  287. /// \param bitStream the bitstream to copy from
  288. void Write( BitStream *bitStream, BitSize_t numberOfBits );
  289. void Write( BitStream *bitStream );
  290. void Write( BitStream &bitStream, BitSize_t numberOfBits );
  291. void Write( BitStream &bitStream );\
  292. /// \brief Write a float into 2 bytes, spanning the range between \a floatMin and \a floatMax
  293. /// \param[in] x The float to write
  294. /// \param[in] floatMin Predetermined minimum value of f
  295. /// \param[in] floatMax Predetermined maximum value of f
  296. void WriteFloat16( float x, float floatMin, float floatMax );
  297. /// Write one type serialized as another (smaller) type, to save bandwidth
  298. /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t
  299. /// Example: int num=53; WriteCasted<uint8_t>(num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes)
  300. /// \param[in] value The value to write
  301. template <class serializationType, class sourceType >
  302. void WriteCasted( const sourceType &value );
  303. /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range
  304. /// Then write only those bits
  305. /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program
  306. /// \param[in] value Integer value to write, which should be between \a minimum and \a maximum
  307. /// \param[in] minimum Minimum value of \a value
  308. /// \param[in] maximum Maximum value of \a value
  309. /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Read().
  310. template <class templateType>
  311. void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false );
  312. /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum
  313. template <class templateType>
  314. void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false );
  315. /// \brief Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.
  316. /// \details Will further compress y or z axis aligned vectors.
  317. /// Accurate to 1/32767.5.
  318. /// \param[in] x x
  319. /// \param[in] y y
  320. /// \param[in] z z
  321. template <class templateType> // templateType for this function must be a float or double
  322. void WriteNormVector( templateType x, templateType y, templateType z );
  323. /// \brief Write a vector, using 10 bytes instead of 12.
  324. /// \details Loses accuracy to about 3/10ths and only saves 2 bytes,
  325. /// so only use if accuracy is not important.
  326. /// \param[in] x x
  327. /// \param[in] y y
  328. /// \param[in] z z
  329. template <class templateType> // templateType for this function must be a float or double
  330. void WriteVector( templateType x, templateType y, templateType z );
  331. /// \brief Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.
  332. /// \param[in] w w
  333. /// \param[in] x x
  334. /// \param[in] y y
  335. /// \param[in] z z
  336. template <class templateType> // templateType for this function must be a float or double
  337. void WriteNormQuat( templateType w, templateType x, templateType y, templateType z);
  338. /// \brief Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each.
  339. /// \details Use 6 bytes instead of 36
  340. /// Lossy, although the result is renormalized
  341. template <class templateType> // templateType for this function must be a float or double
  342. void WriteOrthMatrix(
  343. templateType m00, templateType m01, templateType m02,
  344. templateType m10, templateType m11, templateType m12,
  345. templateType m20, templateType m21, templateType m22 );
  346. /// \brief Read an array or casted stream of byte.
  347. /// \details The array is raw data. There is no automatic endian conversion with this function
  348. /// \param[in] output The result byte array. It should be larger than @em numberOfBytes.
  349. /// \param[in] numberOfBytes The number of byte to read
  350. /// \return true on success false if there is some missing bytes.
  351. bool Read( char* output, const unsigned int numberOfBytes );
  352. /// \brief Read a float into 2 bytes, spanning the range between \a floatMin and \a floatMax
  353. /// \param[in] outFloat The float to read
  354. /// \param[in] floatMin Predetermined minimum value of f
  355. /// \param[in] floatMax Predetermined maximum value of f
  356. bool ReadFloat16( float &outFloat, float floatMin, float floatMax );
  357. /// Read one type serialized to another (smaller) type, to save bandwidth
  358. /// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t
  359. /// Example: int num; ReadCasted<uint8_t>(num); would read 1 bytefrom the stream, and put the value in an integer
  360. /// \param[in] value The value to write
  361. template <class serializationType, class sourceType >
  362. bool ReadCasted( sourceType &value );
  363. /// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range
  364. /// Then read only those bits
  365. /// \note A static is used so that the required number of bits for (maximum-minimum) is only calculated once. This does require that \a minimum and \maximum are fixed values for a given line of code for the life of the program
  366. /// \param[in] value Integer value to read, which should be between \a minimum and \a maximum
  367. /// \param[in] minimum Minimum value of \a value
  368. /// \param[in] maximum Maximum value of \a value
  369. /// \param[in] allowOutsideRange If true, all sends will take an extra bit, however value can deviate from outside \a minimum and \a maximum. If false, will assert if the value deviates. This should match the corresponding value passed to Write().
  370. template <class templateType>
  371. bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false );
  372. /// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum
  373. template <class templateType>
  374. bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false );
  375. /// \brief Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.
  376. /// \details Will further compress y or z axis aligned vectors.
  377. /// Accurate to 1/32767.5.
  378. /// \param[in] x x
  379. /// \param[in] y y
  380. /// \param[in] z z
  381. /// \return true on success, false on failure.
  382. template <class templateType> // templateType for this function must be a float or double
  383. bool ReadNormVector( templateType &x, templateType &y, templateType &z );
  384. /// \brief Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector.
  385. /// \details Loses accuracy to about 3/10ths and only saves 2 bytes,
  386. /// so only use if accuracy is not important.
  387. /// \param[in] x x
  388. /// \param[in] y y
  389. /// \param[in] z z
  390. /// \return true on success, false on failure.
  391. template <class templateType> // templateType for this function must be a float or double
  392. bool ReadVector( templateType &x, templateType &y, templateType &z );
  393. /// \brief Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes.
  394. /// \param[in] w w
  395. /// \param[in] x x
  396. /// \param[in] y y
  397. /// \param[in] z z
  398. /// \return true on success, false on failure.
  399. template <class templateType> // templateType for this function must be a float or double
  400. bool ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z);
  401. /// \brief Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolatig the 4th.
  402. /// \details Use 6 bytes instead of 36
  403. /// Lossy, although the result is renormalized
  404. /// \return true on success, false on failure.
  405. template <class templateType> // templateType for this function must be a float or double
  406. bool ReadOrthMatrix(
  407. templateType &m00, templateType &m01, templateType &m02,
  408. templateType &m10, templateType &m11, templateType &m12,
  409. templateType &m20, templateType &m21, templateType &m22 );
  410. /// \brief Sets the read pointer back to the beginning of your data.
  411. void ResetReadPointer( void );
  412. /// \brief Sets the write pointer back to the beginning of your data.
  413. void ResetWritePointer( void );
  414. /// \brief This is good to call when you are done with the stream to make
  415. /// sure you didn't leave any data left over void
  416. void AssertStreamEmpty( void );
  417. /// \brief RAKNET_DEBUG_PRINTF the bits in the stream. Great for debugging.
  418. void PrintBits( char *out ) const;
  419. void PrintBits( void ) const;
  420. void PrintHex( char *out ) const;
  421. void PrintHex( void ) const;
  422. /// \brief Ignore data we don't intend to read
  423. /// \param[in] numberOfBits The number of bits to ignore
  424. void IgnoreBits( const BitSize_t numberOfBits );
  425. /// \brief Ignore data we don't intend to read
  426. /// \param[in] numberOfBits The number of bytes to ignore
  427. void IgnoreBytes( const unsigned int numberOfBytes );
  428. /// \brief Move the write pointer to a position on the array.
  429. /// \param[in] offset the offset from the start of the array.
  430. /// \attention
  431. /// \details Dangerous if you don't know what you are doing!
  432. /// For efficiency reasons you can only write mid-stream if your data is byte aligned.
  433. void SetWriteOffset( const BitSize_t offset );
  434. /// \brief Returns the length in bits of the stream
  435. inline BitSize_t GetNumberOfBitsUsed( void ) const {return GetWriteOffset();}
  436. inline BitSize_t GetWriteOffset( void ) const {return numberOfBitsUsed;}
  437. /// \brief Returns the length in bytes of the stream
  438. inline BitSize_t GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );}
  439. /// \brief Returns the number of bits into the stream that we have read
  440. inline BitSize_t GetReadOffset( void ) const {return readOffset;}
  441. /// \brief Sets the read bit index
  442. void SetReadOffset( const BitSize_t newReadOffset ) {readOffset=newReadOffset;}
  443. /// \brief Returns the number of bits left in the stream that haven't been read
  444. inline BitSize_t GetNumberOfUnreadBits( void ) const {return numberOfBitsUsed - readOffset;}
  445. /// \brief Makes a copy of the internal data for you \a _data will point to
  446. /// the stream. Partial bytes are left aligned.
  447. /// \param[out] _data The allocated copy of GetData()
  448. /// \return The length in bits of the stream.
  449. BitSize_t CopyData( unsigned char** _data ) const;
  450. /// \internal
  451. /// Set the stream to some initial data.
  452. void SetData( unsigned char *inByteArray );
  453. /// Gets the data that BitStream is writing to / reading from.
  454. /// Partial bytes are left aligned.
  455. /// \return A pointer to the internal state
  456. inline unsigned char* GetData( void ) const {return data;}
  457. /// \brief Write numberToWrite bits from the input source.
  458. /// \details Right aligned data means in the case of a partial byte, the bits are aligned
  459. /// from the right (bit 0) rather than the left (as in the normal
  460. /// internal representation) You would set this to true when
  461. /// writing user data, and false when copying bitstream data, such
  462. /// as writing one bitstream to another.
  463. /// \param[in] inByteArray The data
  464. /// \param[in] numberOfBitsToWrite The number of bits to write
  465. /// \param[in] rightAlignedBits if true data will be right aligned
  466. void WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits = true );
  467. /// \brief Align the bitstream to the byte boundary and then write the
  468. /// specified number of bits.
  469. /// \details This is faster than WriteBits but
  470. /// wastes the bits to do the alignment and requires you to call
  471. /// ReadAlignedBits at the corresponding read position.
  472. /// \param[in] inByteArray The data
  473. /// \param[in] numberOfBytesToWrite The size of input.
  474. void WriteAlignedBytes( const unsigned char *inByteArray, const unsigned int numberOfBytesToWrite );
  475. // Endian swap bytes already in the bitstream
  476. void EndianSwapBytes( int byteOffset, int length );
  477. /// \brief Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite
  478. /// \param[in] inByteArray The data
  479. /// \param[in] inputLength The size of input.
  480. /// \param[in] maxBytesToWrite Max bytes to write
  481. void WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite );
  482. /// \brief Read bits, starting at the next aligned bits.
  483. /// \details Note that the modulus 8 starting offset of the sequence must be the same as
  484. /// was used with WriteBits. This will be a problem with packet
  485. /// coalescence unless you byte align the coalesced packets.
  486. /// \param[in] inOutByteArray The byte array larger than @em numberOfBytesToRead
  487. /// \param[in] numberOfBytesToRead The number of byte to read from the internal state
  488. /// \return true if there is enough byte.
  489. bool ReadAlignedBytes( unsigned char *inOutByteArray, const unsigned int numberOfBytesToRead );
  490. /// \brief Reads what was written by WriteAlignedBytesSafe.
  491. /// \param[in] inOutByteArray The data
  492. /// \param[in] maxBytesToRead Maximum number of bytes to read
  493. /// \return true on success, false on failure.
  494. bool ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead );
  495. bool ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead );
  496. /// \brief Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to
  497. /// \param[in] outByteArray outByteArray will be deleted if it is not a pointer to 0
  498. /// \return true on success, false on failure.
  499. bool ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead );
  500. bool ReadAlignedBytesSafeAlloc( char **outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead );
  501. /// \brief Align the next write and/or read to a byte boundary.
  502. /// \details This can be used to 'waste' bits to byte align for efficiency reasons It
  503. /// can also be used to force coalesced bitstreams to start on byte
  504. /// boundaries so so WriteAlignedBits and ReadAlignedBits both
  505. /// calculate the same offset when aligning.
  506. inline void AlignWriteToByteBoundary( void ) {numberOfBitsUsed += 8 - ( (( numberOfBitsUsed - 1 ) & 7) + 1 );}
  507. /// \brief Align the next write and/or read to a byte boundary.
  508. /// \details This can be used to 'waste' bits to byte align for efficiency reasons It
  509. /// can also be used to force coalesced bitstreams to start on byte
  510. /// boundaries so so WriteAlignedBits and ReadAlignedBits both
  511. /// calculate the same offset when aligning.
  512. inline void AlignReadToByteBoundary( void ) {readOffset += 8 - ( (( readOffset - 1 ) & 7 ) + 1 );}
  513. /// \brief Read \a numberOfBitsToRead bits to the output source.
  514. /// \details alignBitsToRight should be set to true to convert internal
  515. /// bitstream data to userdata. It should be false if you used
  516. /// WriteBits with rightAlignedBits false
  517. /// \param[in] inOutByteArray The resulting bits array
  518. /// \param[in] numberOfBitsToRead The number of bits to read
  519. /// \param[in] alignBitsToRight if true bits will be right aligned.
  520. /// \return true if there is enough bits to read
  521. bool ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight = true );
  522. /// \brief Write a 0
  523. void Write0( void );
  524. /// \brief Write a 1
  525. void Write1( void );
  526. /// \brief Reads 1 bit and returns true if that bit is 1 and false if it is 0.
  527. bool ReadBit( void );
  528. /// \brief If we used the constructor version with copy data off, this
  529. /// *makes sure it is set to on and the data pointed to is copied.
  530. void AssertCopyData( void );
  531. /// \brief Use this if you pass a pointer copy to the constructor
  532. /// *(_copyData==false) and want to overallocate to prevent
  533. /// reallocation.
  534. void SetNumberOfBitsAllocated( const BitSize_t lengthInBits );
  535. /// \brief Reallocates (if necessary) in preparation of writing numberOfBitsToWrite
  536. void AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite );
  537. /// \internal
  538. /// \return How many bits have been allocated internally
  539. BitSize_t GetNumberOfBitsAllocated(void) const;
  540. /// \brief Read strings, non reference.
  541. bool Read(char *varString);
  542. bool Read(unsigned char *varString);
  543. /// Write zeros until the bitstream is filled up to \a bytes
  544. void PadWithZeroToByteLength( unsigned int bytes );
  545. /// Get the number of leading zeros for a number
  546. /// \param[in] x Number to test
  547. static int NumberOfLeadingZeroes( uint8_t x );
  548. static int NumberOfLeadingZeroes( uint16_t x );
  549. static int NumberOfLeadingZeroes( uint32_t x );
  550. static int NumberOfLeadingZeroes( uint64_t x );
  551. static int NumberOfLeadingZeroes( int8_t x );
  552. static int NumberOfLeadingZeroes( int16_t x );
  553. static int NumberOfLeadingZeroes( int32_t x );
  554. static int NumberOfLeadingZeroes( int64_t x );
  555. /// \internal Unrolled inner loop, for when performance is critical
  556. void WriteAlignedVar8(const char *inByteArray);
  557. /// \internal Unrolled inner loop, for when performance is critical
  558. bool ReadAlignedVar8(char *inOutByteArray);
  559. /// \internal Unrolled inner loop, for when performance is critical
  560. void WriteAlignedVar16(const char *inByteArray);
  561. /// \internal Unrolled inner loop, for when performance is critical
  562. bool ReadAlignedVar16(char *inOutByteArray);
  563. /// \internal Unrolled inner loop, for when performance is critical
  564. void WriteAlignedVar32(const char *inByteArray);
  565. /// \internal Unrolled inner loop, for when performance is critical
  566. bool ReadAlignedVar32(char *inOutByteArray);
  567. inline void Write(const char * const inStringVar)
  568. {
  569. RakString::Serialize(inStringVar, this);
  570. }
  571. inline void Write(const wchar_t * const inStringVar)
  572. {
  573. RakWString::Serialize(inStringVar, this);
  574. }
  575. inline void Write(const unsigned char * const inTemplateVar)
  576. {
  577. Write((const char*)inTemplateVar);
  578. }
  579. inline void Write(char * const inTemplateVar)
  580. {
  581. Write((const char*)inTemplateVar);
  582. }
  583. inline void Write(unsigned char * const inTemplateVar)
  584. {
  585. Write((const char*)inTemplateVar);
  586. }
  587. inline void WriteCompressed(const char * const inStringVar)
  588. {
  589. RakString::SerializeCompressed(inStringVar,this,0,false);
  590. }
  591. inline void WriteCompressed(const wchar_t * const inStringVar)
  592. {
  593. RakWString::Serialize(inStringVar,this);
  594. }
  595. inline void WriteCompressed(const unsigned char * const inTemplateVar)
  596. {
  597. WriteCompressed((const char*) inTemplateVar);
  598. }
  599. inline void WriteCompressed(char * const inTemplateVar)
  600. {
  601. WriteCompressed((const char*) inTemplateVar);
  602. }
  603. inline void WriteCompressed(unsigned char * const inTemplateVar)
  604. {
  605. WriteCompressed((const char*) inTemplateVar);
  606. }
  607. /// ---- Member function template specialization declarations ----
  608. // Used for VC7
  609. #if defined(_MSC_VER) && _MSC_VER == 1300
  610. /// Write a bool to a bitstream.
  611. /// \param[in] var The value to write
  612. template <>
  613. void Write(const bool &var);
  614. /// Write a systemAddress to a bitstream
  615. /// \param[in] var The value to write
  616. template <>
  617. void Write(const SystemAddress &var);
  618. /// Write a uint24_t to a bitstream
  619. /// \param[in] var The value to write
  620. template <>
  621. void Write(const uint24_t &var);
  622. /// Write a RakNetGUID to a bitsteam
  623. /// \param[in] var The value to write
  624. template <>
  625. void Write(const RakNetGuid &var);
  626. /// Write a string to a bitstream
  627. /// \param[in] var The value to write
  628. template <>
  629. void Write(const char* const &var);
  630. template <>
  631. void Write(const unsigned char* const &var);
  632. template <>
  633. void Write(char* const &var);
  634. template <>
  635. void Write(unsigned char* const &var);
  636. template <>
  637. void Write(const RakString &var);
  638. template <>
  639. void Write(const RakWString &var);
  640. /// \brief Write a systemAddress.
  641. /// \details If the current value is different from the last value
  642. /// the current value will be written. Otherwise, a single bit will be written
  643. /// \param[in] currentValue The current value to write
  644. /// \param[in] lastValue The last value to compare against
  645. template <>
  646. void WriteDelta(const SystemAddress &currentValue, const SystemAddress &lastValue);
  647. template <>
  648. void WriteDelta(const uint24_t &currentValue, const uint24_t &lastValue);
  649. template <>
  650. void WriteDelta(const RakNetGUID &currentValue, const RakNetGUID &lastValue);
  651. /// \brief Write a bool delta.
  652. /// \details Same thing as just calling Write
  653. /// \param[in] currentValue The current value to write
  654. /// \param[in] lastValue The last value to compare against
  655. template <>
  656. void WriteDelta(const bool &currentValue, const bool &lastValue);
  657. template <>
  658. void WriteCompressed(const SystemAddress &var);
  659. template <>
  660. void WriteCompressed(const uint24_t &var);
  661. template <>
  662. void WriteCompressed(const RakNetGUID &var);
  663. template <>
  664. void WriteCompressed(const bool &var);
  665. /// For values between -1 and 1
  666. template <>
  667. void WriteCompressed(const float &var);
  668. /// For values between -1 and 1
  669. template <>
  670. void WriteCompressed(const double &var);
  671. /// Compressed string
  672. template <>
  673. void WriteCompressed(const char* var);
  674. template <>
  675. void WriteCompressed(const unsigned char* var);
  676. template <>
  677. void WriteCompressed(char* var);
  678. template <>
  679. void WriteCompressed(unsigned char* var);
  680. template <>
  681. void WriteCompressed(const RakString &var);
  682. template <>
  683. void WriteCompressed(const RakWString &var);
  684. /// \brief Write a bool delta.
  685. /// \details Same thing as just calling Write
  686. /// \param[in] currentValue The current value to write
  687. /// \param[in] lastValue The last value to compare against
  688. template <>
  689. void WriteCompressedDelta(const bool &currentValue, const bool &lastValue);
  690. /// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue)
  691. /// when we have an unknown second bool
  692. template <>
  693. void WriteCompressedDelta(const bool &currentValue);
  694. /// \brief Read a bool from a bitstream.
  695. /// \param[in] var The value to read
  696. /// \return true on success, false on failure.
  697. template <>
  698. bool Read(bool &var);
  699. /// \brief Read a systemAddress from a bitstream.
  700. /// \param[in] var The value to read
  701. /// \return true on success, false on failure.
  702. template <>
  703. bool Read(SystemAddress &var);
  704. template <>
  705. bool Read(uint24_t &var);
  706. template <>
  707. bool Read(RakNetGUID &var);
  708. /// \brief Read a String from a bitstream.
  709. /// \param[in] var The value to read
  710. /// \return true on success, false on failure.
  711. template <>
  712. bool Read(char *&var);
  713. template <>
  714. bool Read(wchar_t *&var);
  715. template <>
  716. bool Read(unsigned char *&var);
  717. template <>
  718. bool Read(RakString &var);
  719. template <>
  720. bool Read(RakWString &var);
  721. /// \brief Read a bool from a bitstream.
  722. /// \param[in] var The value to read
  723. /// \return true on success, false on failure.
  724. template <>
  725. bool ReadDelta(bool &var);
  726. template <>
  727. bool ReadCompressed(SystemAddress &var);
  728. template <>
  729. bool ReadCompressed(uint24_t &var);
  730. template <>
  731. bool ReadCompressed(RakNetGUID &var);
  732. template <>
  733. bool ReadCompressed(bool &var);
  734. template <>
  735. bool ReadCompressed(float &var);
  736. /// For values between -1 and 1
  737. /// \return true on success, false on failure.
  738. template <>
  739. bool ReadCompressed(double &var);
  740. template <>
  741. bool ReadCompressed(char* &var);
  742. template <>
  743. bool ReadCompressed(wchar_t* &var);
  744. template <>
  745. bool ReadCompressed(unsigned char *&var);
  746. template <>
  747. bool ReadCompressed(RakString &var);
  748. template <>
  749. bool ReadCompressed(RakWString &var);
  750. /// \brief Read a bool from a bitstream.
  751. /// \param[in] var The value to read
  752. /// \return true on success, false on failure.
  753. template <>
  754. bool ReadCompressedDelta(bool &var);
  755. #endif
  756. inline static bool DoEndianSwap(void) {
  757. #ifndef __BITSTREAM_NATIVE_END
  758. return IsNetworkOrder()==false;
  759. #else
  760. return false;
  761. #endif
  762. }
  763. inline static bool IsBigEndian(void)
  764. {
  765. return IsNetworkOrder();
  766. }
  767. inline static bool IsNetworkOrder(void) {bool r = IsNetworkOrderInternal(); return r;}
  768. // Not inline, won't compile on PC due to winsock include errors
  769. static bool IsNetworkOrderInternal(void);
  770. static void ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length);
  771. static void ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length);
  772. private:
  773. BitStream( const BitStream &invalid) {
  774. (void) invalid;
  775. RakAssert(0);
  776. }
  777. BitStream& operator = ( const BitStream& invalid ) {
  778. (void) invalid;
  779. RakAssert(0);
  780. static BitStream i;
  781. return i;
  782. }
  783. /// \brief Assume the input source points to a native type, compress and write it.
  784. void WriteCompressed( const unsigned char* inByteArray, const unsigned int size, const bool unsignedData );
  785. /// \brief Assume the input source points to a compressed native type. Decompress and read it.
  786. bool ReadCompressed( unsigned char* inOutByteArray, const unsigned int size, const bool unsignedData );
  787. BitSize_t numberOfBitsUsed;
  788. BitSize_t numberOfBitsAllocated;
  789. BitSize_t readOffset;
  790. unsigned char *data;
  791. /// true if the internal buffer is copy of the data passed to the constructor
  792. bool copyData;
  793. /// BitStreams that use less than BITSTREAM_STACK_ALLOCATION_SIZE use the stack, rather than the heap to store data. It switches over if BITSTREAM_STACK_ALLOCATION_SIZE is exceeded
  794. unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE];
  795. };
  796. template <class templateType>
  797. inline bool BitStream::Serialize(bool writeToBitstream, templateType &inOutTemplateVar)
  798. {
  799. if (writeToBitstream)
  800. Write(inOutTemplateVar);
  801. else
  802. return Read(inOutTemplateVar);
  803. return true;
  804. }
  805. template <class templateType>
  806. inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue)
  807. {
  808. if (writeToBitstream)
  809. WriteDelta(inOutCurrentValue, lastValue);
  810. else
  811. return ReadDelta(inOutCurrentValue);
  812. return true;
  813. }
  814. template <class templateType>
  815. inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue)
  816. {
  817. if (writeToBitstream)
  818. WriteDelta(inOutCurrentValue);
  819. else
  820. return ReadDelta(inOutCurrentValue);
  821. return true;
  822. }
  823. template <class templateType>
  824. inline bool BitStream::SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar)
  825. {
  826. if (writeToBitstream)
  827. WriteCompressed(inOutTemplateVar);
  828. else
  829. return ReadCompressed(inOutTemplateVar);
  830. return true;
  831. }
  832. template <class templateType>
  833. inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue)
  834. {
  835. if (writeToBitstream)
  836. WriteCompressedDelta(inOutCurrentValue,lastValue);
  837. else
  838. return ReadCompressedDelta(inOutCurrentValue);
  839. return true;
  840. }
  841. //Stoppedhere
  842. template <class templateType>
  843. inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue)
  844. {
  845. if (writeToBitstream)
  846. WriteCompressedDelta(inOutCurrentValue);
  847. else
  848. return ReadCompressedDelta(inOutCurrentValue);
  849. return true;
  850. }
  851. inline bool BitStream::Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes )
  852. {
  853. if (writeToBitstream)
  854. Write(inOutByteArray, numberOfBytes);
  855. else
  856. return Read(inOutByteArray, numberOfBytes);
  857. return true;
  858. }
  859. template <class serializationType, class sourceType >
  860. bool BitStream::SerializeCasted( bool writeToBitstream, sourceType &value )
  861. {
  862. if (writeToBitstream) WriteCasted<serializationType>(value);
  863. else return ReadCasted<serializationType>(value);
  864. return true;
  865. }
  866. template <class templateType>
  867. bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange )
  868. {
  869. int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum));
  870. return SerializeBitsFromIntegerRange(writeToBitstream,value,minimum,maximum,requiredBits,allowOutsideRange);
  871. }
  872. template <class templateType>
  873. bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange )
  874. {
  875. if (writeToBitstream) WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
  876. else return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
  877. return true;
  878. }
  879. template <class templateType>
  880. inline bool BitStream::SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z )
  881. {
  882. if (writeToBitstream)
  883. WriteNormVector(x,y,z);
  884. else
  885. return ReadNormVector(x,y,z);
  886. return true;
  887. }
  888. template <class templateType>
  889. inline bool BitStream::SerializeVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z )
  890. {
  891. if (writeToBitstream)
  892. WriteVector(x,y,z);
  893. else
  894. return ReadVector(x,y,z);
  895. return true;
  896. }
  897. template <class templateType>
  898. inline bool BitStream::SerializeNormQuat(bool writeToBitstream, templateType &w, templateType &x, templateType &y, templateType &z)
  899. {
  900. if (writeToBitstream)
  901. WriteNormQuat(w,x,y,z);
  902. else
  903. return ReadNormQuat(w,x,y,z);
  904. return true;
  905. }
  906. template <class templateType>
  907. inline bool BitStream::SerializeOrthMatrix(
  908. bool writeToBitstream,
  909. templateType &m00, templateType &m01, templateType &m02,
  910. templateType &m10, templateType &m11, templateType &m12,
  911. templateType &m20, templateType &m21, templateType &m22 )
  912. {
  913. if (writeToBitstream)
  914. WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22);
  915. else
  916. return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22);
  917. return true;
  918. }
  919. inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits )
  920. {
  921. if (writeToBitstream)
  922. WriteBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits);
  923. else
  924. return ReadBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits);
  925. return true;
  926. }
  927. template <class templateType>
  928. inline void BitStream::Write(const templateType &inTemplateVar)
  929. {
  930. #ifdef _MSC_VER
  931. #pragma warning(disable:4127) // conditional expression is constant
  932. #endif
  933. if (sizeof(inTemplateVar)==1)
  934. WriteBits( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true );
  935. else
  936. {
  937. #ifndef __BITSTREAM_NATIVE_END
  938. if (DoEndianSwap())
  939. {
  940. unsigned char output[sizeof(templateType)];
  941. ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType));
  942. WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true );
  943. }
  944. else
  945. #endif
  946. WriteBits( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true );
  947. }
  948. }
  949. template <class templateType>
  950. inline void BitStream::WritePtr(templateType *inTemplateVar)
  951. {
  952. #ifdef _MSC_VER
  953. #pragma warning(disable:4127) // conditional expression is constant
  954. #endif
  955. if (sizeof(templateType)==1)
  956. WriteBits( ( unsigned char* ) inTemplateVar, sizeof( templateType ) * 8, true );
  957. else
  958. {
  959. #ifndef __BITSTREAM_NATIVE_END
  960. if (DoEndianSwap())
  961. {
  962. unsigned char output[sizeof(templateType)];
  963. ReverseBytes((unsigned char*) inTemplateVar, output, sizeof(templateType));
  964. WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true );
  965. }
  966. else
  967. #endif
  968. WriteBits( ( unsigned char* ) inTemplateVar, sizeof(templateType) * 8, true );
  969. }
  970. }
  971. /// \brief Write a bool to a bitstream.
  972. /// \param[in] inTemplateVar The value to write
  973. template <>
  974. inline void BitStream::Write(const bool &inTemplateVar)
  975. {
  976. if ( inTemplateVar )
  977. Write1();
  978. else
  979. Write0();
  980. }
  981. /// \brief Write a systemAddress to a bitstream.
  982. /// \param[in] inTemplateVar The value to write
  983. template <>
  984. inline void BitStream::Write(const SystemAddress &inTemplateVar)
  985. {
  986. Write(inTemplateVar.GetIPVersion());
  987. if (inTemplateVar.GetIPVersion()==4)
  988. {
  989. // Hide the address so routers don't modify it
  990. SystemAddress var2=inTemplateVar;
  991. uint32_t binaryAddress=~inTemplateVar.address.addr4.sin_addr.s_addr;
  992. // Don't endian swap the address or port
  993. WriteBits((unsigned char*)&binaryAddress, sizeof(binaryAddress)*8, true);
  994. unsigned short p = var2.GetPortNetworkOrder();
  995. WriteBits((unsigned char*)&p, sizeof(unsigned short)*8, true);
  996. }
  997. else
  998. {
  999. #if RAKNET_SUPPORT_IPV6==1
  1000. // Don't endian swap
  1001. WriteBits((const unsigned char*) &inTemplateVar.address.addr6, sizeof(inTemplateVar.address.addr6)*8, true);
  1002. #endif
  1003. }
  1004. }
  1005. template <>
  1006. inline void BitStream::Write(const uint24_t &inTemplateVar)
  1007. {
  1008. AlignWriteToByteBoundary();
  1009. AddBitsAndReallocate(3*8);
  1010. if (IsBigEndian()==false)
  1011. {
  1012. data[( numberOfBitsUsed >> 3 ) + 0] = ((unsigned char *)&inTemplateVar.val)[0];
  1013. data[( numberOfBitsUsed >> 3 ) + 1] = ((unsigned char *)&inTemplateVar.val)[1];
  1014. data[( numberOfBitsUsed >> 3 ) + 2] = ((unsigned char *)&inTemplateVar.val)[2];
  1015. }
  1016. else
  1017. {
  1018. data[( numberOfBitsUsed >> 3 ) + 0] = ((unsigned char *)&inTemplateVar.val)[3];
  1019. data[( numberOfBitsUsed >> 3 ) + 1] = ((unsigned char *)&inTemplateVar.val)[2];
  1020. data[( numberOfBitsUsed >> 3 ) + 2] = ((unsigned char *)&inTemplateVar.val)[1];
  1021. }
  1022. numberOfBitsUsed+=3*8;
  1023. }
  1024. template <>
  1025. inline void BitStream::Write(const RakNetGUID &inTemplateVar)
  1026. {
  1027. Write(inTemplateVar.g);
  1028. }
  1029. /// \brief Write a string to a bitstream.
  1030. /// \param[in] var The value to write
  1031. template <>
  1032. inline void BitStream::Write(const RakString &inTemplateVar)
  1033. {
  1034. inTemplateVar.Serialize(this);
  1035. }
  1036. template <>
  1037. inline void BitStream::Write(const RakWString &inTemplateVar)
  1038. {
  1039. inTemplateVar.Serialize(this);
  1040. }
  1041. template <>
  1042. inline void BitStream::Write(const char * const &inStringVar)
  1043. {
  1044. RakString::Serialize(inStringVar, this);
  1045. }
  1046. template <>
  1047. inline void BitStream::Write(const wchar_t * const &inStringVar)
  1048. {
  1049. RakWString::Serialize(inStringVar, this);
  1050. }
  1051. template <>
  1052. inline void BitStream::Write(const unsigned char * const &inTemplateVar)
  1053. {
  1054. Write((const char*)inTemplateVar);
  1055. }
  1056. template <>
  1057. inline void BitStream::Write(char * const &inTemplateVar)
  1058. {
  1059. Write((const char*)inTemplateVar);
  1060. }
  1061. template <>
  1062. inline void BitStream::Write(unsigned char * const &inTemplateVar)
  1063. {
  1064. Write((const char*)inTemplateVar);
  1065. }
  1066. /// \brief Write any integral type to a bitstream.
  1067. /// \details If the current value is different from the last value
  1068. /// the current value will be written. Otherwise, a single bit will be written
  1069. /// \param[in] currentValue The current value to write
  1070. /// \param[in] lastValue The last value to compare against
  1071. template <class templateType>
  1072. inline void BitStream::WriteDelta(const templateType &currentValue, const templateType &lastValue)
  1073. {
  1074. if (currentValue==lastValue)
  1075. {
  1076. Write(false);
  1077. }
  1078. else
  1079. {
  1080. Write(true);
  1081. Write(currentValue);
  1082. }
  1083. }
  1084. /// \brief Write a bool delta. Same thing as just calling Write
  1085. /// \param[in] currentValue The current value to write
  1086. /// \param[in] lastValue The last value to compare against
  1087. template <>
  1088. inline void BitStream::WriteDelta(const bool &currentValue, const bool &lastValue)
  1089. {
  1090. (void) lastValue;
  1091. Write(currentValue);
  1092. }
  1093. /// \brief WriteDelta when you don't know what the last value is, or there is no last value.
  1094. /// \param[in] currentValue The current value to write
  1095. template <class templateType>
  1096. inline void BitStream::WriteDelta(const templateType &currentValue)
  1097. {
  1098. Write(true);
  1099. Write(currentValue);
  1100. }
  1101. /// \brief Write any integral type to a bitstream.
  1102. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  1103. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  1104. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  1105. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  1106. /// \param[in] inTemplateVar The value to write
  1107. template <class templateType>
  1108. inline void BitStream::WriteCompressed(const templateType &inTemplateVar)
  1109. {
  1110. #ifdef _MSC_VER
  1111. #pragma warning(disable:4127) // conditional expression is constant
  1112. #endif
  1113. if (sizeof(inTemplateVar)==1)
  1114. WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true );
  1115. else
  1116. {
  1117. #ifndef __BITSTREAM_NATIVE_END
  1118. #ifdef _MSC_VER
  1119. #pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'unsigned short', possible loss of data
  1120. #endif
  1121. if (DoEndianSwap())
  1122. {
  1123. unsigned char output[sizeof(templateType)];
  1124. ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType));
  1125. WriteCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true );
  1126. }
  1127. else
  1128. #endif
  1129. WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true );
  1130. }
  1131. }
  1132. template <>
  1133. inline void BitStream::WriteCompressed(const SystemAddress &inTemplateVar)
  1134. {
  1135. Write(inTemplateVar);
  1136. }
  1137. template <>
  1138. inline void BitStream::WriteCompressed(const RakNetGUID &inTemplateVar)
  1139. {
  1140. Write(inTemplateVar);
  1141. }
  1142. template <>
  1143. inline void BitStream::WriteCompressed(const uint24_t &var)
  1144. {
  1145. Write(var);
  1146. }
  1147. template <>
  1148. inline void BitStream::WriteCompressed(const bool &inTemplateVar)
  1149. {
  1150. Write(inTemplateVar);
  1151. }
  1152. /// For values between -1 and 1
  1153. template <>
  1154. inline void BitStream::WriteCompressed(const float &inTemplateVar)
  1155. {
  1156. RakAssert(inTemplateVar > -1.01f && inTemplateVar < 1.01f);
  1157. float varCopy=inTemplateVar;
  1158. if (varCopy < -1.0f)
  1159. varCopy=-1.0f;
  1160. if (varCopy > 1.0f)
  1161. varCopy=1.0f;
  1162. Write((unsigned short)((varCopy+1.0f)*32767.5f));
  1163. }
  1164. /// For values between -1 and 1
  1165. template <>
  1166. inline void BitStream::WriteCompressed(const double &inTemplateVar)
  1167. {
  1168. RakAssert(inTemplateVar > -1.01 && inTemplateVar < 1.01);
  1169. double varCopy=inTemplateVar;
  1170. if (varCopy < -1.0f)
  1171. varCopy=-1.0f;
  1172. if (varCopy > 1.0f)
  1173. varCopy=1.0f;
  1174. Write((uint32_t)((varCopy+1.0)*2147483648.0));
  1175. }
  1176. /// Compress the string
  1177. template <>
  1178. inline void BitStream::WriteCompressed(const RakString &inTemplateVar)
  1179. {
  1180. inTemplateVar.SerializeCompressed(this,0,false);
  1181. }
  1182. template <>
  1183. inline void BitStream::WriteCompressed(const RakWString &inTemplateVar)
  1184. {
  1185. inTemplateVar.Serialize(this);
  1186. }
  1187. template <>
  1188. inline void BitStream::WriteCompressed(const char * const &inStringVar)
  1189. {
  1190. RakString::SerializeCompressed(inStringVar,this,0,false);
  1191. }
  1192. template <>
  1193. inline void BitStream::WriteCompressed(const wchar_t * const &inStringVar)
  1194. {
  1195. RakWString::Serialize(inStringVar,this);
  1196. }
  1197. template <>
  1198. inline void BitStream::WriteCompressed(const unsigned char * const &inTemplateVar)
  1199. {
  1200. WriteCompressed((const char*) inTemplateVar);
  1201. }
  1202. template <>
  1203. inline void BitStream::WriteCompressed(char * const &inTemplateVar)
  1204. {
  1205. WriteCompressed((const char*) inTemplateVar);
  1206. }
  1207. template <>
  1208. inline void BitStream::WriteCompressed(unsigned char * const &inTemplateVar)
  1209. {
  1210. WriteCompressed((const char*) inTemplateVar);
  1211. }
  1212. /// \brief Write any integral type to a bitstream.
  1213. /// \details If the current value is different from the last value
  1214. /// the current value will be written. Otherwise, a single bit will be written
  1215. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  1216. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  1217. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  1218. /// \param[in] currentValue The current value to write
  1219. /// \param[in] lastValue The last value to compare against
  1220. template <class templateType>
  1221. inline void BitStream::WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue)
  1222. {
  1223. if (currentValue==lastValue)
  1224. {
  1225. Write(false);
  1226. }
  1227. else
  1228. {
  1229. Write(true);
  1230. WriteCompressed(currentValue);
  1231. }
  1232. }
  1233. /// \brief Write a bool delta. Same thing as just calling Write
  1234. /// \param[in] currentValue The current value to write
  1235. /// \param[in] lastValue The last value to compare against
  1236. template <>
  1237. inline void BitStream::WriteCompressedDelta(const bool &currentValue, const bool &lastValue)
  1238. {
  1239. (void) lastValue;
  1240. Write(currentValue);
  1241. }
  1242. /// \brief Save as WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue)
  1243. /// when we have an unknown second parameter
  1244. template <class templateType>
  1245. inline void BitStream::WriteCompressedDelta(const templateType &currentValue)
  1246. {
  1247. Write(true);
  1248. WriteCompressed(currentValue);
  1249. }
  1250. /// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue)
  1251. /// when we have an unknown second bool
  1252. template <>
  1253. inline void BitStream::WriteCompressedDelta(const bool &currentValue)
  1254. {
  1255. Write(currentValue);
  1256. }
  1257. /// \brief Read any integral type from a bitstream. Define __BITSTREAM_NATIVE_END if you need endian swapping.
  1258. /// \param[in] outTemplateVar The value to read
  1259. template <class templateType>
  1260. inline bool BitStream::Read(templateType &outTemplateVar)
  1261. {
  1262. #ifdef _MSC_VER
  1263. #pragma warning(disable:4127) // conditional expression is constant
  1264. #endif
  1265. if (sizeof(outTemplateVar)==1)
  1266. return ReadBits( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true );
  1267. else
  1268. {
  1269. #ifndef __BITSTREAM_NATIVE_END
  1270. #ifdef _MSC_VER
  1271. #pragma warning(disable:4244) // '=' : conversion from 'unsigned long' to 'unsigned short', possible loss of data
  1272. #endif
  1273. if (DoEndianSwap())
  1274. {
  1275. unsigned char output[sizeof(templateType)];
  1276. if (ReadBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ))
  1277. {
  1278. ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType));
  1279. return true;
  1280. }
  1281. return false;
  1282. }
  1283. else
  1284. #endif
  1285. return ReadBits( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true );
  1286. }
  1287. }
  1288. /// \brief Read a bool from a bitstream.
  1289. /// \param[in] outTemplateVar The value to read
  1290. template <>
  1291. inline bool BitStream::Read(bool &outTemplateVar)
  1292. {
  1293. if ( readOffset + 1 > numberOfBitsUsed )
  1294. return false;
  1295. if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) // Is it faster to just write it out here?
  1296. outTemplateVar = true;
  1297. else
  1298. outTemplateVar = false;
  1299. // Has to be on a different line for Mac
  1300. readOffset++;
  1301. return true;
  1302. }
  1303. /// \brief Read a systemAddress from a bitstream.
  1304. /// \param[in] outTemplateVar The value to read
  1305. template <>
  1306. inline bool BitStream::Read(SystemAddress &outTemplateVar)
  1307. {
  1308. unsigned char ipVersion;
  1309. Read(ipVersion);
  1310. if (ipVersion==4)
  1311. {
  1312. outTemplateVar.address.addr4.sin_family=AF_INET;
  1313. // Read(var.binaryAddress);
  1314. // Don't endian swap the address or port
  1315. uint32_t binaryAddress;
  1316. ReadBits( ( unsigned char* ) & binaryAddress, sizeof(binaryAddress) * 8, true );
  1317. // Unhide the IP address, done to prevent routers from changing it
  1318. outTemplateVar.address.addr4.sin_addr.s_addr=~binaryAddress;
  1319. bool b = ReadBits(( unsigned char* ) & outTemplateVar.address.addr4.sin_port, sizeof(outTemplateVar.address.addr4.sin_port) * 8, true);
  1320. outTemplateVar.debugPort=ntohs(outTemplateVar.address.addr4.sin_port);
  1321. return b;
  1322. }
  1323. else
  1324. {
  1325. #if RAKNET_SUPPORT_IPV6==1
  1326. bool b = ReadBits((unsigned char*) &outTemplateVar.address.addr6, sizeof(outTemplateVar.address.addr6)*8, true);
  1327. outTemplateVar.debugPort=ntohs(outTemplateVar.address.addr6.sin6_port);
  1328. return b;
  1329. #else
  1330. return false;
  1331. #endif
  1332. }
  1333. }
  1334. template <>
  1335. inline bool BitStream::Read(uint24_t &outTemplateVar)
  1336. {
  1337. AlignReadToByteBoundary();
  1338. if ( readOffset + 3*8 > numberOfBitsUsed )
  1339. return false;
  1340. if (IsBigEndian()==false)
  1341. {
  1342. ((unsigned char *)&outTemplateVar.val)[0]=data[ (readOffset >> 3) + 0];
  1343. ((unsigned char *)&outTemplateVar.val)[1]=data[ (readOffset >> 3) + 1];
  1344. ((unsigned char *)&outTemplateVar.val)[2]=data[ (readOffset >> 3) + 2];
  1345. ((unsigned char *)&outTemplateVar.val)[3]=0;
  1346. }
  1347. else
  1348. {
  1349. ((unsigned char *)&outTemplateVar.val)[3]=data[ (readOffset >> 3) + 0];
  1350. ((unsigned char *)&outTemplateVar.val)[2]=data[ (readOffset >> 3) + 1];
  1351. ((unsigned char *)&outTemplateVar.val)[1]=data[ (readOffset >> 3) + 2];
  1352. ((unsigned char *)&outTemplateVar.val)[0]=0;
  1353. }
  1354. readOffset+=3*8;
  1355. return true;
  1356. }
  1357. template <>
  1358. inline bool BitStream::Read(RakNetGUID &outTemplateVar)
  1359. {
  1360. return Read(outTemplateVar.g);
  1361. }
  1362. template <>
  1363. inline bool BitStream::Read(RakString &outTemplateVar)
  1364. {
  1365. return outTemplateVar.Deserialize(this);
  1366. }
  1367. template <>
  1368. inline bool BitStream::Read(RakWString &outTemplateVar)
  1369. {
  1370. return outTemplateVar.Deserialize(this);
  1371. }
  1372. template <>
  1373. inline bool BitStream::Read(char *&varString)
  1374. {
  1375. return RakString::Deserialize(varString,this);
  1376. }
  1377. template <>
  1378. inline bool BitStream::Read(wchar_t *&varString)
  1379. {
  1380. return RakWString::Deserialize(varString,this);
  1381. }
  1382. template <>
  1383. inline bool BitStream::Read(unsigned char *&varString)
  1384. {
  1385. return RakString::Deserialize((char*) varString,this);
  1386. }
  1387. /// \brief Read any integral type from a bitstream.
  1388. /// \details If the written value differed from the value compared against in the write function,
  1389. /// var will be updated. Otherwise it will retain the current value.
  1390. /// ReadDelta is only valid from a previous call to WriteDelta
  1391. /// \param[in] outTemplateVar The value to read
  1392. template <class templateType>
  1393. inline bool BitStream::ReadDelta(templateType &outTemplateVar)
  1394. {
  1395. bool dataWritten;
  1396. bool success;
  1397. success=Read(dataWritten);
  1398. if (dataWritten)
  1399. success=Read(outTemplateVar);
  1400. return success;
  1401. }
  1402. /// \brief Read a bool from a bitstream.
  1403. /// \param[in] outTemplateVar The value to read
  1404. template <>
  1405. inline bool BitStream::ReadDelta(bool &outTemplateVar)
  1406. {
  1407. return Read(outTemplateVar);
  1408. }
  1409. /// \brief Read any integral type from a bitstream.
  1410. /// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
  1411. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  1412. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  1413. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  1414. /// \param[in] outTemplateVar The value to read
  1415. template <class templateType>
  1416. inline bool BitStream::ReadCompressed(templateType &outTemplateVar)
  1417. {
  1418. #ifdef _MSC_VER
  1419. #pragma warning(disable:4127) // conditional expression is constant
  1420. #endif
  1421. if (sizeof(outTemplateVar)==1)
  1422. return ReadCompressed( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true );
  1423. else
  1424. {
  1425. #ifndef __BITSTREAM_NATIVE_END
  1426. if (DoEndianSwap())
  1427. {
  1428. unsigned char output[sizeof(templateType)];
  1429. if (ReadCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true ))
  1430. {
  1431. ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType));
  1432. return true;
  1433. }
  1434. return false;
  1435. }
  1436. else
  1437. #endif
  1438. return ReadCompressed( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true );
  1439. }
  1440. }
  1441. template <>
  1442. inline bool BitStream::ReadCompressed(SystemAddress &outTemplateVar)
  1443. {
  1444. return Read(outTemplateVar);
  1445. }
  1446. template <>
  1447. inline bool BitStream::ReadCompressed(uint24_t &outTemplateVar)
  1448. {
  1449. return Read(outTemplateVar);
  1450. }
  1451. template <>
  1452. inline bool BitStream::ReadCompressed(RakNetGUID &outTemplateVar)
  1453. {
  1454. return Read(outTemplateVar);
  1455. }
  1456. template <>
  1457. inline bool BitStream::ReadCompressed(bool &outTemplateVar)
  1458. {
  1459. return Read(outTemplateVar);
  1460. }
  1461. /// For values between -1 and 1
  1462. template <>
  1463. inline bool BitStream::ReadCompressed(float &outTemplateVar)
  1464. {
  1465. unsigned short compressedFloat;
  1466. if (Read(compressedFloat))
  1467. {
  1468. outTemplateVar = ((float)compressedFloat / 32767.5f - 1.0f);
  1469. return true;
  1470. }
  1471. return false;
  1472. }
  1473. /// For values between -1 and 1
  1474. template <>
  1475. inline bool BitStream::ReadCompressed(double &outTemplateVar)
  1476. {
  1477. uint32_t compressedFloat;
  1478. if (Read(compressedFloat))
  1479. {
  1480. outTemplateVar = ((double)compressedFloat / 2147483648.0 - 1.0);
  1481. return true;
  1482. }
  1483. return false;
  1484. }
  1485. /// For strings
  1486. template <>
  1487. inline bool BitStream::ReadCompressed(RakString &outTemplateVar)
  1488. {
  1489. return outTemplateVar.DeserializeCompressed(this,false);
  1490. }
  1491. template <>
  1492. inline bool BitStream::ReadCompressed(RakWString &outTemplateVar)
  1493. {
  1494. return outTemplateVar.Deserialize(this);
  1495. }
  1496. template <>
  1497. inline bool BitStream::ReadCompressed(char *&outTemplateVar)
  1498. {
  1499. return RakString::DeserializeCompressed(outTemplateVar,this,false);
  1500. }
  1501. template <>
  1502. inline bool BitStream::ReadCompressed(wchar_t *&outTemplateVar)
  1503. {
  1504. return RakWString::Deserialize(outTemplateVar,this);
  1505. }
  1506. template <>
  1507. inline bool BitStream::ReadCompressed(unsigned char *&outTemplateVar)
  1508. {
  1509. return RakString::DeserializeCompressed((char*) outTemplateVar,this,false);
  1510. }
  1511. /// \brief Read any integral type from a bitstream.
  1512. /// \details If the written value differed from the value compared against in the write function,
  1513. /// var will be updated. Otherwise it will retain the current value.
  1514. /// the current value will be updated.
  1515. /// For floating point, this is lossy, using 2 bytes for a float and 4 for a double. The range must be between -1 and +1.
  1516. /// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
  1517. /// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
  1518. /// ReadCompressedDelta is only valid from a previous call to WriteDelta
  1519. /// \param[in] outTemplateVar The value to read
  1520. template <class templateType>
  1521. inline bool BitStream::ReadCompressedDelta(templateType &outTemplateVar)
  1522. {
  1523. bool dataWritten;
  1524. bool success;
  1525. success=Read(dataWritten);
  1526. if (dataWritten)
  1527. success=ReadCompressed(outTemplateVar);
  1528. return success;
  1529. }
  1530. /// \brief Read a bool from a bitstream.
  1531. /// \param[in] outTemplateVar The value to read
  1532. template <>
  1533. inline bool BitStream::ReadCompressedDelta(bool &outTemplateVar)
  1534. {
  1535. return Read(outTemplateVar);
  1536. }
  1537. template <class destinationType, class sourceType >
  1538. void BitStream::WriteCasted( const sourceType &value )
  1539. {
  1540. destinationType val = (destinationType) value;
  1541. Write(val);
  1542. }
  1543. template <class templateType>
  1544. void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, bool allowOutsideRange )
  1545. {
  1546. int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum));
  1547. WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
  1548. }
  1549. template <class templateType>
  1550. void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, const int requiredBits, bool allowOutsideRange )
  1551. {
  1552. RakAssert(maximum>=minimum);
  1553. RakAssert(allowOutsideRange==true || (value>=minimum && value<=maximum));
  1554. if (allowOutsideRange)
  1555. {
  1556. if (value<minimum || value>maximum)
  1557. {
  1558. Write(true);
  1559. Write(value);
  1560. return;
  1561. }
  1562. Write(false);
  1563. }
  1564. templateType valueOffMin=value-minimum;
  1565. if (IsBigEndian()==true)
  1566. {
  1567. unsigned char output[sizeof(templateType)];
  1568. ReverseBytes((unsigned char*)&valueOffMin, output, sizeof(templateType));
  1569. WriteBits(output,requiredBits);
  1570. }
  1571. else
  1572. {
  1573. WriteBits((unsigned char*) &valueOffMin,requiredBits);
  1574. }
  1575. }
  1576. template <class templateType> // templateType for this function must be a float or double
  1577. void BitStream::WriteNormVector( templateType x, templateType y, templateType z )
  1578. {
  1579. #ifdef _DEBUG
  1580. RakAssert(x <= 1.01 && y <= 1.01 && z <= 1.01 && x >= -1.01 && y >= -1.01 && z >= -1.01);
  1581. #endif
  1582. WriteFloat16((float)x,-1.0f,1.0f);
  1583. WriteFloat16((float)y,-1.0f,1.0f);
  1584. WriteFloat16((float)z,-1.0f,1.0f);
  1585. }
  1586. template <class templateType> // templateType for this function must be a float or double
  1587. void BitStream::WriteVector( templateType x, templateType y, templateType z )
  1588. {
  1589. templateType magnitude = sqrt(x * x + y * y + z * z);
  1590. Write((float)magnitude);
  1591. if (magnitude > 0.00001f)
  1592. {
  1593. WriteCompressed((float)(x/magnitude));
  1594. WriteCompressed((float)(y/magnitude));
  1595. WriteCompressed((float)(z/magnitude));
  1596. // Write((unsigned short)((x/magnitude+1.0f)*32767.5f));
  1597. // Write((unsigned short)((y/magnitude+1.0f)*32767.5f));
  1598. // Write((unsigned short)((z/magnitude+1.0f)*32767.5f));
  1599. }
  1600. }
  1601. template <class templateType> // templateType for this function must be a float or double
  1602. void BitStream::WriteNormQuat( templateType w, templateType x, templateType y, templateType z)
  1603. {
  1604. Write((bool)(w<0.0));
  1605. Write((bool)(x<0.0));
  1606. Write((bool)(y<0.0));
  1607. Write((bool)(z<0.0));
  1608. Write((unsigned short)(fabs(x)*65535.0));
  1609. Write((unsigned short)(fabs(y)*65535.0));
  1610. Write((unsigned short)(fabs(z)*65535.0));
  1611. // Leave out w and calculate it on the target
  1612. }
  1613. template <class templateType> // templateType for this function must be a float or double
  1614. void BitStream::WriteOrthMatrix(
  1615. templateType m00, templateType m01, templateType m02,
  1616. templateType m10, templateType m11, templateType m12,
  1617. templateType m20, templateType m21, templateType m22 )
  1618. {
  1619. double qw;
  1620. double qx;
  1621. double qy;
  1622. double qz;
  1623. // Convert matrix to quat
  1624. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
  1625. float sum;
  1626. sum = 1 + m00 + m11 + m22;
  1627. if (sum < 0.0f) sum=0.0f;
  1628. qw = sqrt( sum ) / 2;
  1629. sum = 1 + m00 - m11 - m22;
  1630. if (sum < 0.0f) sum=0.0f;
  1631. qx = sqrt( sum ) / 2;
  1632. sum = 1 - m00 + m11 - m22;
  1633. if (sum < 0.0f) sum=0.0f;
  1634. qy = sqrt( sum ) / 2;
  1635. sum = 1 - m00 - m11 + m22;
  1636. if (sum < 0.0f) sum=0.0f;
  1637. qz = sqrt( sum ) / 2;
  1638. if (qw < 0.0) qw=0.0;
  1639. if (qx < 0.0) qx=0.0;
  1640. if (qy < 0.0) qy=0.0;
  1641. if (qz < 0.0) qz=0.0;
  1642. qx = _copysign( (double) qx, (double) (m21 - m12) );
  1643. qy = _copysign( (double) qy, (double) (m02 - m20) );
  1644. qz = _copysign( (double) qz, (double) (m10 - m01) );
  1645. WriteNormQuat(qw,qx,qy,qz);
  1646. }
  1647. template <class serializationType, class sourceType >
  1648. bool BitStream::ReadCasted( sourceType &value )
  1649. {
  1650. serializationType val;
  1651. bool success = Read(val);
  1652. value=(sourceType) val;
  1653. return success;
  1654. }
  1655. template <class templateType>
  1656. bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange )
  1657. {
  1658. int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum));
  1659. return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
  1660. }
  1661. template <class templateType>
  1662. bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange )
  1663. {
  1664. RakAssert(maximum>=minimum);
  1665. if (allowOutsideRange)
  1666. {
  1667. bool isOutsideRange;
  1668. Read(isOutsideRange);
  1669. if (isOutsideRange)
  1670. return Read(value);
  1671. }
  1672. unsigned char output[sizeof(templateType)];
  1673. memset(output,0,sizeof(output));
  1674. bool success = ReadBits(output,requiredBits);
  1675. if (success)
  1676. {
  1677. if (IsBigEndian()==true)
  1678. ReverseBytesInPlace(output,sizeof(output));
  1679. memcpy(&value,output,sizeof(output));
  1680. value+=minimum;
  1681. }
  1682. return success;
  1683. }
  1684. template <class templateType> // templateType for this function must be a float or double
  1685. bool BitStream::ReadNormVector( templateType &x, templateType &y, templateType &z )
  1686. {
  1687. float xIn,yIn,zIn;
  1688. ReadFloat16(xIn,-1.0f,1.0f);
  1689. ReadFloat16(yIn,-1.0f,1.0f);
  1690. ReadFloat16(zIn,-1.0f,1.0f);
  1691. x=xIn;
  1692. y=yIn;
  1693. z=zIn;
  1694. return true;
  1695. }
  1696. template <class templateType> // templateType for this function must be a float or double
  1697. bool BitStream::ReadVector( templateType &x, templateType &y, templateType &z )
  1698. {
  1699. float magnitude;
  1700. //unsigned short sx,sy,sz;
  1701. if (!Read(magnitude))
  1702. return false;
  1703. if (magnitude>0.00001f)
  1704. {
  1705. // Read(sx);
  1706. // Read(sy);
  1707. // if (!Read(sz))
  1708. // return false;
  1709. // x=((float)sx / 32767.5f - 1.0f) * magnitude;
  1710. // y=((float)sy / 32767.5f - 1.0f) * magnitude;
  1711. // z=((float)sz / 32767.5f - 1.0f) * magnitude;
  1712. float cx=0.0f,cy=0.0f,cz=0.0f;
  1713. ReadCompressed(cx);
  1714. ReadCompressed(cy);
  1715. if (!ReadCompressed(cz))
  1716. return false;
  1717. x=cx;
  1718. y=cy;
  1719. z=cz;
  1720. x*=magnitude;
  1721. y*=magnitude;
  1722. z*=magnitude;
  1723. }
  1724. else
  1725. {
  1726. x=0.0;
  1727. y=0.0;
  1728. z=0.0;
  1729. }
  1730. return true;
  1731. }
  1732. template <class templateType> // templateType for this function must be a float or double
  1733. bool BitStream::ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z)
  1734. {
  1735. bool cwNeg=false, cxNeg=false, cyNeg=false, czNeg=false;
  1736. unsigned short cx,cy,cz;
  1737. Read(cwNeg);
  1738. Read(cxNeg);
  1739. Read(cyNeg);
  1740. Read(czNeg);
  1741. Read(cx);
  1742. Read(cy);
  1743. if (!Read(cz))
  1744. return false;
  1745. // Calculate w from x,y,z
  1746. x=(templateType)(cx/65535.0);
  1747. y=(templateType)(cy/65535.0);
  1748. z=(templateType)(cz/65535.0);
  1749. if (cxNeg) x=-x;
  1750. if (cyNeg) y=-y;
  1751. if (czNeg) z=-z;
  1752. float difference = 1.0f - x*x - y*y - z*z;
  1753. if (difference < 0.0f)
  1754. difference=0.0f;
  1755. w = (templateType)(sqrt(difference));
  1756. if (cwNeg)
  1757. w=-w;
  1758. return true;
  1759. }
  1760. template <class templateType> // templateType for this function must be a float or double
  1761. bool BitStream::ReadOrthMatrix(
  1762. templateType &m00, templateType &m01, templateType &m02,
  1763. templateType &m10, templateType &m11, templateType &m12,
  1764. templateType &m20, templateType &m21, templateType &m22 )
  1765. {
  1766. float qw,qx,qy,qz;
  1767. if (!ReadNormQuat(qw,qx,qy,qz))
  1768. return false;
  1769. // Quat to orthogonal rotation matrix
  1770. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm
  1771. double sqw = (double)qw*(double)qw;
  1772. double sqx = (double)qx*(double)qx;
  1773. double sqy = (double)qy*(double)qy;
  1774. double sqz = (double)qz*(double)qz;
  1775. m00 = (templateType)(sqx - sqy - sqz + sqw); // since sqw + sqx + sqy + sqz =1
  1776. m11 = (templateType)(-sqx + sqy - sqz + sqw);
  1777. m22 = (templateType)(-sqx - sqy + sqz + sqw);
  1778. double tmp1 = (double)qx*(double)qy;
  1779. double tmp2 = (double)qz*(double)qw;
  1780. m10 = (templateType)(2.0 * (tmp1 + tmp2));
  1781. m01 = (templateType)(2.0 * (tmp1 - tmp2));
  1782. tmp1 = (double)qx*(double)qz;
  1783. tmp2 = (double)qy*(double)qw;
  1784. m20 =(templateType)(2.0 * (tmp1 - tmp2));
  1785. m02 = (templateType)(2.0 * (tmp1 + tmp2));
  1786. tmp1 = (double)qy*(double)qz;
  1787. tmp2 = (double)qx*(double)qw;
  1788. m21 = (templateType)(2.0 * (tmp1 + tmp2));
  1789. m12 = (templateType)(2.0 * (tmp1 - tmp2));
  1790. return true;
  1791. }
  1792. template <class templateType>
  1793. BitStream& operator<<(BitStream& out, templateType& c)
  1794. {
  1795. out.Write(c);
  1796. return out;
  1797. }
  1798. template <class templateType>
  1799. BitStream& operator>>(BitStream& in, templateType& c)
  1800. {
  1801. bool success = in.Read(c);
  1802. (void)success;
  1803. RakAssert(success);
  1804. return in;
  1805. }
  1806. }
  1807. #ifdef _MSC_VER
  1808. #pragma warning( pop )
  1809. #endif
  1810. #endif
  1811. #endif // VC6
粤ICP备19079148号