-
Notifications
You must be signed in to change notification settings - Fork 332
/
wireshared.lua
1285 lines (1111 loc) · 34.8 KB
/
wireshared.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
WireLib = WireLib or {}
local pairs = pairs
local setmetatable = setmetatable
local rawget = rawget
local next = next
local IsValid = IsValid
local LocalPlayer = LocalPlayer
local Entity = Entity
local string = string
local string_gsub = string.gsub
local string_char = string.char
local string_match = string.match
local string_sub = string.sub
local utf8_char = utf8.char
local hook = hook
-- extra table functions
-- Returns a noniterable version of tbl. So indexing still works, but pairs(tbl) won't find anything
-- Useful for hiding entity lookup tables, since Garrydupe uses util.TableToJSON, which crashes on tables with entity keys
function table.MakeNonIterable(tbl) -- luacheck: ignore
return setmetatable({}, { __index = tbl, __setindex = tbl})
end
-- Compacts an array by rejecting entries according to cb.
function table.Compact(tbl, cb, n) -- luacheck: ignore
n = n or #tbl
local cpos = 1
for i = 1, n do
if cb(tbl[i]) then
tbl[cpos] = tbl[i]
cpos = cpos + 1
end
end
while (cpos <= n) do
tbl[cpos] = nil
cpos = cpos + 1
end
end
-- Removes `value` from `tbl` by shifting last element of `tbl` to its place.
-- Returns index of `value` if it was removed, nil otherwise.
function table.RemoveFastByValue(tbl, value)
for i, v in ipairs(tbl) do
if v == value then
tbl[i] = tbl[#tbl]
tbl[#tbl] = nil
return i
end
end
end
function string.GetNormalizedFilepath( path ) -- luacheck: ignore
local null = string.find(path, "\x00", 1, true)
if null then path = string.sub(path, 1, null-1) end
local tbl = string.Explode( "[/\\]+", path, true )
local i = 1
while i <= #tbl do
if tbl[i] == "." or tbl[i]=="" then
table.remove(tbl, i)
elseif tbl[i] == ".." then
table.remove(tbl, i)
if i>1 then
i = i - 1
table.remove(tbl, i)
end
else
i = i + 1
end
end
return table.concat(tbl, "/")
end
-- works like pairs() except that it iterates sorted by keys.
-- criterion is optional and should be a function(a,b) returning whether a is less than b. (same as table.sort's criterions)
function pairs_sortkeys(tbl, criterion)
local tmp = {}
for k, _ in pairs(tbl) do table.insert(tmp,k) end
table.sort(tmp, criterion)
local iter, state, index, k = ipairs(tmp)
return function()
index,k = iter(state, index)
if index == nil then return nil end
return k,tbl[k]
end
end
-- sorts by values
function pairs_sortvalues(tbl, criterion)
local crit = criterion and
function(a,b)
return criterion(tbl[a],tbl[b])
end
or
function(a,b)
return tbl[a] < tbl[b]
end
local tmp = {}
tbl = tbl or {}
for k, _ in pairs(tbl) do table.insert(tmp,k) end
table.sort(tmp, crit)
local iter, state, index, k = ipairs(tmp)
return function()
index,k = iter(state, index)
if index == nil then return nil end
return k,tbl[k]
end
end
--- Iterates over a table like `pairs`, but also removes each field from the
--- table as it does so. Adding to the table while iterating is allowed, and
--- each added entry will be consumed in some future iteration.
function pairs_consume(table)
return function()
local k, v = next(table)
if k then table[k] = nil return k, v end
end
end
-- like ipairs, except it maps the value with mapfunction before returning.
function ipairs_map(tbl, mapfunction)
local iter, state, k = ipairs(tbl)
return function(state, k)
local v
k,v = iter(state, k)
if k == nil then return nil end
return k,mapfunction(v)
end, state, k
end
-- like pairs, except it maps the value with mapfunction before returning.
function pairs_map(tbl, mapfunction)
local iter, state, k = pairs(tbl)
return function(state, k)
local v
k,v = iter(state, k)
if k == nil then return nil end
return k,mapfunction(v)
end, state, k
end
-- end extra table functions
local table = table
local pairs_sortvalues = pairs_sortvalues
local ipairs_map = ipairs_map
--------------------------------------------------------------------------------
do -- containers
local function new(metatable, ...)
local tbl = {}
setmetatable(tbl, metatable)
local init = metatable.Initialize
if init then init(tbl, ...) end
return tbl
end
local function newclass(container_name)
local meta = { new = new }
meta.__index = meta
WireLib.containers[container_name] = meta
return meta
end
WireLib.containers = { new = new, newclass = newclass }
do -- class autocleanup
local autocleanup = newclass("autocleanup")
function autocleanup:Initialize(depth, parent, parentindex)
rawset(self, "depth", depth or 0)
rawset(self, "parent", parent)
rawset(self, "parentindex", parentindex)
rawset(self, "data", {})
end
function autocleanup:__index(index)
local data = rawget(self, "data")
local element = data[index]
if element then return element end
local depth = rawget(self, "depth")
if depth == 0 then return nil end
element = new(autocleanup, depth-1, self, index)
return element
end
function autocleanup:__newindex(index, value)
local data = rawget(self, "data")
local parent = rawget(self, "parent")
local parentindex = rawget(self, "parentindex")
if value ~= nil and not next(data) and parent then parent[parentindex] = self end
data[index] = value
if value == nil and not next(data) and parent then parent[parentindex] = nil end
end
function autocleanup:__pairs()
local data = rawget(self, "data")
return pairs(data)
end
pairs_ac = autocleanup.__pairs
end -- class autocleanup
end -- containers
--------------------------------------------------------------------------------
--[[ wire_addnotify: send notifications to the client
WireLib.AddNotify([ply, ]Message, Type, Duration[, Sound])
If ply is left out, the notification is sent to everyone. If Sound is left out, no sound is played.
On the client, only the local player can be notified.
]]
do
-- The following sounds can be used:
NOTIFYSOUND_NONE = 0 -- optional, default
NOTIFYSOUND_DRIP1 = 1
NOTIFYSOUND_DRIP2 = 2
NOTIFYSOUND_DRIP3 = 3
NOTIFYSOUND_DRIP4 = 4
NOTIFYSOUND_DRIP5 = 5
NOTIFYSOUND_ERROR1 = 6
NOTIFYSOUND_CONFIRM1 = 7
NOTIFYSOUND_CONFIRM2 = 8
NOTIFYSOUND_CONFIRM3 = 9
NOTIFYSOUND_CONFIRM4 = 10
if CLIENT then
local sounds = {
[NOTIFYSOUND_DRIP1 ] = "ambient/water/drip1.wav",
[NOTIFYSOUND_DRIP2 ] = "ambient/water/drip2.wav",
[NOTIFYSOUND_DRIP3 ] = "ambient/water/drip3.wav",
[NOTIFYSOUND_DRIP4 ] = "ambient/water/drip4.wav",
[NOTIFYSOUND_DRIP5 ] = "ambient/water/drip5.wav",
[NOTIFYSOUND_ERROR1 ] = "buttons/button10.wav",
[NOTIFYSOUND_CONFIRM1] = "buttons/button3.wav",
[NOTIFYSOUND_CONFIRM2] = "buttons/button14.wav",
[NOTIFYSOUND_CONFIRM3] = "buttons/button15.wav",
[NOTIFYSOUND_CONFIRM4] = "buttons/button17.wav",
}
function WireLib.AddNotify(ply, Message, Type, Duration, Sound)
if isstring(ply) then
Message, Type, Duration, Sound = ply, Message, Type, Duration
elseif ply ~= LocalPlayer() then
return
end
GAMEMODE:AddNotify(Message, Type, Duration)
if Sound and sounds[Sound] then surface.PlaySound(sounds[Sound]) end
end
net.Receive("wire_addnotify", function(netlen)
local Message = net.ReadString()
local Type = net.ReadUInt(8)
local Duration = net.ReadFloat()
local Sound = net.ReadUInt(8)
WireLib.AddNotify(LocalPlayer(), Message, Type, Duration, Sound)
end)
elseif SERVER then
NOTIFY_GENERIC = 0
NOTIFY_ERROR = 1
NOTIFY_UNDO = 2
NOTIFY_HINT = 3
NOTIFY_CLEANUP = 4
util.AddNetworkString("wire_addnotify")
function WireLib.AddNotify(ply, Message, Type, Duration, Sound)
if isstring(ply) then ply, Message, Type, Duration, Sound = nil, ply, Message, Type, Duration end
if ply and not ply:IsValid() then return end
net.Start("wire_addnotify")
net.WriteString(Message)
net.WriteUInt(Type or 0,8)
net.WriteFloat(Duration)
net.WriteUInt(Sound or 0,8)
if ply then net.Send(ply) else net.Broadcast() end
end
end
end -- wire_addnotify
--[[ wire_clienterror: displays Lua errors on the client
Usage: WireLib.ClientError("Hello", ply)
]]
if CLIENT then
net.Receive("wire_clienterror", function(netlen)
local message = net.ReadString()
print("sv: "..message)
local lines = string.Explode("\n", message)
for i,line in ipairs(lines) do
if i == 1 then
WireLib.AddNotify(line, NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1)
else
WireLib.AddNotify(line, NOTIFY_ERROR, 7)
end
end
end)
elseif SERVER then
util.AddNetworkString("wire_clienterror")
function WireLib.ClientError(message, ply)
net.Start("wire_clienterror")
net.WriteString(message)
net.Send(ply)
end
end
function WireLib.ErrorNoHalt(message)
-- ErrorNoHalt clips messages to 512 characters, so chain calls if necessary
for i=1,#message, 511 do
ErrorNoHalt(message:sub(i,i+510))
end
end
--- Generate a random version 4 UUID and return it as a string.
function WireLib.GenerateUUID()
-- It would be easier to generate this by word rather than by byte, but
-- MSVC's RAND_MAX = 0x7FFF, which means math.random(0, 0xFFFF) won't
-- return all possible values.
local bytes = {}
for i = 1, 16 do bytes[i] = math.random(0, 0xFF) end
bytes[7] = bit.bor(0x40, bit.band(bytes[7], 0x0F))
bytes[9] = bit.bor(0x80, bit.band(bytes[7], 0x3F))
return string.format("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", unpack(bytes))
end
local PERSISTENT_UUID_KEY = "WireLib.GetServerUUID"
if SERVER then
--- Return a persistent UUID associated with the server.
function WireLib.GetServerUUID()
local uuid = cookie.GetString(PERSISTENT_UUID_KEY)
if not uuid then
uuid = WireLib.GenerateUUID()
cookie.Set(PERSISTENT_UUID_KEY, uuid)
end
return uuid
end
util.AddNetworkString(PERSISTENT_UUID_KEY)
hook.Add("PlayerInitialSpawn", PERSISTENT_UUID_KEY, function(player)
net.Start(PERSISTENT_UUID_KEY)
net.WriteString(WireLib.GetServerUUID())
net.Send(player)
end)
else
local SERVER_UUID
net.Receive(PERSISTENT_UUID_KEY, function() SERVER_UUID = net.ReadString() end)
function WireLib.GetServerUUID() return SERVER_UUID end
end
--[[ wire_netmsg system
A basic framework for entities that should send newly connecting players data
Server requirements: ENT:Retransmit(ply) -- Should send all data to one player
Client requirements:
WireLib.netRegister(self) in ENT:Initialize()
ENT:Receive()
To send:
function ENT:Retransmit(ply)
WireLib.netStart(self) -- This automatically net.WriteEntity(self)'s
net.Write*...
WireLib.netEnd(ply) -- you can pass a Player or a table of players to only send to some clients, otherwise it broadcasts
end
To receive:
function ENT:Receive()
net.Read*...
end
To unregister: WireLib.netUnRegister(self) -- Happens automatically on entity removal
]]
if SERVER then
util.AddNetworkString("wire_netmsg_register")
util.AddNetworkString("wire_netmsg_registered")
function WireLib.netStart(self)
net.Start("wire_netmsg_registered")
net.WriteEntity(self)
end
function WireLib.netEnd(ply)
if ply then net.Send(ply) else net.Broadcast() end
end
net.Receive("wire_netmsg_register", function(netlen, ply)
local self = net.ReadEntity()
if IsValid(self) and self.Retransmit then self:Retransmit(ply) end
end)
elseif CLIENT then
function WireLib.netRegister(self)
net.Start("wire_netmsg_register") net.WriteEntity(self) net.SendToServer()
end
net.Receive("wire_netmsg_registered", function(netlen)
local self = net.ReadEntity()
if IsValid(self) and self.Receive then self:Receive() end
end)
end
--[[ wire_ports: client-side input/output names/types/descs
umsg format:
any number of the following:
Char start
start==0: break
start==-1: delete inputs
start==-2: delete outputs
start==-3: set eid
start==-4: connection state
start > 0:
Char amount
abs(amount)*3 strings describing name, type, desc
]]
-- Checks if the entity has wire ports.
-- Works for every entity that has wire in-/output.
-- Very important and useful for checks!
function WireLib.HasPorts(ent)
local entTbl = ent:GetTable()
if entTbl.IsWire then return true end
if entTbl.Base == "base_wire_entity" then return true end
-- Checks if the entity is in the list, it checks if the entity has self.in-/outputs too.
local In, Out = WireLib.GetPorts(ent)
if In and (entTbl.Inputs or CLIENT) then return true end
if Out and (entTbl.Outputs or CLIENT) then return true end
return false
end
if SERVER then
local INPUT,OUTPUT = 1,-1
local DELETE,PORT,LINK = 1,2,3
local ents_with_inputs = {}
local ents_with_outputs = {}
--local IOlookup = { [INPUT] = ents_with_inputs, [OUTPUT] = ents_with_outputs }
util.AddNetworkString("wire_ports")
timer.Create("Debugger.PoolTypeStrings",1,1,function()
if WireLib.Debugger and WireLib.Debugger.formatPort then
for typename,_ in pairs(WireLib.Debugger.formatPort) do util.AddNetworkString(typename) end -- Reduce bandwidth
end
end)
local queue = {}
function WireLib.GetPorts(ent)
local eid = ent:EntIndex()
return ents_with_inputs[eid], ents_with_outputs[eid]
end
function WireLib.RemoveOutPort(ent, name)
local outputs = ents_with_outputs[ent:EntIndex()]
if outputs then
for k, v in ipairs(outputs) do
if v[1] == name then
table.remove(outputs, k)
end
end
end
end
function WireLib._RemoveWire(eid, DontSend) -- To remove the inputs without to remove the entity. Very important for IsWire checks!
local hasinputs, hasoutputs = ents_with_inputs[eid], ents_with_outputs[eid]
if hasinputs or hasoutputs then
ents_with_inputs[eid] = nil
ents_with_outputs[eid] = nil
if not DontSend then
net.Start("wire_ports")
net.WriteInt(-3, 8) -- set eid
net.WriteUInt(eid, 16) -- entity id
if hasinputs then net.WriteInt(-1, 8) end -- delete inputs
if hasoutputs then net.WriteInt(-2, 8) end -- delete outputs
net.WriteInt(0, 8) -- break
net.Broadcast()
end
end
end
hook.Add("EntityRemoved", "wire_ports", function(ent)
if not ent:IsPlayer() then
WireLib._RemoveWire(ent:EntIndex())
end
end)
function WireLib._SetInputs(ent, lqueue)
local queue = lqueue or queue
local eid = ent:EntIndex()
if not ents_with_inputs[eid] then ents_with_inputs[eid] = {} end
queue[#queue+1] = { eid, DELETE, INPUT }
for Name, CurPort in pairs_sortvalues(ent.Inputs, WireLib.PortComparator) do
local entry = { Name, CurPort.Type, CurPort.Desc or "" }
ents_with_inputs[eid][#ents_with_inputs[eid]+1] = entry
queue[#queue+1] = { eid, PORT, INPUT, entry, CurPort.Num }
end
for _, CurPort in pairs_sortvalues(ent.Inputs, WireLib.PortComparator) do
WireLib._SetLink(CurPort, lqueue)
end
end
function WireLib._SetOutputs(ent, lqueue)
local queue = lqueue or queue
local eid = ent:EntIndex()
if not ents_with_outputs[eid] then ents_with_outputs[eid] = {} end
queue[#queue+1] = { eid, DELETE, OUTPUT }
for Name, CurPort in pairs_sortvalues(ent.Outputs, WireLib.PortComparator) do
local entry = { Name, CurPort.Type, CurPort.Desc or "" }
ents_with_outputs[eid][#ents_with_outputs[eid]+1] = entry
queue[#queue+1] = { eid, PORT, OUTPUT, entry, CurPort.Num }
end
end
function WireLib._SetLink(input, lqueue)
local ent = input.Entity
local num = input.Num
local state = input.SrcId and true or false
local queue = lqueue or queue
local eid = ent:EntIndex()
queue[#queue+1] = {eid, LINK, num, state}
end
local eid = 0
local numports, firstportnum, portstrings = {}, {}, {}
local function writeCurrentStrings()
-- Write the current (input or output) string information
for IO=OUTPUT,INPUT,2 do -- so, k= -1 and k= 1
if numports[IO] then
net.WriteInt(firstportnum[IO], 8) -- Control code for inputs/outputs is also the offset (the first port number we're writing over)
net.WriteUInt(numports[IO], 8) -- Send number of ports
net.WriteBit(IO==OUTPUT)
for i=1,numports[IO]*3 do net.WriteString(portstrings[IO][i] or "") end
numports[IO] = nil
end
end
end
local function writemsg(msg)
-- First write a signed int for the command code
-- Then sometimes write extra data specific to the command (type varies)
if msg[1] ~= eid then
eid = msg[1]
writeCurrentStrings() -- We're switching to talking about a different entity, lets send port information
net.WriteInt(-3,8)
net.WriteUInt(eid,16)
end
local msgtype = msg[2]
if msgtype == DELETE then
numports[msg[3]] = nil
net.WriteInt(msg[3] == INPUT and -1 or -2, 8)
elseif msgtype == PORT then
local _,_,IO,entry,num = unpack(msg)
if not numports[IO] then
firstportnum[IO] = num
numports[IO] = 0
portstrings[IO] = {}
end
local i = numports[IO]*3
portstrings[IO][i+1] = entry[1]
portstrings[IO][i+2] = entry[2]
portstrings[IO][i+3] = entry[3]
numports[IO] = numports[IO]+1
elseif msgtype == LINK then
local _,_,num,state = unpack(msg)
net.WriteInt(-4, 8)
net.WriteUInt(num, 8)
net.WriteBit(state)
end
end
local function FlushQueue(lqueue, ply)
-- Zero these two for the writemsg function
eid = 0
numports = {}
net.Start("wire_ports")
for i=1,#lqueue do
writemsg(lqueue[i])
end
writeCurrentStrings()
net.WriteInt(0,8)
if ply then net.Send(ply) else net.Broadcast() end
end
hook.Add("Think", "wire_ports", function()
if not next(queue) then return end
FlushQueue(queue)
queue = {}
end)
hook.Add("PlayerInitialSpawn", "wire_ports", function(ply)
local lqueue = {}
for eid, _ in pairs(ents_with_inputs) do
WireLib._SetInputs(Entity(eid), lqueue)
end
for eid, _ in pairs(ents_with_outputs) do
WireLib._SetOutputs(Entity(eid), lqueue)
end
FlushQueue(lqueue, ply)
end)
elseif CLIENT then
local ents_with_inputs = {}
local ents_with_outputs = {}
net.Receive("wire_ports", function(netlen)
local eid = 0
local connections = {} -- In case any cmd -4's come in before link strings
while true do
local cmd = net.ReadInt(8)
if cmd == 0 then
break
elseif cmd == -1 then
ents_with_inputs[eid] = nil
elseif cmd == -2 then
ents_with_outputs[eid] = nil
elseif cmd == -3 then
eid = net.ReadUInt(16)
elseif cmd == -4 then
connections[#connections+1] = {eid, net.ReadUInt(8), net.ReadBit() ~= 0} -- Delay this process till after the loop
elseif cmd > 0 then
local entry
local amount = net.ReadUInt(8)
if net.ReadBit() ~= 0 then
-- outputs
entry = ents_with_outputs[eid]
if not entry then
entry = {}
ents_with_outputs[eid] = entry
end
else
-- inputs
entry = ents_with_inputs[eid]
if not entry then
entry = {}
ents_with_inputs[eid] = entry
end
end
local endindex = cmd+amount-1
for i = cmd,endindex do
entry[i] = {net.ReadString(), net.ReadString(), net.ReadString()}
end
end
end
for i=1, #connections do
local eid, num, state = unpack(connections[i])
local entry = ents_with_inputs[eid]
if not entry then
entry = {}
ents_with_inputs[eid] = entry
elseif entry[num] then
entry[num][4] = state
end
end
end)
function WireLib.GetPorts(ent)
local eid = ent:EntIndex()
return ents_with_inputs[eid], ents_with_outputs[eid]
end
function WireLib._RemoveWire(eid) -- To remove the inputs without to remove the entity.
ents_with_inputs[eid] = nil
ents_with_outputs[eid] = nil
end
local flag = false
function WireLib.TestPorts()
flag = not flag
if flag then
local lasteid = 0
hook.Add("HUDPaint", "wire_ports_test", function()
local ent = LocalPlayer():GetEyeTraceNoCursor().Entity
--if not ent:IsValid() then return end
local eid = IsValid(ent) and ent:EntIndex() or lasteid
lasteid = eid
local text = "ID "..eid.."\nInputs:\n"
for _,name,tp,desc,connected in ipairs_map(ents_with_inputs[eid] or {}, unpack) do
text = text..(connected and "-" or " ")
text = text..string.format("%s (%s) [%s]\n", name, tp, desc)
end
text = text.."\nOutputs:\n"
for _,name,tp,desc in ipairs_map(ents_with_outputs[eid] or {}, unpack) do
text = text..string.format("%s (%s) [%s]\n", name, tp, desc)
end
draw.DrawText(text,"Trebuchet24",10,300,Color(255,255,255,255),0)
end)
else
hook.Remove("HUDPaint", "wire_ports_test")
end
end
end
--[[
Returns the "distance" between two strings
ie the amount of character swaps you have to do to get the first string to equal the second
Example:
levenshtein( "test", "toast" ) returns 2, because two steps: 'e' swapped to 'o', and 'a' is added
Very useful for searching algorithms
Used by custom spawn menu search & gate tool search, for example
Credits go to: http://lua-users.org/lists/lua-l/2009-07/msg00461.html
]]
function WireLib.levenshtein( s, t )
local d, sn, tn = {}, #s, #t
local byte, min = string.byte, math.min
for i = 0, sn do d[i * tn] = i end
for j = 0, tn do d[j] = j end
for i = 1, sn do
local si = byte(s, i)
for j = 1, tn do
d[i*tn+j] = min(d[(i-1)*tn+j]+1, d[i*tn+j-1]+1, d[(i-1)*tn+j-1]+(si == byte(t,j) and 0 or 1))
end
end
return d[#d]
end
--[[
nicenumber
by Divran
Adds several functions to format numbers into millions, billions, etc
Adds a function to format a number (assumed seconds) into a duration (weeks, days, hours, minutes, seconds, etc)
This is used, for example, by the wire screen.
]]
WireLib.nicenumber = {}
local nicenumber = WireLib.nicenumber
local numbers = {
{
name = "septillion",
short = "sep",
symbol = "Y",
prefix = "yotta",
zeroes = 10^24,
},
{
name = "sextillion",
short = "sex",
symbol = "Z",
prefix = "zetta",
zeroes = 10^21,
},
{
name = "quintillion",
short = "quint",
symbol = "E",
prefix = "exa",
zeroes = 10^18,
},
{
name = "quadrillion",
short = "quad",
symbol = "P",
prefix = "peta",
zeroes = 10^15,
},
{
name = "trillion",
short = "T",
symbol = "T",
prefix = "tera",
zeroes = 10^12,
},
{
name = "billion",
short = "B",
symbol = "B",
prefix = "giga",
zeroes = 10^9,
},
{
name = "million",
short = "M",
symbol = "M",
prefix = "mega",
zeroes = 10^6,
},
{
name = "thousand",
short = "K",
symbol = "K",
prefix = "kilo",
zeroes = 10^3
}
}
local one = {
name = "ones",
short = "",
symbol = "",
prefix = "",
zeroes = 1
}
-- returns a table of tables that inherit from the above info
local floor = math.floor
function nicenumber.info( n, steps )
if not n or n < 0 then return {} end
if n > 10 ^ 300 then n = 10 ^ 300 end
local t = {}
steps = steps or #numbers
local displayones = true
local cursteps = 0
for i = 1, #numbers do
local zeroes = numbers[i].zeroes
local nn = floor(n / zeroes)
if nn > 0 then
cursteps = cursteps + 1
if cursteps > steps then break end
t[#t+1] = setmetatable({value = nn},{__index = numbers[i]})
n = n % numbers[i].zeroes
displayones = false
end
end
if n >= 0 and displayones then
t[#t+1] = setmetatable({value = n},{__index = one})
end
return t
end
local sub = string.sub
-- returns string
-- example 12B 34M
function nicenumber.format( n, steps )
local t = nicenumber.info( n, steps )
steps = steps or #numbers
local str = ""
for i=1,#t do
if i > steps then break end
str = str .. t[i].value .. t[i].symbol .. " "
end
return sub( str, 1, -2 ) -- remove trailing space
end
-- returns string with decimals
-- example 12.34B
local round = math.Round
function nicenumber.formatDecimal( n, decimals )
local t = nicenumber.info( n, 1 )
decimals = decimals or 2
local largest = t[1]
if largest then
n = n / largest.zeroes
return round( n, decimals ) .. largest.symbol
else
return "0"
end
end
-------------------------
-- nicetime
-------------------------
local times = {
{ "y", 31556926 }, -- years
{ "mon", 2629743.83 }, -- months
{ "w", 604800 }, -- weeks
{ "d", 86400 }, -- days
{ "h", 3600 }, -- hours
{ "m", 60 }, -- minutes
{ "s", 1 }, -- seconds
}
function nicenumber.nicetime( n )
n = math.abs( n )
if n == 0 then return "0s" end
local prev_name = ""
local prev_val = 0
for i=1,#times do
local name = times[i][1]
local num = times[i][2]
local temp = floor(n / num)
if temp > 0 or prev_name ~= "" then
if prev_name ~= "" then
return prev_val .. prev_name .. " " .. temp .. name
else
prev_name = name
prev_val = temp
n = n % num
end
end
end
if prev_name ~= "" then
return prev_val .. prev_name
else
return "0s"
end
end
function WireLib.isnan(n)
return n ~= n
end
local isnan = WireLib.isnan
-- This function clamps the position before moving the entity
local minx, miny, minz = -16384, -16384, -16384
local maxx, maxy, maxz = 16384, 16384, 16384
local clamp = math.Clamp
function WireLib.clampPos(pos)
pos = Vector(pos)
pos.x = clamp(pos.x, minx, maxx)
pos.y = clamp(pos.y, miny, maxy)
pos.z = clamp(pos.z, minz, maxz)
return pos
end
function WireLib.setPos(ent, pos)
if isnan(pos.x) or isnan(pos.y) or isnan(pos.z) then return end
return ent:SetPos(WireLib.clampPos(pos))
end
function WireLib.setLocalPos(ent, pos)
if isnan(pos.x) or isnan(pos.y) or isnan(pos.z) then return end
return ent:SetLocalPos(WireLib.clampPos(pos))
end
function WireLib.setAng(ent, ang)
if isnan(ang.pitch) or isnan(ang.yaw) or isnan(ang.roll) then return end
return ent:SetAngles(ang)
end
function WireLib.setLocalAng(ent, ang)
if isnan(ang.pitch) or isnan(ang.yaw) or isnan(ang.roll) then return end
return ent:SetLocalAngles(ang)
end
local escapeChars = { n = "\n", r = "\r", t = "\t", ["\\"] = "\\", ["'"] = "'", ["\""] = "\"", a = "\a",
b = "\b", f = "\f", v = "\v" }
--- Replaces escape sequences with the appropriate character. Uses Lua escape sequences. Invalid sequences are skipped.
--- @param str string
function WireLib.ParseEscapes(str)
str = string_gsub(str, "\\(.?)([^\\]?[^\\]?[^\\]?[^\\]?[^\\]?[^\\]?[^\\]?}?)", function(i, arg)
if escapeChars[i] then
return escapeChars[i] .. arg
elseif i == "x" then
local num = string_match(arg, "^(%x%x)")
if not num then return false end
return string_char(tonumber(num, 16)) .. string_sub(arg, #num + 1)
elseif i >= "0" and i <= "9" then
local num = string_match(arg, "^(%d?%d?)")
if not num then return false end
local tonum = tonumber(i .. num)
return tonum < 256 and (string_char(tonum) .. string_sub(arg, #num + 1))
elseif i == "u" then
local num = string_match(arg, "^{(%x%x?%x?%x?%x?%x?)}")
if not num then return false end
local tonum = tonumber(num, 16)