-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobal
More file actions
6424 lines (5908 loc) · 260 KB
/
Copy pathGlobal
File metadata and controls
6424 lines (5908 loc) · 260 KB
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
-- ~~~~~~
-- Script by dzikakulka
-- Issues, history at: http://github.com/tjakubo2/TTS_xwing
--
-- Based on a work of: Flolania, Hera Vertigo
-- ~~~~~~
-- ~~~~~~
-- Code contributions
-- - Characted width data: Indimeco
-- - http://github.com/Indimeco/Tabletop-Simulator-Misc
-- ~~~~~~
-- Should the code execute print functions or skip them?
-- This should be set to false on every release
print_debug = true
TTS_print = print
function print(...)
if print_debug == true then
TTS_print(table.unpack({...}))
end
end
-- Vector manipulation
----#include TTS_lib/Vector/Vector
-- ~~~~~~
-- Script by dzikakulka
-- Issues, history at: http://github.com/tjakubo2/TTS_lib
--
-- Library for all vector-related operations
-- Description and usage in README.md in this lib folder in repository
-- ~~~~~~
if not package.loaded['Vector'] then
Vect = {}
package.loaded['Vector'] = Vect
-- Sum of two vectors (of any size)
Vect.Sum = function(vec1, vec2)
assert(type(vec1) == 'table', 'Vect.Sum: arg#1 not a table!')
assert(type(vec2) == 'table', 'Vect.Sum: arg#2 not a table!')
local out = {}
local k = 1
while vec1[k] ~= nil and vec2[k] ~= nil do
out[k] = vec1[k]+vec2[k]
k = k+1
end
return out
end
-- Inverse of a vector
Vect.Inverse = function(vector)
assert(type(vector) == 'table', 'Vect.Inverse: arg#1 not a table!')
local out = {}
local k = 1
while vector[k] ~= nil do
out[k] = 1/vector[k]
k = k+1
end
return out
end
-- Multiply each element of a vector by a factor
Vect.Scale = function(vector, factor)
assert(type(vector) == 'table', 'Vect.Scale: arg#1 not a table!')
assert(type(factor) == 'number', 'Vect.Scale: arg#2 not a number!')
local out = {}
local k = 1
while vector[k] ~= nil do
out[k] = vector[k]*factor
k = k+1
end
return out
end
-- Multiply each element of a vector by an element from factor vector
-- (element-wise vector multiplication)
Vect.ScaleEach = function(vector, factorVec)
assert(type(vector) == 'table', 'Vect.ScaleEach: arg#1 not a table!')
assert(type(factorVec) == 'table', 'Vect.ScaleEach: arg#2 not a table!')
local out = {}
local k = 1
while vector[k] ~= nil and factorVec[k] ~= nil do
out[k] = vector[k]*factorVec[k]
k = k+1
end
return out
end
-- Length of vector on X-Z plane (ignoring height)
Vect.Length = function(vector)
assert(type(vector) == 'table', 'Vect.Length: arg#1 not a table!')
return math.sqrt(vector[1]*vector[1] + vector[3]*vector[3])
end
-- Rotation of a 3D vector over its second element axis, arg in radians
-- Elements past 3rd are copied
Vect.RotateRad = function(vector, radRotation)
assert(type(vector) == 'table', 'Vect.RotateRad: arg#1 not a table!')
assert(type(radRotation) == 'number', 'Vect.RotateRad: arg#2 not a number!')
local newX = math.cos(radRotation) * vector[1] + math.sin(radRotation) * vector[3]
local newZ = math.sin(radRotation) * vector[1] * -1 + math.cos(radRotation) * vector[3]
local out = {newX, vector[2], newZ}
local k=4
while vector[k] ~= nil do
table.insert(out, vector[k])
k = k+1
end
return out
end
-- Distance between two points
-- Points as vectors or objects (their positions)
Vect.Distance = function(pos1, pos2)
assert(type(pos1) == 'table' or type(pos1) == 'userdata', 'Vect.Distance: arg#1 not a table/object!')
assert(type(pos2) == 'table' or type(pos2) == 'userdata', 'Vect.Distance: arg#2 not a table/object!')
if type(pos1) == 'userdata' then
pos1 = pos1.getPosition()
end
if type(pos2) == 'userdata' then
pos2 = pos2.getPosition()
end
return Vect.Length(Vect.Between(pos1, pos2))
end
-- Print vector elements
Vect.Print = function(vec, name)
assert(type(vec) == 'table', 'Vect.Print: arg#1 not a table!')
local out = '['
if name then
out = name .. ' => ' .. out
end
local k = 1
while vec[k] ~= nil do
out = out .. math.round(vec[k], 3) .. ' : '
k = k+1
end
out = out:sub(1,-3) .. ']'
print(out)
end
-- Round to decPlaces decimal places
-- if decPlaces nil round to nearest integer
math.round = function(arg, decPlaces)
if decPlaces == nil then decPlaces = 0 end
if decPlaces == 0 then
frac = arg - math.floor(arg)
if frac >= 0.5 then
return math.ceil(arg)
else
return math.floor(arg)
end
else
local mult = 10^(decPlaces or 0)
return math.floor(arg * mult + 0.5) / mult
end
end
-- Dot product
Vect.DotProd = function(vec1, vec2)
assert(type(vec1) == 'table', 'Vect.DotProd: arg#1 not a table!')
assert(type(vec2) == 'table', 'Vect.DotProd: arg#2 not a table!')
local sum = 0
local k = 1
while vec1[k] ~= nil and vec2[k] ~= nil do
sum = sum + vec1[k]*vec2[k]
k = k+1
end
return sum
end
-- Element-by-element comparison
-- Fails if length uneven
Vect.Compare = function(vec1, vec2)
assert(type(vec1) == 'table', 'Vect.Compare: arg#1 not a table!')
assert(type(vec2) == 'table', 'Vect.Compare: arg#2 not a table!')
if #vec1 ~= #vec2 then
return false
end
local k = 1
while vec1[k] ~= nil and vec2[k] ~= nil do
if vec1[k] ~= vec2[k] then
return false
end
k = k+1
end
return true
end
-- Euclidean norm
Vect.Norm = function(vec)
local selfDot = Vect.DotProd(vec, vec)
return math.sqrt(selfDot)
end
-- Convert a vector to unit vector in the same direction
-- Return zero vector for zero vector
Vect.ToUnit = function(vec)
if Vect.Norm(vec) == 0 then
return vec
end
return Vect.Scale(vec, 1/Vect.Norm(vec))
end
-- Angle between vectors in radians
-- If second argument not provided, calculate typical angle (from [1, 0, 0, ...] )
Vect.Angle = function(vec1, vec2)
if vec2 == nil then
vec2 = {1}
for k = 2, #vec1, 1 do
table.insert(vec2, 0)
end
end
return math.acos( Vect.DotProd(vec1, vec2) / (Vect.Norm(vec1)*Vect.Norm(vec2)) )
end
-- Angle between vectors in radians, in plane
-- If second argument not provided, calculate typical angle (from [1, 0, 0, ...] )
Vect.Angle2D = function(vec1, vec2)
if vec2 == nil then
vec2 = {1}
for k = 2, #vec1, 1 do
table.insert(vec2, 0)
end
end
return ( math.atan2(vec2[3], vec2[1]) - math.atan2(vec1[3], vec1[1]) )
end
-- Same as Vect.Angle but in degrees
Vect.AngleDeg = function(vec1, vec2)
return math.deg(Vect.Angle(vec1, vec2))
end
-- Same as Vect.Angle2D but in degrees
Vect.AngleDeg2D = function(vec1, vec2)
return math.deg(Vect.Angle2D(vec1, vec2))
end
-- Vector pointing from one position to another
Vect.Between = function(fromVec, toVec)
return Vect.Sum(toVec, Vect.Scale(fromVec, -1))
end
-- Vector pointing between two points
Vect.Middle = function(p1, p2)
return Vect.Sum(p1, Vect.Scale(Vect.Between(p1, p2), 0.5))
end
-- Subtract vector from another
Vect.Sub = function(vec1, vec2)
return Vect.Sum(vec1, Vect.Scale(vec2, -1))
end
-- Opposite of a vector
Vect.Opposite = function(vector)
return Vect.Scale(vector, -1)
end
-- Rotation of a 3D vector over its second element axis, arg in degrees
-- Elements past 3rd are copied
Vect.RotateDeg = function(vector, degRotation)
local radRotation = math.rad(degRotation)
return Vect.RotateRad(vector, radRotation)
end
-- Scale the vector to have set length
-- Negative "length" - opposite of set length
Vect.SetLength = function(vector, len)
return Vect.Scale(vector, len/Vect.Length(vector))
end
end
----#include TTS_lib/Vector/Vector
-- Standard libraries extentions
----#include TTS_lib/Util/Util
-- ~~~~~~
-- Script by dzikakulka
-- Issues, history at: http://github.com/tjakubo2/TTS_lib
--
-- Misc functions for extending Lua functionality
-- Description and usage in README.md in this lib folder in repository
-- ~~~~~~
if not package.loaded['Util'] then
package.loaded['Util'] = true
-- Return value limited by min and max bounds
math.clamp = function(var, min, max)
if min and var < min then
return min
elseif max and var > max then
return max
end
return var
end
-- Sign function, zero for zero
math.sgn = function(arg)
if arg < 0 then
return -1
elseif arg > 0 then
return 1
end
return 0
end
-- Round to decPlaces decimal places
-- if decPlaces nil round to nearest integer
math.round = function(arg, decPlaces)
if decPlaces == nil then decPlaces = 0 end
if decPlaces == 0 then
frac = arg - math.floor(arg)
if frac >= 0.5 then
return math.ceil(arg)
else
return math.floor(arg)
end
else
local mult = 10^(decPlaces or 0)
return math.floor(arg * mult + 0.5) / mult
end
end
-- Check if table is empty
table.empty = function(tab)
return (next(tab) == nil)
end
-- Mash together two tables
table.join = function(tab1, tab2)
local out = {}
for k=1,#tab1 do
out[k] = tab1[k]
end
local off = #tab1
for k=1,#tab2 do
out[k+off] = tab2[k]
end
return out
end
-- Shallow table copy
-- Does not include metatables
table.shallowcopy = function(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else
copy = orig
end
return copy
end
-- Deep table copy
-- Includes metatables, avoids __pairs, recursive
table.deepcopy = function(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[table.deepcopy(orig_key)] = table.deepcopy(orig_value)
end
if getmetatable(orig) then
setmetatable(copy, table.deepcopy(getmetatable(orig)))
end
else
copy = orig
end
return copy
end
-- Elements count
-- Unlike #table, also counts non-number keyed values
table.size = function(tab)
local count = 0
for _ in pairs(tab) do
count = count + 1
end
return count
end
-- Return the element that return minimal value from eval function
-- Only iterates through numeric keys part
table.min = function(tab, eval)
if not tab[1] then return end
local min = { el = tab[1], val = eval(tab[1]) }
for k=2,#tab do
local val = eval(tab[k])
if val < min.val then
min.val = val
min.el = tab[k]
end
end
return min.el, min.val
end
-- Same as table.min, but takes the maximum
table.max = function(tab, eval)
local function invEval(el)
return -1*eval(el)
end
local el, min = table.min(tab, invEval)
return el, -1*min
end
-- Return those values in tab that return true from valid function
table.sieve = function(tab, valid)
local passed = {}
local rejected = {}
for k,v in ipairs(tab) do
if valid(v) then
if type(k) == 'number' then
table.insert(passed, v)
else
passed[k] = v
end
else
if type(k) == 'number' then
table.insert(rejected, v)
else
rejected[k] = v
end
end
end
return passed, rejected
end
-- Try to find en element in the table, return key if found, nil otherwise
table.find = function(tab, el)
for k,v in pairs(tab) do
if v == el then
return k
end
end
end
-- Shallow table print
table.print = function(tab, prefix)
prefix = prefix or 'Table'
print(prefix .. ':')
local function stringify(v)
local str = tostring(v)
if type(v) == 'string' then
str = '\'' .. str .. '\''
end
return str
end
for k,v in pairs(tab) do
print(' [' .. stringify(k) .. '] -> ' .. stringify(v))
end
print('')
end
-- Deep table print (sensitive to cycles!)
table.print_r = function(tab, prefix, indent)
prefix = prefix or 'Table'
local indent = indent or 1
print(prefix .. ':')
local function stringify(v)
local str = tostring(v)
if type(v) == 'string' then
str = '\'' .. str .. '\''
end
return str
end
local indentStr = string.rep(' ', indent)
for k,v in pairs(tab) do
print(indentStr .. '[' .. stringify(k) .. '] -> ' .. stringify(v))
if type(v) == 'table' then
table.print_r(v, indentStr .. stringify(v), indent+1)
end
end
if indent == 1 then
print('')
end
end
-- Apply a function on each table element
table.process = function(tab, fcn)
local out = {}
for k,v in pairs(tab) do
out[k] = fcn(v)
end
return out
end
-- Check if string begins with the argument (no regex)
string.beginswith = function(str, prefix)
return (str:sub(1, prefix:len()) == prefix)
end
string.startswith = string.beginswith
-- Check if the string ends with the argument (no regex)
string.endswith = function(str, prefix)
return (str:sub(-1*prefix:len(), -1) == prefix)
end
-- CHeck if string contains argument anywhere in it (no regex)
string.contains = function(str, query)
return (str:find(query, 1, true) ~= nil)
end
end
----#include TTS_lib/Util/Util
-- Standard event handling
----#include TTS_lib/EventSub/EventSub
-- ~~~~~~
-- Script by dzikakulka
-- Issues, history at: http://github.com/tjakubo2/TTS_lib
--
-- Simple framework for adding many subscribers of default events (onLoad, update, onChat etc)
-- Description and usage in README.md in this lib folder in repository
-- ~~~~~~
if not package.loaded['EventSub'] then
EventSub = {}
package.loaded['EventSub'] = EventSub
event_sub = EventSub -- alias
-- Table mapping event names to table of handler functions
EventSub.subs = {}
-- Initialize subscriber table for given event function, save current one if exists
EventSub.AddEvent = function(eventName)
EventSub.subs[eventName] = {}
if type(_G[eventName]) == 'function' then
table.insert(EventSub.subs[eventName], _G[eventName])
end
-- Set the global event function to call each handler pasing its parameters
_G[eventName] = function(...)
for _,handler in ipairs(EventSub.subs[eventName]) do
handler(table.unpack({...}))
end
end
end
-- Method for adding subscribers
EventSub.Register = function(eventName, handler)
assert(type(eventName) == 'string', 'EventSub.Register: Provided event name not a string!')
assert(type(handler) == 'function', 'EventSub.Register: Provided handler not a function!')
if not EventSub.subs[eventName] then
EventSub.AddEvent(eventName)
end
table.insert(EventSub.subs[eventName], handler)
end
end
----#include TTS_lib/EventSub/EventSub
-- Object type abstraction
----#include TTS_lib/ObjType/ObjType
-- ~~~~~~
-- Script by dzikakulka
-- Issues, history at: http://github.com/tjakubo2/TTS_lib
--
-- Package for easy object "type" definitions and searching nearby things
-- Description and usage in README.md in this lib folder in repository
-- ~~~~~~
if not package.loaded['ObjType'] then
if not package.loaded['Vector'] then
error('ObjType package: depends on Vector package (not loaded)')
end
if not package.loaded['Util'] then
error('ObjType package: depends on Util package (not loaded)')
end
ObjType = {}
package.loaded['ObjType'] = ObjType
ObjType.types = {}
-- Add a type definition
ObjType.AddType = function(typeName, fcn)
ObjType.types[typeName] = fcn
end
ObjType.AddType('any', function() return true end)
-- Return true if object matches type
ObjType.IsOfType = function(obj, typeName)
if not typeName or not ObjType.types[typeName] then
error('ObjType.IsOfType: queried type \'' .. typeName .. '\' not defined')
end
return ObjType.types[typeName](obj)
end
-- Return a table of all type this object matches
ObjType.GetTypes = function(obj)
local types = {}
for type, typeFcn in pairs(ObjType.types) do
if typeFcn(obj) then
types[type] = true
end
end
return types
end
-- Cast a regular sphere and return hit objects
ObjType.SphereCast = function(center, distance)
local hits = Physics.cast({
origin = Vect.Sum(center, {0, -1.1*distance, 0}),
direction = {0, distance/500, 0},
type = 2,
size = {distance*2, distance*2, distance*2},
debug = false
})
local nearData = {}
for k, hitData in pairs(hits) do
table.insert(nearData, hitData.hit_object)
--table.insert(nearData, {obj = hitData.hit_object, dist=Vect.Distance(hitData.point, center)})
end
return nearData
end
-- Cast a box of given size and orientation and return hit objects
ObjType.BoxCast = function(center, orientation, size)
local hits = Physics.cast({
origin = Vect.Sum(center, {0, -1.1*size[2], 0}),
direction = {0, size[2]/200, 0},
type = 3,
size = size,
orientation = orientation,
debug = false
})
local nearData = {}
for k, hitData in pairs(hits) do
table.insert(nearData, hitData.hit_object)
--table.insert(nearData, {obj = hitData.hit_object, dist=Vect.Distance(hitData.point, center)})
end
return nearData
end
-- Get the object matching provided type, nearest to position/object in some radius
-- Args:
-- centerPosObj <- Center position (vector) or object
-- maxDist <- Max distance to check in
-- objType <- Required type of the nearest object
-- excl <- Table of objects excluded from search
-- Return: nearestObject, distance
ObjType.GetNearestOfType = function(centerPosObj, maxDist, objType, excl)
local centerPos = centerPosObj
if type(centerPosObj) == 'userdata' then
excl[centerPosObj] = true
centerPos = centerPosObj.getPosition()
end
local nearOfType = ObjType.GetNearOfType(centerPos, objType, maxDist, excl)
return table.min(nearOfType, function(obj) return Vect.Distance(cenerPos, obj) end)
end
-- Get all objects in given radius matching given type
-- Args identical like in ObjType.GetNearestOfType
-- Return: table of objects
ObjType.GetNearOfType = function(centerPosObj, maxDist, objType, excl)
excl = excl or {}
for k,v in ipairs(excl) do
excl[v] = true
excl[k] = nil
end
maxDist = maxDist or 100
assert(type(objType) == 'string', 'Obj.GetNearOfType: search type not provided')
local centerPos = centerPosObj
if type(centerPosObj) == 'userdata' then
excl[centerPosObj] = true
centerPos = centerPosObj.getPosition()
end
local nearData = ObjType.SphereCast(centerPos, maxDist)
nearData = table.sieve(nearData, function(obj) return (not excl[obj] and ObjType.IsOfType(obj, objType)) end)
return nearData
end
-- Get the all objects inside a box matching given type
-- Args:
-- centerPosObj <- Center position (vector) or object
-- orient <- Box orientation (vector)
-- size <- Box size (vector)
-- objType <- Required type of the nearest object
-- excl <- Table of objects excluded from search
-- Return: table of objects
ObjType.GetBoxOfType = function(centerPosObj, orient, size, objType, excl)
excl = excl or {}
for k,v in ipairs(excl) do
excl[v] = true
excl[k] = nil
end
assert(type(objType) == 'string', 'Obj.GetNearOfType: search type not provided')
local centerPos = centerPosObj
if type(centerPosObj) == 'userdata' then
excl[centerPosObj] = true
centerPos = centerPosObj.getPosition()
end
local boxData = ObjType.BoxCast(centerPos, orient, size)
boxData = table.sieve(boxData, function(obj) return (not excl[obj] and ObjType.IsOfType(obj, objType)) end)
return boxData
end
end
----#include TTS_lib/ObjType/ObjType
-- Save/load management
----#include TTS_lib/SaveManager/SaveManager
if not package.loaded['SaveManager'] then
-- Require EventSub so we can hook into onLoad
if not package.loaded['EventSub'] then
error('SaveManager package: depends on EventSub package (not loaded)')
end
local ES = package.loaded['EventSub']
SaveManager = {}
package.loaded['SaveManager'] = SaveManager
SaveManager.moduleList = {}
SaveManager.Register = function(key, saveFcn, restoreFcn)
assert(type(key) == 'string', 'SaveManager.Register: No table key provided!')
assert(type(saveFcn) == 'function', 'SaveManager.Register: No save function provided!')
assert(type(restoreFcn) == 'function', 'SaveManager.Register: No restore function provided!')
if SaveManager.moduleList[key] then
error('SaveManager.Register: Key \'' .. key .. '\' already reserved!')
end
SaveManager.moduleList[key] = {save = saveFcn, restore = restoreFcn}
end
SaveManager.onLoad = function(saveData)
local saveTable = SaveManager.Decode(saveData)
if type(saveTable) ~= 'table' then print('skip') return end
local responses = {}
for key,module in pairs(SaveManager.moduleList) do
if saveTable[key] and (not table.empty(saveTable[key]) ) then
local response = module.restore(saveTable[key])
if type(response) == 'string' then
table.insert(responses, response)
end
end
end
if not table.empty(responses) then
table.insert(responses, 1, 'Attempting to restore state...')
end
SaveManager.Notify(responses)
end
ES.Register('onLoad', SaveManager.onLoad)
if type(onSave) == 'function' then
error('SaveManager: onSave event trigger already defined!')
end
function onSave()
local saveData = {}
for key,module in pairs(SaveManager.moduleList) do
local moduleSave = module.save()
if type(moduleSave) == 'table' and (not table.empty(moduleSave)) then
saveData[key] = moduleSave
end
end
return SaveManager.Encode(saveData)
end
SaveManager.Encode = function(dataTable)
return JSON.encode(dataTable)
end
SaveManager.Decode = function(encodedData)
return JSON.decode(encodedData)
end
SaveManager.Notify = function(responses)
if not table.empty(responses) then
printToAll(table.concat(responses, '\n'), {0.8, 0.1, 0.8})
end
end
end
----#include TTS_lib/SaveManager/SaveManager
-- Component sizes, unit conversion methods
----#include TTS_xwing/src/Dimensions
-- ~~~~~~
-- Script by dzikakulka
-- Issues, history at: http://github.com/tjakubo2/TTS_xwing
--
-- X-Wing related measurements for TTS
-- ~~~~~~
-- 40mm = 1.445igu
-- (s1 length / small base size)
-- 1mm = 0.036125igu
mm_igu_ratio = 0.036125
-- Milimeter dimensions of ship bases
mm_smallBase = 40
mm_mediumBase = 60
mm_largeBase = 80
mm_baseSize = {}
mm_baseSize.small = 40
mm_baseSize.smallBase = 40
mm_baseSize.medium = 60
mm_baseSize.mediumBase = 60
mm_baseSize.large = 80
mm_baseSize.largeBase = 80
-- Milimeter dimensions for cards
mm_upgrade_width = 41
mm_upgrade_height = 63
mm_pilot_width = 63.5
mm_pilot_height = 88
mm_cardSize = {}
mm_cardSize.upgrade = {width = 41, height = 63}
mm_cardSize.pilot = {width = 63.5, height = 88}
-- Milimeter dimension for dial cards
mm_dialSize = 54
-- Convert argument from MILIMETERS to IN-GAME UNITS
function Convert_mm_igu(milimeters)
return milimeters*mm_igu_ratio
end
-- Convert argument from IN-GAME UNITS to MILIMETERS
function Convert_igu_mm(in_game_units)
return in_game_units/mm_igu_ratio
end
----#include TTS_xwing/src/Dimensions
-- Data on ship types, sizes etc.
----#include TTS_xwing/src/ModelDB
-- ~~~~~~
-- Script by dzikakulka
-- Issues, history at: http://github.com/tjakubo2/TTS_xwing
--
-- Database for recognizing TTS figurines as X-Wing ships
-- ~~~~~~
ModelDB = {}
-- Get an SSL-invariant version of a link
ModelDB.RectifyLink = function(link)
return link:gsub('https', 'http')
end
-- Save model data on the object itself
ModelDB.SaveData = function(data, obj)
obj.setTable('__ModelDB_data', data)
end
-- Load data from an object
ModelDB.LoadData = function(obj)
return obj.getTable('__ModelDB_data')
end
-- List of ships we warned about being unrocognized in the script
ModelDB.warnList = {}
-- Warn user that this model is outsourced or unrecognized for some other reason
ModelDB.UnrecognizedWarn = function(model)
if not ModelDB.warnList[model] then
broadcastToAll(model.getName() .. '\'s model not recognized - use LGS in name if large base and contact author about the issue', {1, 0.1, 0.1})
ModelDB.warnList[model] = true
end
end
-- Get the data about on object (ship model)
-- Return: {
-- arcType <- 'P' (primary only) / 'T' (primary turret) / 'R' (aux rear) / 'S' (aux side) / 'M' (mobile)
-- type <- ship type name (e.g. 'TIE Phantom'), for faction-variant ships faction name is added (e.g. 'Y-Wing Scum')
-- faction <- 'Rebel' / 'Scum' / 'Imperial'
-- baseSize <- 'large' / 'small'
-- }
-- Return empty table when ship unrecognized
-- After finding the data once it is saved on the object to speed up future calls
ModelDB.GetData = function(model)
local saved = ModelDB.LoadData(model)
if saved then
return saved
end
local modelMesh = ModelDB.RectifyLink(model.getCustomObject().mesh)
for faction, l1 in pairs(ModelDB.data) do
for baseSize, l2 in pairs(l1) do
for type, entry in pairs(l2) do
for _,mesh in pairs(entry.meshes) do
if ModelDB.RectifyLink(mesh) == modelMesh then
local out = table.shallowcopy(entry)
out.meshes = nil
out.type = type
out.faction = faction
out.baseSize = baseSize
local collData = ModelDB.colliders[baseSize]
local collLink = ModelDB.RectifyLink(model.getCustomObject().collider)
for collType, collSet in pairs(collData) do
if table.find(collSet, collLink) then
out.collider = collType
break
end
end
out.collider = out.collider or 'unknown'
ModelDB.SaveData(out, model)
return out
end
end
end
end
end
ModelDB.UnrecognizedWarn(model)
return {}
end
-- Callable version of the ModelDB.GetData()
function API_ModelDB_GetData(arg)
local model = arg
if type(arg) == 'table' then
model = arg[1] or arg.obj or arg.model
end
return ModelDB.GetData(model)
end
ModelDB.SetCollider = function(model, type)
local data = ModelDB.GetData(model)
if not data.baseSize or (data.collider == type) then
return
end
local custom = model.getCustomObject()
custom.collider = ModelDB.colliders[data.baseSize][type][1]
model.setCustomObject(custom)
return model.reload()
end
function API_ModelDB_SetCollider(args)
return ModelDB.SetCollider(table.unpack(args))
end
ModelDB.colliders = {
['small'] = {
['full'] = {'http://cloud-3.steamusercontent.com/ugc/856097073971964332/9FA07C37B1615A416F306081D9152902A9BFE9EE/'},
['box'] = {'http://cloud-3.steamusercontent.com/ugc/82591194029068301/41D4D10265D8B4B9FC1B0C640F9F8D94C816CE89/'}
},
['medium'] = {
['full'] = {'http://cloud-3.steamusercontent.com/ugc/910171138480725070/8C8491BD45C04862AF39EA80AD45C3B12984F157/'},
['box'] = {'http://cloud-3.steamusercontent.com/ugc/910171138480721745/24224D6392DD29B35FF017FD4A5D2459A9E66652/'}
},
['large'] = {
['full'] = {'http://cloud-3.steamusercontent.com/ugc/909045930378567212/D07FE8989663A82E41F61A774DCCE5BD111B3492/'},
['box'] = {'http://cloud-3.steamusercontent.com/ugc/909045930378581594/0DB3DD458E4F44A1FDC062470957B67878BA4CCB/'}
}
}
boxCollider = {
['small'] = 'http://cloud-3.steamusercontent.com/ugc/82591194029068301/41D4D10265D8B4B9FC1B0C640F9F8D94C816CE89/',
['medium'] = 'http://cloud-3.steamusercontent.com/ugc/910171138480721745/24224D6392DD29B35FF017FD4A5D2459A9E66652/',
['large'] = 'http://cloud-3.steamusercontent.com/ugc/909045930378581594/0DB3DD458E4F44A1FDC062470957B67878BA4CCB/'
}
fullCollider = {
['small'] = 'http://cloud-3.steamusercontent.com/ugc/856097073971964332/9FA07C37B1615A416F306081D9152902A9BFE9EE/',
['medium'] = 'http://cloud-3.steamusercontent.com/ugc/910171138480725070/8C8491BD45C04862AF39EA80AD45C3B12984F157/',
['large'] = 'http://cloud-3.steamusercontent.com/ugc/909045930378567212/D07FE8989663A82E41F61A774DCCE5BD111B3492/'
}
-- Ship data
-- First level: tables keyed by faction name
-- Second level: tables keyed by ship size
-- Third level: entries keyed by ship type
-- Entry: {
-- arcType: 'P' (primary only) / 'T' (turret) / 'R' (rear aux) / 'S' (side aux) / 'M' (mobile)
-- }
ModelDB.data = {
['Rebel'] = {
['small'] = {
['X-Wing'] = {
arcType = 'B',
meshes = {'https://paste.ee/r/54FLC', 'http://cloud-3.steamusercontent.com/ugc/918052948360433857/8A34F442252CAB28DA35B0AC1A71727619EE0160/'} },
['Y-Wing Rebel'] = {
arcType = 'B',
meshes = {'https://paste.ee/r/8CtXr','http://cloud-3.steamusercontent.com/ugc/916925021436403067/6A63EB9F88F19CD9FBF054819F8CF48B3EDA7F8D/'} },
['A-Wing'] = {
arcType = 'B',
meshes = {'https://paste.ee/r/8CtXr', 'http://cloud-3.steamusercontent.com/ugc/916924876572358861/60ED8B33063D8B2B5839F73349BA90B86FEEDE5C/'} },
['B-Wing'] = {
arcType = 'B',
meshes = {'https://paste.ee/r/8CtXr', 'http://cloud-3.steamusercontent.com/ugc/918052678140240779/168ECD873CB31974AEBD28FDDED1EDAEA536BE07/'} },
['HWK-290 Rebel'] = {
arcType = 'B',
meshes = {'https://paste.ee/r/MySkn', 'http://cloud-3.steamusercontent.com/ugc/918052832513487328/69315DA5CA41137CD71B3C6F0A099D6E882D1B53/'} },
['Attack Shuttle'] = {
arcType = 'B',
meshes = {'https://paste.ee/r/jrwRJ', 'http://cloud-3.steamusercontent.com/ugc/82591194029086137/2D8471654F7BA70A5B65BB3A5DC4EB6CBE8F7C1C/'} },
['E-Wing'] = {
arcType = 'B',
meshes = {'http://cloud-3.steamusercontent.com/ugc/919177944211462889/6EC124B3D284A43AFBC0E771882BC11FC72CBD19/'} },
['Z-95 Headhunter Rebel'] = {