-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTradersExtended.cs
More file actions
652 lines (512 loc) · 29.9 KB
/
TradersExtended.cs
File metadata and controls
652 lines (512 loc) · 29.9 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
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using ServerSync;
using System.IO;
using System;
using Newtonsoft.Json;
using System.Linq;
using System.Collections;
namespace TradersExtended
{
[BepInPlugin(pluginID, pluginName, pluginVersion)]
[BepInDependency("randyknapp.mods.epicloot", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("Azumatt.AzuExtendedPlayerInventory", BepInDependency.DependencyFlags.SoftDependency)]
[BepInDependency("shudnal.ExtraSlots", BepInDependency.DependencyFlags.SoftDependency)]
[BepInIncompatibility("randyknapp.mods.auga")]
public partial class TradersExtended : BaseUnityPlugin
{
public const string pluginID = "shudnal.TradersExtended";
public const string pluginName = "Traders Extended";
public const string pluginVersion = "1.3.12";
private readonly Harmony harmony = new Harmony(pluginID);
internal static readonly ConfigSync configSync = new ConfigSync(pluginID) { DisplayName = pluginName, CurrentVersion = pluginVersion, MinimumRequiredVersion = pluginVersion };
public static ManualLogSource logger;
internal static TradersExtended instance;
public static ConfigEntry<bool> modEnabled;
private static ConfigEntry<bool> loggingEnabled;
private static ConfigEntry<bool> configLocked;
public static ConfigEntry<bool> checkForDiscovery;
private static ConfigEntry<string> checkForDiscoveryIgnoreItems;
public static ConfigEntry<bool> traderRepair;
public static ConfigEntry<int> traderRepairCost;
private static ConfigEntry<string> tradersToRepairWeapons;
private static ConfigEntry<string> tradersToRepairArmor;
public static ConfigEntry<bool> traderUseCoins;
public static ConfigEntry<bool> traderUseFlexiblePricing;
public static ConfigEntry<int> traderCoinsMinimumAmount;
public static ConfigEntry<int> traderCoinsIncreaseAmount;
public static ConfigEntry<int> traderCoinsDecreaseAmount;
public static ConfigEntry<int> traderCoinsMaximumAmount;
public static ConfigEntry<float> traderDiscount;
public static ConfigEntry<float> traderMarkup;
public static ConfigEntry<int> traderCoinsReplenishmentRate;
public static ConfigEntry<bool> traderCoinsSendReplenishmentMessage;
public static ConfigEntry<bool> coinsPatch;
public static ConfigEntry<float> coinsWeight;
public static ConfigEntry<int> coinsStackSize;
public static ConfigEntry<string> tradersCustomPrefabs;
public static ConfigEntry<bool> disableVanillaItems;
public static ConfigEntry<float> qualityMultiplier;
public static ConfigEntry<bool> hideEquippedAndHotbarItems;
public static ConfigEntry<bool> addCommonValuableItemsToSellList;
public static ConfigEntry<Vector2> fixedStoreGuiPosition;
public static ConfigEntry<bool> enableBuyBack;
public static ConfigEntry<Color> colorBuybackNormal;
public static ConfigEntry<Color> colorBuybackHighlighted;
public static ConfigEntry<Color> colorBuybackText;
public static readonly Dictionary<string, List<TradeableItem>> tradeableItems = new Dictionary<string, List<TradeableItem>>();
public static readonly Dictionary<string, List<TradeableItem>> sellableItems = new Dictionary<string, List<TradeableItem>>();
private static readonly CustomSyncedValue<Dictionary<string, string>> configsJSON = new CustomSyncedValue<Dictionary<string, string>>(configSync, "JSON configs", new Dictionary<string, string>());
private static DirectoryInfo pluginDirectory;
private static DirectoryInfo configDirectory;
public static Component epicLootPlugin;
public static HashSet<string> _ignoreItemDiscovery = new HashSet<string>();
public static HashSet<string> _tradersToRepairWeapons = new HashSet<string>();
public static HashSet<string> _tradersToRepairArmor = new HashSet<string>();
public enum ItemsListType
{
Buy,
Sell
}
void Awake()
{
harmony.PatchAll();
instance = this;
logger = Logger;
pluginDirectory = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent;
configDirectory = new DirectoryInfo(Paths.ConfigPath);
ConfigInit();
_ = configSync.AddLockingConfigEntry(configLocked);
configsJSON.ValueChanged += new Action(StartConfigLoad);
epicLootPlugin = GetComponent("EpicLoot");
Game.isModded = true;
}
void Update()
{
AmountDialog.Update();
}
void OnDestroy()
{
Config.Save();
instance = null;
harmony?.UnpatchSelf();
}
public static void LogInfo(object data)
{
if (loggingEnabled.Value)
instance.Logger.LogInfo(data);
}
private void ConfigInit()
{
config("General", "NexusID", 2509, "Nexus mod ID for updates", false);
modEnabled = config("General", "Enabled", defaultValue: true, "Enable this mod. Reload the game to take effect.");
configLocked = config("General", "Lock Configuration", defaultValue: true, "Configuration is locked and can be changed by server admins only.");
loggingEnabled = config("General", "Logging enabled", defaultValue: false, "Enable logging. [Not Synced with Server]", false);
checkForDiscovery = config("Item discovery", "Sell only discovered items", defaultValue: true, "Trader will not sell items had not discovered by a buyer.");
checkForDiscoveryIgnoreItems = config("Item discovery", "Undiscovered items list to sell", defaultValue: "", "Trader will sell items from that list without check for discovery. Vanilla items are included by default.");
checkForDiscoveryIgnoreItems.SettingChanged += (sender, args) => FillConfigLists();
coinsPatch = config("Item coins", "Change values", defaultValue: false, "Change properties of coins item");
coinsWeight = config("Item coins", "Coins weight", defaultValue: 0f, "Weight of single coin");
coinsStackSize = config("Item coins", "Coins stack size", defaultValue: 2000, "Max size of coins stack");
traderRepair = config("Trader repair", "Traders can repair items", defaultValue: true, "Traders will have an ability to repair items");
tradersToRepairWeapons = config("Trader repair", "Traders capable to repair weapons", defaultValue: "Haldor", "Prefab name of Traders that have an ability to repair weapons");
tradersToRepairArmor = config("Trader repair", "Traders capable to repair armor", defaultValue: "Hildir", "Prefab name of Traders that have an ability to repair armor");
traderRepairCost = config("Trader repair", "Traders repair cost", defaultValue: 2, "Cost of repair in gold");
tradersToRepairWeapons.SettingChanged += (sender, args) => FillConfigLists();
tradersToRepairArmor.SettingChanged += (sender, args) => FillConfigLists();
traderUseCoins = config("Trader coins", "Traders use coins", defaultValue: true, "Traders will have an limited daily refilled amount of coins");
traderUseFlexiblePricing = config("Trader coins", "Traders use flexible pricing", defaultValue: true, "Traders will give a discount when their amount of coins is more than minimum or will set a markup when their amount of coins is less than minimum. Amount changes gradually.");
traderCoinsMinimumAmount = config("Trader coins pricing", "Amount of coins after replenishment minimum", defaultValue: 2000, "Minimum amount of coins trader will have after replenishment.");
traderCoinsIncreaseAmount = config("Trader coins pricing", "Amount of coins replenished daily", defaultValue: 1000, "Amount of coins added to current amount until maximum is reached");
traderCoinsDecreaseAmount = config("Trader coins pricing", "Amount of coins removed daily", defaultValue: 0, "Amount of coins removed from current amount until maximum is reached");
traderCoinsMaximumAmount = config("Trader coins pricing", "Amount of coins after replenishment maximum", defaultValue: 6000, "Maximum amount of coins for replenishments to stop.");
traderDiscount = config("Trader coins pricing", "Trader discount", defaultValue: 0.7f, "Discount for items to buy from trader when current amount of coins is more than maximum replenishment amount.");
traderMarkup = config("Trader coins pricing", "Trader markup", defaultValue: 1.5f, "Markup for items to buy from trader when current amount of coins is less than minimum replenishment amount.");
traderCoinsReplenishmentRate = config("Trader coins pricing", "Trader coins replenishment rate in days", defaultValue: 1, "Amount of coins is updated at morning");
traderCoinsSendReplenishmentMessage = config("Trader coins pricing", "Send replenishment message in the morning", defaultValue: true, "Show message when trader coins are updated");
tradersCustomPrefabs = config("Misc", "Custom traders prefab names", defaultValue: "", "List of custom prefab names of Trader added by mods to control coins. Prefab name, case sensitive, comma separated");
disableVanillaItems = config("Misc", "Disable vanilla items", defaultValue: false, "Disable vanilla items on traders. Custom traders could or could not work depending on their implementation.");
qualityMultiplier = config("Misc", "Quality multiplier", defaultValue: 0.0f, "Quality multiplier for price. Each level of additional quality level adds that percent of price.");
hideEquippedAndHotbarItems = config("Misc", "Hide equipped and hotbar items", defaultValue: true, "Equippable items from first row of inventory and all items currently equipped will not be shown at the sell list.");
addCommonValuableItemsToSellList = config("Misc", "Add common valuable items to sell list", defaultValue: true, "Add common valuable items to all traders sell list.");
fixedStoreGuiPosition = config("Misc", "Fixed position for Store GUI", defaultValue: Vector2.zero, "If set then Store GUI will take that absolute position.");
addCommonValuableItemsToSellList.SettingChanged += (sender, args) => StartConfigLoad();
fixedStoreGuiPosition.SettingChanged += (sender, args) => StorePanel.SetStoreGuiPosition();
enableBuyBack = config("Trader buyback", "Enable buyback for last item sold", defaultValue: true, "First item to buy will be the last item you have recently sold.");
colorBuybackNormal = config("Trader buyback", "Item background color", defaultValue: new Color(0f, 0.42f, 0.42f), "Color of buyback item background.");
colorBuybackHighlighted = config("Trader buyback", "Item highlighted color", defaultValue: new Color(0.25f, 0.62f, 0.62f), "Color of highlighted buyback item.");
colorBuybackText = config("Trader buyback", "Item font color", defaultValue: new Color(1f, 0.81f, 0f), "Color of buyback item name.");
InitCommands();
}
ConfigEntry<T> config<T>(string group, string name, T defaultValue, ConfigDescription description, bool synchronizedSetting = true)
{
ConfigEntry<T> configEntry = Config.Bind(group, name, defaultValue, description);
SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry(configEntry);
syncedConfigEntry.SynchronizedConfig = synchronizedSetting;
return configEntry;
}
ConfigEntry<T> config<T>(string group, string name, T defaultValue, string description, bool synchronizedSetting = true) => config(group, name, defaultValue, new ConfigDescription(description), synchronizedSetting);
public static void InitCommands()
{
new Terminal.ConsoleCommand("tradersextended", "save - Save full item list into config folder, itemlist - Save filtered item list into config folder", delegate (Terminal.ConsoleEventArgs args)
{
if (args.Length >= 2)
{
string action = args.FullLine.Substring(args[0].Length + 1);
if (action == "save")
{
SaveFromObjectDB(args.Context);
}
else if (action == "itemlist")
{
ExportItemListFromObjectDB(args.Context);
}
}
else
{
args.Context.AddString("Actions: save - Save full item list into config folder, itemlist - Save filtered item list into config folder");
}
}, isCheat: false, isNetwork: false, onlyServer: false, isSecret: false, allowInDevBuild: false, () => new List<string>() {
"save",
"itemlist"
}, alwaysRefreshTabOptions: true, remoteCommand: false);
new Terminal.ConsoleCommand("settradercoins", "[trader] [amount]", delegate (Terminal.ConsoleEventArgs args)
{
if (args.Length <= 1)
return false;
TraderCoins.SetTraderCoins(args[1].GetStableHashCode(), args.TryParameterInt(2, traderCoinsMinimumAmount.Value));
return true;
}, isCheat: true, isNetwork: false, onlyServer: true, isSecret: false, allowInDevBuild: false, () => TraderCoins.GetTraderPrefabs(), alwaysRefreshTabOptions: true, remoteCommand: false, onlyAdmin: true);
}
public static void SaveFromObjectDB(Terminal context)
{
List<TradeableItem> allItems = new List<TradeableItem>();
foreach (GameObject prefab in ObjectDB.instance.m_items)
{
if (!prefab.TryGetComponent(out ItemDrop itemDrop))
continue;
allItems.Add(new TradeableItem()
{
prefab = prefab.name,
price = Math.Max(itemDrop.m_itemData.m_shared.m_value, 1)
});
}
string JSON = JsonConvert.SerializeObject(allItems, Formatting.Indented);
Directory.CreateDirectory(Path.Combine(configDirectory.FullName, pluginID));
string filename = Path.Combine(configDirectory.FullName, pluginID, "ObjectDB.list.json");
File.WriteAllText(filename, JSON);
context.AddString($"Saved {allItems.Count} items to \"\\config\\{pluginID}\\ObjectDB.list.json\"");
}
public class ItemToExport
{
public string p;
public string n;
public int se;
public int b;
public int s;
public string f;
}
public static void ExportItemListFromObjectDB(Terminal context)
{
List<ItemToExport> allItems = new List<ItemToExport>();
HashSet<string> itemNames = new HashSet<string>();
Trader[] traders = Resources.FindObjectsOfTypeAll<Trader>();
foreach (Trader trader in traders)
foreach (Trader.TradeItem item in trader.m_items)
{
if (itemNames.Contains(item.m_prefab.name))
continue;
itemNames.Add(item.m_prefab.name);
if (item.m_prefab.m_itemData.m_shared.m_name.IsNullOrWhiteSpace() || item.m_prefab.m_itemData.m_shared.m_description == null ||
item.m_prefab.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.None || item.m_prefab.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Customization)
continue;
allItems.Add(new ItemToExport()
{
p = item.m_prefab.name,
n = Localization.instance.Localize(item.m_prefab.m_itemData.m_shared.m_name),
se = Math.Max(item.m_prefab.m_itemData.m_shared.m_value, 0),
b = item.m_price,
s = item.m_stack,
f = Utils.GetPrefabName(trader.name)
});
}
allItems.Do(item => LogInfo($"{item.p} {item.f}"));
var enemies = Resources.FindObjectsOfTypeAll<Humanoid>().Where(human => human.TryGetComponent<BaseAI>(out _));
foreach (Humanoid humanoid in enemies)
foreach (GameObject item in humanoid.m_defaultItems)
{
if (!item.TryGetComponent(out ItemDrop itemDrop))
continue;
if (itemNames.Contains(item.name))
continue;
itemNames.Add(item.name);
}
foreach (GameObject prefab in ObjectDB.instance.m_items)
{
if (!prefab.TryGetComponent(out ItemDrop itemDrop))
continue;
if (itemNames.Contains(prefab.name))
continue;
itemNames.Add(prefab.name);
if (!itemDrop.m_itemData.m_shared.m_name.StartsWith("$"))
continue;
if (itemDrop.m_itemData.m_shared.m_description == null ||
itemDrop.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.None ||
itemDrop.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Customization)
continue;
if (itemDrop.m_itemData.m_shared.m_value > 0)
allItems.Add(new ItemToExport()
{
p = itemDrop.name,
n = Localization.instance.Localize(itemDrop.m_itemData.m_shared.m_name),
se = itemDrop.m_itemData.m_shared.m_value,
});
else
allItems.Add(new ItemToExport()
{
p = itemDrop.name,
n = Localization.instance.Localize(itemDrop.m_itemData.m_shared.m_name)
});
}
JsonSerializerSettings settings = new JsonSerializerSettings
{
Formatting = Formatting.None,
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
string JSON = JsonConvert.SerializeObject(allItems.OrderBy(item => item.p).OrderByDescending(item => item.f), settings);
Directory.CreateDirectory(Path.Combine(configDirectory.FullName, pluginID));
string filename = Path.Combine(configDirectory.FullName, pluginID, "ItemList.json");
File.WriteAllText(filename, JSON);
context.AddString($"Saved {allItems.Count} items to \"\\config\\{pluginID}\\ItemList.json\"");
}
public static void FillConfigLists()
{
_ignoreItemDiscovery = new HashSet<string>(checkForDiscoveryIgnoreItems.Value.Split(',').Select(p => p.Trim().ToLower()).Where(p => !string.IsNullOrWhiteSpace(p)).ToList());
_tradersToRepairWeapons = new HashSet<string>(tradersToRepairWeapons.Value.Split(',').Select(p => TraderName(p.Trim())).Where(p => !string.IsNullOrWhiteSpace(p)).ToList());
_tradersToRepairArmor = new HashSet<string>(tradersToRepairArmor.Value.Split(',').Select(p => TraderName(p.Trim())).Where(p => !string.IsNullOrWhiteSpace(p)).ToList());
}
public static bool IgnoreItemDiscovery(string prefabName)
{
return _ignoreItemDiscovery.Contains(prefabName);
}
public static void SetupConfigWatcher()
{
string filter = $"{pluginID}.*.json";
FileSystemWatcher fileSystemWatcherPlugin = new FileSystemWatcher(pluginDirectory.FullName, filter);
fileSystemWatcherPlugin.Changed += new FileSystemEventHandler(ReadConfigs);
fileSystemWatcherPlugin.Created += new FileSystemEventHandler(ReadConfigs);
fileSystemWatcherPlugin.Renamed += new RenamedEventHandler(ReadConfigs);
fileSystemWatcherPlugin.Deleted += new FileSystemEventHandler(ReadConfigs);
fileSystemWatcherPlugin.IncludeSubdirectories = true;
fileSystemWatcherPlugin.SynchronizingObject = ThreadingHelper.SynchronizingObject;
fileSystemWatcherPlugin.EnableRaisingEvents = true;
FileSystemWatcher fileSystemWatcherConfig = new FileSystemWatcher(configDirectory.FullName, filter);
fileSystemWatcherConfig.Changed += new FileSystemEventHandler(ReadConfigs);
fileSystemWatcherConfig.Created += new FileSystemEventHandler(ReadConfigs);
fileSystemWatcherConfig.Renamed += new RenamedEventHandler(ReadConfigs);
fileSystemWatcherConfig.Deleted += new FileSystemEventHandler(ReadConfigs);
fileSystemWatcherConfig.IncludeSubdirectories = true;
fileSystemWatcherConfig.SynchronizingObject = ThreadingHelper.SynchronizingObject;
fileSystemWatcherConfig.EnableRaisingEvents = true;
ReadConfigs(null, null);
}
private static void ReadConfigs(object sender, FileSystemEventArgs eargs)
{
Dictionary<string, string> localConfig = new Dictionary<string, string>();
foreach (FileInfo file in pluginDirectory.GetFiles("*.json", SearchOption.AllDirectories))
{
string[] filename = file.Name.Split('.');
if (filename.Length != 5)
continue;
if (!file.Name.ToLower().StartsWith(pluginID.ToLower()))
continue;
if (!Enum.TryParse(filename[3], true, out ItemsListType list))
continue;
LogInfo($"Found {file.FullName}");
string listKey = TraderListKey(filename[2], list) + ".plugin";
try
{
using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader reader = new StreamReader(fs))
{
localConfig.Add(listKey, reader.ReadToEnd());
reader.Close();
fs.Dispose();
}
}
catch (Exception e)
{
logger.LogWarning($"Error reading file ({file.FullName})! Error: {e.Message}");
}
}
foreach (FileInfo file in configDirectory.GetFiles("*.json", SearchOption.AllDirectories))
{
string[] filename = file.Name.Split('.');
if (filename.Length != 5)
continue;
if (!file.Name.ToLower().StartsWith(pluginID.ToLower()))
continue;
if (!Enum.TryParse(filename[3], true, out ItemsListType list))
continue;
LogInfo($"Found {file.FullName}");
string listKey = TraderListKey(filename[2], list) + ".config";
try
{
using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader reader = new StreamReader(fs))
{
localConfig.Add(listKey, reader.ReadToEnd());
reader.Close();
fs.Dispose();
}
}
catch (Exception e)
{
logger.LogWarning($"Error reading file ({file.FullName})! Error: {e.Message}");
}
}
foreach (string resource in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
if (!resource.StartsWith("TradersExtended.Configs.") && !resource.EndsWith(".json"))
continue;
string[] resName = resource.Replace("TradersExtended.Configs.", "").Replace(".json", "").Split('.');
if (resName.Length != 2)
continue;
if (!Enum.TryParse(resName[1], true, out ItemsListType listType))
continue;
string list = TraderListKey(resName[0], listType) + ".internal";
LogInfo($"Found resource {list}");
try
{
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource))
using (StreamReader reader = new StreamReader(stream))
{
localConfig.Add(list, reader.ReadToEnd());
reader.Close();
stream.Dispose();
}
}
catch (Exception e)
{
logger.LogWarning($"Error reading resource ({resource})! Error: {e.Message}");
}
}
configsJSON.AssignLocalValue(localConfig);
}
private static void StartConfigLoad()
{
instance.StartCoroutine(LoadConfigs());
}
private static IEnumerator LoadConfigs()
{
tradeableItems.Clear();
sellableItems.Clear();
foreach (KeyValuePair<string, string> configJSON in configsJSON.Value)
{
string[] configKey = configJSON.Key.Split('.');
string trader = configKey[0];
Enum.TryParse(configKey[1], true, out ItemsListType list);
if (list == ItemsListType.Buy)
LoadTradeableItems(configJSON.Value, trader);
else
LoadSellableItems(configJSON.Value, trader);
}
if (addCommonValuableItemsToSellList.Value)
yield return AddCommonValuableItems();
}
private static void LoadTradeableItems(string JSON, string trader)
{
string listKey = TraderListKey(trader, ItemsListType.Buy);
if (!tradeableItems.ContainsKey(listKey))
tradeableItems.Add(listKey, new List<TradeableItem>());
List<TradeableItem> itemsFromFile;
try
{
itemsFromFile = JsonConvert.DeserializeObject<List<TradeableItem>>(JSON);
}
catch (Exception e)
{
logger.LogWarning($"Error parsing items ({listKey})! Error: {e.Message}");
return;
}
List<TradeableItem> items = itemsFromFile == null ? new List<TradeableItem>() : tradeableItems[listKey].Concat(itemsFromFile).ToList();
LogInfo($"Loaded {(itemsFromFile == null ? 0 : itemsFromFile.Count)} tradeable item from {listKey}");
tradeableItems[listKey] = items;
}
private static void LoadSellableItems(string JSON, string trader)
{
string listKey = TraderListKey(trader, ItemsListType.Sell);
if (!sellableItems.ContainsKey(listKey))
sellableItems.Add(listKey, new List<TradeableItem>());
List<TradeableItem> itemsFromFile;
try
{
itemsFromFile = JsonConvert.DeserializeObject<List<TradeableItem>>(JSON);
}
catch (Exception e)
{
logger.LogWarning($"Error parsing items ({listKey})! Error: {e.Message}");
return;
}
List<TradeableItem> items = sellableItems[listKey].Concat(itemsFromFile).ToList();
LogInfo($"Loaded {(itemsFromFile == null ? 0 : itemsFromFile.Count)} sellable item from {listKey}");
sellableItems[listKey] = items;
}
private static IEnumerator AddCommonValuableItems()
{
yield return new WaitUntil(() => (bool)ObjectDB.instance);
string listKey = CommonListKey(ItemsListType.Sell);
if (!sellableItems.ContainsKey(listKey))
sellableItems[listKey] = new List<TradeableItem>();
int itemsCount = sellableItems[listKey].Count;
foreach (GameObject prefab in ObjectDB.instance.m_items)
{
if (!prefab.TryGetComponent(out ItemDrop itemDrop))
continue;
if (itemDrop.m_itemData.m_shared.m_value <= 0)
continue;
if (IsItemInSellList(prefab.name))
continue;
sellableItems[listKey].Add(new TradeableItem()
{
prefab = prefab.name,
price = itemDrop.m_itemData.m_shared.m_value
});
}
LogInfo($"Loaded {sellableItems[listKey].Count - itemsCount} common valuable items from ObjectDB");
}
private static bool IsItemInSellList(string prefabName)
{
foreach (string listKey in sellableItems.Keys)
if (sellableItems[listKey].Any(item => item.prefab == prefabName))
return true;
return false;
}
internal static string TraderName(Trader trader)
{
return Utils.GetPrefabName(trader.name).ToLower().Replace("$npc_", "").Replace("npc_", "");
}
internal static string TraderName(string name)
{
return name.ToLower().Replace("$npc_", "").Replace("npc_", "");
}
public static string TraderListKey(Trader trader, ItemsListType type)
{
return TraderListKey(TraderName(trader), type);
}
public static string TraderListKey(string name, ItemsListType type)
{
return $"{TraderName(name)}.{type}";
}
public static string CommonListKey(ItemsListType type)
{
return TraderListKey("common", type);
}
}
}