-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmap_manipulation_tool_api.lua
4336 lines (3983 loc) · 155 KB
/
map_manipulation_tool_api.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
--[[
By Mohamed RACHID
Please follow the license "Mozilla Public License 2.0" or greater. https://www.mozilla.org/en-US/MPL/2.0/
To be simple: if you distribute a modified version then you share the sources.
Limitations:
- You cannot do several operations on the same BspContext at once.
--]]
-- https://developer.valvesoftware.com/wiki/Source_BSP_File_Format
-- https://developer.valvesoftware.com/wiki/Source_BSP_File_Format/Game-Specific
-- TODO - objets de contexte contenant :
-- id Stéam du jeu ou 0 ?
-- TODO - membres par défaut, avec commentaires descriptifs
-- TODO - fichier journal
-- TODO - interdire remplacement (sans effet) & suppression (sans effet) de LUMP_GAME_LUMP
print("map_manipulation_tool_api")
-- Local copies, not changing how the code is written, for greater loop efficiency:
local SysTime = SysTime
local bit = bit
local coroutine = coroutine
local ipairs = ipairs
local math = math
local pairs = pairs
local string = string
local unpack = unpack
local table = table
module("map_manipulation_tool_api", package.seeall)
--- Constants ---
BUFFER_LENGTH = 4194304 -- 4 MiB
FULL_ZERO_BUFFER = nil -- BUFFER_LENGTH of null data, set only on 1st API use
local WEAK_KEYS = {__mode = "k"}
local WEAK_VALUES = {__mode = "v"}
local DICTIONARY_DEFAULT_0 = {__index = function() return 0 end}
local FLOAT_TEXT_NAN
local FLOAT_TEXT_INF_POSI
local FLOAT_TEXT_INF_NEGA
-- lump_t variants:
local LUMP_T_USUAL = nil -- usual
local LUMP_T_L4D2 = 1 -- Left 4 Dead 2 / Contagion
--- Utility ---
do
-- 32-bit integers are signed, other lengths are unsigned
local bit_bor = bit.bor
local bit_lshift = bit.lshift
local string_byte = string.byte
function data_to_le(data)
-- Decode a binary string into a 4-byte-max little-endian integer
local result = 0
local bytes = {string_byte(data, 1, #data)}
for i = #bytes, 1, -1 do
result = bit_bor(bit_lshift(result, 8), bytes[i])
end
return result
end
function data_to_be(data)
-- 32-bit integers are signed, other lengths are unsigned
local result = 0
local bytes = {string_byte(data, 1, #data)}
for i = 1, #bytes, 1 do
result = bit_bor(bit_lshift(result, 8), bytes[i])
end
return result
end
end
do
-- Functions to decode single-precision floats:
local _nan = math.log(-1.)
local _inf_posi = 1./0.
local _inf_nega = -1./0.
FLOAT_TEXT_NAN = tostring(_nan)
FLOAT_TEXT_INF_POSI = tostring(_inf_posi)
FLOAT_TEXT_INF_NEGA = tostring(_inf_nega)
local specialValues = {
-- Includes positive & negative int32 equivalents
[0x00000000] = 0., -- 0
[0x80000000] = -0., -- -0
[-2147483648] = -0., -- -0
[0x7f800000] = _inf_posi, -- inf
[0xff800000] = _inf_nega, -- -inf
[-8388608] = _inf_nega, -- -inf
[0xffc00001] = _nan, -- qNaN
[-4194303] = _nan, -- qNaN
[0xff800001] = _nan, -- sNaN
[-8388607] = _nan, -- sNaN
}
local bit_rshift = bit.rshift
local bit_band = bit.band
local bit_bor = bit.bor
local function _integer_to_float32(integer_)
-- Decode a single-precision float from its a 32-bit integer representation
-- It also returns the original integer, which is accuracy-safe.
local exponent
local float_ = specialValues[integer_]
if not float_ then
exponent = bit_band(bit_rshift(integer_, 23), 0xFF) -- unsigned: exponent as a signed integer is uncommon
if exponent == 0xFF then
-- zero & most NaN representations already handled with specialValues
float_ = _nan
end
end
if not float_ then
local negative_bit = bit_rshift(integer_, 31)
local mantissa = bit_band(integer_, 0x7FFFFF)
if exponent ~= 0 then
exponent = exponent - 127
mantissa = bit_bor(0x800000, mantissa) -- implicit '1' bit (before point)
else -- subnormal
exponent = -126
mantissa = mantissa
end
-- - 23 to offset the binary point by 23 digits to the left
float_ = mantissa * (2 ^ (exponent - 23))
float_ = (negative_bit ~= 1) and float_ or -float_
end
return float_
end
function data_to_float32_le(data)
-- TODO - tester
return _integer_to_float32(data_to_le(data))
end
function data_to_float32_be(data)
return _integer_to_float32(data_to_be(data))
end
end
function int32_to_le_data(num)
local bytes = {
bit.band(num, 0xFF),
bit.band(bit.rshift(num, 8), 0xFF),
bit.band(bit.rshift(num, 16), 0xFF),
bit.band(bit.rshift(num, 24), 0xFF),
}
return string.char(unpack(bytes))
end
function int16_to_le_data(num)
local bytes = {
bit.band(num, 0xFF),
bit.band(bit.rshift(num, 8), 0xFF),
}
return string.char(unpack(bytes))
end
function int32_to_be_data(num)
local bytes = {
bit.band(bit.rshift(num, 24), 0xFF),
bit.band(bit.rshift(num, 16), 0xFF),
bit.band(bit.rshift(num, 8), 0xFF),
bit.band(num, 0xFF),
}
return string.char(unpack(bytes))
end
function int16_to_be_data(num)
local bytes = {
bit.band(bit.rshift(num, 8), 0xFF),
bit.band(num, 0xFF),
}
return string.char(unpack(bytes))
end
do
-- Functions to encode single-precision floats
-- Note: values are clamped naturally below min/max values and explicitly around +/- 0.
local bit_band = bit.band
local bit_bor = bit.bor
local bit_lshift = bit.lshift
local math_floor = math.floor
local tostring = tostring
local string_format = string.format
local string_match = string.match
local tonumber = tonumber
local math_max = math.max
local specialValues = {
-- To ensure proper conversion, the string representation is used.
[tostring( 0.)] = 0x00000000, -- 0
[tostring(-0.)] = 0x80000000, -- -0
[tostring( 1./0.)] = 0x7f800000, -- inf
[tostring(-1./0.)] = 0xff800000, -- -inf
[tostring(math.log(-1.))] = 0xffc00001, -- qNaN
}
--[[
local function _debug_binary_float32(integer_)
-- Only for debugging
local digits = {"\t\t"}
for digitId = 31, 0, -1 do
digits[#digits + 1] = tostring(bit.band(bit.rshift(integer_, digitId), 1))
if digitId == 31 or digitId == 23 then
digits[#digits + 1] = " "
end
end
print(table.concat(digits))
end
]]
local function _float32_to_int32(float_)
local integer_ = specialValues[tostring(float_)]
if not integer_ then
-- Take away the sign:
local negative = (float_ < 0.)
if negative then
float_ = -float_
end
local exponent
local mantissa -- as written (without the explicit '1' bit)
local subnormal = false
local roundUp
-- Find the proper exponent & calculate the mantissa:
for exponent_ = 127, -127, -1 do
-- -127 is fake and means that it is a subnormal number.
if exponent_ == -127 then
exponent_ = -126
subnormal = true
end
mantissa = float_ / (2 ^ (exponent_ - 23)) -- as float, including implicit #23 bit
roundUp = ((mantissa % 1.) >= 0.5) -- supposedly it is not >=, but it should not matter
mantissa = math_floor(mantissa) -- as 24-bit integer (more bits if overflow)
if subnormal or mantissa >= 0x800000 then -- found 1st '1' bit in 24-bit mantissa
exponent = exponent_
break
end
end
-- Correct the mantissa:
if mantissa >= 0xffffff then
if exponent >= 127 then
-- prevent overflow:
exponent = 127
mantissa = 0xffffff
elseif roundUp or mantissa > 0xffffff then
-- round-up by incrementing exponent:
exponent = exponent + 1
mantissa = 0x800000
end
elseif roundUp then
-- round up if appropriate:
mantissa = mantissa + 1
end
if subnormal and mantissa == 0 then
-- Clamp tiny non-zero to minimum non-zero value:
mantissa = 1
end
mantissa = bit_band(0x7fffff, mantissa) -- as 23-bit integer, excluding implicit #23 bit
-- Calculate the encoded exponent (applying bias):
if not subnormal then
exponent = exponent + 127 -- range: 0x01 to 0xfe
else
exponent = 0x00
end
-- Putting everything together in the final value:
integer_ = bit_bor(
negative and 0x80000000 or 0x00000000,
bit_lshift(exponent, 23),
mantissa
)
end
return integer_
end
function float32_to_le_data(float_)
return int32_to_le_data(_float32_to_int32(float_))
end
function float32_to_be_data(float_)
return int32_to_be_data(_float32_to_int32(float_))
end
--[[
if CLIENT then
-- "([0-9a-f]{2})([0-9a-f]{2}) ([0-9a-f]{2})([0-9a-f]{2})"
-- "\\x$1\\x$2\\x$3\\x$4"
print("Example values from Wikipedia:")
for _, convertAttempts in ipairs({
{"\t1.4012984643e-45 =", "\x00\x00\x00\x01"},
{"\t1.1754942107e-38 =", "\x00\x7f\xff\xff"},
{"\t1.1754943508e-38 =", "\x00\x80\x00\x00"},
{"\t3.4028234664e+38 =", "\x7f\x7f\xff\xff"},
{"\t0.9999999404 =", "\x3f\x7f\xff\xff"},
{"\t1 =", "\x3f\x80\x00\x00"},
{"\t1.0000001192 =", "\x3f\x80\x00\x01"},
{"\t−2 =", "\xc0\x00\x00\x00"},
{"\t+0 =", "\x00\x00\x00\x00"},
{"\t-0 =", "\x80\x00\x00\x00"},
{"\t+infinity =", "\x7f\x80\x00\x00"},
{"\t-infinity =", "\xff\x80\x00\x00"},
{"\t3.14159274101 =", "\x40\x49\x0f\xdb"},
{"\t0.333333343267 =", "\x3e\xaa\xaa\xab"},
{"\tqNaN =", "\xff\xc0\x00\x01"},
{"\tsNaN =", "\xff\x80\x00\x01"},
}) do
local float_ = data_to_float32_be(convertAttempts[2])
local float2 = data_to_float32_be(float32_to_be_data(float_))
print(convertAttempts[1], string.format("%9s\t%9s", tostring(float_), tostring(float2)))
end
print(data_to_float32_be(float32_to_be_data( 5e+120)))
print(data_to_float32_be(float32_to_be_data( 5e-120)))
print(data_to_float32_be(float32_to_be_data(-5e-120)))
print(data_to_float32_be(float32_to_be_data(-5e+120)))
end
]]
function float32_to_decimal_string(float_, decimals)
-- float_: number to convert
-- decimals: number of expected decimals by default (for Vector & Angle), or nil for automatic precision, ignored for large numbers
-- Convert a single-precision number into a string with its decimal representation (like %f), with guaranteed precision.
-- For precision: 8 significant digits are required (2^24), +1 because maybe needed, +1 for extended precision just-in-case.
local text
local base, powerOf10 = string_match(string_format("%.9e", float_), "^([%d%.%-%+ ]+)e([%d%-%+ ]+)$")
base, powerOf10 = tonumber(base), tonumber(powerOf10)
if base and powerOf10 then
if powerOf10 < 9 then
-- usual case:
local minimumDecimals = 9 - powerOf10
decimals = decimals and math_max(decimals, minimumDecimals) or minimumDecimals
else
-- at least 10 significant digits before decimal point:
decimals = 0 -- shorter ouput
end
text = string_format("%." .. decimals .. "f", float_)
else
-- special number:
text = tostring(float_)
end
return text
end
end
do
local isstring = isstring
local string_sub = string.sub
local Vector = Vector
local Angle = Angle
local table_concat = table.concat
local string_format = string.format
local function read3Float32s(context, from)
local data_to_float32 = context.data_to_float32
if not isstring(from) then
from = from:Read(12)
end
return data_to_float32(string_sub(from, 1, 4)),
data_to_float32(string_sub(from, 5, 8)),
data_to_float32(string_sub(from, 9, 12))
end
function decode_Vector(context, from)
-- TODO - supporter Vector chelous encodés bruts
return Vector(read3Float32s(context, from))
end
function decode_QAngle(context, from)
-- TODO - supporter Angle chelous encodés bruts
return Angle(read3Float32s(context, from))
end
function Vector_to_data(context, from)
-- TODO - supporter Vector chelous encodés bruts
local pieces = {
context.float32_to_data(from.x),
context.float32_to_data(from.y),
context.float32_to_data(from.z),
}
return table_concat(pieces)
end
function QAngle_to_data(context, from)
-- TODO - supporter Angle chelous encodés bruts
local pieces = {
context.float32_to_data(from.p),
context.float32_to_data(from.y),
context.float32_to_data(from.r),
}
return table_concat(pieces)
end
function Vector_to_string(from)
-- Very big values are truncated with Vector:__tostring()!
-- There is a loss of precision for small values Vector:__tostring().
-- Note: Vector() probably handles long strings.
-- TODO - supporter Vector chelous encodés bruts
return string_format("%s %s %s",
float32_to_decimal_string(from.x, 6),
float32_to_decimal_string(from.y, 6),
float32_to_decimal_string(from.z, 6)
)
end
function Angle_to_string(from)
-- Very big values are truncated with Angle:__tostring()!
-- There is a loss of precision for small values Angle:__tostring().
-- Note: Angle() probably handles long strings.
-- TODO - supporter Angle chelous encodés bruts
return string_format("%s %s %s",
float32_to_decimal_string(from.p, 3),
float32_to_decimal_string(from.y, 3),
float32_to_decimal_string(from.r, 3)
)
end
end
do
local isstring = isstring
local Color = Color
local string_byte = string.byte
local string_char = string.char
function decode_color32(from)
if not isstring(from) then
from = from:Read(4)
end
return Color(string_byte(from, 1, 4))
end
function ColorFromText(rendercolor, renderamt)
local r, g, b, a
if rendercolor then
do
r, g, b, a = string.match(rendercolor, "^%s*([1-2]?[0-9]?[0-9])%s+([1-2]?[0-9]?[0-9])%s+([1-2]?[0-9]?[0-9])%s+([1-2]?[0-9]?[0-9])")
end
if not r then
r, g, b = string.match(rendercolor, "^%s*([1-2]?[0-9]?[0-9])%s+([1-2]?[0-9]?[0-9])%s+([1-2]?[0-9]?[0-9])")
end
end
if not r then
r, g, b = 255, 255, 255
end
if renderamt then
a = renderamt
end
if not a then
a = 255
end
return Color(tonumber(r), tonumber(g), tonumber(b), tonumber(a))
end
function color32_to_data(from)
return string_char(from.r, from.g, from.b, from.a)
end
end
local writeZeroesInFile
do
local math_min = math.min
local string_rep = string.rep
function writeZeroesInFile(streamDst, remainingBytes)
-- Write remainingBytes NULL bytes in streamDst
while remainingBytes > 0 do
local toWrite_bytes = math_min(BUFFER_LENGTH, remainingBytes)
local buffer = FULL_ZERO_BUFFER
if toWrite_bytes ~= BUFFER_LENGTH then
buffer = string_rep("\0", toWrite_bytes) -- expensive!
end
streamDst:Write(buffer)
remainingBytes = remainingBytes - toWrite_bytes
end
end
end
do
local math_min = math.min
local math_max = math.max
local string_sub = string.sub
local NOT_IMPLEMENTED = "Not implemented"
BytesIO = {
-- Class to manipulate a string like a File (currently only read-only)
-- Returned types should be the same for every case.
-- Borrowed from Python
_wrapped = nil, -- the string to wrap / nil when closed
_length = -1, -- the length of _wrapped
_cursor = -1, -- the current location in the string
_writeable = false, -- always false: read-only
new = function(cls, wrapped, mode)
-- mode: always "rb"
local instance = {}
setmetatable(instance, cls)
if mode == "rb" then
instance._wrapped = wrapped
instance._length = #wrapped
instance._cursor = 0
else
error("Argument mode: invalid value")
end
return instance
end,
Close = function(self)
self._wrapped = nil -- free memory
self._length = -1
self._cursor = -1
end,
Flush = function(self)
-- nothing
end,
Read = function(self, length)
if self._wrapped then
if length > 0 then
local oldCursor = self._cursor
local newCursor = math_min(oldCursor + length, self._length)
if newCursor ~= oldCursor then
self._cursor = newCursor
return string_sub(self._wrapped, oldCursor + 1, newCursor)
else
-- nothing left
return
end
else
return
end
else
return
end
end,
ReadBool = function(self)
error(NOT_IMPLEMENTED)
end,
ReadByte = function(self)
error(NOT_IMPLEMENTED)
end,
ReadDouble = function(self)
error(NOT_IMPLEMENTED)
end,
ReadFloat = function(self)
error(NOT_IMPLEMENTED)
end,
ReadLine = function(self)
error(NOT_IMPLEMENTED)
end,
ReadLong = function(self)
error(NOT_IMPLEMENTED)
end,
ReadShort = function(self)
error(NOT_IMPLEMENTED)
end,
ReadULong = function(self)
error(NOT_IMPLEMENTED)
end,
ReadUShort = function(self)
error(NOT_IMPLEMENTED)
end,
Seek = function(self, pos)
if self._wrapped then
self._cursor = math_min(math_max(0, pos), self._length)
end
end,
Size = function(self)
if self._wrapped then
return self._length
else
return
end
end,
Skip = function(self, amount)
if self._wrapped then
self._cursor = math_min(math_max(0, self._cursor + amount), self._length)
end
end,
Tell = function(self)
if self._wrapped then
return self._cursor
else
return
end
end,
}
BytesIO.__index = BytesIO
setmetatable(BytesIO, FindMetaTable("File"))
end
do
local File = FindMetaTable("File")
local File_Tell = File.Tell
local File_Seek = File.Seek
-- Not using members because instance is a userdata:
local _sizes = setmetatable({}, WEAK_KEYS)
local _sizesUntruncated = setmetatable({}, WEAK_KEYS)
FileForWrite = {
-- Replacement for the File class that keeps trace of the actual current file size
-- It is useless if the file is open in read mode.
new = function(cls, ...)
local instance = file.Open(...)
if instance then
local rawSize = instance:Size()
_sizes[instance] = rawSize
_sizesUntruncated[instance] = rawSize
debug.setmetatable(instance, cls)
end
return instance
end,
Size = function(self)
return _sizes[self]
end,
sizeUntruncated = function(self)
return _sizesUntruncated[self]
end,
truncate = function(self)
-- Erase the rest of the file with NULL-bytes and update the fake size
-- Already truncated space is not erased again.
-- This method does not come standard.
local pos = File_Tell(self)
local lengthOfZeroes = _sizes[self] - pos
if lengthOfZeroes >= 0 then
writeZeroesInFile(self, lengthOfZeroes)
File_Seek(self, pos)
_sizes[self] = pos
else
print("Attempted to FileForWrite:truncate() with FileForWrite:Size() < File:Tell()!")
end
end,
}
do
local function updateSize(stream)
local pos = File_Tell(stream)
if pos > _sizes[stream] then
_sizes[stream] = pos
end
if pos > _sizesUntruncated[stream] then
_sizesUntruncated[stream] = pos
end
end
for methodName, parentMethod in pairs(File) do
if isstring(methodName) and string.sub(methodName, 1, 5) == "Write" and isfunction(parentMethod) then
FileForWrite[methodName] = function(self, ...)
parentMethod(self, ...)
updateSize(self)
end
end
end
end
FileForWrite.__index = FileForWrite
setmetatable(FileForWrite, File)
end
do
function lzmaVbspToStandard(lzmaVbsp)
local id = string.sub(lzmaVbsp, 1, 4)
if id ~= "LZMA" and id ~= "AMZL" then
error("Invalid VBSP LZMA data!")
end
local actualSize = string.sub(lzmaVbsp, 5, 8) -- 32-bit little-endian
local lzmaSize = data_to_le(string.sub(lzmaVbsp, 9, 12)) -- 32-bit little-endian
local lzmaSizeExpected = #lzmaVbsp - 17
local properties = string.sub(lzmaVbsp, 13, 17)
if lzmaSize < lzmaSizeExpected then
print("Warning: lzmaVbspToStandard() - compressed lump with lzmaSize (" .. tostring(lzmaSize) .. " bytes) not filling the whole lump payload (" .. tostring(lzmaSizeExpected) .. " bytes)")
elseif lzmaSize > lzmaSizeExpected then
print("Warning: lzmaVbspToStandard() - compressed lump with lzmaSize (" .. tostring(lzmaSize) .. " bytes) exceeding the lump payload capacity (" .. tostring(lzmaSizeExpected) .. " bytes), expect errors!")
end
return table.concat({
properties,
actualSize, "\0\0\0\0", -- 64-bit little-endian
string.sub(lzmaVbsp, 18),
})
end
function lzmaStandardToVbsp(context, lzmaStandard)
local id
if context.data_to_integer == data_to_le then
id = "LZMA"
else
id = "AMZL"
end
local actualSize = string.sub(lzmaStandard, 6, 9) -- dropping most significant bits from 64-bit little-endian
local lzmaSize = int32_to_le_data(#lzmaStandard - 13)
local properties = string.sub(lzmaStandard, 1, 5)
return table.concat({
id,
actualSize,
lzmaSize,
properties,
string.sub(lzmaStandard, 14),
})
end
end
-- The asynchronous mechanism:
local yieldIfTimeout
do
-- TODO - gérer automatiquement l'ajout d'un hook pour poursuivre le traitement + callback statut + callback fini [avec info succès / échec]
local SysTime = SysTime
local coroutine_running = coroutine.running
local coroutine_yield = coroutine.yield
yieldIfTimeout = function(step, stepCount, stepProgress)
-- Function to be invoked by functions to support asynchronous operation
local work = coroutine_running()
if work ~= nil and work.yieldAt ~= nil and SysTime() >= work.yieldAt then
coroutine_yield(step, stepCount, stepProgress)
end
end
function asyncWork(onFinishedOk, onError, onProgress, interval_s, func, ...)
-- Invoke the given function with the given arguments in a coroutine
-- onFinishedOk : onFinishedOk(vararg result)
-- onError : onError(string errorMessage)
-- onProgress : onProgress(int step, int stepCount, float stepProgress)
-- TODO : asynchrone pour de vrai
-- TODO : SERVER != CLIENT
-- TODO : CLIENT : stopper rendu si menu Echap visible
-- TODO : retourner objet avec : fonction d'annulation
local callData = {xpcall(func, function(errorMessage)
ErrorNoHalt(errorMessage .. "\n" .. debug.traceback())
return errorMessage
end, ...)}
local success = callData[1]
if success then
if onFinishedOk then
onFinishedOk(unpack(callData, 2)) -- return result of func call
end
else
if onError then
onError(unpack(callData, 2)) -- return error message
ErrorNoHalt(callData[2])
end
end
return {--[[TODO]]}
end
end
local callSafe
do
local pcall = pcall
local unpack = unpack
function callSafe(...)
local resultInfo = {pcall(...)}
if not resultInfo[1] then
ErrorNoHalt(resultInfo[2])
end
return unpack(resultInfo)
end
end
local stringToLuaString
do
local string_gsub = string.gsub
local replacements = {
['\0'] = '\\0',
['"'] = '\\"',
["\\"] = "\\\\",
}
for c = 0x01, 0x1F do
replacements[string.char(c)] = string.format("\\x%02X", c)
end
function stringToLuaString(initial)
return '"' .. string_gsub(initial, '.', replacements) .. '"'
end
end
local anyToKeyValueString
do
local string_gsub = string.gsub
local tostring = tostring
local isvector = isvector
local isangle = isangle
local isnumber = isnumber
local string_format = string.format
local replacements = {
["\0"] = "",
['"'] = '\\"',
}
function anyToKeyValueString(initial)
if isvector(initial) then
return '"' .. Vector_to_string(initial) .. '"'
elseif isangle(initial) then
return '"' .. Angle_to_string(initial) .. '"'
elseif isnumber(initial) then
if initial % 1 == 0 and initial >= -2147483648 and initial <= 4294967295 then
-- int32 value:
if initial >= 0 then
return string_format('"%u"', initial)
else
return string_format('"%d"', initial)
end
else
-- float value:
return '"' .. float32_to_decimal_string(initial) .. '"'
end
else
return '"' .. string_gsub(tostring(initial), '.', replacements) .. '"'
end
end
end
--[[
local dictionaryKeysToLowerCase
do
-- Return a copy of dictionary with keys converted to lowercase
-- Bug "maxdxlevel", "Flags" https://github.com/Facepunch/garrysmod-issues/issues/4400
local string_lower = string.lower
function dictionaryKeysToLowerCase(dictionary)
local dictionary_ = {}
for k, v in pairs(dictionary_) do
dictionary_[string_lower(k)] = v
end
return dictionary_
end
end
-- Solution: preserveKeyCase = false
]]
local keyValuesTextKeepNumberPrecision
do
-- Avoid automatically decoding numbers in the text by adding a space after each quoted number
-- This is necessary because util.KeyValuesToTable() automatically decodes numbers as either int or float32!
-- Reading back Lua numbers (float64) losts precision because the conversion rounds down.
local string_gsub = string.gsub
function keyValuesTextKeepNumberPrecision(text)
text = string_gsub(text, '"([0-9]+%.?[0-9]*)"', '"%1 "')
return text
end
end
local keyValuesIntoStringValues
do
-- Set all values as strings in a keyvalues table
-- This alters the given table.
-- This is useful because values may be strings as well as numbers.
local istable = istable
local next = next
local pairs = pairs
local tostring = tostring
function keyValuesIntoStringValues(keyValues)
local firstEntryValue = ({next(keyValues)})[2]
if istable(firstEntryValue) and firstEntryValue.Key ~= nil then
-- Case: table returned by util.KeyValuesToTablePreserveOrder()
for i = 1, #keyValues do
local keyValue = keyValues[i]
keyValue.Value = tostring(keyValue.Value)
end
else
-- Case: table returned by util.KeyValuesToTable() or any other sort of dictionary
for Key, Value in pairs(keyValues) do
keyValues[Key] = tostring(Value)
end
end
return keyValues
end
end
--- Entities ---
--[[
local noLuaEntityClasses = {
-- Crash if missing (or suspected):
["worldspawn"] = true,
["info_node"] = true, -- suspected
["info_node_air"] = true, -- suspected
["info_node_air_hint"] = true, -- suspected
["info_node_climb"] = true,
["info_node_hint"] = true,
-- Not working if missing:
["env_skypaint"] = true, -- for 2D skybox
["env_tonemap_controller"] = true, -- for lighting parameters (especially HDR)
["sky_camera"] = true, -- for 3D skybox
}
]]
-- There are many entity classes that do not support being created in Lua: non-working state or crashes can happen.
--[[
local entityClassesWithoutModelIntoLua = {
-- Entity classes that do not have a model but can be moved into Lua:
["ambient_generic"] = true,
--["game_text"] = true, -- no: branding purpose
--["infodecal"] = true, -- no: branding purpose
["light"] = true,
--["light_spot"] = true, -- unknown
--["lua_run"] = true, -- no: branding & protection purposes
--["point_spotlight"] = true, -- unknown
-- Spawn points [garrysmod\gamemodes\base\gamemode\player.lua]:
["info_player_start"] = true,
["info_player_deathmatch"] = true,
["info_player_combine"] = true,
["info_player_rebel"] = true,
["info_player_counterterrorist"] = true,
["info_player_terrorist"] = true,
["info_player_axis"] = true,
["info_player_allies"] = true,
["gmod_player_start"] = true,
["info_player_teamspawn"] = true,
["ins_spawnpoint"] = true,
["aoc_spawnpoint"] = true,
["dys_spawn_point"] = true,
["info_player_pirate"] = true,
["info_player_viking"] = true,
["info_player_knight"] = true,
["diprip_start_team_blue"] = true,
["diprip_start_team_red"] = true,
["info_player_red"] = true,
["info_player_blue"] = true,
["info_player_coop"] = true,
["info_player_human"] = true,
["info_player_zombie"] = true,
["info_player_zombiemaster"] = true,
["info_survivor_rescue"] = true,
}
local entityClassesWithModelNoLua = {
-- Entity classes that have a model but should not be moved into Lua:
["trigger_hurt"] = true, -- no: used for map protection
["func_occluder"] = true, -- not working
["func_physbox"] = true, -- removed after creation?!
["func_door"] = true, -- investigation
["func_rotating"] = true, -- investigation
["trigger_hurt"] = true, -- investigation
["trigger_multiple"] = true, -- investigation
["trigger_push"] = true, -- investigation
}
]]
local entityClassesForceLua = {
-- Entity classes that should be moved into Lua despite having no model or a built-in model:
-- In addition, class names starting with npc_ / weapon_ / item_ are forced too.
["ambient_generic"] = true,
["env_sprite"] = true,
["func_breakable"] = true,
["func_breakable_surf"] = true,
["func_brush"] = true,
["func_button"] = true,
["func_door"] = true,
["func_door_rotating"] = true,
["func_movelinear"] = true,
["func_platrot"] = true,
--["func_rotating"] = true, -- investigation
["light"] = true,
["light_dynamic"] = true, -- almost sure
--["light_spot"] = true, -- TODO - investigation
--["point_spotlight"] = true, -- TODO - investigation
-- Spawn points [garrysmod\gamemodes\base\gamemode\player.lua]:
["info_player_start"] = true,
["info_player_deathmatch"] = true,
["info_player_combine"] = true,
["info_player_rebel"] = true,
["info_player_counterterrorist"] = true,
["info_player_terrorist"] = true,
["info_player_axis"] = true,
["info_player_allies"] = true,
["gmod_player_start"] = true,
["info_player_teamspawn"] = true,
["ins_spawnpoint"] = true,
["aoc_spawnpoint"] = true,
["dys_spawn_point"] = true,