/
PowerlessElectronics.cs
551 lines (443 loc) · 18.2 KB
/
PowerlessElectronics.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
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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oxide.Core;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Oxide.Plugins
{
[Info("Powerless Electronics", "WhiteThunder", "1.2.4")]
[Description("Allows electrical entities to generate their own power when not plugged in.")]
internal class PowerlessElectronics : CovalencePlugin
{
#region Fields
private const string PermissionAll = "powerlesselectronics.all";
private const string PermissionEntityFormat = "powerlesselectronics.{0}";
private Configuration _config;
#endregion
#region Hooks
private void Init()
{
Unsubscribe(nameof(OnEntitySpawned));
}
private void OnServerInitialized()
{
// Don't overwrite the config if invalid since the user will lose their config!
if (!_config.UsingDefaults)
{
var addedPrefabs = _config.AddMissingPrefabs();
if (addedPrefabs != null)
{
LogWarning($"Discovered and added {addedPrefabs.Count} electrical entity types to Configuration.\n - {string.Join("\n - ", addedPrefabs)}");
SaveConfig();
}
}
_config.GeneratePermissionNames();
// Register permissions only after discovering prefabs.
permission.RegisterPermission(PermissionAll, this);
foreach (var entry in _config.Entities)
{
permission.RegisterPermission(entry.Value.PermissionName, this);
}
foreach (var entity in BaseNetworkable.serverEntities)
{
var ioEntity = entity as IOEntity;
if (ioEntity != null)
{
ProcessIOEntity(ioEntity, delay: false);
}
}
Subscribe(nameof(OnEntitySpawned));
}
private void OnEntitySpawned(IOEntity ioEntity)
{
ProcessIOEntity(ioEntity, delay: true);
}
private void OnIORefCleared(IOEntity.IORef ioRef, IOEntity ioEntity)
{
ProcessIOEntity(ioEntity, delay: true);
}
#endregion
#region Helper Methods
private static bool InputUpdateWasBlocked(IOEntity ioEntity, int inputSlot, int amount)
{
var hookResult = Interface.CallHook("OnPowerlessInputUpdate", inputSlot, ioEntity, amount);
return hookResult is bool && (bool)hookResult == false;
}
private static bool IsHybridIOEntity(IOEntity ioEntity)
{
return ioEntity is ElectricFurnaceIO
|| ioEntity is ElevatorIOEntity
|| ioEntity is MicrophoneStandIOEntity
|| (ioEntity is SimpleLight && ioEntity.GetParentEntity() is WeaponRack);
}
private static BaseEntity GetOwnerEntity(IOEntity ioEntity)
{
var parent = ioEntity.GetParentEntity();
if ((object)parent == null)
return ioEntity;
return IsHybridIOEntity(ioEntity) ? parent : ioEntity;
}
private static bool ShouldIgnoreEntity(IOEntity ioEntity)
{
// Parented entities are assumed to be controlled by other plugins that can manage power themselves
// Exception being entities that are parented in vanilla
if (ioEntity.HasParent()
&& !IsHybridIOEntity(ioEntity)
&& !(ioEntity is IndustrialCrafter)
&& !(ioEntity is StorageMonitor))
return true;
// Turrets and sam sites with switches on them are assumed to be controlled by other plugins
if ((ioEntity is AutoTurret || ioEntity is SamSite) && GetChildEntity<ElectricSwitch>(ioEntity) != null)
return true;
return false;
}
private static void MaybeProvidePower(IOEntity ioEntity, EntityConfig entityConfig)
{
if (ShouldIgnoreEntity(ioEntity))
return;
foreach (var inputSlot in entityConfig.InputSlots)
{
var powerAmount = entityConfig.GetPowerForSlot(inputSlot);
// Don't update power if specified to be 0 to avoid conflicts with other plugins
if (powerAmount > 0 && !HasConnectedInput(ioEntity, inputSlot))
{
TryProvidePower(ioEntity, inputSlot, powerAmount);
}
}
}
private static T GetChildEntity<T>(BaseEntity entity) where T : BaseEntity
{
foreach (var child in entity.children)
{
var childOfType = child as T;
if (childOfType != null)
return childOfType;
}
return null;
}
private static bool HasConnectedInput(IOEntity ioEntity, int inputSlot)
{
return inputSlot < ioEntity.inputs.Length
&& ioEntity.inputs[inputSlot].connectedTo.Get() != null;
}
private static void TryProvidePower(IOEntity ioEntity, int inputSlot, int powerAmount)
{
if (ioEntity.inputs.Length > inputSlot && !InputUpdateWasBlocked(ioEntity, inputSlot, powerAmount))
{
ioEntity.UpdateFromInput(powerAmount, inputSlot);
}
}
private void ProcessIOEntity(IOEntity ioEntity, bool delay)
{
if (ioEntity == null)
return;
var entityConfig = GetEntityConfig(ioEntity);
// Entity not supported
if (entityConfig == null)
return;
if (!entityConfig.Enabled)
return;
if (!EntityOwnerHasPermission(ioEntity, entityConfig))
return;
if (delay)
{
var ioEntity2 = ioEntity;
var entityConfig2 = entityConfig;
NextTick(() =>
{
if (ioEntity2 == null)
return;
MaybeProvidePower(ioEntity2, entityConfig2);
});
}
else
{
MaybeProvidePower(ioEntity, entityConfig);
}
}
private bool EntityOwnerHasPermission(IOEntity ioEntity, EntityConfig entityConfig)
{
if (!entityConfig.RequirePermission)
return true;
var ownerEntity = GetOwnerEntity(ioEntity);
if (ownerEntity.OwnerID == 0)
return false;
var ownerIdString = ownerEntity.OwnerID.ToString();
return permission.UserHasPermission(ownerIdString, PermissionAll)
|| permission.UserHasPermission(ownerIdString, entityConfig.PermissionName);
}
#endregion
#region Configuration
private EntityConfig GetEntityConfig(IOEntity ioEntity)
{
EntityConfig entityConfig;
return _config.Entities.TryGetValue(ioEntity.ShortPrefabName, out entityConfig) ? entityConfig : null;
}
[JsonObject(MemberSerialization.OptIn)]
private class Configuration : BaseConfiguration
{
private static readonly string[] IgnoredEntities = {
// Has inputs to move the lift but does not consume power (elevatorioentity is the right one).
"elevator",
// Has inputs to toggle on/off but does not consume power.
"small_fuel_generator.deployed",
// Has audio input only
"connectedspeaker.deployed",
"soundlight.deployed",
// Static entity
"caboose_xorswitch",
// Has no power input
"fogmachine",
"snowmachine",
"strobelight",
};
private static bool HasElectricalInput(IOEntity ioEntity)
{
foreach (var input in ioEntity.inputs)
{
if (input.type == IOEntity.IOType.Electric)
return true;
}
return false;
}
[JsonProperty("Entities")]
public Dictionary<string, EntityConfig> Entities = new Dictionary<string, EntityConfig>()
{
["andswitch.entity"] = new EntityConfig()
{
InputSlots = new[] { 0, 1 },
PowerAmounts = new[] { 0, 0 }
},
["electrical.combiner.deployed"] = new EntityConfig()
{
InputSlots = new[] { 0, 1 },
PowerAmounts = new[] { 0, 0 }
},
// Has no pickup entity.
["electrical.modularcarlift.deployed"] = new EntityConfig(),
// Has no pickup entity.
["elevatorioentity"] = new EntityConfig(),
["fluidswitch"] = new EntityConfig
{
InputSlots = new[] { 2 }
},
["industrialconveyor.deployed"] = new EntityConfig
{
InputSlots = new[] { 1 }
},
["industrialcrafter.deployed"] = new EntityConfig
{
InputSlots = new[] { 1 }
},
// Has no pickup entity.
["microphonestandio.entity"] = new EntityConfig(),
["electricfurnace.io"] = new EntityConfig(),
["orswitch.entity"] = new EntityConfig
{
InputSlots = new[] { 0, 1 },
PowerAmounts = new[] { 0, 0 }
},
["poweredwaterpurifier.deployed"] = new EntityConfig
{
InputSlots = new[] { 1 }
},
["xorswitch.entity"] = new EntityConfig
{
InputSlots = new[] { 0, 1 },
PowerAmounts = new[] { 0, 0 }
},
};
public List<string> AddMissingPrefabs()
{
var addedPrefabs = new List<string>();
foreach (var prefab in GameManifest.Current.entities)
{
var ioEntity = GameManager.server.FindPrefab(prefab.ToLower())?.GetComponent<IOEntity>();
if (ioEntity == null || string.IsNullOrEmpty(ioEntity.ShortPrefabName))
continue;
EntityConfig entityConfig;
if (Entities.TryGetValue(ioEntity.ShortPrefabName, out entityConfig))
continue;
if (!HasElectricalInput(ioEntity)
|| ioEntity.pickup.itemTarget == null
|| ioEntity.ShortPrefabName.ToLower().Contains("static")
|| IgnoredEntities.Contains(ioEntity.ShortPrefabName.ToLower()))
continue;
addedPrefabs.Add(ioEntity.ShortPrefabName);
}
if (addedPrefabs.Count == 0)
return null;
foreach (var shortPrefabName in addedPrefabs)
{
Entities[shortPrefabName] = new EntityConfig();
}
SortEntities();
addedPrefabs.Sort();
return addedPrefabs;
}
public void GeneratePermissionNames()
{
foreach (var entry in Entities)
{
// Make the permission name less redundant
entry.Value.PermissionName = string.Format(PermissionEntityFormat, entry.Key)
.Replace("electric.", string.Empty)
.Replace("electrical.", string.Empty)
.Replace(".deployed", string.Empty)
.Replace("_deployed", string.Empty)
.Replace(".entity", string.Empty);
}
}
private void SortEntities()
{
var shortPrefabNames = Entities.Keys.ToList();
shortPrefabNames.Sort();
var newEntities = new Dictionary<string, EntityConfig>();
foreach (var shortName in shortPrefabNames)
{
newEntities[shortName] = Entities[shortName];
}
Entities = newEntities;
}
}
[JsonObject(MemberSerialization.OptIn)]
internal class EntityConfig
{
private static readonly int[] StandardInputSlot = { 0 };
[JsonProperty("RequirePermission")]
public bool RequirePermission = false;
// Hidden from config when it's using the default value
[JsonProperty("InputSlots")]
public int[] InputSlots = StandardInputSlot;
public bool ShouldSerializeInputSlots() =>
!InputSlots.SequenceEqual(StandardInputSlot);
// Hidden from config when the plural form is used
[JsonProperty("PowerAmount")]
public int PowerAmount = 0;
public bool ShouldSerializePowerAmount() =>
PowerAmounts == null;
// Hidden from config when null
[JsonProperty("PowerAmounts", DefaultValueHandling = DefaultValueHandling.Ignore)]
public int[] PowerAmounts;
public string PermissionName;
public bool Enabled
{
get
{
for (var i = 0; i < InputSlots.Length; i++)
{
if (GetPowerForSlot(InputSlots[i]) > 0)
return true;
}
return false;
}
}
public int GetPowerForSlot(int slotNumber)
{
var index = Array.IndexOf(InputSlots, slotNumber);
// We can't power an input slot that we don't know about
if (index == -1)
return 0;
// Allow plural array form to take precedence if present
if (PowerAmounts == null)
return PowerAmount;
// InputSlots and PowerAmounts are expected to be parallel arrays
return index < PowerAmounts.Length ? PowerAmounts[index] : 0;
}
}
private Configuration GetDefaultConfig() => new Configuration();
#endregion
#region Configuration Helpers
[JsonObject(MemberSerialization.OptIn)]
private class BaseConfiguration
{
public bool UsingDefaults;
public string ToJson() => JsonConvert.SerializeObject(this);
public Dictionary<string, object> ToDictionary() => JsonHelper.Deserialize(ToJson()) as Dictionary<string, object>;
}
private static class JsonHelper
{
public static object Deserialize(string json) => ToObject(JToken.Parse(json));
private static object ToObject(JToken token)
{
switch (token.Type)
{
case JTokenType.Object:
return token.Children<JProperty>()
.ToDictionary(prop => prop.Name,
prop => ToObject(prop.Value));
case JTokenType.Array:
return token.Select(ToObject).ToList();
default:
return ((JValue)token).Value;
}
}
}
private bool MaybeUpdateConfig(BaseConfiguration config)
{
var currentWithDefaults = config.ToDictionary();
var currentRaw = Config.ToDictionary(x => x.Key, x => x.Value);
return MaybeUpdateConfigDict(currentWithDefaults, currentRaw);
}
private bool MaybeUpdateConfigDict(Dictionary<string, object> currentWithDefaults, Dictionary<string, object> currentRaw)
{
bool changed = false;
foreach (var key in currentWithDefaults.Keys)
{
object currentRawValue;
if (currentRaw.TryGetValue(key, out currentRawValue))
{
var defaultDictValue = currentWithDefaults[key] as Dictionary<string, object>;
var currentDictValue = currentRawValue as Dictionary<string, object>;
if (defaultDictValue != null)
{
if (currentDictValue == null)
{
currentRaw[key] = currentWithDefaults[key];
changed = true;
}
else if (MaybeUpdateConfigDict(defaultDictValue, currentDictValue))
changed = true;
}
}
else
{
currentRaw[key] = currentWithDefaults[key];
changed = true;
}
}
return changed;
}
protected override void LoadDefaultConfig() => _config = GetDefaultConfig();
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>();
if (_config == null)
{
throw new JsonException();
}
if (MaybeUpdateConfig(_config))
{
LogWarning("Configuration appears to be outdated; updating and saving");
SaveConfig();
}
}
catch
{
LogWarning($"Configuration file {Name}.json is invalid; using defaults");
_config.UsingDefaults = true;
LoadDefaultConfig();
}
}
protected override void SaveConfig()
{
Log($"Configuration changes saved to {Name}.json");
Config.WriteObject(_config, true);
}
#endregion
}
}