Repository navigation
Expand file tree
/
Copy pathmodmain.lua
More file actions
3068 lines (2536 loc) · 100 KB
/
Copy pathmodmain.lua
File metadata and controls
3068 lines (2536 loc) · 100 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
--[[
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 = nil,
FUEL_TYPES = {
BURNABLE = "Fuel",
CAVE = "Light", -- miner hat / lanterns, light bulbs n stuff
CHEMICAL = "Fuel",
CORK = "Fuel",
GASOLINE = "Gasoline", -- DS: not actually used anywhere?
MAGIC = "Durability", -- amulets that aren't refuelable (ex. chilled amulet)
MECHANICAL = "Durability", -- SW: iron wind
MOLEHAT = "Night vision", -- Moggles
NIGHTMARE = "Nightmare fuel",
NONE = "Time", -- will never be refueled...............................
ONEMANBAND = "Durability",
PIGTORCH = "Fuel",
SPIDERHAT = "Durability", -- Spider Hat
TAR = "Tar", -- SW
USAGE = "Durability",
},
COLORS = {
-- stats
HUNGER = "#DEB639",
SANITY = "#C67823",
HEALTH = "#A22B23",
ENLIGHTENMENT = "#ACC5C3",
-- 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
-- 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
-- mob
FEATHER = "#331D43", -- black feather
FROG = "#69725C",
-- misc
ROYAL_PURPLE = "#6225D1", -- r
LIGHT_PINK = "#ffb6c1",
CAMO = "#4D6B43",
MOB_SPAWN = "#ee6666",
},
CONTROLS = {
-- CONTROL_MENU_MISC_3 = L
TOGGLE_INSIGHT_MENU = CONTROL_OPEN_CRAFTING, -- L2
}
}
-- Provide to Global
_G.Insight = Insight
-- meh
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
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
PrefabFiles = {"insight_range_indicator", "insight_map_marker"}
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")
util = import("util")
Color = import("helpers/color")
entityManager = import("entitymanager")()
rpcNetwork = import("rpcnetwork")
combatHelper = import("helpers/combat")
widgetLib = {
image = import("widgets/image_lib"),
imagebutton = import("widgets/imagebutton_lib"),
text = import("widgets/text_lib"),
}
TRACK_INFORMATION_REQUESTS = DEBUG_ENABLED and false
local player_contexts = {}
local mod_component_cache = {}
local log_buffer = ""
local LOG_LIMIT = 4500000 -- 4.5 million
local SERVER_OWNER_HAS_OPTED_IN = nil
local descriptors = createTable(100)
local prefab_descriptors = {}
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", "eater", "poisonable", "sleeper", "freezable", -- may be interesting looking into
"thief", "characterspecific", "resurrector", "brushable", "rideable", "mood", "thrower", "windproofer", "creatureprox", "groundpounder", "prototyper", -- maybe interesting looking into
--notable
"bundlemaker", --used in bundling wrap before items
"inventoryitem", "moisturelistener", "propagator", "stackable", "cookable", "bait", "blowinwind", "blowinwindgust", "floatable", "selfstacker", "book", -- don't care
"dryable", "highlight", "cooker", "lighter", "instrument", "poisonhealer", "trader", "smotherer", "knownlocations", "homeseeker", "occupier", "talker", "inventory", -- don't care
"named", "activatable", "transformer", "deployable", "upgrader", "playerprox", "flotsamspawner", "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", -- 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", "constructionsite", "playeravatardata", "petleash", "giftreceiver", -- may be interesting looking into
"grogginess", "workmultiplier", "mine", "aura", -- 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
"hauntable", "savedrotation", "halloweenmoonmutable", "storytellingprop", "floater", "spawnfader", "transparentonsanity", "beefalometrics", "uniqueid", "reticule", "spellcaster", -- don't care
"complexprojectile", "shedder", "disappears", "oceanfishingtackle", "shelf", "ghostlyelixirable", "maprevealable", "winter_treeseed", "summoningitem", "portablestructure", "deployhelper", -- don't care
"symbolswapdata", "amphibiouscreature", "gingerbreadhunt", "nutrients_visual_manager", "vase", "vasedecoration", "worldsettingstimer", "murderable", "poppable", "balloonmaker", -- 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", "flotsamgenerator", "brightmarespawner",
"sandstorms", "messagebottlemanager", "forestpetrification", "penguinspawner", "sharklistener", "frograin", "waterphysics", "butterflyspawner", "worldmeteorshower",
"worlddeciduoustreeupdater", "schoolspawner", "specialeventsetup", "playerspawner", "walkableplatformmanager", "lureplantspawner", "wavemanager",
-- Caves
"retrofitcavemap_anr", "caveins", "grottowaterfallsoundcontroller", "grottowarmanager", "archivemanager",
-- 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
}
--================================================================================================================================================================--
--= Functions ====================================================================================================================================================--
--================================================================================================================================================================--
--- Checks whether we are in DS.
-- @return boolean
function IsDS()
return TheSim:GetGameID() == "DS"
end
--- Checks whether we are in DST.
-- @treturn boolean
function IsDST()
return TheSim:GetGameID() == "DST"
end
--- Checks whether the mod is running on a client
-- @treturn boolean
function IsClient()
return IsDST() and TheNet:GetIsClient()
end
--- Checks whether the mod is running on a client that is also the host.
-- @treturn boolean
function IsClientHost()
return IsDST() and TheNet:IsDedicated() == false and TheNet:GetIsMasterSimulation() == true
--return IsDST() and TheNet:IsDedicated() == false and TheWorld.ismastersim == true
end
--- Checks whether the mod is running in The Forge.
-- @treturn boolean
function IsForge()
return IsDST() and TheNet:GetDefaultGameMode() == "lavaarena"
end
--- Checks if argument is a widget.
-- @param arg
-- @treturn boolean
function IsWidget(arg)
return arg and arg.inst and arg.inst.widget and true
end
--- Checks if argument is a prefab.
-- @param arg
-- @treturn boolean
function IsPrefab(arg)
return type(arg) == 'table' and arg.GUID and arg.prefab and true
end
--- Return player's Insight component.
-- @tparam Player player
-- @treturn ?Insight|nil
function GetInsight(player)
assert(player, "[Insight]: GetInsight called without player")
if IsDST() then
return player.replica.insight
else
return player.components.insight
end
end
--- Returns player's insight context.
-- @tparam Player player
-- @treturn ?table|nil
function GetPlayerContext(player)
assert(IsPrefab(player), "[Insight]: GetPlayerContext called on non-player")
local context
if IsDST() 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({ fromInspection=false }, { __index=context })
end
--return context
end
--- Creates player's insight context.
-- @tparam Player player Player to create context for.
-- @tparam table config Insight configuration.
-- @tparam table external_config Configuration from client mods.
-- @tparam table etc
function CreatePlayerContext(player, config, external_config, etc)
assert(player, "[Insight]: Player is missing!")
assert(config, "[Insight]: Config is missing!")
assert(external_config, "[Insight]: External_config is missing!")
local mt = {
__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"
}
local context = {
player = player,
config = config,
external_config = external_config,
usingIcons = config["info_style"] == "icon",
lstr = import("language/language")(config, etc.locale),
is_server_owner = etc.is_server_owner,
etc = etc
}
if context.is_server_owner then
if context.config["crash_reporter"] then
SERVER_OWNER_HAS_OPTED_IN = true
for id, shard in pairs(Shard_GetConnectedShards()) do
--mprint("sending data to:", id)
rpcNetwork.SendModRPCToShard(GetShardModRPC(modname, "CrashReporter"), id, compress({ server_owner_enabled=true }))
end
end
end
setmetatable(context.config, mt)
setmetatable(context.external_config, mt)
setmetatable(context, mt)
player_contexts[player] = context
end
--- Returns the component's origin.
-- @string componentname
-- @treturn ?string|nil nil if it is native, string is mod's fancy name
local function GetComponentOrigin(componentname)
if IsDS() 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
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
-- @string prefabname
-- @treturn ?string|nil nil if it is native, string is mod's fancy name
function GetPrefabOrigin(prefabname)
if IsDS() 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.
-- @tparam Prefab item
-- @treturn ?Prefab|nil The player/creature that is holding the item.
function GetItemPossessor(item)
assert(IsDS() or (IsDST() and TheWorld.ismastersim), "GetItemPosessor not called from master")
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.
-- @treturn Integer (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 d = debug.getinfo(2, "Sl")
prefix = string.format("%s:%s:", d.source or "?", d.currentline or 0)
end
return print(prefix .. "[" .. ModInfoname(modname) .. "]:", msg)
end
function dprint(...)
if not DEBUG_ENABLED then
return
end
mprint(...)
end
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
local res = "[" .. ModInfoname(modname) .. " - SERVER]: " .. msg
if IsClient() then
print(res)
else
rpcNetwork.SendModRPCToClient(GetClientModRPC(modname, "Print"), MyKleiID, res)
end
-- _G.Insight.env.rpcNetwork.SendModRPCToClient(GetClientModRPC(_G.Insight.env.modname, "Print"), ThePlayer.userid, "rek"
end
--- Returns the descriptor method for an item. Returns false if descriptor failed to load or does not exist.
-- @tparam string name
-- @treturn ?function|false
local function GetComponentDescriptor(name)
if descriptors[name] == nil then
-- never processed before
local safe, res = pcall(import, "descriptors/" .. name)
descriptors[name] = (safe and res) or false
if safe then
if type(res) == "table" then
assert(type(res.Describe) == "function", string.format("[Insight]: attempt to return '%s' as a complex descriptor with Describe as '%s'", name, tostring(res.Describe)))
-- complex
Insight.descriptors[name] = setmetatable(deepcopy(res), { __index = function(self, index) error(string.format("descriptor '%s' does not have index '%s'", name, index)) end })
else
--Insight.descriptors[name] = res
mprint(safe, res)
error(string.format("Attempt to return '%s' in descriptor '%s'", tostring(res), name))
end
else
--dprint("?????", safe, res)
Insight.descriptors[name] = false
end
if not safe then
-- [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 not res:find("not exist") then
descriptors[name] = function() return {priority = -0.5, description = "<color=#ff0000>ERROR LOADING COMPONENT DESCRIPTOR \"" .. name .. "\"</color>:\n" .. res} end
end
dprint(string.format("FAILED TO LOAD DESCRIPTOR %s: %s", name, res))
end
-- reprocess
return GetComponentDescriptor(name)
--[[
elseif type(descriptors[name]) == "function" then
-- simple function return
return descriptors[name]
--]]
elseif type(descriptors[name]) == "table" then
-- looks like its a complex descriptor
return descriptors[name].Describe
else
-- its not good :(
return descriptors[name]
end
end
local function GetPrefabDescriptor(name)
if prefab_descriptors[name] == nil then
-- never processed before
local safe, res = pcall(import, "prefab_descriptors/" .. name)
prefab_descriptors[name] = (safe and res) or false
if not safe then
if res:find("loading") then
prefab_descriptors[name] = function() return {priority = -0.5, description = "ERROR LOADING PREFAB DESCRIPTOR \"" .. name .. "\": " .. res} end
else
--descriptors[name] = function() return {priority = -0.5, description = "ERROR LOADING PREFAB DESCRIPTOR \"" .. name .. "\": " .. res} end
end
end
-- reprocess
return GetPrefabDescriptor(name)
elseif type(prefab_descriptors[name]) == "function" then
-- yay
return prefab_descriptors[name]
else
-- its not good :(
return prefab_descriptors[name]
end
end
local function GetSpecialData(describe_data)
local special_data = {}
for j, k in pairs(describe_data) do
if j ~= 'name' and j ~= 'description' and j ~= 'priority' then
special_data[j] = k
end
end
return special_data
end
--- Retrives our information for an item.
-- @tparam Prefab item
-- @tparam Player player
-- @tparam table params
-- @treturn string
local function GetEntityInformation(item, player, params)
-- some mods (https://steamcommunity.com/sharedfiles/filedetails/?id=2081254154) were setting .item to a non-prefab
-- 5/2/2020
local assembled = {
GUID = item.GUID,
information = "", --string.rep("hello there <color=HEALTH> monty python 123</color> dingo bongo\n" .. GetTime(), 4),
alt_information = "",
special_data = {},
raw = (params.raw and {}) or nil,
}
--[[
if not IsPrefab(item) then
assembled.GUID = "?"
assembled.information = "Not a prefab"
return assembled
end
--]]
local player_context = GetPlayerContext(player)
if not player_context then
assembled.raw = nil
assembled.information = "missing player context for " .. player.name
return assembled
end
player_context.fromInspection = params.fromInspection or false
local isForge = IsForge() -- why call this multiple times later?
local components = item.components
local chunks = {}
local len_chunks = 0
for name, component in pairs(components) do
local descriptor = GetComponentDescriptor(name)
if descriptor then
local datas = {descriptor(component, player_context)}
for i, d in pairs(datas) do
--for i = 1, #datas do -- doesn't account for nils
--local d = datas[i]
if d and ((not params.ignore_worldly) or (params.ignore_worldly == true and not d.worldly)) then
assert(type(d.priority)=="number", "Invalid priority for:" .. name)
if d.name ~= nil and type(d.name) ~= "string" then
error("invalid chosen name for a descriptor")
elseif d.name == nil and #datas > 1 then
error("missing name for a multiple-return descriptor") -- when returning multiple tables, need to manually specify the names
end
d.name = d.name or name -- chosen name or default component name
if isForge == false or (isForge == true and name == "health") then
--fprint(item, "component", name, d.description)
--table.insert(chunks, d)
chunks[len_chunks+1] = d; len_chunks = len_chunks + 1;
end
end
end
elseif player_context.config["DEBUG_SHOW_DISABLED"] and table.contains(descriptors_ignore, name) then
--table.insert(chunks, {priority = -2, name = name, description = "Disabled descriptor: " .. name})
chunks[len_chunks+1] = {priority = -2, name = name, description = "Disabled descriptor: " .. name}; len_chunks = len_chunks + 1;
elseif player_context.config["DEBUG_SHOW_NOTIMPLEMENTED"] and not table.contains(descriptors_ignore, name) then
local description = "No information for: " .. name
local origin = GetComponentOrigin(name)
if origin then
description = string.format("[%s] No information for: %s", origin, name)
end
--table.insert(chunks, {priority = -1, name = name, description = description})
chunks[len_chunks+1] = {priority = -1, name = name, description = description}; len_chunks = len_chunks + 1;
end
end
-- sort by priority
table.sort(chunks, function(a, b)
local p1, p2 = a.priority or 0, b.priority or 0
if p1 == p2 and a.description and b.description then
return a.description < b.description -- key code means letters further down the alphabet have a higher value, so we need smaller of them to sort alphabetically
else
return p1 > p2 -- we need higher value priority
end
end)
-- assembly time
-- if there's no data, why bother?
--if #chunks == 0 then
if len_chunks == 0 then
assembled.information = nil
assembled.alt_information = nil
return assembled
end
--fprint(item, "has some info")
for i = 1, #chunks do
--for i,v in pairs(chunks) do
local v = chunks[i]
if assembled.special_data[v.name] == nil then
assembled.special_data[v.name] = GetSpecialData(v)
end
-- collect the description if one was provided
if type(v.description) == "string" then
v.description = ResolveColors(v.description) -- resolve any color tags that reference the Insight table's colors
assembled.information = assembled.information .. v.description
--[[
if v.alt_description then
assembled.alt_information = assembled.alt_information .. ResolveColors(v.alt_description)
else
assembled.alt_information = assembled.alt_information .. v.description
end
--]]
if i < #chunks then
assembled.information = assembled.information .. "\n"
--assembled.alt_information = assembled.alt_information .. "\n"
end
if params.raw == true then
assembled.raw[v.name] = v.description
end
elseif v.description ~= nil then
-- should have been caught in the previous statement
error(string.format("invalid description: %s | Descriptor: %s", tostring(v.description), v.name))
end
if type(v.alt_description) == "string" then
assembled.alt_information = assembled.alt_information .. ResolveColors(v.alt_description)
if i < #chunks then
assembled.alt_information = assembled.alt_information .. "\n"
end
elseif v.alt_description == nil and v.description ~= nil then
assembled.alt_information = assembled.alt_information .. v.description
if i < #chunks then
assembled.alt_information = assembled.alt_information .. "\n"
end
elseif v.alt_description ~= nil then
-- should have been caught in the previous statement
error(string.format("invalid alt_description: %s | Descriptor: %s", tostring(v.alt_description), v.name))
end
end
if assembled.information == "" then
assembled.information = nil
end
if assembled.alt_information == "" then
assembled.alt_information = nil
end
return assembled
end
--- Middleman between GetEntityInformation's server side and the client, really only important for DST
function RequestEntityInformation(item, player, params)
--if true then return nil end
assert(type(params) == "table", "RequestEntityInformation expected 'params' as a table")
if TRACK_INFORMATION_REQUESTS then
dprint("SERVER got:", item, player, params)
end
-- might as well
if not item then
--dprint(player, "requested information for nil.")
return nil
end
-- DST
if not IsPrefab(item) then
if IsDST() then
mprint(string.format("%s requested information for %s, mastersim: %s", player.name, tostring(item), tostring(TheWorld.ismastersim)))
else
mprint(string.format("Requested information for %s", tostring(item)))
end
return {GUID = params.id or 0, info = "not a real item?", special_data = {}}
end
local insight = GetInsight(player)
if not insight then
mprint(player.name, "is missing insight component.")
return {GUID = params.id or 0, info = "missing insight component", special_data = {}}
end
if IsDS() then
-- DS
local info = GetEntityInformation(item, player, params)
info.GUID = params.id
insight.entity_data[item] = info
return info
end
--local ok = DEBUG_ENABLED and ("is_active: " .. tostring(entityManager:IsEntityActive(item)) .. "\n") or ""
local id = params.id
-- GUIDs vary between server and client
if TheWorld.ismastersim then
--dprint(player, "is requesting info for", item)
local data = GetEntityInformation(item, player, params)
if not id then
if IsClientHost() then
-- understandable
id = item.GUID
else
-- we shouldn't be here
mprint("&&&&&&&&&&&&&& guid missing in server RQST")
id = item.GUID
end
end
data.GUID = id
if TRACK_INFORMATION_REQUESTS then
dprint("Information set for", item)
end
insight:SetEntityData(item, data)
else
-- client is asking for information
insight:RequestInformation(item, params) -- clients have to go through this at some point, unless client is host and its a forest-only world
end
if TRACK_INFORMATION_REQUESTS then
--dprint("Information returning for", item)
end
if insight.entity_data[item] then
return insight.entity_data[item]
end
return ok or nil
end
function GetWorldInformation(player) -- refactor?
--if true then return {} end
local is_dst = IsDST()
local world = TheWorld or GetWorld() -- implict game check
local context = GetPlayerContext(player)
if not context then
return
end
--assert(context, "how is context missing in GetWorldInformation for " .. player.name)
if is_dst and not context.config["display_world_events"] then
return {
GUID = world.GUID,
information = nil,
special_data = {},
raw = {}
}
end
local data = GetEntityInformation(world, player, {raw = true})
--[[
-- cant visualize this at the moment
{
GUID = ...
information = ...,
special_data = {...},
raw = {
component = description
}
}
]]
for i,v in pairs(data.raw) do
data.special_data[i].worldly = true
end
--[[
for i = 1, 7 do
local x = "test" .. i
data.special_data[x] = { worldly=true }
data.raw[x] = x
end
--]]
if GetWorldType() >= 2 then
local descriptor = GetComponentDescriptor("krakener")
if descriptor then
local krakener = descriptor(player.components.krakener, context)
for j, k in pairs(krakener) do
if j ~= 'description' and j ~= 'priority' then
if data.special_data["krakener"] == nil then
data.special_data["krakener"] = {}
end
data.special_data["krakener"][j] = k
end
end
data.raw["krakener"] = krakener.description
data.special_data["krakener"].worldly = true
end
end
if is_dst then
local helper = world.shard.components.shard_insight
-- antlion
--[[
local antlion_timer = helper:GetAntlionData() or -1
if antlion_timer >= 0 then
data.special_data["antlion"] = {
icon = {
atlas = "images/Antlion.xml",
tex = "Antlion.tex",
},
worldly = true,
from = "prefab"
}
data.raw["antlion"] = TimeToText(time.new(antlion_timer, context))
end
--]]
-- antlion (could use sinkholespawner)
if data.raw["antlion"] == nil and helper:GetAntlionData() then