summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/Net/OVR_BitStream.h
blob: 0c7c7b4f6d239dcab72f88533c79aba8162b8031 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
/************************************************************************************

PublicHeader:   n/a
Filename    :   OVR_BitStream.h
Content     :   A generic serialization toolkit for packing data to a binary stream.
Created     :   June 10, 2014
Authors     :   Kevin Jenkins

Copyright   :   Copyright 2014 Oculus VR, Inc. All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.1 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

************************************************************************************/

#ifndef OVR_Bitstream_h
#define OVR_Bitstream_h

#include <math.h>
#include "../Kernel/OVR_Types.h"
#include "../Kernel/OVR_Std.h"
#include "../Kernel/OVR_String.h"

namespace OVR { namespace Net {

typedef uint32_t BitSize_t;
#define BITSTREAM_STACK_ALLOCATION_SIZE 256
#define BITS_TO_BYTES(x) (((x)+7)>>3)
#define BYTES_TO_BITS(x) ((x)<<3)


//-----------------------------------------------------------------------------
// BitStream

// Generic serialization class to binary stream
class BitStream : public NewOverrideBase
{
public:
	/// Default Constructor
	BitStream();

	/// \brief Create the bitstream, with some number of bytes to immediately allocate.
	/// \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.
	/// In that case all it does is save you one or more realloc calls.
	/// \param[in] initialBytesToAllocate the number of bytes to pre-allocate.
	BitStream( const unsigned int initialBytesToAllocate );

	/// \brief Initialize the BitStream, immediately setting the data it contains to a predefined pointer.
	/// \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.
	/// You shouldn't call Write functions with \a _copyData as false, as this will write to unallocated memory
	/// 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:
	/// \code
	/// RakNet::BitStream bs(packet->data, packet->length, false);
	/// \endcode
	/// \param[in] _data An array of bytes.
	/// \param[in] lengthInBytes Size of the \a _data.
	/// \param[in] _copyData true or false to make a copy of \a _data or not.
	BitStream( char* _data, const unsigned int lengthInBytes, bool _copyData );

	// Destructor
	~BitStream();

public:
	/// Resets the bitstream for reuse.
	void Reset( void );

	/// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream.  
	/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutTemplateVar The value to write
	/// \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.
	template <class templateType>
	bool Serialize(bool writeToBitstream, templateType &inOutTemplateVar);

	/// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream. 
	/// \details If the current value is different from the last value
	/// the current value will be written.  Otherwise, a single bit will be written
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutCurrentValue The current value to write
	/// \param[in] lastValue The last value to compare against.  Only used if \a writeToBitstream is true.
	/// \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.
	template <class templateType>
	bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue);

	/// \brief Bidirectional version of SerializeDelta when you don't know what the last value is, or there is no last value.
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutCurrentValue The current value to write
	/// \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.
	template <class templateType>
	bool SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue);

	/// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream.
	/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
	/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
	/// 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.
	/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutTemplateVar The value to write
	/// \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.
	template <class templateType>
	bool SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar);

	/// \brief Bidirectional serialize/deserialize any integral type to/from a bitstream.  
	/// \details If the current value is different from the last value
	/// the current value will be written.  Otherwise, a single bit will be written
	/// 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.
	/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
	/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutCurrentValue The current value to write
	/// \param[in] lastValue The last value to compare against.  Only used if \a writeToBitstream is true.
	/// \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.
	template <class templateType>
	bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue);

	/// \brief Save as SerializeCompressedDelta(templateType &currentValue, const templateType &lastValue) when we have an unknown second parameter
	/// \return true on data read. False on insufficient data in bitstream
	template <class templateType>
	bool SerializeCompressedDelta(bool writeToBitstream, templateType &inOutTemplateVar);

	/// \brief Bidirectional serialize/deserialize an array or casted stream or raw data.  This does NOT do endian swapping.
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutByteArray a byte buffer
	/// \param[in] numberOfBytes the size of \a input in bytes
	/// \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.
	bool Serialize(bool writeToBitstream,  char* inOutByteArray, const unsigned int numberOfBytes );

	/// \brief Serialize a float into 2 bytes, spanning the range between \a floatMin and \a floatMax
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutFloat The float to write
	/// \param[in] floatMin Predetermined minimum value of f
	/// \param[in] floatMax Predetermined maximum value of f
	bool SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax);

	/// Serialize one type casted to another (smaller) type, to save bandwidth
	/// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t
	/// 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)
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] value The value to serialize
	template <class serializationType, class sourceType >
	bool SerializeCasted( bool writeToBitstream, sourceType &value );

	/// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range
	/// Then serialize only those bits
	/// \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
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] value Integer value to write, which should be between \a minimum and \a maximum
	/// \param[in] minimum Minimum value of \a value
	/// \param[in] maximum Maximum value of \a value
	/// \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
	template <class templateType>
	bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false );
	/// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum
	template <class templateType>
	bool SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false );

	/// \brief Bidirectional serialize/deserialize a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.  
	/// \details Will further compress y or z axis aligned vectors.
	/// Accurate to 1/32767.5.
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	/// \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.
	template <class templateType> // templateType for this function must be a float or double
	bool SerializeNormVector(bool writeToBitstream,  templateType &x, templateType &y, templateType &z );

	/// \brief Bidirectional serialize/deserialize a vector, using 10 bytes instead of 12.
	/// \details Loses accuracy to about 3/10ths and only saves 2 bytes, so only use if accuracy is not important.
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	/// \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.
	template <class templateType> // templateType for this function must be a float or double
	bool SerializeVector(bool writeToBitstream,  templateType &x, templateType &y, templateType &z );

	/// \brief Bidirectional serialize/deserialize a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes. Slightly lossy.
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] w w
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	/// \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.
	template <class templateType> // templateType for this function must be a float or double
	bool SerializeNormQuat(bool writeToBitstream,  templateType &w, templateType &x, templateType &y, templateType &z);

	/// \brief Bidirectional serialize/deserialize an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each.
	/// \details Use 6 bytes instead of 36
	/// Lossy, although the result is renormalized
	/// \return true on success, false on failure.
	template <class templateType> // templateType for this function must be a float or double
	bool SerializeOrthMatrix(
		bool writeToBitstream,
		templateType &m00, templateType &m01, templateType &m02,
		templateType &m10, templateType &m11, templateType &m12,
		templateType &m20, templateType &m21, templateType &m22 );

	/// \brief Bidirectional serialize/deserialize numberToSerialize bits to/from the input. 
	/// \details Right aligned data means in the case of a partial byte, the bits are aligned
	/// from the right (bit 0) rather than the left (as in the normal
	/// internal representation) You would set this to true when
	/// writing user data, and false when copying bitstream data, such
	/// as writing one bitstream to another
	/// \param[in] writeToBitstream true to write from your data to this bitstream.  False to read from this bitstream and write to your data
	/// \param[in] inOutByteArray The data
	/// \param[in] numberOfBitsToSerialize The number of bits to write
	/// \param[in] rightAlignedBits if true data will be right aligned
	/// \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.
	bool SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits = true );

	/// \brief Write any integral type to a bitstream.  
	/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
	/// \param[in] inTemplateVar The value to write
	template <class templateType>
	void Write(const templateType &inTemplateVar);

	/// \brief Write the dereferenced pointer to any integral type to a bitstream.  
	/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
	/// \param[in] inTemplateVar The value to write
	template <class templateType>
	void WritePtr(templateType *inTemplateVar);

	/// \brief Write any integral type to a bitstream.  
	/// \details If the current value is different from the last value
	/// the current value will be written.  Otherwise, a single bit will be written
	/// \param[in] currentValue The current value to write
	/// \param[in] lastValue The last value to compare against
	template <class templateType>
	void WriteDelta(const templateType &currentValue, const templateType &lastValue);

	/// \brief WriteDelta when you don't know what the last value is, or there is no last value.
	/// \param[in] currentValue The current value to write
	template <class templateType>
	void WriteDelta(const templateType &currentValue);

	/// \brief Write any integral type to a bitstream.  
	/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
	/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
	/// 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.
	/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
	/// \param[in] inTemplateVar The value to write
	template <class templateType>
	void WriteCompressed(const templateType &inTemplateVar);

	/// \brief Write any integral type to a bitstream.  
	/// \details If the current value is different from the last value
	/// the current value will be written.  Otherwise, a single bit will be written
	/// 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.
	/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
	/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
	/// \param[in] currentValue The current value to write
	/// \param[in] lastValue The last value to compare against
	template <class templateType>
	void WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue);

	/// \brief Save as WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue) when we have an unknown second parameter
	template <class templateType>
	void WriteCompressedDelta(const templateType &currentValue);

	/// \brief Read any integral type from a bitstream.  
	/// \details Define __BITSTREAM_NATIVE_END if you need endian swapping.
	/// \param[in] outTemplateVar The value to read
	/// \return true on success, false on failure.
	template <class templateType>
	bool Read(templateType &outTemplateVar);

	/// \brief Read any integral type from a bitstream.  
	/// \details If the written value differed from the value compared against in the write function,
	/// var will be updated.  Otherwise it will retain the current value.
	/// ReadDelta is only valid from a previous call to WriteDelta
	/// \param[in] outTemplateVar The value to read
	/// \return true on success, false on failure.
	template <class templateType>
	bool ReadDelta(templateType &outTemplateVar);

	/// \brief Read any integral type from a bitstream.  
	/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
	/// 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.
	/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
	/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
	/// \param[in] outTemplateVar The value to read
	/// \return true on success, false on failure.
	template <class templateType>
	bool ReadCompressed(templateType &outTemplateVar);

	/// \brief Read any integral type from a bitstream.  
	/// \details If the written value differed from the value compared against in the write function,
	/// var will be updated.  Otherwise it will retain the current value.
	/// the current value will be updated.
	/// 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.
	/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
	/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
	/// ReadCompressedDelta is only valid from a previous call to WriteDelta
	/// \param[in] outTemplateVar The value to read
	/// \return true on success, false on failure.
	template <class templateType>
	bool ReadCompressedDelta(templateType &outTemplateVar);

	/// \brief Read one bitstream to another.
	/// \param[in] numberOfBits bits to read
	/// \param bitStream the bitstream to read into from
	/// \return true on success, false on failure.
	bool Read( BitStream *bitStream, BitSize_t numberOfBits );
	bool Read( BitStream *bitStream );
	bool Read( BitStream &bitStream, BitSize_t numberOfBits );
	bool Read( BitStream &bitStream );

	/// \brief Write an array or casted stream or raw data.  This does NOT do endian swapping.
	/// \param[in] inputByteArray a byte buffer
	/// \param[in] numberOfBytes the size of \a input in bytes
	void Write( const char* inputByteArray, const unsigned int numberOfBytes );

	/// \brief Write one bitstream to another.
	/// \param[in] numberOfBits bits to write
	/// \param bitStream the bitstream to copy from
	void Write( BitStream *bitStream, BitSize_t numberOfBits );
	void Write( BitStream *bitStream );
	void Write( BitStream &bitStream, BitSize_t numberOfBits );
	void Write( BitStream &bitStream );\

	/// \brief Write a float into 2 bytes, spanning the range between \a floatMin and \a floatMax
	/// \param[in] x The float to write
	/// \param[in] floatMin Predetermined minimum value of f
	/// \param[in] floatMax Predetermined maximum value of f
	void WriteFloat16( float x, float floatMin, float floatMax );

	/// Write one type serialized as another (smaller) type, to save bandwidth
	/// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t
	/// Example: int num=53; WriteCasted<uint8_t>(num); would use 1 byte to write what would otherwise be an integer (4 or 8 bytes)
	/// \param[in] value The value to write
	template <class serializationType, class sourceType >
	void WriteCasted( const sourceType &value );

	/// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range
	/// Then write only those bits
	/// \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
	/// \param[in] value Integer value to write, which should be between \a minimum and \a maximum
	/// \param[in] minimum Minimum value of \a value
	/// \param[in] maximum Maximum value of \a value
	/// \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().
	template <class templateType>
	void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false );
	/// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum
	template <class templateType>
	void WriteBitsFromIntegerRange( const templateType value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false );

	/// \brief Write a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.  
	/// \details Will further compress y or z axis aligned vectors.
	/// Accurate to 1/32767.5.
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	template <class templateType> // templateType for this function must be a float or double
	void WriteNormVector( templateType x, templateType y, templateType z );

	/// \brief Write a vector, using 10 bytes instead of 12.
	/// \details Loses accuracy to about 3/10ths and only saves 2 bytes, 
	/// so only use if accuracy is not important.
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	template <class templateType> // templateType for this function must be a float or double
	void WriteVector( templateType x, templateType y, templateType z );

	/// \brief Write a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes.  Slightly lossy.
	/// \param[in] w w
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	template <class templateType> // templateType for this function must be a float or double
	void WriteNormQuat( templateType w, templateType x, templateType y, templateType z);

	/// \brief Write an orthogonal matrix by creating a quaternion, and writing 3 components of the quaternion in 2 bytes each.
	/// \details Use 6 bytes instead of 36
	/// Lossy, although the result is renormalized
	template <class templateType> // templateType for this function must be a float or double
	void WriteOrthMatrix(
		templateType m00, templateType m01, templateType m02,
		templateType m10, templateType m11, templateType m12,
		templateType m20, templateType m21, templateType m22 );

	/// \brief Read an array or casted stream of byte.
	/// \details The array is raw data. There is no automatic endian conversion with this function
	/// \param[in] output The result byte array. It should be larger than @em numberOfBytes.
	/// \param[in] numberOfBytes The number of byte to read
	/// \return true on success false if there is some missing bytes.
	bool Read( char* output, const unsigned int numberOfBytes );

	/// \brief Read a float into 2 bytes, spanning the range between \a floatMin and \a floatMax
	/// \param[in] outFloat The float to read
	/// \param[in] floatMin Predetermined minimum value of f
	/// \param[in] floatMax Predetermined maximum value of f
	bool ReadFloat16( float &outFloat, float floatMin, float floatMax );

	/// Read one type serialized to another (smaller) type, to save bandwidth
	/// serializationType should be uint8_t, uint16_t, uint24_t, or uint32_t
	/// Example: int num; ReadCasted<uint8_t>(num); would read 1 bytefrom the stream, and put the value in an integer
	/// \param[in] value The value to write
	template <class serializationType, class sourceType >
	bool ReadCasted( sourceType &value );

	/// Given the minimum and maximum values for an integer type, figure out the minimum number of bits to represent the range
	/// Then read only those bits
	/// \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
	/// \param[in] value Integer value to read, which should be between \a minimum and \a maximum
	/// \param[in] minimum Minimum value of \a value
	/// \param[in] maximum Maximum value of \a value
	/// \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().
	template <class templateType>
	bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange=false );
	/// \param[in] requiredBits Primarily for internal use, called from above function() after calculating number of bits needed to represent maximum-minimum
	template <class templateType>
	bool ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange=false );

	/// \brief Read a normalized 3D vector, using (at most) 4 bytes + 3 bits instead of 12-24 bytes.  
	/// \details Will further compress y or z axis aligned vectors.
	/// Accurate to 1/32767.5.
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	/// \return true on success, false on failure.
	template <class templateType> // templateType for this function must be a float or double
	bool ReadNormVector( templateType &x, templateType &y, templateType &z );

	/// \brief Read 3 floats or doubles, using 10 bytes, where those float or doubles comprise a vector.
	/// \details Loses accuracy to about 3/10ths and only saves 2 bytes, 
	/// so only use if accuracy is not important.
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	/// \return true on success, false on failure.
	template <class templateType> // templateType for this function must be a float or double
	bool ReadVector( templateType &x, templateType &y, templateType &z );

	/// \brief Read a normalized quaternion in 6 bytes + 4 bits instead of 16 bytes.
	/// \param[in] w w
	/// \param[in] x x
	/// \param[in] y y
	/// \param[in] z z
	/// \return true on success, false on failure.
	template <class templateType> // templateType for this function must be a float or double
	bool ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z);

	/// \brief Read an orthogonal matrix from a quaternion, reading 3 components of the quaternion in 2 bytes each and extrapolatig the 4th.
	/// \details Use 6 bytes instead of 36
	/// Lossy, although the result is renormalized
	/// \return true on success, false on failure.
	template <class templateType> // templateType for this function must be a float or double
	bool ReadOrthMatrix(
		templateType &m00, templateType &m01, templateType &m02,
		templateType &m10, templateType &m11, templateType &m12,
		templateType &m20, templateType &m21, templateType &m22 );

	/// \brief Sets the read pointer back to the beginning of your data.
	void ResetReadPointer( void );

	/// \brief Sets the write pointer back to the beginning of your data.
	void ResetWritePointer( void );

	/// \brief This is good to call when you are done with the stream to make
	/// sure you didn't leave any data left over void
	void AssertStreamEmpty( void );

	/// \brief RAKNET_DEBUG_PRINTF the bits in the stream.  Great for debugging.
	void PrintBits( char *out ) const;
	void PrintBits( void ) const;
	void PrintHex( char *out ) const;
	void PrintHex( void ) const;

	/// \brief Ignore data we don't intend to read
	/// \param[in] numberOfBits The number of bits to ignore
	void IgnoreBits( const BitSize_t numberOfBits );

	/// \brief Ignore data we don't intend to read
	/// \param[in] numberOfBits The number of bytes to ignore
	void IgnoreBytes( const unsigned int numberOfBytes );

	/// \brief Move the write pointer to a position on the array.
	/// \param[in] offset the offset from the start of the array.
	/// \attention
	/// \details Dangerous if you don't know what you are doing!
	/// For efficiency reasons you can only write mid-stream if your data is byte aligned.
	void SetWriteOffset( const BitSize_t offset );

	/// \brief Returns the length in bits of the stream
	inline BitSize_t GetNumberOfBitsUsed( void ) const {return GetWriteOffset();}
	inline BitSize_t GetWriteOffset( void ) const {return numberOfBitsUsed;}

	/// \brief Returns the length in bytes of the stream
	inline BitSize_t GetNumberOfBytesUsed( void ) const {return BITS_TO_BYTES( numberOfBitsUsed );}

	/// \brief Returns the number of bits into the stream that we have read
	inline BitSize_t GetReadOffset( void ) const {return readOffset;}

	/// \brief Sets the read bit index
	void SetReadOffset( const BitSize_t newReadOffset ) {readOffset=newReadOffset;}

	/// \brief Returns the number of bits left in the stream that haven't been read
	inline BitSize_t GetNumberOfUnreadBits( void ) const {return numberOfBitsUsed - readOffset;}

	/// \brief Makes a copy of the internal data for you \a _data will point to
	/// the stream. Partial bytes are left aligned.
	/// \param[out] _data The allocated copy of GetData()
	/// \return The length in bits of the stream.
	BitSize_t CopyData( unsigned char** _data ) const;

	/// \internal
	/// Set the stream to some initial data.
	void SetData( unsigned char *inByteArray );

	/// Gets the data that BitStream is writing to / reading from.
	/// Partial bytes are left aligned.
	/// \return A pointer to the internal state
	inline char* GetData( void ) const {return (char*) data;}

	/// \brief Write numberToWrite bits from the input source.
	/// \details Right aligned data means in the case of a partial byte, the bits are aligned
	/// from the right (bit 0) rather than the left (as in the normal
	/// internal representation) You would set this to true when
	/// writing user data, and false when copying bitstream data, such
	/// as writing one bitstream to another.
	/// \param[in] inByteArray The data
	/// \param[in] numberOfBitsToWrite The number of bits to write
	/// \param[in] rightAlignedBits if true data will be right aligned
	void WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits = true );

	/// \brief Align the bitstream to the byte boundary and then write the
	/// specified number of bits.  
	/// \details This is faster than WriteBits but
	/// wastes the bits to do the alignment and requires you to call
	/// ReadAlignedBits at the corresponding read position.
	/// \param[in] inByteArray The data
	/// \param[in] numberOfBytesToWrite The size of input.
	void WriteAlignedBytes( const unsigned char *inByteArray, const unsigned int numberOfBytesToWrite );

	// Endian swap bytes already in the bitstream
	void EndianSwapBytes( int byteOffset, int length );

	/// \brief Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite
	/// \param[in] inByteArray The data
	/// \param[in] inputLength The size of input.
	/// \param[in] maxBytesToWrite Max bytes to write
	void WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite );

	/// \brief Read bits, starting at the next aligned bits. 
	/// \details Note that the modulus 8 starting offset of the sequence must be the same as
	/// was used with WriteBits. This will be a problem with packet
	/// coalescence unless you byte align the coalesced packets.
	/// \param[in] inOutByteArray The byte array larger than @em numberOfBytesToRead
	/// \param[in] numberOfBytesToRead The number of byte to read from the internal state
	/// \return true if there is enough byte.
	bool ReadAlignedBytes( unsigned char *inOutByteArray, const unsigned int numberOfBytesToRead );

	/// \brief Reads what was written by WriteAlignedBytesSafe.
	/// \param[in] inOutByteArray The data
	/// \param[in] maxBytesToRead Maximum number of bytes to read
	/// \return true on success, false on failure.
	bool ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead );
	bool ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead );

	/// \brief Same as ReadAlignedBytesSafe() but allocates the memory for you using new, rather than assuming it is safe to write to
	/// \param[in] outByteArray outByteArray will be deleted if it is not a pointer to 0
	/// \return true on success, false on failure.
	bool ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead );
	bool ReadAlignedBytesSafeAlloc( char **outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead );

	/// \brief Align the next write and/or read to a byte boundary.  
	/// \details This can be used to 'waste' bits to byte align for efficiency reasons It
	/// can also be used to force coalesced bitstreams to start on byte
	/// boundaries so so WriteAlignedBits and ReadAlignedBits both
	/// calculate the same offset when aligning.
	inline void AlignWriteToByteBoundary( void ) {numberOfBitsUsed += 8 - ( (( numberOfBitsUsed - 1 ) & 7) + 1 );}

	/// \brief Align the next write and/or read to a byte boundary.  
	/// \details This can be used to 'waste' bits to byte align for efficiency reasons It
	/// can also be used to force coalesced bitstreams to start on byte
	/// boundaries so so WriteAlignedBits and ReadAlignedBits both
	/// calculate the same offset when aligning.
	inline void AlignReadToByteBoundary( void ) {readOffset += 8 - ( (( readOffset - 1 ) & 7 ) + 1 );}

	/// \brief Read \a numberOfBitsToRead bits to the output source.
	/// \details alignBitsToRight should be set to true to convert internal
	/// bitstream data to userdata. It should be false if you used
	/// WriteBits with rightAlignedBits false
	/// \param[in] inOutByteArray The resulting bits array
	/// \param[in] numberOfBitsToRead The number of bits to read
	/// \param[in] alignBitsToRight if true bits will be right aligned.
	/// \return true if there is enough bits to read
	bool ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight = true );

	/// \brief Write a 0
	void Write0( void );

	/// \brief Write a 1
	void Write1( void );

	/// \brief Reads 1 bit and returns true if that bit is 1 and false if it is 0.
	bool ReadBit( void );

	/// \brief If we used the constructor version with copy data off, this
	/// *makes sure it is set to on and the data pointed to is copied.
	void AssertCopyData( void );

	/// \brief Use this if you pass a pointer copy to the constructor
	/// *(_copyData==false) and want to overallocate to prevent
	/// reallocation.
	void SetNumberOfBitsAllocated( const BitSize_t lengthInBits );

	/// \brief Reallocates (if necessary) in preparation of writing numberOfBitsToWrite
	void AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite );

	/// \internal
	/// \return How many bits have been allocated internally
	BitSize_t GetNumberOfBitsAllocated(void) const;

	/// Write zeros until the bitstream is filled up to \a bytes
	void PadWithZeroToByteLength( unsigned int bytes );

	/// Get the number of leading zeros for a number
	/// \param[in] x Number to test
	static int NumberOfLeadingZeroes( uint8_t x );
	static int NumberOfLeadingZeroes( uint16_t x );
	static int NumberOfLeadingZeroes( uint32_t x );
	static int NumberOfLeadingZeroes( uint64_t x );
	static int NumberOfLeadingZeroes( int8_t x );
	static int NumberOfLeadingZeroes( int16_t x );
	static int NumberOfLeadingZeroes( int32_t x );
	static int NumberOfLeadingZeroes( int64_t x );

	/// \internal Unrolled inner loop, for when performance is critical
	void WriteAlignedVar8(const char *inByteArray);
	/// \internal Unrolled inner loop, for when performance is critical
	bool ReadAlignedVar8(char *inOutByteArray);
	/// \internal Unrolled inner loop, for when performance is critical
	void WriteAlignedVar16(const char *inByteArray);
	/// \internal Unrolled inner loop, for when performance is critical
	bool ReadAlignedVar16(char *inOutByteArray);
	/// \internal Unrolled inner loop, for when performance is critical
	void WriteAlignedVar32(const char *inByteArray);
	/// \internal Unrolled inner loop, for when performance is critical
	bool ReadAlignedVar32(char *inOutByteArray);

	inline void Write(const char * const inStringVar)
	{
		uint16_t l = (uint16_t) OVR_strlen(inStringVar);
		Write(l);
		WriteAlignedBytes((const unsigned char*) inStringVar, (const unsigned int) l);
	}
	inline void Write(const unsigned char * const inTemplateVar)
	{
		Write((const char*)inTemplateVar);
	}
	inline void Write(char * const inTemplateVar)
	{
		Write((const char*)inTemplateVar);
	}
	inline void Write(unsigned char * const inTemplateVar)
	{
		Write((const char*)inTemplateVar);
	}

	/// ---- Member function template specialization declarations ----
	// Used for VC7
#if defined(OVR_CC_MSVC) && _MSC_VER == 1300
	/// Write a bool to a bitstream.
	/// \param[in] var The value to write
	template <>
	void Write(const bool &var);

	/// Write a RakNetGUID to a bitsteam
	/// \param[in] var The value to write
	template <>
	void Write(const RakNetGuid &var);

	/// Write a string to a bitstream
	/// \param[in] var The value to write
	template <>
	void Write(const char* const &var);
	template <>
	void Write(const unsigned char* const &var);
	template <>
	void Write(char* const &var);
	template <>
	void Write(unsigned char* const &var);
	template <>
	void Write(const OVR::String &var);

	/// \brief Write a bool delta.  
	/// \details Same thing as just calling Write
	/// \param[in] currentValue The current value to write
	/// \param[in] lastValue The last value to compare against
	template <>
	void WriteDelta(const bool &currentValue, const bool &lastValue);

	template <>
	void WriteCompressed(const bool &var);

	/// For values between -1 and 1
	template <>
	void WriteCompressed(const float &var);

	/// For values between -1 and 1
	template <>
	void WriteCompressed(const double &var);
	
	/// \brief Write a bool delta.  
	/// \details Same thing as just calling Write
	/// \param[in] currentValue The current value to write
	/// \param[in] lastValue The last value to compare against
	template <>
	void WriteCompressedDelta(const bool &currentValue, const bool &lastValue);

	/// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) 
	/// when we have an unknown second bool
	template <>
	void WriteCompressedDelta(const bool &currentValue);

	/// \brief Read a bool from a bitstream.
	/// \param[in] var The value to read
	/// \return true on success, false on failure.
	template <>
	bool Read(bool &var);

	/// \brief Read a String from a bitstream.
	/// \param[in] var The value to read
	/// \return true on success, false on failure.
	template <>
	bool Read(char *&var);
	template <>
	bool Read(wchar_t *&var);
	template <>
	bool Read(unsigned char *&var);

	/// \brief Read a bool from a bitstream.
	/// \param[in] var The value to read
	/// \return true on success, false on failure.
	template <>
	bool ReadDelta(bool &var);

	template <>
	bool ReadCompressed(bool &var);

	template <>
	bool ReadCompressed(float &var);

	/// For values between -1 and 1
	/// \return true on success, false on failure.
	template <>
	bool ReadCompressed(double &var);

	template <>
	bool ReadCompressed(char* &var);
	template <>
	bool ReadCompressed(wchar_t* &var);
	template <>
	bool ReadCompressed(unsigned char *&var);
	template <>
	bool ReadCompressed(OVR::String &var);

	/// \brief Read a bool from a bitstream.
	/// \param[in] var The value to read
	/// \return true on success, false on failure.
	template <>
	bool ReadCompressedDelta(bool &var);
#endif

	inline static bool DoEndianSwap(void) {
#ifndef __BITSTREAM_NATIVE_END
		return IsNetworkOrder()==false;
#else
		return false;
#endif
	}
	inline static bool IsBigEndian(void)
	{
		return IsNetworkOrder();
	}
	inline static bool IsNetworkOrder(void) {bool r = IsNetworkOrderInternal(); return r;}
	// Not inline, won't compile on PC due to winsock include errors
	static bool IsNetworkOrderInternal(void);
	static void ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length);
	static void ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length);

private:

	BitStream( const BitStream &invalid) {
		(void) invalid;
		OVR_ASSERT(0);
	}

	BitStream& operator = ( const BitStream& invalid ) {
		(void) invalid;
		OVR_ASSERT(0);
		static BitStream i;
		return i;
	}

	/// \brief Assume the input source points to a native type, compress and write it.
	void WriteCompressed( const unsigned char* inByteArray, const unsigned int size, const bool unsignedData );

	/// \brief Assume the input source points to a compressed native type. Decompress and read it.
	bool ReadCompressed( unsigned char* inOutByteArray,	const unsigned int size, const bool unsignedData );


	BitSize_t numberOfBitsUsed;

	BitSize_t numberOfBitsAllocated;

	BitSize_t readOffset;

	unsigned char *data;

	/// true if the internal buffer is copy of the data passed to the constructor
	bool copyData;

	/// 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
	unsigned char stackData[BITSTREAM_STACK_ALLOCATION_SIZE];
};

template <class templateType>
inline bool BitStream::Serialize(bool writeToBitstream, templateType &inOutTemplateVar)
{
	if (writeToBitstream)
		Write(inOutTemplateVar);
	else
		return Read(inOutTemplateVar);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue)
{
	if (writeToBitstream)
		WriteDelta(inOutCurrentValue, lastValue);
	else
		return ReadDelta(inOutCurrentValue);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeDelta(bool writeToBitstream, templateType &inOutCurrentValue)
{
	if (writeToBitstream)
		WriteDelta(inOutCurrentValue);
	else
		return ReadDelta(inOutCurrentValue);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeCompressed(bool writeToBitstream, templateType &inOutTemplateVar)
{
	if (writeToBitstream)
		WriteCompressed(inOutTemplateVar);
	else
		return ReadCompressed(inOutTemplateVar);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue, const templateType &lastValue)
{
	if (writeToBitstream)
		WriteCompressedDelta(inOutCurrentValue,lastValue);
	else
		return ReadCompressedDelta(inOutCurrentValue);
	return true;
}
//Stoppedhere
template <class templateType>
inline bool BitStream::SerializeCompressedDelta(bool writeToBitstream, templateType &inOutCurrentValue)
{
	if (writeToBitstream)
		WriteCompressedDelta(inOutCurrentValue);
	else
		return ReadCompressedDelta(inOutCurrentValue);
	return true;
}

inline bool BitStream::Serialize(bool writeToBitstream, char* inOutByteArray, const unsigned int numberOfBytes )
{
	if (writeToBitstream)
		Write(inOutByteArray, numberOfBytes);
	else
		return Read(inOutByteArray, numberOfBytes);
	return true;
}

template <class serializationType, class sourceType >
bool BitStream::SerializeCasted( bool writeToBitstream, sourceType &value )
{
	if (writeToBitstream) WriteCasted<serializationType>(value);
	else return ReadCasted<serializationType>(value);
	return true;
}

template <class templateType>
bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange )
{
	int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum));
	return SerializeBitsFromIntegerRange(writeToBitstream,value,minimum,maximum,requiredBits,allowOutsideRange);
}
template <class templateType>
bool BitStream::SerializeBitsFromIntegerRange( bool writeToBitstream, templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange )
{
	if (writeToBitstream) WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
	else return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeNormVector(bool writeToBitstream, templateType &x, templateType &y, templateType &z )
{
	if (writeToBitstream)
		WriteNormVector(x,y,z);
	else
		return ReadNormVector(x,y,z);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeVector(bool writeToBitstream,  templateType &x, templateType &y, templateType &z )
{
	if (writeToBitstream)
		WriteVector(x,y,z);
	else
		return ReadVector(x,y,z);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeNormQuat(bool writeToBitstream,  templateType &w, templateType &x, templateType &y, templateType &z)
{
	if (writeToBitstream)
		WriteNormQuat(w,x,y,z);
	else
		return ReadNormQuat(w,x,y,z);
	return true;
}

template <class templateType>
inline bool BitStream::SerializeOrthMatrix(
	bool writeToBitstream,
	templateType &m00, templateType &m01, templateType &m02,
	templateType &m10, templateType &m11, templateType &m12,
	templateType &m20, templateType &m21, templateType &m22 )
{
	if (writeToBitstream)
		WriteOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22);
	else
		return ReadOrthMatrix(m00,m01,m02,m10,m11,m12,m20,m21,m22);
	return true;
}

inline bool BitStream::SerializeBits(bool writeToBitstream, unsigned char* inOutByteArray, const BitSize_t numberOfBitsToSerialize, const bool rightAlignedBits )
{
	if (writeToBitstream)
		WriteBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits);
	else
		return ReadBits(inOutByteArray,numberOfBitsToSerialize,rightAlignedBits);
	return true;
}

template <class templateType>
inline void BitStream::Write(const templateType &inTemplateVar)
{
#ifdef OVR_CC_MSVC
#pragma warning(disable:4127)   // conditional expression is constant
#endif
	if (sizeof(inTemplateVar)==1)
		WriteBits( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true );
	else
	{
#ifndef __BITSTREAM_NATIVE_END
		if (DoEndianSwap())
		{
			unsigned char output[sizeof(templateType)];
			ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType));
			WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true );
		}
		else
#endif
			WriteBits( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true );
	}
}

template <class templateType>
inline void BitStream::WritePtr(templateType *inTemplateVar)
{
#ifdef OVR_CC_MSVC
#pragma warning(disable:4127)   // conditional expression is constant
#endif
	if (sizeof(templateType)==1)
		WriteBits( ( unsigned char* ) inTemplateVar, sizeof( templateType ) * 8, true );
	else
	{
#ifndef __BITSTREAM_NATIVE_END
		if (DoEndianSwap())
		{
			unsigned char output[sizeof(templateType)];
			ReverseBytes((unsigned char*) inTemplateVar, output, sizeof(templateType));
			WriteBits( ( unsigned char* ) output, sizeof(templateType) * 8, true );
		}
		else
#endif
			WriteBits( ( unsigned char* ) inTemplateVar, sizeof(templateType) * 8, true );
	}
}

/// \brief Write a bool to a bitstream.
/// \param[in] inTemplateVar The value to write
template <>
inline void BitStream::Write(const bool &inTemplateVar)
{
	if ( inTemplateVar )
		Write1();
	else
		Write0();
}


/// \brief Write a string to a bitstream.
/// \param[in] var The value to write
template <>
inline void BitStream::Write(const OVR::String &inTemplateVar)
{
	uint16_t l = (uint16_t) inTemplateVar.GetLength();
	Write(l);
	WriteAlignedBytes((const unsigned char*) inTemplateVar.ToCStr(), (const unsigned int) l);
}
template <>
inline void BitStream::Write(const char * const &inStringVar)
{
	uint16_t l = (uint16_t) strlen(inStringVar);
	Write(l);
	WriteAlignedBytes((const unsigned char*) inStringVar, (const unsigned int) l);
}
template <>
inline void BitStream::Write(const unsigned char * const &inTemplateVar)
{
	Write((const char*)inTemplateVar);
}
template <>
inline void BitStream::Write(char * const &inTemplateVar)
{
	Write((const char*)inTemplateVar);
}
template <>
inline void BitStream::Write(unsigned char * const &inTemplateVar)
{
	Write((const char*)inTemplateVar);
}

/// \brief Write any integral type to a bitstream.  
/// \details If the current value is different from the last value
/// the current value will be written.  Otherwise, a single bit will be written
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against
template <class templateType>
inline void BitStream::WriteDelta(const templateType &currentValue, const templateType &lastValue)
{
	if (currentValue==lastValue)
	{
		Write(false);
	}
	else
	{
		Write(true);
		Write(currentValue);
	}
}

/// \brief Write a bool delta. Same thing as just calling Write
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against
template <>
inline void BitStream::WriteDelta(const bool &currentValue, const bool &lastValue)
{
	(void) lastValue;

	Write(currentValue);
}

/// \brief WriteDelta when you don't know what the last value is, or there is no last value.
/// \param[in] currentValue The current value to write
template <class templateType>
inline void BitStream::WriteDelta(const templateType &currentValue)
{
	Write(true);
	Write(currentValue);
}

/// \brief Write any integral type to a bitstream.  
/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
/// 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.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// \param[in] inTemplateVar The value to write
template <class templateType>
inline void BitStream::WriteCompressed(const templateType &inTemplateVar)
{
#ifdef OVR_CC_MSVC
#pragma warning(disable:4127)   // conditional expression is constant
#endif
	if (sizeof(inTemplateVar)==1)
		WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof( templateType ) * 8, true );
	else
	{
#ifndef __BITSTREAM_NATIVE_END
#ifdef OVR_CC_MSVC
#pragma warning(disable:4244)   // '=' : conversion from 'unsigned long' to 'uint16_t', possible loss of data
#endif

		if (DoEndianSwap())
		{
			unsigned char output[sizeof(templateType)];
			ReverseBytes((unsigned char*)&inTemplateVar, output, sizeof(templateType));
			WriteCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true );
		}
		else
#endif
			WriteCompressed( ( unsigned char* ) & inTemplateVar, sizeof(templateType) * 8, true );
	}
}

template <>
inline void BitStream::WriteCompressed(const bool &inTemplateVar)
{
	Write(inTemplateVar);
}

/// For values between -1 and 1
template <>
inline void BitStream::WriteCompressed(const float &inTemplateVar)
{
	OVR_ASSERT(inTemplateVar > -1.01f && inTemplateVar < 1.01f);
	float varCopy=inTemplateVar;
	if (varCopy < -1.0f)
		varCopy=-1.0f;
	if (varCopy > 1.0f)
		varCopy=1.0f;
	Write((uint16_t)((varCopy+1.0f)*32767.5f));
}

/// For values between -1 and 1
template <>
inline void BitStream::WriteCompressed(const double &inTemplateVar)
{
	OVR_ASSERT(inTemplateVar > -1.01 && inTemplateVar < 1.01);
	double varCopy=inTemplateVar;
	if (varCopy < -1.0f)
		varCopy=-1.0f;
	if (varCopy > 1.0f)
		varCopy=1.0f;
	Write((uint32_t)((varCopy+1.0)*2147483648.0));
}

/// \brief Write any integral type to a bitstream.  
/// \details If the current value is different from the last value
/// the current value will be written.  Otherwise, a single bit will be written
/// 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.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against
template <class templateType>
inline void BitStream::WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue)
{
	if (currentValue==lastValue)
	{
		Write(false);
	}
	else
	{
		Write(true);
		WriteCompressed(currentValue);
	}
}

/// \brief Write a bool delta.  Same thing as just calling Write
/// \param[in] currentValue The current value to write
/// \param[in] lastValue The last value to compare against
template <>
inline void BitStream::WriteCompressedDelta(const bool &currentValue, const bool &lastValue)
{
	(void) lastValue;

	Write(currentValue);
}

/// \brief Save as WriteCompressedDelta(const templateType &currentValue, const templateType &lastValue) 
/// when we have an unknown second parameter
template <class templateType>
inline void BitStream::WriteCompressedDelta(const templateType &currentValue)
{
	Write(true);
	WriteCompressed(currentValue);
}

/// \brief Save as WriteCompressedDelta(bool currentValue, const templateType &lastValue) 
/// when we have an unknown second bool
template <>
inline void BitStream::WriteCompressedDelta(const bool &currentValue)
{
	Write(currentValue);
}

/// \brief Read any integral type from a bitstream.  Define __BITSTREAM_NATIVE_END if you need endian swapping.
/// \param[in] outTemplateVar The value to read
template <class templateType>
inline bool BitStream::Read(templateType &outTemplateVar)
{
#ifdef OVR_CC_MSVC
#pragma warning(disable:4127)   // conditional expression is constant
#endif
	if (sizeof(outTemplateVar)==1)
		return ReadBits( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true );
	else
	{
#ifndef __BITSTREAM_NATIVE_END
#ifdef OVR_CC_MSVC
#pragma warning(disable:4244)   // '=' : conversion from 'unsigned long' to 'uint16_t', possible loss of data
#endif
		if (DoEndianSwap())
		{
			unsigned char output[sizeof(templateType)];
			if (ReadBits( ( unsigned char* ) output, sizeof(templateType) * 8, true ))
			{
				ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType));
				return true;
			}
			return false;
		}
		else
#endif
			return ReadBits( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true );
	}
}

/// \brief Read a bool from a bitstream.
/// \param[in] outTemplateVar The value to read
template <>
inline bool BitStream::Read(bool &outTemplateVar)
{
	if ( readOffset + 1 > numberOfBitsUsed )
		return false;

	if ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) )   // Is it faster to just write it out here?
		outTemplateVar = true;
	else
		outTemplateVar = false;

	// Has to be on a different line for Mac
	readOffset++;

	return true;
}

template <>
inline bool BitStream::Read(OVR::String &outTemplateVar)
{
	bool b;
	uint16_t l;
	b=Read(l);
	if (b && l>0)
	{
		AlignReadToByteBoundary();
		outTemplateVar.AssignString((const char*) (data + ( readOffset >> 3 )), (size_t) l);
		IgnoreBytes(l);
	}
	else
	{
		AlignReadToByteBoundary();
	}
	return b;
}
template <>
inline bool BitStream::Read(char *&varString)
{
	bool b;
	uint16_t l;
	b=Read(l);
	if (b && l>0)
	{
		memcpy(varString, data + ( readOffset >> 3 ), l);
		IgnoreBytes(l);
	}
	else
	{
		AlignReadToByteBoundary();
	}
	return b;
}
template <>
inline bool BitStream::Read(unsigned char *&varString)
{
	bool b;
	uint16_t l;
	b=Read(l);
	if (b && l>0)
	{
		memcpy(varString, data + ( readOffset >> 3 ), l);
		IgnoreBytes(l);
	}
	else
	{
		AlignReadToByteBoundary();
	}
	return b;
}

/// \brief Read any integral type from a bitstream.  
/// \details If the written value differed from the value compared against in the write function,
/// var will be updated.  Otherwise it will retain the current value.
/// ReadDelta is only valid from a previous call to WriteDelta
/// \param[in] outTemplateVar The value to read
template <class templateType>
inline bool BitStream::ReadDelta(templateType &outTemplateVar)
{
	bool dataWritten;
	bool success;
	success=Read(dataWritten);
	if (dataWritten)
		success=Read(outTemplateVar);
	return success;
}

/// \brief Read a bool from a bitstream.
/// \param[in] outTemplateVar The value to read
template <>
inline bool BitStream::ReadDelta(bool &outTemplateVar)
{
	return Read(outTemplateVar);
}

/// \brief Read any integral type from a bitstream.  
/// \details Undefine __BITSTREAM_NATIVE_END if you need endian swapping.
/// 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.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// \param[in] outTemplateVar The value to read
template <class templateType>
inline bool BitStream::ReadCompressed(templateType &outTemplateVar)
{
#ifdef OVR_CC_MSVC
#pragma warning(disable:4127)   // conditional expression is constant
#endif
	if (sizeof(outTemplateVar)==1)
		return ReadCompressed( ( unsigned char* ) &outTemplateVar, sizeof(templateType) * 8, true );
	else
	{
#ifndef __BITSTREAM_NATIVE_END
		if (DoEndianSwap())
		{
			unsigned char output[sizeof(templateType)];
			if (ReadCompressed( ( unsigned char* ) output, sizeof(templateType) * 8, true ))
			{
				ReverseBytes(output, (unsigned char*)&outTemplateVar, sizeof(templateType));
				return true;
			}
			return false;
		}
		else
#endif
			return ReadCompressed( ( unsigned char* ) & outTemplateVar, sizeof(templateType) * 8, true );
	}
}

template <>
inline bool BitStream::ReadCompressed(bool &outTemplateVar)
{
	return Read(outTemplateVar);
}

/// For values between -1 and 1
template <>
inline bool BitStream::ReadCompressed(float &outTemplateVar)
{
	uint16_t compressedFloat;
	if (Read(compressedFloat))
	{
		outTemplateVar = ((float)compressedFloat / 32767.5f - 1.0f);
		return true;
	}
	return false;
}

/// For values between -1 and 1
template <>
inline bool BitStream::ReadCompressed(double &outTemplateVar)
{
	uint32_t compressedFloat;
	if (Read(compressedFloat))
	{
		outTemplateVar = ((double)compressedFloat / 2147483648.0 - 1.0);
		return true;
	}
	return false;
}

/// \brief Read any integral type from a bitstream.  
/// \details If the written value differed from the value compared against in the write function,
/// var will be updated.  Otherwise it will retain the current value.
/// the current value will be updated.
/// 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.
/// For non-floating point, this is lossless, but only has benefit if you use less than half the bits of the type
/// If you are not using __BITSTREAM_NATIVE_END the opposite is true for types larger than 1 byte
/// ReadCompressedDelta is only valid from a previous call to WriteDelta
/// \param[in] outTemplateVar The value to read
template <class templateType>
inline bool BitStream::ReadCompressedDelta(templateType &outTemplateVar)
{
	bool dataWritten;
	bool success;
	success=Read(dataWritten);
	if (dataWritten)
		success=ReadCompressed(outTemplateVar);
	return success;
}

/// \brief Read a bool from a bitstream.
/// \param[in] outTemplateVar The value to read
template <>
inline bool BitStream::ReadCompressedDelta(bool &outTemplateVar)
{
	return Read(outTemplateVar);
}

template <class destinationType, class sourceType >
void BitStream::WriteCasted( const sourceType &value )
{
	destinationType val = (destinationType) value;
	Write(val);
}

template <class templateType>
void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, bool allowOutsideRange )
{
	int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum));
	WriteBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
}
template <class templateType>
void BitStream::WriteBitsFromIntegerRange( const templateType value, const templateType minimum,const templateType maximum, const int requiredBits, bool allowOutsideRange )
{
	OVR_ASSERT(maximum>=minimum);
	OVR_ASSERT(allowOutsideRange==true || (value>=minimum && value<=maximum));
	if (allowOutsideRange)
	{
		if (value<minimum || value>maximum)
		{
			Write(true);
			Write(value);
			return;
		}
		Write(false);
	}
	templateType valueOffMin=value-minimum;
	if (IsBigEndian()==true)
	{
		unsigned char output[sizeof(templateType)];
		ReverseBytes((unsigned char*)&valueOffMin, output, sizeof(templateType));
		WriteBits(output,requiredBits);
	}
	else
	{
		WriteBits((unsigned char*) &valueOffMin,requiredBits);
	}
}

template <class templateType> // templateType for this function must be a float or double
void BitStream::WriteNormVector( templateType x, templateType y, templateType z )
{
#ifdef _DEBUG
	OVR_ASSERT(x <= 1.01 && y <= 1.01 && z <= 1.01 && x >= -1.01 && y >= -1.01 && z >= -1.01);
#endif

	WriteFloat16((float)x,-1.0f,1.0f);
	WriteFloat16((float)y,-1.0f,1.0f);
	WriteFloat16((float)z,-1.0f,1.0f);
}

template <class templateType> // templateType for this function must be a float or double
void BitStream::WriteVector( templateType x, templateType y, templateType z )
{
	templateType magnitude = sqrt(x * x + y * y + z * z);
	Write((float)magnitude);
	if (magnitude > 0.00001f)
	{
		WriteCompressed((float)(x/magnitude));
		WriteCompressed((float)(y/magnitude));
		WriteCompressed((float)(z/magnitude));
		//	Write((uint16_t)((x/magnitude+1.0f)*32767.5f));
		//	Write((uint16_t)((y/magnitude+1.0f)*32767.5f));
		//	Write((uint16_t)((z/magnitude+1.0f)*32767.5f));
	}
}

template <class templateType> // templateType for this function must be a float or double
void BitStream::WriteNormQuat( templateType w, templateType x, templateType y, templateType z)
{
	Write((bool)(w<0.0));
	Write((bool)(x<0.0));
	Write((bool)(y<0.0));
	Write((bool)(z<0.0));
	Write((uint16_t)(fabs(x)*65535.0));
	Write((uint16_t)(fabs(y)*65535.0));
	Write((uint16_t)(fabs(z)*65535.0));
	// Leave out w and calculate it on the target
}

template <class templateType> // templateType for this function must be a float or double
void BitStream::WriteOrthMatrix(
	templateType m00, templateType m01, templateType m02,
	templateType m10, templateType m11, templateType m12,
	templateType m20, templateType m21, templateType m22 )
{

	double qw;
	double qx;
	double qy;
	double qz;

	// Convert matrix to quat
	// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
	float sum;
	sum = 1 + m00 + m11 + m22;
	if (sum < 0.0f) sum=0.0f;
	qw = sqrt( sum  ) / 2;
	sum = 1 + m00 - m11 - m22;
	if (sum < 0.0f) sum=0.0f;
	qx = sqrt( sum  ) / 2;
	sum = 1 - m00 + m11 - m22;
	if (sum < 0.0f) sum=0.0f;
	qy = sqrt( sum  ) / 2;
	sum = 1 - m00 - m11 + m22;
	if (sum < 0.0f) sum=0.0f;
	qz = sqrt( sum  ) / 2;
	if (qw < 0.0) qw=0.0;
	if (qx < 0.0) qx=0.0;
	if (qy < 0.0) qy=0.0;
	if (qz < 0.0) qz=0.0;
#ifdef OVR_OS_WIN32
	qx = _copysign( (double) qx, (double) (m21 - m12) );
	qy = _copysign( (double) qy, (double) (m02 - m20) );
	qz = _copysign( (double) qz, (double) (m10 - m01) );
#else
	qx = copysign( (double) qx, (double) (m21 - m12) );
	qy = copysign( (double) qy, (double) (m02 - m20) );
	qz = copysign( (double) qz, (double) (m10 - m01) );
#endif

	WriteNormQuat(qw,qx,qy,qz);
}

template <class serializationType, class sourceType >
bool BitStream::ReadCasted( sourceType &value )
{
	serializationType val;
	bool success = Read(val);
	value=(sourceType) val;
	return success;
}

template <class templateType>
bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, bool allowOutsideRange )
{
	int requiredBits=BYTES_TO_BITS(sizeof(templateType))-NumberOfLeadingZeroes(templateType(maximum-minimum));
	return ReadBitsFromIntegerRange(value,minimum,maximum,requiredBits,allowOutsideRange);
}
template <class templateType>
bool BitStream::ReadBitsFromIntegerRange( templateType &value, const templateType minimum, const templateType maximum, const int requiredBits, bool allowOutsideRange )
{
	OVR_ASSERT(maximum>=minimum);
	if (allowOutsideRange)
	{
		bool isOutsideRange;
		Read(isOutsideRange);
		if (isOutsideRange)
			return Read(value);
	}
	unsigned char output[sizeof(templateType)];
	memset(output,0,sizeof(output));
	bool success = ReadBits(output,requiredBits);
	if (success)
	{
		if (IsBigEndian()==true)
			ReverseBytesInPlace(output,sizeof(output));
		memcpy(&value,output,sizeof(output));

		value+=minimum;
	}

	return success;
}

template <class templateType> // templateType for this function must be a float or double
bool BitStream::ReadNormVector( templateType &x, templateType &y, templateType &z )
{
	float xIn,yIn,zIn;
	ReadFloat16(xIn,-1.0f,1.0f);
	ReadFloat16(yIn,-1.0f,1.0f);
	ReadFloat16(zIn,-1.0f,1.0f);
	x=xIn;
	y=yIn;
	z=zIn;
	return true;
}

template <class templateType> // templateType for this function must be a float or double
bool BitStream::ReadVector( templateType &x, templateType &y, templateType &z )
{
	float magnitude;
	//uint16_t sx,sy,sz;
	if (!Read(magnitude))
		return false;
	if (magnitude>0.00001f)
	{
		//	Read(sx);
		//	Read(sy);
		//	if (!Read(sz))
		//		return false;
		//	x=((float)sx / 32767.5f - 1.0f) * magnitude;
		//	y=((float)sy / 32767.5f - 1.0f) * magnitude;
		//	z=((float)sz / 32767.5f - 1.0f) * magnitude;
		float cx=0.0f,cy=0.0f,cz=0.0f;
		ReadCompressed(cx);
		ReadCompressed(cy);
		if (!ReadCompressed(cz))
			return false;
		x=cx;
		y=cy;
		z=cz;
		x*=magnitude;
		y*=magnitude;
		z*=magnitude;
	}
	else
	{
		x=0.0;
		y=0.0;
		z=0.0;
	}
	return true;
}

template <class templateType> // templateType for this function must be a float or double
bool BitStream::ReadNormQuat( templateType &w, templateType &x, templateType &y, templateType &z)
{
	bool cwNeg=false, cxNeg=false, cyNeg=false, czNeg=false;
	uint16_t cx,cy,cz;
	Read(cwNeg);
	Read(cxNeg);
	Read(cyNeg);
	Read(czNeg);
	Read(cx);
	Read(cy);
	if (!Read(cz))
		return false;

	// Calculate w from x,y,z
	x=(templateType)(cx/65535.0);
	y=(templateType)(cy/65535.0);
	z=(templateType)(cz/65535.0);
	if (cxNeg) x=-x;
	if (cyNeg) y=-y;
	if (czNeg) z=-z;
	float difference = 1.0f - x*x - y*y - z*z;
	if (difference < 0.0f)
		difference=0.0f;
	w = (templateType)(sqrt(difference));
	if (cwNeg)
		w=-w;

	return true;
}

template <class templateType> // templateType for this function must be a float or double
bool BitStream::ReadOrthMatrix(
	templateType &m00, templateType &m01, templateType &m02,
	templateType &m10, templateType &m11, templateType &m12,
	templateType &m20, templateType &m21, templateType &m22 )
{
	float qw,qx,qy,qz;
	if (!ReadNormQuat(qw,qx,qy,qz))
		return false;

	// Quat to orthogonal rotation matrix
	// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToMatrix/index.htm
	double sqw = (double)qw*(double)qw;
	double sqx = (double)qx*(double)qx;
	double sqy = (double)qy*(double)qy;
	double sqz = (double)qz*(double)qz;
	m00 =  (templateType)(sqx - sqy - sqz + sqw); // since sqw + sqx + sqy + sqz =1
	m11 = (templateType)(-sqx + sqy - sqz + sqw);
	m22 = (templateType)(-sqx - sqy + sqz + sqw);

	double tmp1 = (double)qx*(double)qy;
	double tmp2 = (double)qz*(double)qw;
	m10 = (templateType)(2.0 * (tmp1 + tmp2));
	m01 = (templateType)(2.0 * (tmp1 - tmp2));

	tmp1 = (double)qx*(double)qz;
	tmp2 = (double)qy*(double)qw;
	m20 =(templateType)(2.0 * (tmp1 - tmp2));
	m02 = (templateType)(2.0 * (tmp1 + tmp2));
	tmp1 = (double)qy*(double)qz;
	tmp2 = (double)qx*(double)qw;
	m21 = (templateType)(2.0 * (tmp1 + tmp2));
	m12 = (templateType)(2.0 * (tmp1 - tmp2));

	return true;
}

template <class templateType>
BitStream& operator<<(BitStream& out, templateType& c)
{
	out.Write(c);
	return out;
}
template <class templateType>
BitStream& operator>>(BitStream& in, templateType& c)
{
	bool success = in.Read(c);
	(void)success;

	OVR_ASSERT(success);
	return in;
}


}} // OVR::Net

#endif