forked from xmnovotny/VoxelTycoon-ScheduleStopwatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VehicleScheduleCapacity.cs
463 lines (424 loc) · 17.9 KB
/
VehicleScheduleCapacity.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
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
using System;
using System.Collections.Generic;
using VoxelTycoon;
using VoxelTycoon.Tracks;
using VoxelTycoon.Tracks.Tasks;
namespace ScheduleStopwatch
{
public partial class VehicleScheduleCapacity
{
public VehicleSchedule VehicleSchedule { get; }
public event Action<VehicleScheduleCapacity> DataChanged;
/* capacity and item transfers are valid (=i.e. there is no problem with calculation of that data) */
public bool HasValidData
{
get
{
if (_hasValidData == null)
{
Invalidate();
}
return _hasValidData.Value;
}
}
public VehicleScheduleCapacity(VehicleSchedule vehicleSchedule)
{
VehicleSchedule = vehicleSchedule ?? throw new ArgumentNullException(nameof(vehicleSchedule));
_hasValidData = null;
_dirty = true;
SubscribeUnitStorageChange();
}
public void MarkDirty()
{
_dirty = true;
_hasValidData = null;
}
public IReadOnlyDictionary<Item, TransferData> GetTransfers(RootTask task)
{
Invalidate();
if (_transfers.TryGetValue(task, out TaskTransfers transfer))
{
return transfer.Transfers;
}
return null;
}
/* Returns total of transferred items per schedule (=sum of unloaded items) */
public IReadOnlyDictionary<Item, TransferData> GetTotalTransfers()
{
return TotalTransfers?.Transfers;
}
public void OnVehicleEdited()
{
SubscribeUnitStorageChange();
MarkDirty();
OnDataChanged();
}
public IReadOnlyDictionary<Item, TransferData> GetRouteTotalTransfers(bool skipForOnlyOneVehicle=true) {
if (!HasValidData || VehicleSchedule.Vehicle.Route != null)
{
TaskTransfers totalTransfers = new TaskTransfers();
VehicleRoute route = VehicleSchedule.Vehicle.Route;
if (skipForOnlyOneVehicle && route.Vehicles.Count == 1)
{
return null;
}
foreach (Vehicle vehicle in route.Vehicles.ToArray())
{
if (vehicle.IsEnabled)
{
VehicleScheduleData vehicleData = VehicleScheduleDataManager.Current[vehicle];
float? mult;
if (vehicleData == null || !vehicleData.Capacity.HasValidData || (mult = vehicleData.ScheduleMonthlyMultiplier) == null)
{
return null;
}
totalTransfers.Add(vehicleData.Capacity.TotalTransfers, mult, vehicleData.ScheduleAvereageDuration.Estimated);
}
}
return totalTransfers.Transfers;
}
return null;
}
public TransfersPerStationCont GetRouteTransfersPerStation(bool skipForOnlyOneVehicle = true)
{
if (!HasValidData || VehicleSchedule.Vehicle.Route != null)
{
TransfersPerStationCont totalTransfers = new TransfersPerStationCont();
VehicleRoute route = VehicleSchedule.Vehicle.Route;
if (skipForOnlyOneVehicle && route.Vehicles.Count == 1)
{
return null;
}
foreach (Vehicle vehicle in route.Vehicles.ToArray())
{
if (vehicle.IsEnabled)
{
VehicleScheduleData vehicleData = VehicleScheduleDataManager.Current[vehicle];
float? mult;
if (vehicleData == null || !vehicleData.Capacity.HasValidData || (mult = vehicleData.ScheduleMonthlyMultiplier) == null)
{
return null;
}
totalTransfers.Add(vehicleData.Capacity.GetTransfersPerStation(), mult, vehicleData.ScheduleAvereageDuration.Estimated);
}
}
return totalTransfers.AsReadonly();
}
return null;
}
public IReadOnlyDictionary<Item, TransferData> GetRouteTaskTransfers(RootTask task, bool skipForOnlyOneVehicle = true)
{
if (task == null)
{
throw new ArgumentNullException("task");
}
if (!HasValidData || VehicleSchedule.Vehicle.Route != null)
{
TaskTransfers routeTransfers = new TaskTransfers();
VehicleRoute route = VehicleSchedule.Vehicle.Route;
if (skipForOnlyOneVehicle && route.Vehicles.Count == 1)
{
return null;
}
int taskIndex = task.GetIndex();
foreach (Vehicle vehicle in route.Vehicles.ToArray())
{
if (vehicle.IsEnabled)
{
VehicleScheduleData vehicleData = VehicleScheduleDataManager.Current[vehicle];
float? mult;
if (vehicleData == null || !vehicleData.Capacity.HasValidData || (mult = vehicleData.ScheduleMonthlyMultiplier) == null)
{
return null;
}
routeTransfers.Add(vehicleData.Capacity.GetTransfers(vehicle.Schedule.GetTasks()[taskIndex]), mult, vehicleData.ScheduleAvereageDuration.Estimated);
}
}
return routeTransfers.Transfers;
}
return null;
}
public TransfersPerStationCont GetTransfersPerStation()
{
return TransfersPerStation?.AsReadonly();
}
public TransfersPerStationCont GetTransfersPerStation(int unitIndex)
{
Invalidate();
if (_transfPerStationPerUnit == null)
{
_transfPerStationPerUnit = new Dictionary<int, TransfersPerStationCont>();
}
if (!_transfPerStationPerUnit.TryGetValue(unitIndex, out TransfersPerStationCont result))
{
if (!TransfPerUnit.TryGetValue(unitIndex, out Dictionary<RootTask, TaskTransfers> transfers)) {
transfers = null;
}
result = new TransfersPerStationCont(transfers);
_transfPerStationPerUnit.Add(unitIndex, result);
}
return result.AsReadonly();
}
private struct StorageState
{
public Storage storage;
public int count;
public StorageState(Storage storage, int count = 0)
{
this.storage = storage;
this.count = count;
}
}
private void SubscribeUnitStorageChange()
{
foreach (VehicleUnit unit in VehicleSchedule.Vehicle.Units.ToArray())
{
unit.StorageChanged -= this.OnVehicleUnitStorageChange;
unit.StorageChanged += this.OnVehicleUnitStorageChange;
}
}
private void Invalidate()
{
if (_dirty)
{
_totalTransfers = null;
_transfPerStation = null;
_transfPerUnit = null;
_transfPerStationPerUnit = null;
_storages = null;
BuildTaskTransfers();
_dirty = false;
}
}
/**
* Simulate refit task on provided storages.
* Returns false when the refit task has no item to refit (=Auto refit)
*/
private bool Refit(RefitTask refitTask, Dictionary<VehicleUnit, StorageState> storages)
{
Item item = refitTask.Item;
if (item == null)
{
//refit to auto = cannot determine begin state
return false;
}
ImmutableUniqueList<VehicleUnit> targetUnits = refitTask.GetTargetUnits();
int targetUnitsCount = targetUnits.Count;
StorageManager storageManager = LazyManager<StorageManager>.Current;
for (var k = 0; k < targetUnitsCount; k++)
{
VehicleUnit targetUnit = targetUnits[k];
storageManager.TryGetStorage(targetUnit.SharedData.AssetId, item, out Storage newStorage);
if (newStorage != null && storages.ContainsKey(targetUnit) && (storages[targetUnit].storage == null || storages[targetUnit].storage.Item != newStorage.Item))
{
storages[targetUnit] = new StorageState(newStorage);
}
}
return true;
}
/**
* Simulate transfer task on provided storages.
*/
private bool Transfer(TransferTask transferTask, Dictionary<VehicleUnit, StorageState> storages, ref TaskTransfers taskTransfers, ref TaskTransfers[] taskTransfersPerUnit, bool calculateTransfer = false, bool calculateTransferPerUnit = false)
{
ImmutableUniqueList<VehicleUnit> targetUnits = transferTask.GetTargetUnits();
int targetUnitsCount = targetUnits.Count;
for (int k = 0; k < targetUnitsCount; k++)
{
VehicleUnit targetUnit = targetUnits[k];
if (storages.TryGetValue(targetUnit, out StorageState storage))
{
if (storage.storage == null)
{
//autorefitable storage = cannot determine transfer
return false;
}
int newCount = transferTask is LoadTask ? storage.storage.Capacity : 0;
if (storage.count != newCount)
{
if (calculateTransfer)
{
if (taskTransfers == null)
{
taskTransfers = new TaskTransfers();
}
taskTransfers.Add(storage.storage.Item, newCount - storage.count);
}
if (calculateTransferPerUnit)
{
int unitIndex = targetUnit.Vehicle.Units.IndexOf(targetUnit);
if (taskTransfersPerUnit == null)
{
taskTransfersPerUnit = new TaskTransfers[targetUnit.Vehicle.Units.Count];
}
if (taskTransfersPerUnit[unitIndex] == null) {
taskTransfersPerUnit[unitIndex] = new TaskTransfers();
}
taskTransfersPerUnit[unitIndex].Add(storage.storage.Item, newCount - storage.count);
}
storage.count = newCount;
storages[targetUnit] = storage;
}
}
}
return true;
}
private Dictionary<VehicleUnit, StorageState> ActualStorages
{
get
{
if (_storages == null)
{
Vehicle vehicle = VehicleSchedule.Vehicle;
ImmutableList<VehicleUnit> units = vehicle.Units;
int unitsCount = units.Count;
_storages = new Dictionary<VehicleUnit, StorageState>(unitsCount);
for (var i = 0; i < unitsCount; i++)
{
_storages.Add(units[i], new StorageState(units[i].Storage));
}
}
return _storages;
}
}
private bool ProcessSchedule(Dictionary<VehicleUnit, StorageState> storages, bool onlyRefit, Dictionary<RootTask, TaskTransfers> transfers = null, Dictionary<int, Dictionary<RootTask, TaskTransfers>> transfersPerUnit = null)
{
ImmutableList<RootTask> tasks = VehicleSchedule.GetTasks();
int tasksCount = tasks.Count;
for (int i = 0; i < tasksCount; i++)
{
RootTask task = tasks[i];
ImmutableList<SubTask> subTasks = task.GetSubTasks();
int subTaskCount = subTasks.Count;
TaskTransfers transfer = null;
TaskTransfers[] transferPerUnit = null;
for (int j = 0; j < subTaskCount; j++)
{
SubTask subTask = subTasks[j];
if (subTask is RefitTask refitTask)
{
if (!Refit(refitTask, storages))
{
return false;
}
} else
if (!onlyRefit && subTask is TransferTask transferTask)
{
if (!Transfer(transferTask, storages, ref transfer, ref transferPerUnit, transfers != null, transfersPerUnit != null))
{
return false;
}
}
}
if (transfer != null)
{
transfers.Add(task, transfer);
}
if (transferPerUnit != null && transferPerUnit.Length > 0)
{
for(int j = 0; j < transferPerUnit.Length; j++)
{
TaskTransfers unitTransfer = transferPerUnit[j];
if (unitTransfer != null)
{
if (!transfersPerUnit.TryGetValue(j, out Dictionary<RootTask, TaskTransfers> unitTransfers))
{
unitTransfers = new Dictionary<RootTask, TaskTransfers>();
transfersPerUnit.Add(j, unitTransfers);
}
if (unitTransfers.TryGetValue(task, out TaskTransfers addedUnitTransfers)) {
addedUnitTransfers.Add(unitTransfer);
} else
{
unitTransfers.Add(task, unitTransfer);
}
}
}
}
}
return true;
}
private void BuildTaskTransfers()
{
_transfers.Clear();
_hasValidData = false;
Dictionary<VehicleUnit, StorageState> storages = ActualStorages;
if (!ProcessSchedule(storages, true)) //find start state of storages
{
return; //some refit is set to auto
}
if (!ProcessSchedule(storages, false)) //find start state of loaded items
return; //some vehicle unit has stroage setted to auto and there is no refit in the schedule for set it to the specific item
ProcessSchedule(storages, false, _transfers); //finally simulate counts loaded and unloaded for each task
_hasValidData = true;
}
private void BuildTransfersPerUnit()
{
if (_hasValidData == true)
{
_transfPerUnit = new Dictionary<int, Dictionary<RootTask, TaskTransfers>>();
ProcessSchedule(ActualStorages, false, null, _transfPerUnit); //finally simulate counts loaded and unloaded for each task
}
}
private void OnVehicleUnitStorageChange(object _, Storage __, Storage ___)
{
if (!((VehicleSchedule.CurrentTask as RootTask)?.CurrentSubTask is RefitTask))
{
MarkDirty();
OnDataChanged();
}
}
private void OnDataChanged()
{
DataChanged?.Invoke(this);
}
private TaskTransfers TotalTransfers
{
get
{
Invalidate();
if (_totalTransfers == null && HasValidData)
{
_totalTransfers = new TaskTransfers();
foreach (TaskTransfers taskTransfers in _transfers.Values)
{
_totalTransfers.Add(taskTransfers);
}
}
return _totalTransfers;
}
}
private TransfersPerStationCont TransfersPerStation
{
get
{
Invalidate();
if (_transfPerStation == null && HasValidData)
{
_transfPerStation = new TransfersPerStationCont(_transfers);
}
return _transfPerStation;
}
}
private Dictionary<int, Dictionary<RootTask, TaskTransfers>> TransfPerUnit
{
get
{
Invalidate();
if (_hasValidData == true && _transfPerUnit == null)
{
BuildTransfersPerUnit();
}
return _transfPerUnit;
}
}
private readonly Dictionary<RootTask, TaskTransfers> _transfers = new Dictionary<RootTask, TaskTransfers>();
private TaskTransfers _totalTransfers;
private TransfersPerStationCont _transfPerStation;
private Dictionary<VehicleUnit, StorageState> _storages;
private Dictionary<int, Dictionary<RootTask, TaskTransfers>> _transfPerUnit; //key = vehicle unit index
private Dictionary<int, TransfersPerStationCont> _transfPerStationPerUnit; //key = vehicle unit index
private bool _dirty = true;
private bool? _hasValidData = null; //null = data must be invalidated, false = there are no valid data after invalidating (cannot calculate it)
}
}