-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmodmain.lua
3989 lines (3300 loc) · 126 KB
/
modmain.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
--[[
Copyright (C) 2020, 2021 penguin0616
This file is part of Insight.
The source code of this program is shared under the RECEX
SHARED SOURCE LICENSE (version 1.0).
The source code is shared for referrence and academic purposes
with the hope that people can read and learn from it. This is not
Free and Open Source software, and code is not redistributable
without permission of the author. Read the RECEX SHARED
SOURCE LICENSE for details
The source codes does not come with any warranty including
the implied warranty of merchandise.
You should have received a copy of the RECEX SHARED SOURCE
LICENSE in the form of a LICENSE file in the root of the source
directory. If not, please refer to
<https://raw.githubusercontent.com/Recex/Licenses/master/SharedSourceLicense/LICENSE.txt>
]]
---------------------------------------
-- Main script of the mod.
-- @module modmain
-- @author penguin0616
-- modify environment to inherit from klei's environment as a fallback
-- __newindex is left blank so all declarations are in our new environment
-- normally I'd just keep __index directly set to klei's environment,
-- but the mods loader assumes that unassigned variables won't error
-- so i have to tweak __index more than I want to, though ideally I would avoid it to avoid another unoptimization
do
-- ds/scripts/strict.lua is why _G stuff keeps being rude
-- get that sweet sweet local optimization
local GLOBAL = GLOBAL
local modEnv = GLOBAL.getfenv(1)
local rawget, setmetatable = GLOBAL.rawget, GLOBAL.setmetatable
setmetatable(modEnv, {
__index = function(self, index)
return rawget(GLOBAL, index)
end
})
_G = GLOBAL
end
local _string, xpcall, package, tostring, print, os, unpack, require, getfenv, setmetatable, next, assert, tonumber, io, rawequal, collectgarbage, getmetatable, module, rawset, math, debug, pcall, table, newproxy, type, coroutine, _G, select, gcinfo, pairs, rawget, loadstring, ipairs, _VERSION, dofile, setfenv, load, error, loadfile = string, xpcall, package, tostring, print, os, unpack, require, getfenv, setmetatable, next, assert, tonumber, io, rawequal, collectgarbage, getmetatable, module, rawset, math, debug, pcall, table, newproxy, type, coroutine, _G, select, gcinfo, pairs, rawget, loadstring, ipairs, _VERSION, dofile, setfenv, load, error, loadfile
local TheInput, TheInputProxy, TheGameService, TheShard, TheNet, FontManager, PostProcessor, TheItems, EnvelopeManager, TheRawImgui, ShadowManager, TheSystemService, TheInventory, MapLayerManager, RoadManager, TheLeaderboards, TheSim = TheInput, TheInputProxy, TheGameService, TheShard, TheNet, FontManager, PostProcessor, TheItems, EnvelopeManager, TheRawImgui, ShadowManager, TheSystemService, TheInventory, MapLayerManager, RoadManager, TheLeaderboards, TheSim
--[[
DEFAULTFONT = "opensans"
DIALOGFONT = "opensans"
TITLEFONT = "bp100"
UIFONT = "bp50"
BUTTONFONT = "buttonfont"
NEWFONT = "spirequal"
NEWFONT_SMALL = "spirequal_small"
NEWFONT_OUTLINE = "spirequal_outline"
NEWFONT_OUTLINE_SMALL = "spirequal_outline_small"
NUMBERFONT = "stint-ucr"
TALKINGFONT = "talkingfont"
TALKINGFONT_WORMWOOD = "talkingfont_wormwood"
TALKINGFONT_HERMIT = "talkingfont_hermit"
CHATFONT = "bellefair"
HEADERFONT = "hammerhead"
CHATFONT_OUTLINE = "bellefair_outline"
SMALLNUMBERFONT = "stint-small"
BODYTEXTFONT = "stint-ucr"
CODEFONT = "ptmono"
--]]
-- Mod table
local Insight = {
env = getfenv(1),
kramped = {
values = {},
players = {},
},
active_hunts = {},
descriptors = {}, -- 130 descriptors as of April 17, 2021
prefab_descriptors = {},
post_inits = {
describe = {},
prefab_describe = {}
},
COLORS = {
-- stats
HUNGER = "#DEB639",
SANITY = "#C67823",
HEALTH = "#A22B23",
ENLIGHTENMENT = "#ACC5C3",
AGE = "#714E85", -- age meter
MIGHTINESS = "#0B704A",
INSPIRATION = "#6F3483", -- from the inspiration meter
-- mechanic
LIGHT = "#CCBC78", -- light tab icon
--DAMAGE = "#AAA79F", --"#C7C7C7", -- fight tab sword
-- nature
POND = "#344147", -- pond water,
WET = "#95BFF2", -- just converted constants.lua -> WET_TEXT_COLOR to hex
SHALLOWS = "#66A570", -- shallows in SW
NATURE = "#9BD554", --"#8BA94B", -- palm tree
-- took these time ones from the clock
DAY_BRIGHT = "#FDD356",
DAY_DARK = "#BF9F41",
DUSK_BRIGHT = "#A55B52",
DUSK_DARK = "#7B433D",
NIGHT_BRIGHT = "#4A546B",
NIGHT_DARK = "#7B433D",
-- foods
MEAT = "#955D70", -- meat icon
MONSTER = "#7D4381", -- monster meat icon
FISH = "#727A8D", -- fish icon
VEGGIE = "#BF8801", -- pumpkin icon
FRUIT = "#9A3035", -- pomegranite (whole) icon
EGG = "#E4CFA5", -- egg icon
SWEETENER = "#DDA305", -- honeycomb
FROZEN = "#A3C3DF", -- ice icon
FAT = "#AF774D", -- literally only butter (and coconuts)
DAIRY = "#A3C3DF", -- FROZEN; --"#EFF9EC", -- electric milk icon; ok this is indistinguishable
DECORATION = "#8C4041", -- literally only butterfly wings
MAGIC = "#9864F5", -- only mandrake. but they don't look magical, so royal purple it is.
PRECOOK = "#ffffff", -- yep.
DRIED = "#ffffff", -- yep.
INEDIBLE = "#614A24", -- coconut
BUG = "#804E32", -- bean bug
SEED = "#8EA152", -- birchnut
ANTIHISTAMINE = "#9CCFBD", -- inner light blue from cutnettle
-- mob
FEATHER = "#331D43", -- black feather
FROG = "#69725C",
-- misc
ROYAL_PURPLE = "#6225D1", -- r
LIGHT_PINK = "#ffb6c1",
CAMO = "#4D6B43",
MOB_SPAWN = "#ee6666",
BLACK = "#2f3e49", -- #1b2a35 was the original intent, but needed to be lighter. so I bumped it up by 20 on r,g,b.
PLANAR = "#b079e8", -- -- darker #b079e8, lighter #c99cf7
LUNAR_ALIGNED = "#5ADFAD", -- Got from the bright edge of the lunar rift icon
SHADOW_ALIGNED = "#DD2C31", -- This was originally "#9C2C31", but I made it more intense because it looked too similar to HEALTH on wigfrid's lunar/shadow songs.
PERCENT_GOOD = "#66cc00",
PERCENT_BAD = "#dd5555",
},
ENTITY_INFORMATION_FLAGS = {
RAW = 1,
FROM_INSPECTION = 2,
IGNORE_WORLDLY = 4,
},
HOT_RELOAD_FNS = {},
}
-- Provide to Global
_G.Insight = Insight
-- miscellaneous debug stuff
MyKleiID = "KU_md6wbcj2"
WORKSHOP_ID_DS = "workshop-2081254154"
WORKSHOP_ID_DST = "workshop-2189004162"
-- declarations or module loading
DEBUG_ENABLED = (
TheSim:GetGameID() == "DST" and (
TheNet:GetUserID() == MyKleiID or -- me
TheNet:GetUserID() == "OU_76561198277438128" or
false --TheNet:GetUserID() == "KU_or9kA0Ka"
) and true)
or TheSim:GetGameID() == "DS" and (
TheSim:GetUserID() == "317172400@steam" -- steamid32
)
or GetModConfigData("DEBUG_ENABLED", true) or false
DEBUG_OPTIONS = {
INSIGHT_MENU_DATA_ORIGIN = false,
SHOW_INFO_ORIGIN = false,
}
ALLOW_SERVER_DEBUGGING = DEBUG_ENABLED -- todo make a more accessible for standard users with mod compatibility issues?
if DEBUG_ENABLED then
_G.ENCODE_SAVES = false
end
if TheSim:GetGameID() == "DS" then
print = nolineprint
end
if false and DEBUG_ENABLED and (TheSim:GetGameID() == "DS" or false) then
Print(VERBOSITY.DEBUG, "hello world 1")
_G.VERBOSITY_LEVEL = VERBOSITY.DEBUG
print("INSIGHT - GAME VERBOSITY_LEVEL:", _G.VERBOSITY_LEVEL)
Print(VERBOSITY.DEBUG, "hello world 2")
end
string = setmetatable({}, {__index = function(self, index) local x = _G.string[index]; rawset(self, index, x); return x; end})
import = kleiloadlua(MODROOT .. "scripts/import.lua")()
Time = import("time")
Color = import("helpers/color")
rpcNetwork = import("rpcnetwork")
attackRangeHelper = import("helpers/attack_range")
entity_tracker = import("helpers/entitytracker")
TRACK_INFORMATION_REQUESTS = DEBUG_ENABLED and false
DEBUG_SHOW_NOTIMPLEMENTED_MODDED = false
-- maybe one day i'll do something 64-bit specific or something
is64bit = #tostring{}:match("(%w+)$") == 16
is32bit = not is64bit
local player_contexts = {}
local mod_component_cache = {}
local log_buffer = ""
local LOG_LIMIT = 0700000 -- 0.7 million
local SERVER_OWNER_HAS_OPTED_IN = false
local descriptors_ignore = {
--"mapiconhandler", -- this is just from a mod i use :^)
"obsidiantool", -- might be worth looking into more, but I got the damage buff accounted for in weapon.lua, so I don't see a need to do more with this
"bloomable", -- hamlet trees
"fixable", -- hamlet pig houses
"lootdropper", "periodicspawner", "shearable", "mystery", "freezable", -- may be interesting looking into
"thief", "characterspecific", "resurrector", "rideable", "mood", "thrower", "windproofer", "creatureprox", "groundpounder", "prototyper", -- maybe interesting looking into
"worldsettings", "piratespawner", "dockmanager", "undertile", "cursable", "battery", "batteryuser", "dataanalyzer", "upgrademoduleowner", -- may be interesting looking into
"craftingstation", "ruinsshadelingspawner",
--notable
"bundlemaker", --used in bundling wrap before items
"inventoryitem", "moisturelistener", "stackable", "cookable", "bait", "blowinwind", "blowinwindgust", "floatable", "selfstacker", -- don't care
"dryable", "highlight", "cooker", "lighter", "instrument", "poisonhealer", "trader", "smotherer", "knownlocations", "occupier", "talker", -- don't care
"named", "activatable", "transformer", "deployable", "upgrader", "playerprox", "rowboatwakespawner", "plantable", "waveobstacle", -- don't care
"fader", "lighttweener", "sleepingbag", "machine", "floodable", "firedetector", "heater", "tiletracker", "payable", "useableitem", "drawable", "shaver", -- don't care
"gridnudger", "entitytracker", "appeasable", "currency", "mateable", "sizetweener", "saltlicker", "sinkable", "sticker", "projectile", "hiddendanger", "deciduoustreeupdater", -- don't care
"geyserfx", "blinkstaff", "scaler", -- don't care,
-- Worldly DS stuff
"ambientsoundmixer", "globalcolourmodifier", "moisturemanager", "inventorymoisture", -- world
"optionswatcher", "giantgrubspawner", "flowerspawner_rainforest", "interiorspawner", "periodicpoopmanager", "roottrunkinventory", "bramblemanager", "canopymanager", "ripplemanager", "cloudpuffmanager", "shadowmanager", -- world (hamlet)
"economy", "cityalarms", "banditmanager", "quaker_interior", "glowflyspawner", -- world (hamlet) (might be interesting)
"nightmareambientsoundmixer", --gamelogic
"colourcubemanager", "seasonmanager", "bigfooter", "flowerspawner", "doydoyspawner", "debugger", "rainbowjellymigration", "globalsettings", "flooding", "mosquitospawner", -- specific world types
"volcanoambience", "volcanowave", "whalehunter", -- specific world types
-- now for DST stuff
"wardrobe", "plantregrowth", "bloomer", "drownable", "embarker", "inventoryitemmoisture", "playeravatardata", "petleash", "giftreceiver", -- may be interesting looking into
"grogginess", "workmultiplier", "aura", "writeable", "shaveable", "spidermutator", "raindome", "acidinfusible", "decoratedgrave_ghostmanager", -- may be interesting looking into
"resistance", -- for the armor blocking of bone armor
"playerinspectable", "playeractionpicker", "playervision", "pinnable", "playercontroller", "playervoter", "singingshelltrigger", "tackler", "sleepingbaguser", "skinner", "playermetrics",-- from mousing over player
"sheltered", "grue", "wisecracker", "constructionbuilder", "playerlightningtarget", "rider", "distancetracker", "frostybreather", "foodaffinity", "stormwatcher", "areaaware", "age", "steeringwheeluser", -- from mousing over player
"touchstonetracker", "constructionbuilderuidata", "birdattractor", "attuner", "builder", "bundler", "carefulwalker", "catcher", "colouradder", "colourtweener", "inkable", "walkingplankuser", -- from mousing over player
"sandstormwatcher", "reader", "plantregistryupdater", "moonstormwatcher", "hudindicatable", "cookbookupdater", "wereeater", -- from mousing over player
"hauntable", "savedrotation", "halloweenmoonmutable", "storytellingprop", "floater", "spawnfader", "transparentonsanity", "beefalometrics", "uniqueid", "reticule", -- don't care
"complexprojectile", "shedder", "disappears", "shelf", "maprevealable", "winter_treeseed", "summoningitem", "portablestructure", "deployhelper", -- don't care
"symbolswapdata", "amphibiouscreature", "gingerbreadhunt", "nutrients_visual_manager", "vase", "vasedecoration", "murderable", "poppable", "balloonmaker", "heavyobstaclephysics", -- don't care
"markable_proxy", "saved_scale", "gingerbreadhunter", "bedazzlement", "bedazzler", "anchor", "distancefade", "pocketwatch_dismantler", "carnivalevent", "heavyobstacleusetarget", -- don't care
"cattoy", "updatelooper", "upgrademoduleremover", "hudindicatablemanager", "moonstormlightningmanager", "playerhearing", "walkableplatformplayer", "hudindicatorwatcher", "seamlessplayerswapper", -- don't care
"boatcannonuser", "stageactor", "boatdrifter", "boatphysics", "boatring", "boatringdata", "healthsyncer", "hull", "hullhealth", "walkableplatform", "teleportedoverride", -- don't care
"npc_talker", "simplemagicgrower", "moonaltarlink", "farmtiller", "aoespell", "aoetargeting", "closeinspector", "waxable", "rainimmunity", "snowmandecor", -- don't care
"forgerepairable", "boatpatch", "submersible", "erasablepaper", "lunarplant_tentacle_weapon", "nightlightmanager", "clientpickupsoundsuppressor", -- don't care
"linkeditemmanager", "nightlightmanager", -- don't care
-- NEW:
"farmplanttendable", "plantresearchable", "fertilizerresearchable", "yotb_stagemanager",
-- TheWorld
"worldstate", "groundcreep", "skeletonsweeper", "uniqueprefabids", "ocean", "oceancolor", "sisturnregistry", "singingshellmanager",
-- Forest & Caves
"yotc_raceprizemanager", "shadowhandspawner", "desolationspawner", "ambientlighting", "worldoverseer", "forestresourcespawner", "shadowcreaturespawner", "chessunlocks", "feasts",
"regrowthmanager", "townportalregistry", "hallucinations", "dsp", "dynamicmusic",
-- Forest
"squidspawner", "moosespawner", "birdspawner", "worldwind", "retrofitforestmap_anr", "deerherdspawner", "deerherding", "wildfires", "brightmarespawner",
"sandstorms", "forestpetrification", "penguinspawner", "sharklistener", "frograin", "waterphysics", "butterflyspawner", "worldmeteorshower",
"worlddeciduoustreeupdater", "schoolspawner", "specialeventsetup", "playerspawner", "walkableplatformmanager", "lureplantspawner", "wavemanager",
-- Caves
"retrofitcavemap_anr", "caveins", "grottowaterfallsoundcontroller", "grottowarmanager", "archivemanager", "miasmamanager",
-- Misc
"ambientsound", -- forest, caves, forge, gorge
"colourcube", -- forest, caves, forge, gorge
-- Network/Shard AAAAAAAAAAAAAAAAAAAAAh
-- prefab world_network
--"caveweather", "quaker", "nightmareclock" -- Caves (Network)
--"weather",
--"caveweather",
"shardstate", -- idk
"worldreset", -- when no one left alive
"seasons", -- seasons
"worldtemperature", -- world temperature
"clock", -- clock
"autosaver", -- autosaver
"worldvoter", -- idc to look enough into
}
-- i don't want datadumper saving the metatable
--[[
_modinfo = deepcopy(modinfo)
setmetatable(_modinfo.configuration_options, {
__index = function(self, index)
for k,v in pairs(self) do
if v.name == index then
return v
end
end
end
})
for i,v in pairs(_modinfo.configuration_options) do
setmetatable(v.options, {
__index = function(self, index)
for k,v in pairs(self) do
if v.description == index then
return v
end
end
end
})
end
--]]
--================================================================================================================================================================--
--= Functions ====================================================================================================================================================--
--================================================================================================================================================================--
--- Checks whether we are in DS.
---@return boolean
function IsDS()
return TheSim:GetGameID() == "DS"
end
IS_DS = IsDS()
--- Checks whether we are in DST.
---@return boolean
function IsDST()
return TheSim:GetGameID() == "DST"
end
IS_DST = IsDST()
--- Checks whether the mod is running on a client
---@return boolean
function IsClient()
return IS_DST and TheNet:GetIsClient()
end
IS_CLIENT = IsClient()
--- Checks whether the mod is running on a dedicated server
-- This is basically (IsClient() or IsClientHost())
---@return boolean
function IsDedicated()
return IS_DST and TheNet:IsDedicated()
end
IS_DEDICATED = IsDedicated()
--- Checks whether the mod is running on a client that is also the host.
---@return boolean
function IsClientHost()
return IS_DST and TheNet:IsDedicated() == false and TheNet:GetIsMasterSimulation() == true
--return IS_DST and TheNet:IsDedicated() == false and TheWorld.ismastersim == true
end
IS_CLIENT_HOST = IsClientHost()
--- Checks whether the mod is running on something that has full game control. Essentially anything in DS and worlds in DST where you are the host.
---@return boolean
function IsExecutiveAuthority()
return TheSim:GetGameID() == "DS" or TheNet:GetIsMasterSimulation() == true
end
IS_EXECUTIVE_AUTHORITY = IsExecutiveAuthority()
--- Checks whether the mod is running in The Forge.
---@return boolean
function IsForge()
return IS_DST and TheNet:GetDefaultGameMode() == "lavaarena"
end
IS_FORGE = IsForge()
--- Checks if argument is a widget.
---@param arg
---@return boolean
function IsWidget(arg)
return arg and arg.inst and arg.inst.widget and true
end
--- Checks if argument is a prefab.
---@param arg
---@return boolean
function IsPrefab(arg)
return type(arg) == 'table' and arg.GUID and arg.prefab and true
end
--- Return player's Insight component or replica, depending on what side we're running on.
---@param player EntityScript
---@return Insight|nil
function GetInsight(player)
if IS_EXECUTIVE_AUTHORITY then
return player.components.insight
else
return player.replica.insight
end
end
function GetLocalInsight(player)
if IS_DS then
return player.components.insight
else
return player.replica.insight
end
end
--- Returns player's insight context.
---@param player EntityScript
---@return table|nil @Wrapper of player's context
function GetPlayerContext(player)
if not IsPrefab(player) then
error("[Insight]: GetPlayerContext called on non-player")
end
local context
if IS_DST and TheWorld.ismastersim then
-- i know we'll have it
context = player_contexts[player]
else
-- will be the only context
context = player_contexts[player]
end
if context then
return setmetatable({ FROM_INSPECTION=false }, { __index=context })
end
--return context
end
function ValidateComplexConfiguration(player, complex_config_table)
for name, config in pairs(modinfo.complex_configuration_options) do
local val = complex_config_table[name]
if config.type == "listbox" then
if type(val) ~= "table" then
complex_config_table[name] = {}
mprintf("!!!!!!!!!! %s had an invalid complex config for %s: %s (%s)", tostring(player), name, tostring(val), type(val))
end
end
end
end
local CONTEXT_META = {
__newindex = function()
error("context is readonly")
end;
--__tostring = function(self) return string.format("Player Context (%s): %s", tostring(self.player), self._name or "ADDR") end,
__metatable = "[Insight] The metatable is locked"
}
--- Creates player's insight context.
---@param player EntityScript Player to create context for.
---@param configs table Holds the different config types: vanilla, external, complex.
---@param etc table
function CreatePlayerContext(player, configs, etc)
if not player then
error("[Insight]: Player is missing!")
end
if type(configs.vanilla) ~= "table" then
if IS_DST then TheNet:Kick(player.userid) return end
error("[Insight]: Config is invalid!")
end
if type(configs.external) ~= "table" then
if IS_DST then TheNet:Kick(player.userid) return end
error("[Insight]: external config is invalid!")
end
if type(configs.complex) ~= "table" then
if IS_DST then TheNet:Kick(player.userid) return end
error("[Insight]: complex config is invalid!")
end
ValidateComplexConfiguration(player, configs.complex)
local context = {
player = player,
config = configs.vanilla,
external_config = configs.external,
complex_config = configs.complex,
time = nil,
usingIcons = configs.vanilla["info_style"] == "icon",
lstr = language(configs.vanilla, etc.locale),
is_server_owner = etc.is_server_owner,
etc = etc
}
context.time = Time:new({ context=context })
if context.is_server_owner then
if context.config["crash_reporter"] then
SERVER_OWNER_HAS_OPTED_IN = true
SyncSecondaryInsightData({ SERVER_OWNER_HAS_OPTED_IN=true })
end
end
setmetatable(context.config, CONTEXT_META)
setmetatable(context.external_config, CONTEXT_META)
setmetatable(context.complex_config, CONTEXT_META)
setmetatable(context, mt)
player_contexts[player] = context
mprint("Created player context for", player)
end
--- Updates a player's context if they already have one.
---@param player EntityScript
---@param data table
function UpdatePlayerContext(player, data)
local context = player_contexts[player]
if not context then
mprint("Can't update missing player context.")
return
end
local oldLang = context.config["language"]
if data.configs then
if type(data.configs.vanilla) ~= "table" then
if IS_DST then TheNet:Kick(player.userid) return end
error("[Insight]: UpdatePlayerContext Config is invalid!")
end
if type(data.configs.external) ~= "table" then
if IS_DST then TheNet:Kick(player.userid) return end
error("[Insight]: UpdatePlayerContext external config is invalid!")
end
if type(data.configs.complex) ~= "table" then
if IS_DST then TheNet:Kick(player.userid) return end
error("[Insight]: UpdatePlayerContext complex config is invalid!")
end
ValidateComplexConfiguration(player, data.configs.complex)
context.config = setmetatable(data.configs.vanilla, CONTEXT_META)
context.external_config = setmetatable(data.configs.external, CONTEXT_META)
context.complex_config = setmetatable(data.configs.complex, CONTEXT_META)
end
data.configs = nil
for i,v in pairs(data) do
context[i] = v
end
local oldUsingIcons = context.usingIcons
context.usingIcons = context.config["info_style"] == "icon"
if oldLang ~= context.config["language"] or oldUsingIcons ~= context.usingIcons then
context.lstr = language(context.config, context.etc.locale)
context.etc.locale = context.config["language"]
end
end
--- Returns the component's origin.
---@param componentname string
---@return string|nil @nil if it is native, string is mod's fancy name
local function GetComponentOrigin(componentname)
if IS_DS then
return false
end
if mod_component_cache[componentname] == false then
return nil
elseif mod_component_cache[componentname] ~= nil then
return mod_component_cache[componentname]
end
local found, cmp = pcall(require, "components/" .. componentname)
if not found or not cmp then
mod_component_cache[componentname] = false
return GetComponentOrigin(componentname)
end
local info = cmp._ctor and debug.getinfo(cmp._ctor, "S")
local parent = string.match(info.source, "(.*)scripts%/components%/")
local mod_folder_name = parent and string.match(parent, "mods%/([^/]+)%/")
--mprint("hey:", recipe.product, info.source, parent, mod_folder_name)
if parent == "" then
-- vanilla
mod_component_cache[componentname] = false
return GetComponentOrigin(componentname)
end
-- modded
for _, modname in pairs(ModManager:GetEnabledModNames()) do
if modname == mod_folder_name then
mod_component_cache[componentname] = KnownModIndex:GetModInfo(modname).name or false
return GetComponentOrigin(componentname)
end
end
--[[
for i,mod in pairs(ModManager.mods) do
-- mod is the env
local data = KnownModIndex:GetModInfo(mod.modname) -- modinfo.lua
--mprint("checking", data.name, "|", MODS_ROOT .. mod.modname .. "/scripts/components/" .. componentname .. ".lua")
local c, x = io.open(MODS_ROOT .. mod.modname .. "/scripts/components/" .. componentname .. ".lua", "r")
if c ~= nil then
io.close(c)
mod_component_cache[componentname] = data.name
return mod.modname
end
end
mod_component_cache[componentname] = false
--]]
return nil
end
--- Returns the prefab's origin
---@param prefabname string
---@return string|nil @nil if it is native, string is mod's fancy name
function GetPrefabOrigin(prefabname)
if IS_DS then
return false
end
--[[
if mod_prefab_cache[prefabname] == false then -- native
return nil
elseif mod_prefab_cache[prefabname] ~= nil then -- modded
return mod_prefab_cache[prefabname]
end
--]]
for i,modname in ipairs(ModManager.enabledmods) do
local mod = ModManager:GetMod(modname)
-- ModInfoname(mod.modname) = workshop-2189004162 (Insight)
for name, prefab in pairs(mod.Prefabs) do
if name == prefabname then
--mod_prefab_cache[prefabname]
return modname
end
end
end
end
--- Retrives item posessor.
---@param item EntityScript The held item.
---@return EntityScript|nil @The player/creature that is holding the item.
function GetItemPossessor(item)
if not (IS_DS or (IS_DST and TheWorld.ismastersim)) then
error("GetItemPosessor not called from master")
end
return item and item.components and item.components.inventoryitem and item.components.inventoryitem:GetGrandOwner()
end
--- Returns the current world type (DLCs and base game) that is active.
---@return number @(0 = Base Game, 1 = Reign of Giants, 2 = Shipwrecked, 3 = Hamlet, -1 = DST)
function GetWorldType()
if TheSim:GetGameID() == "DST" then
return -1 -- Don't Starve Together
-- ds DLC variables don't exist here by the way
end
if IsDLCEnabled(PORKLAND_DLC) then
return 3 -- hamlet
elseif IsDLCEnabled(CAPY_DLC) then
return 2 -- shipwrecked
elseif IsDLCEnabled(REIGN_OF_GIANTS) then
return 1 -- reign of giants
else
return 0 -- base game of Don't Starve
end
end
--- Custom print command specifically for the mod.
--- Indicates that a print came from the mod.
---@param ... @can be pretty much anything
function mprint(...)
local msg, argnum = "", select("#",...)
for i = 1, argnum do
local v = select(i,...)
msg = msg .. tostring(v) .. ( (i < argnum) and "\t" or "" )
end
local prefix = ""
if false then
local i = 2
local d = debug.getinfo(2, "Sln")
while (d.name and d.name:sub(2, 6) == "print") or (d.source == "=[C]") do
i = i + 1
d = debug.getinfo(i, "Sln")
if not d then
d = {}
break
end
end
prefix = string.format("%s:%s:", d.source or "?", d.currentline or 0)
end
return print(prefix .. "[" .. ModInfoname(modname) .. "]:\t" .. msg)
end
--- Mod print with formatting with 'safe' formatting arguments
---@param strf string The string to be formatted.
---@param ... @Can be anything, all inputs here get tostring'd.
function mprintf(strf, ...)
local n = select("#", ...)
local args = {...}
for i = 1, n do
args[i] = tostring(args[i])
end
return mprint(string.format(strf, unpack(args, 1, n)))
end
--- Error with formatting that takes arguments that are made safe.
---@param level number|string If this is a number, this is the error level. If this is a string, this parameter becomes error_pattern.
---@param error_pattern string|... This can be the error pattern if it wasn't used already. Otherwise, it's part of the vararg used for formatting.
function errorf(level, error_pattern, ...)
local t = type(level)
if t == "string" then
-- the level is actually the error pattern
return error(string.format(level, error_pattern, ...), 2)
elseif t == "number" then
-- standard
return error(string.format(error_pattern, ...), (level and level+1) or 2)
else
error("errorf bad args")
end
end
--- Debug print that only shows if DEBUG_ENABLED is true.
function dprint(...)
if not DEBUG_ENABLED then
return
end
mprint(...)
end
--- Debug print with formatting.
---@param strf string The string to be formatted.
---@param ... @Can be anything, all inputs here get tostring'd.
function dprintf(strf, ...)
if not DEBUG_ENABLED then
return
end
local n = select("#", ...)
local args = {...}
for i = 1, n do
args[i] = tostring(args[i])
end
return dprint(string.format(strf, unpack(args, 1, n)))
end
--- Special print I use when testing multiple shard clusters. Sends print string over an RPC to my client.
---@param ... @Can be anything, all inputs here get tostring'd.
function cprint(...)
if not TheNet:GetClientTableForUser(MyKleiID) then
return
end
local msg, argnum = "", select("#",...)
for i = 1, argnum do
local v = select(i,...)
msg = msg .. tostring(v) .. ( (i < argnum) and "\t" or "" )
end
if IsClient() then
msg = "[" .. ModInfoname(modname) .. " - SERVER (BUT ACTUALLY CLIENT)]: " .. msg
print(msg)
elseif ALLOW_SERVER_DEBUGGING then
msg = "[" .. ModInfoname(modname) .. " - SERVER]: " .. msg
rpcNetwork.SendModRPCToClient(GetClientModRPC(modname, "Print"), MyKleiID, msg)
else
mprint("cprint is disabled")
end
-- _G.Insight.env.rpcNetwork.SendModRPCToClient(GetClientModRPC(_G.Insight.env.modname, "Print"), ThePlayer.userid, "rek"
end
local function DoNetworkMoonCycle()
local moon_cycle = GetMoonCycle()
if not moon_cycle then return end
for _, player in pairs(AllPlayers) do
local ist = player.components.insight
if ist then
ist:SendMoonCycle(moon_cycle)
end
end
end
local function InvalidDescriptorIndex(self, index) -- causes crash when checking for stuff :p
error(string.format("Descriptor '%s' does not have index '%s'", tostring(self.name), tostring(index)))
end
local function hex_dump(buf)
if type(buf) == "function" then
buf = string.dump(buf)
end
local s = ""
for i = 1, math.ceil(#buf/16) * 16 do
if (i-1) % 16 == 0 then s = s .. ("%08X "):format(i-1) end
s = s .. ( i > #buf and " " or ("%02X "):format(buf:byte(i)) )
if i % 8 == 0 then s = s .. " " end
if i % 16 == 0 then s = s .. buf:sub(i-16+1, i):gsub("%c",".") .. "\n" end
end
return s
end
--- Unloads a loaded component descriptor and clears the import cache for the file.
---@param name string
function UnloadComponentDescriptor(name)
local path = "descriptors/" .. name
if import.HasLoaded(path) then
import.Clear(path)
mprintf("DESCRIPTOR '%s' IMPORT CLEARED", name)
else
mprintf("DESCRIPTOR '%s' WAS NOT IN IMPORT CACHE", name)
end
if rawget(Insight.descriptors, name) ~= nil then
if Insight.descriptors[name] and Insight.descriptors[name].OnUnload then
Insight.descriptors[name].OnUnload()
end
Insight.descriptors[name] = nil
mprintf("DESCRIPTOR '%s' CACHE CLEARED", name)
else
mprintf("DESCRIPTOR '%s' WAS NOT IN DESCRIPTOR CACHE", name)
end
end
_G.UnloadComponentDescriptor = UnloadComponentDescriptor
--- Loads and returns a component descriptor.
---@param name string Name of the component.
---@return table|false @Returned table from the descriptor, or false if the descriptor failed to load.
local function GetComponentDescriptor(name)
local safe, res = pcall(import, "descriptors/" .. name)
if safe then
if type(res) == "table" then
assert(
res.Describe == nil or type(res.Describe) == "function",
string.format("[Insight]: attempt to return '%s' as a complex descriptor with Describe as '%s'",
name, tostring(res.Describe)
)
)
if getmetatable(res) == nil then
res.name = res.name or name
setmetatable(res, { })
end
-- DS should activate both..? Can't think of a reason otherwise yet, but it feels off.
if res.OnServerInit then
if IS_DS or TheNet:IsDedicated() or IsClientHost() then
res.OnServerInit()
end
end
if res.OnClientInit then
if IS_DS or IsClient() or IsClientHost() then
res.OnClientInit()
end
end
return res
else
local source_read, err = pcall(function()
local f = io.open("../mods/" .. modname .. "/scripts/descriptors/" .. name .. ".lua")
local src = f:read("*a")
mprint("==================== FILE SOURCE ====================")
print("\n[[" .. src:sub(1, 124) .. "]]\n\n[[" .. src:sub(-124) .. "]]")
mprint("==================== HEX DUMP =======================")
local file_fn = import._init_cache[import.ResolvePath("descriptors/" .. name)]
assert(file_fn, "Missing file FN")
mprint("\n" .. hex_dump(file_fn))
end)
if not source_read then
mprint("Could not completely read descriptor file:", err)
end
error(string.format("Attempt to return \"%s\" (type %s) in descriptor '%s'", tostring(res), type(res), name))
--Insight.descriptors[name] = false
return false
end
else
-- [string "../mods/workshop-2189004162/scripts/import...."]:48: [ERR] File does not exist: ../mods/workshop-2189004162/scripts/descriptors/teamattacker.lua
local _, en = string.find(res, ":%d+:%s")
res = string.sub(res, (en or 0)+1)
if res:find("[ERR] File does not exist: " .. MODROOT .. "scripts/descriptors/" .. name .. ".lua", 1, true) then
-- Failed to load itself since it couldn't find itself
else
mprint("Failed to load descriptor", name, "|", res)
return {
Describe = function()
return {
name = name .. "_component_insighterror",
priority = -0.5,
description = "<color=#ff0000>ERROR LOADING COMPONENT DESCRIPTOR \"" .. name .. "\"</color>:\n" .. res,
_error = true,
}
end
}
end
return false
end
end
--- Unloads a loaded prefab descriptor and clears the import cache for the file.
---@param name string
function UnloadPrefabDescriptor(name)
local path = "prefab_descriptors/" .. name
if import.HasLoaded(path) then
import.Clear(path)
mprintf("PREFAB DESCRIPTOR '%s' IMPORT CLEARED", name)
else
mprintf("PREFAB DESCRIPTOR '%s' WAS NOT IN IMPORT CACHE", name)
end
if rawget(Insight.prefab_descriptors, name) ~= nil then
if Insight.prefab_descriptors[name] and Insight.prefab_descriptors[name].OnUnload then
Insight.prefab_descriptors[name].OnUnload()
end
Insight.prefab_descriptors[name] = nil
mprintf("PREFAB DESCRIPTOR '%s' CACHE CLEARED", name)
else
mprintf("PREFAB DESCRIPTOR '%s' WAS NOT IN DESCRIPTOR CACHE", name)
end
end
_G.UnloadPrefabDescriptor = UnloadPrefabDescriptor
--- Loads and returns a prefab descriptor.
---@param name string Prefab name.
---@return table|false @Returned table from the prefab descriptor, or false if the prefab descriptor failed to load.
local function GetPrefabDescriptor(name)
-- This is like an exact duplicate of GetComponentDescriptor, except prefab_descriptors. pensive.
local safe, res = pcall(import, "prefab_descriptors/" .. name)
if safe then
if type(res) == "table" then
assert(
res.Describe == nil or type(res.Describe) == "function",
string.format("[Insight]: attempt to return '%s' as a complex prefab descriptor with Describe as '%s'",
name, tostring(res.Describe)
)
)