forked from Pathoschild/StardewMods
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModEntry.cs
367 lines (320 loc) · 15.7 KB
/
ModEntry.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Pathoschild.Stardew.Automate.Framework;
using Pathoschild.Stardew.Automate.Framework.Models;
using Pathoschild.Stardew.Common;
using Pathoschild.Stardew.Common.Messages;
using Pathoschild.Stardew.Common.Utilities;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using StardewValley.Locations;
namespace Pathoschild.Stardew.Automate
{
/// <summary>The mod entry point.</summary>
internal class ModEntry : Mod
{
/*********
** Fields
*********/
/// <summary>The mod configuration.</summary>
private ModConfig Config;
/// <summary>The configured key bindings.</summary>
private ModConfigKeys Keys;
/// <summary>Constructs machine groups.</summary>
private MachineGroupFactory Factory;
/// <summary>Whether to enable automation for the current save.</summary>
private bool EnableAutomation => Context.IsMainPlayer;
/// <summary>The machines to process.</summary>
private readonly IDictionary<GameLocation, MachineGroup[]> ActiveMachineGroups = new Dictionary<GameLocation, MachineGroup[]>(new ObjectReferenceComparer<GameLocation>());
/// <summary>The disabled machine groups (e.g. machines not connected to a chest).</summary>
private readonly IDictionary<GameLocation, MachineGroup[]> DisabledMachineGroups = new Dictionary<GameLocation, MachineGroup[]>(new ObjectReferenceComparer<GameLocation>());
/// <summary>The locations that should be reloaded on the next update tick.</summary>
private readonly HashSet<GameLocation> ReloadQueue = new HashSet<GameLocation>(new ObjectReferenceComparer<GameLocation>());
/// <summary>The number of ticks until the next automation cycle.</summary>
private int AutomateCountdown;
/// <summary>The current overlay being displayed, if any.</summary>
private OverlayMenu CurrentOverlay;
/*********
** Public methods
*********/
/// <summary>The mod entry point, called after the mod is first loaded.</summary>
/// <param name="helper">Provides methods for interacting with the mod directory, such as read/writing a config file or custom JSON files.</param>
public override void Entry(IModHelper helper)
{
// read data file
const string dataPath = "assets/data.json";
DataModel data = null;
try
{
data = this.Helper.Data.ReadJsonFile<DataModel>(dataPath);
if (data?.FloorNames == null)
this.Monitor.Log($"The {dataPath} file seems to be missing or invalid. Floor connectors will be disabled.", LogLevel.Error);
}
catch (Exception ex)
{
this.Monitor.Log($"The {dataPath} file seems to be invalid. Floor connectors will be disabled.\n{ex}", LogLevel.Error);
}
// read config
this.Config = helper.ReadConfig<ModConfig>();
this.Config.MachinePriority = new Dictionary<string, int>(this.Config.MachinePriority, StringComparer.OrdinalIgnoreCase);
// init
this.Keys = this.Config.Controls.ParseControls(helper.Input, this.Monitor);
this.Factory = new MachineGroupFactory(this.Config);
this.Factory.Add(new AutomationFactory(
connectors: this.Config.ConnectorNames,
automateShippingBin: this.Config.AutomateShippingBin,
monitor: this.Monitor,
reflection: helper.Reflection,
data: data,
betterJunimosCompat: this.Config.ModCompatibility.BetterJunimos && helper.ModRegistry.IsLoaded("hawkfalcon.BetterJunimos"),
autoGrabberModCompat: this.Config.ModCompatibility.AutoGrabberMod && helper.ModRegistry.IsLoaded("Jotser.AutoGrabberMod"),
pullGemstonesFromJunimoHuts: this.Config.PullGemstonesFromJunimoHuts
));
// hook events
helper.Events.GameLoop.SaveLoaded += this.OnSaveLoaded;
helper.Events.Player.Warped += this.OnWarped;
helper.Events.World.BuildingListChanged += this.OnBuildingListChanged;
helper.Events.World.LocationListChanged += this.OnLocationListChanged;
helper.Events.World.ObjectListChanged += this.OnObjectListChanged;
helper.Events.World.TerrainFeatureListChanged += this.OnTerrainFeatureListChanged;
helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked;
helper.Events.Input.ButtonPressed += this.OnButtonPressed;
helper.Events.Multiplayer.ModMessageReceived += this.OnModMessageReceived;
// log info
this.Monitor.VerboseLog($"Initialized with automation every {this.Config.AutomationInterval} ticks.");
}
/// <summary>Get an API that other mods can access. This is always called after <see cref="Entry" />.</summary>
public override object GetApi()
{
return new AutomateAPI(this.Monitor, this.Factory, this.ActiveMachineGroups, this.DisabledMachineGroups);
}
/*********
** Private methods
*********/
/****
** Event handlers
****/
/// <summary>The method invoked when the player loads a save.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnSaveLoaded(object sender, SaveLoadedEventArgs e)
{
// disable if secondary player
if (!this.EnableAutomation)
this.Monitor.Log("Disabled automation (only the main player can automate machines in multiplayer mode).", LogLevel.Warn);
// reset
this.ActiveMachineGroups.Clear();
this.DisabledMachineGroups.Clear();
this.AutomateCountdown = this.Config.AutomationInterval;
this.DisableOverlay();
foreach (GameLocation location in CommonHelper.GetLocations())
this.ReloadQueue.Add(location);
}
/// <summary>The method invoked when the player warps to a new location.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnWarped(object sender, WarpedEventArgs e)
{
if (e.IsLocalPlayer)
this.ResetOverlayIfShown();
}
/// <summary>The method invoked when a location is added or removed.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnLocationListChanged(object sender, LocationListChangedEventArgs e)
{
if (!this.EnableAutomation)
return;
this.Monitor.VerboseLog("Location list changed, reloading machines in affected locations.");
try
{
// remove locations
foreach (GameLocation location in e.Removed)
{
this.ActiveMachineGroups.Remove(location);
this.DisabledMachineGroups.Remove(location);
}
// add locations
foreach (GameLocation location in e.Added)
this.ReloadQueue.Add(location);
}
catch (Exception ex)
{
this.HandleError(ex, "updating locations");
}
}
/// <summary>The method raised after buildings are added or removed in a location.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnBuildingListChanged(object sender, BuildingListChangedEventArgs e)
{
if (!this.EnableAutomation)
return;
if (e.Location is BuildableGameLocation buildableLocation && e.Added.Concat(e.Removed).Any(building => this.Factory.IsAutomatable(buildableLocation, new Vector2(building.tileX.Value, building.tileY.Value), building)))
{
this.Monitor.VerboseLog($"Building list changed in {e.Location.Name}, reloading its machines.");
this.ReloadQueue.Add(e.Location);
}
}
/// <summary>The method invoked when an object is added or removed to a location.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnObjectListChanged(object sender, ObjectListChangedEventArgs e)
{
if (!this.EnableAutomation)
return;
if (e.Added.Concat(e.Removed).Any(obj => this.Factory.IsAutomatable(e.Location, obj.Key, obj.Value)))
{
this.Monitor.VerboseLog($"Object list changed in {e.Location.Name}, reloading its machines.");
this.ReloadQueue.Add(e.Location);
}
}
/// <summary>The method invoked when a terrain feature is added or removed to a location.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnTerrainFeatureListChanged(object sender, TerrainFeatureListChangedEventArgs e)
{
if (!this.EnableAutomation)
return;
if (e.Added.Concat(e.Removed).Any(obj => this.Factory.IsAutomatable(e.Location, obj.Key, obj.Value)))
{
this.Monitor.VerboseLog($"Terrain feature list changed in {e.Location.Name}, reloading its machines.");
this.ReloadQueue.Add(e.Location);
}
}
/// <summary>The method invoked when the in-game clock time changes.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnUpdateTicked(object sender, UpdateTickedEventArgs e)
{
if (!Context.IsWorldReady || !this.EnableAutomation)
return;
try
{
// handle delay
this.AutomateCountdown--;
if (this.AutomateCountdown > 0)
return;
this.AutomateCountdown = this.Config.AutomationInterval;
// reload machines if needed
if (this.ReloadQueue.Any())
{
foreach (GameLocation location in this.ReloadQueue)
this.ReloadMachinesIn(location);
this.ReloadQueue.Clear();
this.ResetOverlayIfShown();
}
// process machines
foreach (MachineGroup group in this.GetActiveMachineGroups())
group.Automate();
}
catch (Exception ex)
{
this.HandleError(ex, "processing machines");
}
}
/// <summary>The method invoked when the player presses a button.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
{
try
{
// toggle overlay
if (Context.IsPlayerFree && this.Keys.ToggleOverlay.JustPressedUnique())
{
if (this.CurrentOverlay != null)
this.DisableOverlay();
else
this.EnableOverlay();
}
}
catch (Exception ex)
{
this.HandleError(ex, "handling key input");
}
}
/// <summary>Raised after a mod message is received over the network.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
private void OnModMessageReceived(object sender, ModMessageReceivedEventArgs e)
{
// update automation if chest options changed
if (Context.IsMainPlayer && e.FromModID == "Pathoschild.ChestsAnywhere" && e.Type == nameof(AutomateUpdateChestMessage))
{
var message = e.ReadAs<AutomateUpdateChestMessage>();
var location = Game1.getLocationFromName(message.LocationName);
var player = Game1.getFarmer(e.FromPlayerID);
string label = player != Game1.MasterPlayer
? $"{player.Name}/{e.FromModID}"
: e.FromModID;
if (location != null)
{
this.Monitor.Log($"Received chest update from {label} for chest at {message.LocationName} ({message.Tile}), updating machines.");
this.ReloadQueue.Add(location);
}
else
this.Monitor.Log($"Received chest update from {label} for chest at {message.LocationName} ({message.Tile}), but no such location was found.");
}
}
/****
** Methods
****/
/// <summary>Get the active machine groups in every location.</summary>
private IEnumerable<MachineGroup> GetActiveMachineGroups()
{
foreach (KeyValuePair<GameLocation, MachineGroup[]> group in this.ActiveMachineGroups)
{
foreach (MachineGroup machineGroup in group.Value)
yield return machineGroup;
}
}
/// <summary>Reload the machines in a given location.</summary>
/// <param name="location">The location whose machines to reload.</param>
private void ReloadMachinesIn(GameLocation location)
{
this.Monitor.VerboseLog($"Reloading machines in {location.Name}...");
// get machine groups
MachineGroup[] machineGroups = this.Factory.GetMachineGroups(location).ToArray();
this.ActiveMachineGroups[location] = machineGroups.Where(p => p.HasInternalAutomation).ToArray();
this.DisabledMachineGroups[location] = machineGroups.Where(p => !p.HasInternalAutomation).ToArray();
// remove unneeded entries
if (!this.ActiveMachineGroups[location].Any())
this.ActiveMachineGroups.Remove(location);
if (!this.DisabledMachineGroups[location].Any())
this.DisabledMachineGroups.Remove(location);
}
/// <summary>Log an error and warn the user.</summary>
/// <param name="ex">The exception to handle.</param>
/// <param name="verb">The verb describing where the error occurred (e.g. "looking that up").</param>
private void HandleError(Exception ex, string verb)
{
this.Monitor.Log($"Something went wrong {verb}:\n{ex}", LogLevel.Error);
CommonHelper.ShowErrorMessage($"Huh. Something went wrong {verb}. The error log has the technical details.");
}
/// <summary>Disable the overlay, if shown.</summary>
private void DisableOverlay()
{
this.CurrentOverlay?.Dispose();
this.CurrentOverlay = null;
}
/// <summary>Enable the overlay.</summary>
private void EnableOverlay()
{
if (this.CurrentOverlay == null)
this.CurrentOverlay = new OverlayMenu(this.Helper.Events, this.Helper.Input, this.Helper.Reflection, this.Factory.GetMachineGroups(Game1.currentLocation));
}
/// <summary>Reset the overlay if it's being shown.</summary>
private void ResetOverlayIfShown()
{
if (this.CurrentOverlay != null)
{
this.DisableOverlay();
this.EnableOverlay();
}
}
}
}