This repository has been archived by the owner on Sep 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
init.lua
1213 lines (1038 loc) · 36.1 KB
/
init.lua
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
--[[
Differences from the original:
Using metatables instead of a function returning a table.
Added Vector3, Color3, Vector2, and UDim2 support.
Deprecated BrickColors.
Changed the creation method from BitBuffer.Create to BitBuffer.new.
OPTIMIZED!
Added a ::Destroy method.
THE API:
Constructor: BitBuffer.new()
Read/Write pairs for reading data from or writing data to the BitBuffer:
BitBuffer::WriteUnsigned(BitWidth: number, Value: number): void
BitBuffer::ReadUnsigned(BitWidth: number): number
Read / Write an unsigned value with a given number of bits. The
value must be a positive integer. For instance, if BitWidth is
4, then there will be 4 magnitude bits, for a value in the
range [0, 2 ^ 4 - 1] = [0, 15]
BitBuffer::WriteSigned(BitWidth: number, Value: number): void
BitBuffer::ReadSigned(BitWidth: number): number
Read / Write a a signed value with a given number of bits. For
instance, if BitWidth is 4 then there will be 1 sign bit and
3 magnitude bits, a value in the range [-2 ^ 3 + 1, 2 ^ 3 - 1] = [-7, 7]
BitBuffer:WriteFloat(MantissaBitWidth: number, ExponentBitWidth: number, Value: number): void
BitBuffer:ReadFloat(MantissaBitWidth, ExponentBitWidth): number
Read / Write a floating point number with a given mantissa and
exponent size in bits.
BitBuffer::WriteFloat8(Float: number): void
BitBuffer::ReadFloat8(): number
BitBuffer::WriteFloat16(Float: number): void
BitBuffer::ReadFloat16(): number
BitBuffer::WriteFloat32(Float: number): void
BitBuffer::ReadFloat32(): number
BitBuffer::WriteFloat64(Float: number): void
BitBuffer::ReadFloat64(): number
Read and write the common types of floating point number that
are used in code. If you want to 100% accurately save an
arbitrary Lua number, then you should use the Float64 format. If
your number is known to be smaller, or you want to save space
and don't need super high precision, then a Float32 will often
suffice. For instance, the Transparency of an object will do
just fine as a Float32.
BitBuffer::WriteBool(Boolean: boolean): void
BitBuffer::ReadBool(): boolean
Read / Write a boolean (true / false) value. Takes one bit worth of space to store.
BitBuffer::WriteString(String: string): void
BitBuffer::ReadString(): string
Read / Write a variable length string. The string may contain embedded nulls.
Only 7 bits / character will be used if the string contains no non-printable characters (greater than 0x80).
****** PLEASE DON'T USE THIS. USE ::WRITECOLOR3 INSTEAD. ******
BitBuffer::WriteBrickColor(Color: BrickColor): void
BitBuffer::ReadBrickColor(): BrickColor
Read / Write a Roblox BrickColor. Provided as an example of reading / writing a derived data type.
Please don't actually use this, just use ::WriteColor3 instead.
BitBuffer::WriteColor3(Color: Color3): void
BitBuffer::ReadColor3(): Color3
Read / Write a Roblox Color3. Use this over the BrickColor methods, PLEASE.
BitBuffer::WriteRotation(CoordinateFrame: CFrame): void
BitBuffer::ReadRotation(): CFrame
Read / Write the rotation part of a given CFrame. Encodes the
rotation in question into 64bits, which is a good size to get
a pretty dense packing, but still while having errors well within
the threshold that Roblox uses for stuff like MakeJoints()
detecting adjacency. Will also perfectly reproduce rotations which
are orthagonally aligned, or inverse-power-of-two rotated on only
a single axix. For other rotations, the results may not be
perfectly stable through read-write cycles (if you read/write an
arbitrary rotation thousands of times there may be detectable
"drift")
BitBuffer::WriteVector3(Vector: Vector3): void
BitBuffer::ReadVector3(): Vector3
BitBuffer::WriteVector3Float32(Vector: Vector3): void
BitBuffer::ReadVector3Float32(): Vector3
Read / write a Vector3. Encodes the vector using 32-bit precision.
For more precision, use BitBuffer::WriteVector3Float64 instead.
BitBuffer::WriteVector3Float64(Vector: Vector3): void
BitBuffer::ReadVector3Float64(): Vector3
Read / write a Vector3. Encodes the vector using 64-bit precision.
For less precision, use BitBuffer::WriteVector3 instead.
BitBuffer::WriteVector2(Vector: Vector2): void
BitBuffer::ReadVector2(): Vector2
BitBuffer::WriteVector2Float32(Vector: Vector2): void
BitBuffer::ReadVector2Float32(): Vector2
Read / write a Vector2. Encodes the vector using 32-bit precision.
For more precision, use BitBuffer::WriteVector2Float64 instead.
BitBuffer::WriteVector2Float64(Vector: Vector2): void
BitBuffer::ReadVector2Float64(): Vector2
Read / write a Vector2. Encodes the vector using 64-bit precision.
For less precision, use BitBuffer::WriteVector2Float32 instead.
BitBuffer::WriteCFrame(CoordinateFrame: CFrame): void
BitBuffer::ReadCFrame(): CFrame
Read / write the whole CFrame. This will call both ::WriteVector3Float64 and ::WriteRotation
to save the entire CFrame, and encodes it using 64-bit precision.
BitBuffer::WriteUDim2(Value: UDim2): void
BitBuffer::ReadUDim2(): UDim2
Read / write a UDim2. Encodes the value using 32-bit precision.
From/To pairs for dumping out the BitBuffer to another format:
BitBuffer::ToString(): string
BitBuffer::FromString(String: string): void
Will replace / dump out the contents of the buffer to / from
a binary chunk encoded as a Lua string. This string is NOT
suitable for storage in the Roblox DataStores, as they do
not handle non-printable characters well.
BitBuffer::ToBase64(): string
BitBuffer::FromBase64(String: string): void
Will replace / dump out the contents of the buffer to / from
a set of Base64 encoded data, as a Lua string. This string
only consists of Base64 printable characters, so it is
ideal for storage in Roblox DataStores.
BitBuffer::ToBase128(): string
BitBuffer::FromBase128(String: string): void
Defaultio added this function. 128 characters can all be written
to DataStores, so this function packs more tightly than saving
in only 64 bit strings. Full disclosure: I have no idea what I'm
doing but I think this is useful.
Buffer / Position Manipulation
BitBuffer::ResetPointer(): void
Will Reset the point in the buffer that is being read / written
to back to the start of the buffer.
BitBuffer::Reset(): void
Will reset the buffer to a clean state, with no contents.
Example Usage:
local function SaveToBuffer(buffer, userData)
buffer:WriteString(userData.HeroName)
buffer:WriteUnsigned(14, userData.Score) --> 14 bits -> [0, 2^14-1] -> [0, 16383]
buffer:WriteBool(userData.HasDoneSomething)
buffer:WriteUnsigned(10, #userData.ItemList) --> [0, 1023]
for _, itemInfo in pairs(userData.ItemList) do
buffer:WriteString(itemInfo.Identifier)
buffer:WriteUnsigned(10, itemInfo.Count) --> [0, 1023]
end
end
local function LoadFromBuffer(buffer, userData)
userData.HeroName = buffer:ReadString()
userData.Score = buffer:ReadUnsigned(14)
userData.HasDoneSomething = buffer:ReadBool()
local itemCount = buffer:ReadUnsigned(10)
for i = 1, itemCount do
local itemInfo = {}
itemInfo.Identifier = buffer:ReadString()
itemInfo.Count = buffer:ReadUnsigned(10)
table.insert(userData.ItemList, itemInfo)
end
end
--...
local buff = BitBuffer.new()
SaveToBuffer(buff, someUserData)
myDataStore:SetAsync(somePlayer.userId, buff:ToBase64())
--...
local data = myDataStore:GetAsync(somePlayer.userId)
local buff = BitBuffer.new()
buff:FromBase64(data)
LoadFromBuffer(buff, someUserData)
--]]
-- This is quite possibly the fastest BitBuffer module.
-- To-do: Remove `self:` calls, they're slow.
local BitBuffer = {
ClassName = "BitBuffer";
__tostring = function()
return "BitBuffer"
end;
}
BitBuffer.__index = BitBuffer
local CHAR_0X10 = string.char(0x10)
local DEPRECATED_WARNING = true
local DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local function ToBase(Number, Base)
Number = math.floor(Number)
if not Base or Base == 10 then
return tostring(Number)
end
local Array = {}
local Sign = ""
if Number < 0 then
Sign = "-"
Number = 0 - Number
end
repeat
local Index = (Number % Base) + 1
Number = math.floor(Number / Base)
table.insert(Array, 1, string.sub(DIGITS, Index, Index))
until Number == 0
return Sign .. table.concat(Array)
end
local function DetermineType(Value)
local ActualType = typeof(Value)
if ActualType == "number" then
if Value % 1 == 0 then
return Value < 0 and "negative integer" or "positive integer"
else
return Value < 0 and "negative number" or "positive number"
end
elseif ActualType == "table" then
local Key = next(Value)
if DetermineType(Key) == "positive integer" then
return "array"
else
return "dictionary"
end
else
return ActualType
end
end
local NumberToBase64, Base64ToNumber = {}, {}
do
local CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
for Index = 1, 64 do
local Character = string.sub(CHARACTERS, Index, Index)
NumberToBase64[Index - 1] = Character
Base64ToNumber[Character] = Index - 1
end
end
-- Credit to Defaultio.
local NumberToBase128, Base128ToNumber = {}, {}
do
local Base128Characters = ""
for Index = 0, 127 do
Base128Characters = Base128Characters .. string.char(Index)
end
for Index = 1, 128 do
local Character = string.sub(Base128Characters, Index, Index)
NumberToBase128[Index - 1] = Character
Base128ToNumber[Character] = Index - 1
end
end
local PowerOfTwo = setmetatable({}, {
__index = function(self, Index)
local Value = 2 ^ Index
self[Index] = Value
return Value
end;
})
for Index = 0, 128 do
local _ = PowerOfTwo[Index]
end
local BrickColorToNumber, NumberToBrickColor = {}, {}
do
for Index = 0, 63 do
local Color = BrickColor.palette(Index)
BrickColorToNumber[Color.Number] = Index
NumberToBrickColor[Index] = Color
end
end
--[[**
Creates a new BitBuffer.
@returns [BitBuffer] The new BitBuffer.
**--]]
function BitBuffer.new()
return setmetatable({
BitPointer = 0;
mBitBuffer = {};
}, BitBuffer)
end
--[[**
Resets the BitBuffer's BitPointer.
@returns [void]
**--]]
function BitBuffer:ResetPointer()
self.BitPointer = 0
end
--[[**
Resets the BitBuffer's BitPointer and buffer table.
@returns [void]
**--]]
function BitBuffer:Reset()
self.mBitBuffer, self.BitPointer = {}, 0
end
--[[**
Reads the given string and writes to the BitBuffer accordingly. Not really useful.
@param [t:string] String The string.
@returns [void]
**--]]
function BitBuffer:FromString(String)
if type(String) ~= "string" then
error(string.format("bad argument #1 in BitBuffer::FromString (string expected, instead got %s)", typeof(String)), 2)
end
self.mBitBuffer, self.BitPointer = {}, 0
local BitPointerValue = 0
for Index = 1, #String do
local ByteCharacter = string.byte(String, Index, Index)
for _ = 1, 8 do
BitPointerValue = BitPointerValue + 1
self.BitPointer = BitPointerValue
self.mBitBuffer[BitPointerValue] = ByteCharacter % 2
ByteCharacter = math.floor(ByteCharacter / 2)
end
end
self.BitPointer = 0
end
--[[**
Writes the BitBuffer to a string.
@returns [t:string] The BitBuffer string.
**--]]
function BitBuffer:ToString()
local String = ""
local Accumulator = 0
local Power = 0
local mBitBuffer = self.mBitBuffer
for Index = 1, math.ceil(#mBitBuffer / 8) * 8 do
Accumulator = Accumulator + PowerOfTwo[Power] * (mBitBuffer[Index] or 0)
Power = Power + 1
if Power >= 8 then
String = String .. string.char(Accumulator)
Accumulator = 0
Power = 0
end
end
return String
end
--[[**
Reads the given Base64 string and writes to the BitBuffer accordingly.
@param [t:string] String The Base64 string.
@returns [void]
**--]]
function BitBuffer:FromBase64(String)
if type(String) ~= "string" then
error(string.format("bad argument #1 in BitBuffer::FromBase64 (string expected, instead got %s)", typeof(String)), 2)
end
self.mBitBuffer, self.BitPointer = {}, 0
local BitPointerValue = 0
for Index = 1, #String do
local Character = string.sub(String, Index, Index)
local ByteCharacter = Base64ToNumber[Character]
if not ByteCharacter then
error("Bad character: 0x" .. ToBase(string.byte(Character), 16), 2)
end
for _ = 1, 6 do
BitPointerValue = BitPointerValue + 1
self.BitPointer = BitPointerValue
self.mBitBuffer[BitPointerValue] = ByteCharacter % 2
ByteCharacter = math.floor(ByteCharacter / 2)
end
if ByteCharacter ~= 0 then
error("Character value 0x" .. ToBase(Base64ToNumber[Character], 16) .. " too large", 2)
end
end
self.BitPointer = 0
end
--[[**
Writes the BitBuffer to a Base64 string.
@returns [t:string] The BitBuffer encoded in Base64.
**--]]
function BitBuffer:ToBase64()
local Array = {}
local Length = 0
local Accumulator = 0
local Power = 0
local mBitBuffer = self.mBitBuffer
for Index = 1, math.ceil(#mBitBuffer / 6) * 6 do
Accumulator = Accumulator + PowerOfTwo[Power] * (mBitBuffer[Index] or 0)
Power = Power + 1
if Power >= 6 then
Length = Length + 1
Array[Length] = NumberToBase64[Accumulator]
Accumulator = 0
Power = 0
end
end
return table.concat(Array)
end
--[[**
Reads the given Base128 string and writes to the BitBuffer accordingly. Not recommended. Credit to Defaultio for the original functions.
@param [t:string] String The Base128 string.
@returns [void]
**--]]
function BitBuffer:FromBase128(String)
if type(String) ~= "string" then
error(string.format("bad argument #1 in BitBuffer::FromBase128 (string expected, instead got %s)", typeof(String)), 2)
end
self.mBitBuffer, self.BitPointer = {}, 0
local BitPointerValue = 0
for Index = 1, #String do
local Character = string.sub(String, Index, Index)
local ByteCharacter = Base128ToNumber[Character]
if not ByteCharacter then
error("Bad character: 0x" .. ToBase(string.byte(Character), 16), 2)
end
for _ = 1, 7 do
BitPointerValue = BitPointerValue + 1
self.BitPointer = BitPointerValue
self.mBitBuffer[BitPointerValue] = ByteCharacter % 2
ByteCharacter = math.floor(ByteCharacter / 2)
end
if ByteCharacter ~= 0 then
error("Character value 0x" .. ToBase(Base128ToNumber[Character], 16) .. " too large", 2)
end
end
self.BitPointer = 0
end
--[[**
Writes the BitBuffer to Base128. Not recommended. Credit to Defaultio for the original functions.
@returns [t:string] The BitBuffer encoded in Base128.
**--]]
function BitBuffer:ToBase128()
local Array = {}
local Length = 0
local Accumulator = 0
local Power = 0
local mBitBuffer = self.mBitBuffer
for Index = 1, math.ceil(#mBitBuffer / 7) * 7 do
Accumulator = Accumulator + PowerOfTwo[Power] * (mBitBuffer[Index] or 0)
Power = Power + 1
if Power >= 7 then
Length = Length + 1
Array[Length] = NumberToBase128[Accumulator]
Accumulator = 0
Power = 0
end
end
return table.concat(Array)
end
--[[**
Dumps the BitBuffer data and prints it.
@returns [void]
**--]]
function BitBuffer:Dump()
local String = ""
local String2 = ""
local Accumulator = 0
local Power = 0
local mBitBuffer = self.mBitBuffer
for Index = 1, math.ceil(#mBitBuffer / 8) * 8 do
String2 = String2 .. (mBitBuffer[Index] or 0)
Accumulator = Accumulator + PowerOfTwo[Power] * (mBitBuffer[Index] or 0)
Power = Power + 1
if Power >= 8 then
String2 = String2 .. " "
String = String .. "0x" .. ToBase(Accumulator, 16) .. " "
Accumulator = 0
Power = 0
end
end
print("[Dump] Bytes:", String)
print("[Dump] Bits:", String2)
end
function BitBuffer:_ReadBit()
self.BitPointer = self.BitPointer + 1
return self.mBitBuffer[self.BitPointer]
end
--[[**
Writes an unsigned number to the BitBuffer.
@param [t:integer] Width The bit width of the value.
@param [t:integer] Value The unsigned integer.
@returns [void]
**--]]
function BitBuffer:WriteUnsigned(Width, Value)
if type(Width) ~= "number" then
error(string.format("bad argument #1 in BitBuffer::WriteUnsigned (number expected, instead got %s)", DetermineType(Width)), 2)
end
if not (Value or type(Value) == "number" or Value >= 0 or Value % 1 == 0) then
error(string.format("bad argument #2 in BitBuffer::WriteUnsigned (positive integer expected, instead got %s)", DetermineType(Value)), 2)
end
-- Store LSB first
for _ = 1, Width do
self.BitPointer = self.BitPointer + 1
self.mBitBuffer[self.BitPointer] = Value % 2
Value = math.floor(Value / 2)
end
if Value ~= 0 then
error("Value " .. tostring(Value) .. " has width greater than " .. Width .. " bits", 2)
end
end
--[[**
Reads an unsigned integer from the BitBuffer.
@param [t:integer] Width The bit width of the value.
@returns [t:integer] The unsigned integer.
**--]]
function BitBuffer:ReadUnsigned(Width)
local Value = 0
for Index = 1, Width do
Value = Value + self:_ReadBit() * PowerOfTwo[Index - 1]
end
return Value
end
--[[**
Writes a signed integer to the BitBuffer.
@param [t:integer] Width The bit width of the value.
@param [t:integer] Value The signed integer.
@returns [void]
**--]]
function BitBuffer:WriteSigned(Width, Value)
if not (Width and Value) then
error("bad arguments in BitBuffer::WriteSigned (missing values)", 2)
end
if Value % 1 ~= 0 then
error("Non-integer value to BitBuffer::WriteSigned", 2)
end
-- Write sign
if Value < 0 then
self.BitPointer = self.BitPointer + 1
self.mBitBuffer[self.BitPointer] = 1
Value = 0 - Value
else
self.BitPointer = self.BitPointer + 1
self.mBitBuffer[self.BitPointer] = 0
end
self:WriteUnsigned(Width - 1, Value)
end
--[[**
Reads a signed integer from the BitBuffer.
@param [t:integer] Width The bit width of the value.
@returns [t:integer] The signed integer.
**--]]
function BitBuffer:ReadSigned(Width)
self.BitPointer = self.BitPointer + 1
return ((-1) ^ self.mBitBuffer[self.BitPointer]) * self:ReadUnsigned(Width - 1)
end
--[[**
Writes a string to the BitBuffer.
@param [t:string] String The string you are writing to the BitBuffer.
@returns [void]
**--]]
function BitBuffer:WriteString(String)
if type(String) ~= "string" then
error(string.format("bad argument #1 in BitBuffer::WriteString (string expected, instead got %s)", typeof(String)), 2)
end
-- First check if it's a 7 or 8 bit width of string
local StringLength = #String
local BitWidth = 7
for Index = 1, StringLength do
if string.byte(String, Index, Index) > 127 then
BitWidth = 8
break
end
end
-- Write the bit width flag
self:WriteUnsigned(1, BitWidth == 7 and 0 or 1) -- 1 for wide chars
-- Now write out the string, terminated with "0x10, 0b0"
-- 0x10 is encoded as "0x10, 0b1"
for Index = 1, StringLength do
local ByteCharacter = string.byte(String, Index, Index)
if ByteCharacter == 0x10 then
self:WriteUnsigned(BitWidth, 0x10)
self:WriteUnsigned(1, 1)
else
self:WriteUnsigned(BitWidth, ByteCharacter)
end
end
-- Write terminator
self:WriteUnsigned(BitWidth, 0x10)
self:WriteUnsigned(1, 0)
end
--[[**
Reads the BitBuffer for a string.
@returns [t:string] The string written to the BitBuffer.
**--]]
function BitBuffer:ReadString()
-- Get bit width
local BitWidth = self:ReadUnsigned(1) == 1 and 8 or 7
-- Loop
local String = ""
while true do
local Character = self:ReadUnsigned(BitWidth)
if Character == 0x10 then
if self:ReadUnsigned(1) == 1 then
String = String .. CHAR_0X10
else
break
end
else
String = String .. string.char(Character)
end
end
return String
end
--[[**
Writes a boolean to the BitBuffer.
@param [t:boolean] Boolean The value you are writing to the BitBuffer.
@returns [void]
**--]]
function BitBuffer:WriteBool(Boolean)
if type(Boolean) ~= "boolean" then
error(string.format("bad argument #1 in BitBuffer::WriteBool (boolean expected, instead got %s)", typeof(Boolean)), 2)
end
self:WriteUnsigned(1, Boolean and 1 or 0)
end
BitBuffer.WriteBoolean = BitBuffer.WriteBool
--[[**
Reads the BitBuffer for a boolean.
@returns [t:boolean] The boolean.
**--]]
function BitBuffer:ReadBool()
return self:ReadUnsigned(1) == 1
end
BitBuffer.ReadBoolean = BitBuffer.ReadBool
-- Read / Write a floating point number with |wfrac| fraction part
-- bits, |wexp| exponent part bits, and one sign bit.
--[[**
Writes a float to the BitBuffer.
@param [t:integer] Fraction The number of bits (probably).
@param [t:integer] WriteExponent The number of bits for the decimal (probably).
@param [t:number] Float The actual number you are writing.
@returns [void]
**--]]
function BitBuffer:WriteFloat(Fraction, WriteExponent, Float)
if not (Fraction and WriteExponent and Float) then
error("missing argument(s)", 2)
end
-- Sign
local Sign = 1
if Float < 0 then
Float = 0 - Float
Sign = -1
end
-- Decompose
local Mantissa, Exponent = math.frexp(Float)
if Exponent == 0 and Mantissa == 0 then
self:WriteUnsigned(Fraction + WriteExponent + 1, 0)
return
else
Mantissa = (Mantissa - 0.5) / 0.5 * PowerOfTwo[Fraction]
end
-- Write sign
self:WriteUnsigned(1, Sign == -1 and 1 or 0)
-- Write mantissa
Mantissa = Mantissa + 0.5
Mantissa = math.floor(Mantissa) -- Not really correct, should round up/down based on the parity of |wexp|
self:WriteUnsigned(Fraction, Mantissa)
-- Write exponent
local MaxExp = PowerOfTwo[WriteExponent - 1] - 1
self:WriteSigned(WriteExponent, Exponent > MaxExp and MaxExp or Exponent < -MaxExp and -MaxExp or Exponent)
end
--[[**
Reads a float from the BitBuffer.
@param [t:integer] Fraction The number of bits (probably).
@param [t:integer] WriteExponent The number of bits for the decimal (probably).
@returns [t:number] The float.
**--]]
function BitBuffer:ReadFloat(Fraction, WriteExponent)
if not (Fraction and WriteExponent) then
error("missing argument(s)", 2)
end
local Sign = self:ReadUnsigned(1) == 1 and -1 or 1
local Mantissa = self:ReadUnsigned(Fraction)
local Exponent = self:ReadSigned(WriteExponent)
if Exponent == 0 and Mantissa == 0 then
return 0
end
Mantissa = Mantissa / PowerOfTwo[Fraction] / 2 + 0.5
return Sign * math.ldexp(Mantissa, Exponent)
end
--[[**
Writes a float8 (quarter precision) to the BitBuffer.
@param [t:number] The float8.
@returns [void]
**--]]
function BitBuffer:WriteFloat8(Float)
self:WriteFloat(3, 4, Float)
end
--[[**
Reads a float8 (quarter precision) from the BitBuffer.
@returns [t:number] The float8.
**--]]
function BitBuffer:ReadFloat8()
local Sign = self:ReadUnsigned(1) == 1 and -1 or 1
local Mantissa = self:ReadUnsigned(3)
local Exponent = self:ReadSigned(4)
if Exponent == 0 and Mantissa == 0 then
return 0
end
Mantissa = Mantissa / PowerOfTwo[3] / 2 + 0.5
return Sign * math.ldexp(Mantissa, Exponent)
end
--[[**
Writes a float16 (half precision) to the BitBuffer.
@param [t:number] The float16.
@returns [void]
**--]]
function BitBuffer:WriteFloat16(Float)
self:WriteFloat(10, 5, Float)
end
--[[**
Reads a float16 (half precision) from the BitBuffer.
@returns [t:number] The float16.
**--]]
function BitBuffer:ReadFloat16()
local Sign = self:ReadUnsigned(1) == 1 and -1 or 1
local Mantissa = self:ReadUnsigned(10)
local Exponent = self:ReadSigned(5)
if Exponent == 0 and Mantissa == 0 then
return 0
end
Mantissa = Mantissa / PowerOfTwo[10] / 2 + 0.5
return Sign * math.ldexp(Mantissa, Exponent)
end
--[[**
Writes a float32 (single precision) to the BitBuffer.
@param [t:number] The float32.
@returns [void]
**--]]
function BitBuffer:WriteFloat32(Float)
self:WriteFloat(23, 8, Float)
end
--[[**
Reads a float32 (single precision) from the BitBuffer.
@returns [t:number] The float32.
**--]]
function BitBuffer:ReadFloat32()
local Sign = self:ReadUnsigned(1) == 1 and -1 or 1
local Mantissa = self:ReadUnsigned(23)
local Exponent = self:ReadSigned(8)
if Exponent == 0 and Mantissa == 0 then
return 0
end
Mantissa = Mantissa / PowerOfTwo[23] / 2 + 0.5
return Sign * math.ldexp(Mantissa, Exponent)
end
--[[**
Writes a float64 (double precision) to the BitBuffer.
@param [t:number] The float64.
@returns [void]
**--]]
function BitBuffer:WriteFloat64(Float)
self:WriteFloat(52, 11, Float)
end
--[[**
Reads a float64 (double precision) from the BitBuffer.
@returns [t:number] The float64.
**--]]
function BitBuffer:ReadFloat64()
local Sign = self:ReadUnsigned(1) == 1 and -1 or 1
local Mantissa = self:ReadUnsigned(52)
local Exponent = self:ReadSigned(11)
if Exponent == 0 and Mantissa == 0 then
return 0
end
Mantissa = Mantissa / PowerOfTwo[52] / 2 + 0.5
return Sign * math.ldexp(Mantissa, Exponent)
end
-- Roblox DataTypes
if DEPRECATED_WARNING then
--[[**
[DEPRECATED] Writes a BrickColor to the BitBuffer.
@param [t:BrickColor] Color The BrickColor you are writing to the BitBuffer.
@returns [void]
**--]]
function BitBuffer:WriteBrickColor(Color)
if typeof(Color) ~= "BrickColor" then
error(string.format("bad argument #1 in BitBuffer::WriteBrickColor (BrickColor expected, instead got %s)", typeof(Color)), 2)
end
warn("::WriteBrickColor is deprecated. Using ::WriteColor3 is suggested instead.")
local BrickColorNumber = BrickColorToNumber[Color.Number]
if not BrickColorNumber then
warn("Attempt to serialize non-pallete BrickColor \"" .. tostring(Color) .. "\" (#" .. Color.Number .. "), using Light Stone Grey instead.")
BrickColorNumber = BrickColorToNumber[1032]
end
self:WriteUnsigned(6, BrickColorNumber)
end
else
--[[**
[DEPRECATED] Writes a BrickColor to the BitBuffer.
@param [t:BrickColor] Color The BrickColor you are writing to the BitBuffer.
@returns [void]
**--]]
function BitBuffer:WriteBrickColor(Color)
if typeof(Color) ~= "BrickColor" then
error(string.format("bad argument #1 in BitBuffer::WriteBrickColor (BrickColor expected, instead got %s)", typeof(Color)), 2)
end
local BrickColorNumber = BrickColorToNumber[Color.Number]
if not BrickColorNumber then
warn("Attempt to serialize non-pallete BrickColor \"" .. tostring(Color) .. "\" (#" .. Color.Number .. "), using Light Stone Grey instead.")
BrickColorNumber = BrickColorToNumber[1032]
end
self:WriteUnsigned(6, BrickColorNumber)
end
end
--[[**
[DEPRECATED] Reads a BrickColor from the BitBuffer.
@returns [t:BrickColor] The BrickColor read from the BitBuffer.
**--]]
function BitBuffer:ReadBrickColor()
return NumberToBrickColor[self:ReadUnsigned(6)]
end
--[[**
Writes the rotation part of a CFrame into the BitBuffer.
@param [t:CFrame] CoordinateFrame The CFrame you wish to write.
@returns [void]
**--]]
function BitBuffer:WriteRotation(CoordinateFrame)
if typeof(CoordinateFrame) ~= "CFrame" then
error(string.format("bad argument #1 in BitBuffer::WriteRotation (CFrame expected, instead got %s)", typeof(CoordinateFrame)), 2)
end
local LookVector = CoordinateFrame.LookVector
local Azumith = math.atan2(-LookVector.X, -LookVector.Z)
local Elevation = math.atan2(LookVector.Y, math.sqrt(LookVector.X * LookVector.X + LookVector.Z * LookVector.Z))
local WithoutRoll = CFrame.new(CoordinateFrame.Position) * CFrame.Angles(0, Azumith, 0) * CFrame.Angles(Elevation, 0, 0)
local _, _, Roll = (WithoutRoll:Inverse() * CoordinateFrame):ToEulerAnglesXYZ()
-- Atan2 -> in the range [-pi, pi]
Azumith = math.floor(((Azumith / 3.1415926535898) * 2097151) + 0.5)
Roll = math.floor(((Roll / 3.1415926535898) * 1048575) + 0.5)
Elevation = math.floor(((Elevation / 1.5707963267949) * 1048575) + 0.5)
self:WriteSigned(22, Azumith)
self:WriteSigned(21, Roll)
self:WriteSigned(21, Elevation)
end
--[[**
Reads the rotation part of a CFrame saved in the BitBuffer.
@returns [t:CFrame] The rotation read from the BitBuffer.
**--]]
function BitBuffer:ReadRotation()
local Azumith = self:ReadSigned(22)
local Roll = self:ReadSigned(21)
local Elevation = self:ReadSigned(21)
Azumith = 3.1415926535898 * (Azumith / 2097151)
Roll = 3.1415926535898 * (Roll / 1048575)
Elevation = 3.1415926535898 * (Elevation / 1048575)
local Rotation = CFrame.Angles(0, Azumith, 0)
Rotation = Rotation * CFrame.Angles(Elevation, 0, 0)
Rotation = Rotation * CFrame.Angles(0, 0, Roll)
return Rotation
end
--[[**
Writes a Color3 to the BitBuffer.
@param [t:Color3] Color The color you want to write into the BitBuffer.
@returns [void]
**--]]
function BitBuffer:WriteColor3(Color)
if typeof(Color) ~= "Color3" then
error(string.format("bad argument #1 in BitBuffer::WriteColor3 (Color3 expected, instead got %s)", typeof(Color)), 2)
end
local R, G, B = Color.R * 255, Color.G * 255, Color.B * 255
self:WriteUnsigned(8, math.floor(R))
self:WriteUnsigned(8, math.floor(G))
self:WriteUnsigned(8, math.floor(B))
end
--[[**
Reads a Color3 from the BitBuffer.
@returns [t:Color3] The color read from the BitBuffer.
**--]]
function BitBuffer:ReadColor3()
return Color3.fromRGB(self:ReadUnsigned(8), self:ReadUnsigned(8), self:ReadUnsigned(8))
end
--[[**
Writes a Vector3 to the BitBuffer. Writes with Float32 precision.
@param [t:Vector3] Vector The vector you want to write into the BitBuffer.
@returns [void]
**--]]
function BitBuffer:WriteVector3(Vector)
if typeof(Vector) ~= "Vector3" then
error(string.format("bad argument #1 in BitBuffer::WriteVector3 (Vector3 expected, instead got %s)", typeof(Vector)), 2)
end
self:WriteFloat32(Vector.X)
self:WriteFloat32(Vector.Y)
self:WriteFloat32(Vector.Z)
end
--[[**
Reads a Vector3 from the BitBuffer. Uses Float32 precision.
@returns [t:Vector3] The vector read from the BitBuffer.
**--]]
function BitBuffer:ReadVector3()
return Vector3.new(self:ReadFloat32(), self:ReadFloat32(), self:ReadFloat32())
end