-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathStackSizeController.cs
More file actions
623 lines (485 loc) · 22.6 KB
/
StackSizeController.cs
File metadata and controls
623 lines (485 loc) · 22.6 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
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Libraries;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("Stack Size Controller", "AnExiledDev/patched by chrome", "4.1.3")]
[Description("Allows configuration of most items max stack size.")]
class StackSizeController : CovalencePlugin
{
[PluginReference]
Plugin AirFuel, GetToDaChoppa, VehicleVendorOptions;
private const string _vanillaDefaultsUri = "https://raw.githubusercontent.com/AnExiledDev/StackSizeController/master/vanilla-defaults.json";
private Configuration _config;
private Dictionary<string, int> _vanillaDefaults;
private readonly List<string> _ignoreList = new List<string>
{
"water",
"water.salt",
"cardtable",
"hat.bunnyhat",
"rustige_egg_e"
};
private void Init()
{
_config = Config.ReadObject<Configuration>();
if (_config == null)
{
Log("Generating Default Config File.");
LoadDefaultConfig();
}
DownloadVanillaDefaults();
EnsureConfigIntegrity();
AddCovalenceCommand("stacksizecontroller.setstack", nameof(SetStackCommand),
"stacksizecontroller.setstack");
AddCovalenceCommand("stacksizecontroller.setstackcat", nameof(SetStackCategoryCommand),
"stacksizecontroller.setstackcat");
AddCovalenceCommand("stacksizecontroller.setallstacks", nameof(SetAllStacksCommand),
"stacksizecontroller.setallstacks");
AddCovalenceCommand("stacksizecontroller.itemsearch", nameof(ItemSearchCommand),
"stacksizecontroller.itemsearch");
AddCovalenceCommand("stacksizecontroller.listcategories", nameof(ListCategoriesCommand),
"stacksizecontroller.listcategories");
AddCovalenceCommand("stacksizecontroller.listcategoryitems", nameof(ListCategoryItemsCommand),
"stacksizecontroller.listcategoryitems");
AddCovalenceCommand("stacksizecontroller.vd", nameof(GenerateVanillaStackSizeFileCommand),
"stacksizecontroller.vd");
}
private void Unload()
{
if (_config.RevertStackSizesToVanillaOnUnload)
{
RevertStackSizes();
}
}
#region Configuration
private class Configuration
{
public bool RevertStackSizesToVanillaOnUnload = true;
public bool AllowStackingItemsWithDurability = true;
public bool HidePrefixWithPluginNameInMessages;
public float GlobalStackMultiplier = 1;
public Dictionary<string, float> CategoryStackMultipliers = GetCategoriesAndDefaults(1)
.ToDictionary(k => k.Key,
k => Convert.ToSingle(k.Value));
public Dictionary<string, float> IndividualItemStackMultipliers = new Dictionary<string, float>();
public Dictionary<string, int> IndividualItemStackSize = new Dictionary<string, int>();
public VersionNumber VersionNumber;
}
private static Dictionary<string, object> GetCategoriesAndDefaults(object defaultValue)
{
Dictionary<string, object> categoryDefaults = new Dictionary<string, object>();
foreach (string category in Enum.GetNames(typeof(ItemCategory)))
{
categoryDefaults.Add(category, defaultValue);
}
return categoryDefaults;
}
protected override void SaveConfig()
{
Config.WriteObject(_config);
}
protected override void LoadDefaultConfig()
{
Configuration defaultConfig = GetDefaultConfig();
defaultConfig.VersionNumber = Version;
Config.WriteObject(defaultConfig);
_config = Config.ReadObject<Configuration>();
}
private void EnsureConfigIntegrity()
{
Configuration configDefault = new Configuration();
if (_config.CategoryStackMultipliers == null)
{
_config.CategoryStackMultipliers = configDefault.CategoryStackMultipliers;
}
if (_config.IndividualItemStackMultipliers == null)
{
_config.IndividualItemStackMultipliers = configDefault.IndividualItemStackMultipliers;
}
_config.VersionNumber = Version;
SaveConfig();
}
private Configuration GetDefaultConfig()
{
return new Configuration();
}
private void UpdateIndividualItemStackMultiplier(int itemId, float multiplier)
{
if (_config.IndividualItemStackMultipliers.ContainsKey(itemId.ToString()))
{
_config.IndividualItemStackMultipliers[itemId.ToString()] = multiplier;
SaveConfig();
return;
}
_config.IndividualItemStackMultipliers.Add(ItemManager.itemDictionary[itemId].shortname, multiplier);
SaveConfig();
}
private void UpdateIndividualItemStackMultiplier(string shortname, float multiplier)
{
if (_config.IndividualItemStackMultipliers.ContainsKey(shortname))
{
_config.IndividualItemStackMultipliers[shortname] = multiplier;
SaveConfig();
return;
}
_config.IndividualItemStackMultipliers.Add(shortname, multiplier);
SaveConfig();
}
private void UpdateIndividualItemStackSize(int itemId, int stackLimit)
{
ItemDefinition item = ItemManager.FindItemDefinition(itemId);
if (_config.IndividualItemStackSize.ContainsKey(item.shortname))
{
_config.IndividualItemStackSize[item.shortname] = stackLimit;
SaveConfig();
return;
}
_config.IndividualItemStackSize.Add(item.shortname, stackLimit);
SaveConfig();
}
private void UpdateIndividualItemStackSize(string shortname, int stackLimit)
{
if (_config.IndividualItemStackSize.ContainsKey(shortname))
{
_config.IndividualItemStackSize[shortname] = stackLimit;
SaveConfig();
return;
}
_config.IndividualItemStackSize.Add(shortname, stackLimit);
SaveConfig();
}
private void PopulateIndividualItemStackSize()
{
if (_config.IndividualItemStackSize.Count == 0)
{
Log($"Populating Individual Item Stack Sizes in configuration.");
_config.IndividualItemStackSize = _vanillaDefaults;
}
else
{
foreach (ItemDefinition itemDefinition in ItemManager.GetItemDefinitions())
{
if (!_config.IndividualItemStackSize.ContainsKey(itemDefinition.shortname))
{
Log($"Adding new item {itemDefinition.shortname} to IndividualItemStackSize in configuration.");
_config.IndividualItemStackSize.Add(itemDefinition.shortname, itemDefinition.stackable);
}
}
}
SaveConfig();
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["NotEnoughArguments"] = "This command requires {0} arguments.",
["InvalidItemShortnameOrId"] =
"Item shortname or id is incorrect. Try stacksizecontroller.itemsearch [partial item name]",
["InvalidCategory"] = "Category not found. Try stacksizecontroller.listcategories",
["OperationSuccessful"] = "Operation completed successfully.",
}, this);
}
private string GetMessage(string key)
{
return lang.GetMessage(key, this);
}
private string GetMessage(string key, string playerId)
{
if (_config.HidePrefixWithPluginNameInMessages || playerId == "server_console")
{
return lang.GetMessage(key, this, playerId);
}
return $"<color=#ff760d><b>[{nameof(StackSizeController)}]</b></color> " +
lang.GetMessage(key, this, playerId);
}
#endregion
#region Hooks
// Credit to WhiteThunder- https://github.com/AnExiledDev/StackSizeController/pull/7
// Fix initial fuel amount for vendor-spawned helis since they use 20% of max stack size of low grade.
private void OnEntitySpawned(Minicopter heli)
{
// Ignore if a known plugin is loaded that adjusts heli fuel.
if (AirFuel != null || GetToDaChoppa != null || VehicleVendorOptions != null)
return;
// Must delay for vendor-spawned helis since the creatorEntity is set after spawn.
NextTick(() =>
{
if (heli == null
// Make sure it's a vendor-spawned heli.
|| !heli.IsSafe()
// Make sure the game hasn't changed unexpectedly.
|| heli.StartingFuelUnits() != -1)
return;
var fuelItem = (heli.GetFuelSystem() as EntityFuelSystem)?.GetFuelItem();
if (fuelItem == null
// Ignore other types of fuel since they will have been placed by mods.
|| fuelItem.info.shortname != "lowgradefuel"
// Ignore if the fuel amount is unexpected, since a mod likely adjusted it.
|| fuelItem.amount != fuelItem.info.stackable / 5)
return;
var hookResult = Interface.CallHook("OnVendorHeliFuelAdjust", heli);
if (hookResult is bool && (bool)hookResult == false)
return;
fuelItem.amount = 100;
fuelItem.MarkDirty();
});
}
int OnMaxStackable(Item item)
{
if (_vanillaDefaults == null)
{
return item.info.stackable;
}
return GetStackSize(item.info);
}
#endregion
#region Commands
private void SetStackCommand(IPlayer player, string command, string[] args)
{
if (args.Length != 2)
{
player.Reply(
string.Format(GetMessage("NotEnoughArguments", player.Id), 2));
return;
}
ItemDefinition itemDefinition = ItemManager.FindItemDefinition(args[0]);
string stackSizeString = args[1];
if (itemDefinition == null)
{
player.Reply(GetMessage("InvalidItemShortnameOrId", player.Id));
return;
}
if (stackSizeString.Substring(stackSizeString.Length - 1) == "x")
{
UpdateIndividualItemStackMultiplier(itemDefinition.itemid,
Convert.ToSingle(stackSizeString.TrimEnd('x')));
SetStackSizes();
player.Reply(GetMessage("OperationSuccessful", player.Id));
return;
}
UpdateIndividualItemStackSize(itemDefinition.shortname, Convert.ToInt32(stackSizeString.TrimEnd('x')));
SetStackSizes();
player.Reply(GetMessage("OperationSuccessful", player.Id));
}
private void SetAllStacksCommand(IPlayer player, string command, string[] args)
{
if (args.Length != 1)
{
player.Reply(
string.Format(GetMessage("NotEnoughArguments", player.Id), 1));
}
foreach (string category in _config.CategoryStackMultipliers.Keys.ToList())
{
_config.CategoryStackMultipliers[category] = Convert.ToInt32(args[0]);
}
SaveConfig();
SetStackSizes();
player.Reply(GetMessage("OperationSuccessful", player.Id));
}
private void SetStackCategoryCommand(IPlayer player, string command, string[] args)
{
if (args.Length != 2)
{
player.Reply(
string.Format(GetMessage("NotEnoughArguments", player.Id), 2));
}
ItemCategory itemCategory = (ItemCategory)Enum.Parse(typeof(ItemCategory), args[0], true);
_config.CategoryStackMultipliers[itemCategory.ToString()] = Convert.ToInt32(args[1].TrimEnd('x'));
SaveConfig();
SetStackSizes();
player.Reply(GetMessage("OperationSuccessful", player.Id));
}
private void ItemSearchCommand(IPlayer player, string command, string[] args)
{
if (args.Length != 1)
{
player.Reply(
string.Format(GetMessage("NotEnoughArguments", player.Id), 1));
}
List<ItemDefinition> itemDefinitions = ItemManager.itemList.Where(itemDefinition =>
itemDefinition.displayName.english.Contains(args[0]) ||
itemDefinition.displayDescription.english.Contains(args[0]) ||
itemDefinition.shortname.Equals(args[0]) ||
itemDefinition.shortname.Contains(args[0]))
.ToList();
TextTable output = new TextTable();
output.AddColumns("Unique Id", "Shortname", "Category", "Vanilla Stack", "Custom Stack");
foreach (ItemDefinition itemDefinition in itemDefinitions)
{
output.AddRow(itemDefinition.itemid.ToString(), itemDefinition.shortname,
itemDefinition.category.ToString(), _vanillaDefaults[itemDefinition.shortname].ToString("N0"),
Mathf.Clamp(GetStackSize(itemDefinition), 0, int.MaxValue).ToString("N0"));
}
player.Reply(output.ToString());
}
private void ListCategoriesCommand(IPlayer player, string command, string[] args)
{
TextTable output = new TextTable();
output.AddColumns("Category Name", "Items In Category");
foreach (string category in Enum.GetNames(typeof(ItemCategory)))
{
output.AddRow(category, ItemManager.itemList.Where(x => x.category.ToString() == category).Count().ToString());
}
player.Reply(output.ToString());
}
private void ListCategoryItemsCommand(IPlayer player, string command, string[] args)
{
if (args.Length != 1)
{
player.Reply(string.Format(GetMessage("NotEnoughArguments", player.Id), 1));
}
ItemCategory itemCategory = (ItemCategory)Enum.Parse(typeof(ItemCategory), args[0]);
TextTable output = new TextTable();
output.AddColumns("Unique Id", "Shortname", "Category", "Vanilla Stack", "Custom Stack", "Multiplier");
foreach (ItemDefinition itemDefinition in ItemManager.GetItemDefinitions()
.Where(itemDefinition => itemDefinition.category == itemCategory))
{
output.AddRow(itemDefinition.itemid.ToString(), itemDefinition.shortname,
itemDefinition.category.ToString(), _vanillaDefaults[itemDefinition.shortname].ToString("N0"),
Mathf.Clamp(GetStackSize(itemDefinition), 0, int.MaxValue).ToString("N0"),
_config.CategoryStackMultipliers[itemDefinition.category.ToString()].ToString());
}
player.Reply(output.ToString());
}
#endregion
#region Dev Use
private void GenerateVanillaStackSizeFileCommand(IPlayer player, string command, string[] args)
{
GenerateVanillaStackSizeFile();
}
private void GenerateVanillaStackSizeFile()
{
RevertStackSizes();
SortedDictionary<string, int> vanillaStackSizes = new SortedDictionary<string, int>();
foreach (ItemDefinition itemDefinition in ItemManager.GetItemDefinitions())
{
vanillaStackSizes.Add(itemDefinition.shortname, itemDefinition.stackable);
}
Interface.Oxide.DataFileSystem.WriteObject(nameof(StackSizeController) + "_vanilla-defaults",
vanillaStackSizes);
SetStackSizes();
Log("Vanilla stack sizes file updated. Custom stack sizes restored.");
}
#endregion
#region Helpers
private void DownloadVanillaDefaults()
{
Log($"Acquiring vanilla defaults file from official GitHub repo and overwriting; {_vanillaDefaultsUri}");
try
{
webrequest.Enqueue(_vanillaDefaultsUri, null, SetVanillaDefaults, this, RequestMethod.GET);
}
catch (Exception ex)
{
LogError($"Exception encountered while attempting to get vanilla defaults: {ex}");
}
}
private void SetVanillaDefaults(int code, string response)
{
if (code != 200 || response == null)
{
LogWarning($"Unable to get result from GitHub, code {code}. If you don't have a vanilla defaults datafile, the plugin will throw errors. " +
$"Reloading should resolve this unless there is something preventing downloads from external sites.");
LogWarning("If the issue persists, check the uMod forums for StackSizeController for a manual fix.");
return;
}
_vanillaDefaults = JsonConvert.DeserializeObject<Dictionary<string, int>>(response);
Interface.Oxide.DataFileSystem.WriteObject(nameof(StackSizeController) +
"_vanilla-defaults", _vanillaDefaults);
// TODO: Consider refactoring workflow to avoid ambiguity
PopulateIndividualItemStackSize();
SetStackSizes();
}
private int GetVanillaStackSize(ItemDefinition itemDefinition)
{
return _vanillaDefaults.ContainsKey(itemDefinition.shortname)
? _vanillaDefaults[itemDefinition.shortname]
: itemDefinition.stackable;
}
private int GetStackSize(int itemId)
{
return GetStackSize(ItemManager.FindItemDefinition(itemId));
}
private int GetStackSize(ItemDefinition itemDefinition)
{
try
{
if (_ignoreList.Contains(itemDefinition.shortname))
{
return GetVanillaStackSize(itemDefinition);
}
int stackable = GetVanillaStackSize(itemDefinition);
// Individual Limit set by shortname
if (_config.IndividualItemStackSize.ContainsKey(itemDefinition.shortname))
{
stackable = _config.IndividualItemStackSize[itemDefinition.shortname];
}
// Individual Multiplier set by shortname
if (_config.IndividualItemStackMultipliers.ContainsKey(itemDefinition.shortname))
{
return Mathf.RoundToInt(stackable * _config.IndividualItemStackMultipliers[itemDefinition.shortname]);
}
// Individual Multiplier set by item id
if (_config.IndividualItemStackMultipliers.ContainsKey(itemDefinition.itemid.ToString()))
{
return Mathf.RoundToInt(stackable * _config.IndividualItemStackMultipliers[itemDefinition.itemid.ToString()]);
}
// Category stack multiplier defined
if (_config.CategoryStackMultipliers.ContainsKey(itemDefinition.category.ToString()) &&
_config.CategoryStackMultipliers[itemDefinition.category.ToString()] > 1.0f)
{
return Mathf.RoundToInt(
stackable * _config.CategoryStackMultipliers[itemDefinition.category.ToString()]);
}
return Mathf.RoundToInt(stackable * _config.GlobalStackMultiplier);
}
catch (Exception ex)
{
LogError("Exception encountered during GetStackSize. Item: " + itemDefinition.shortname + " Ex:" + ex.ToString());
return GetVanillaStackSize(itemDefinition);
}
}
private void SetStackSizes()
{
foreach (ItemDefinition itemDefinition in ItemManager.GetItemDefinitions())
{
if (itemDefinition.condition.enabled && !_config.AllowStackingItemsWithDurability)
{
itemDefinition.stackable = Mathf.Clamp(GetVanillaStackSize(itemDefinition), 1, int.MaxValue);
continue;
}
if (_ignoreList.Contains(itemDefinition.shortname))
{
continue;
}
itemDefinition.stackable = Mathf.Clamp(GetStackSize(itemDefinition), 1, int.MaxValue);
}
}
private void RevertStackSizes()
{
Log("Reverting stack sizes to vanilla defaults.");
foreach (ItemDefinition itemDefinition in ItemManager.GetItemDefinitions())
{
if (itemDefinition.condition.enabled && !_config.AllowStackingItemsWithDurability)
{
continue;
}
if (_ignoreList.Contains(itemDefinition.shortname))
{
continue;
}
itemDefinition.stackable = Mathf.Clamp(GetVanillaStackSize(itemDefinition), 1, int.MaxValue);
}
}
#endregion
}
}