Files
wwdpublic/Content.Server/Gravity/GravityGeneratorSystem.cs
WarMechanic 93ece39fc2 Cherry-Pick "EMP Grenade Actually Sabotages Power" From Wizden (#516)
<!-- Please read these guidelines before opening your PR:
https://docs.spacestation14.io/en/getting-started/pr-guideline -->
<!-- The text between the arrows are comments - they will not be visible
on your PR. -->

## About the PR
<!-- What did you change in this PR? -->
EMP has been changed to target APC-powered-devices (most electrical
devices) as well as batteries to disable them. This means EMP can
interfere with autolathes, airlocks, atmos devices, substations and
SMES. The power draw of a single EMP grenade now cuts out a substation,
and the disabling effect prevents further recharge until it subsides.

EMP duration now also stacks, which creates a novel way to quietly black
out the station by attacking engineering SMES with 3 EMP grenades (6tc
EMP bundle) to black out the station for 3 minutes.

Edit, here's a detailed changelog of the PR,
Functionality:
- EMP disable has been generalised to kill and prevent further function
of every device/battery by interrupting recharge
- As a result of the above, some hard coded interactions have been
culled
- EMP disable duration now stacks with multiple EMP blasts
- EMP is now capable of draining from gravity generators
- The Charger system has been slightly reworked to facilitate
communication between batteries and chargers

Results:
- EMP grenade can disable basically every powered machine, most notably
doors
- EMP grenade has had its power drain upped to 2.7MW, which is slightly
more than a substation and 1/3 a SMES
- EMP grenade can now instantly kill substations
- EMP grenade can now instantly kill gravity generators
- 3 EMP grenades (6tc) can be used to kill SMES and disable recharge for
3 minutes with no evidence on the power monitor.

## Why / Balance
<!-- Why was it changed? Link any discussions or issues here. Please
discuss how this would affect game balance. -->
EMP at 2tc has a relatively low value-proposition when compared to C4
which is also 2tc. While EMP can probably black out one (or two if
you're lucky) APCs and can be used as a defensive option against
Stun/Lasers. C4 can be used to cut wires, substations, SMES, generators,
doors, reinforced walls, people and the list probably continues.

New EMP can be used to soft-bomb station power in an explosion that
isn't globally alarming (salv boom). Targeting the captain's office
directly may let you crowbar in and steal the locker but it leaves
ephemeral evidence in the form of everything electrical shimmering blue.
Opting to bomb substations blacks out a wider area, providing several
degrees of separation from your target. That is to say, new EMP grenade
favours map knowledge and rewards better stealth.

## Technical details
<!-- If this is a code change, summarize at high level how your new code
works. This makes it easier to review. -->
- `C.S/.../EmpSystem.cs` uses TryComp to turn on/off charging for
`C.S/Power/Components/PowerNetworkBatteryComponent`
- `C.S/Power/EntitySystems/PowerReceiverSystem.cs` listens to
`EmpPulseEvent` to turn off. Requests to turn back on are additionally
intercepted by `EmpSystem.cs` and cancelled.
- `C.S/.../GravityGeneratorSystem.cs` listens to `EmpPulseEvent` and
converts energy consumption to a normalised charge
- `C.S/Power/EntitySystems/ApcSystem.cs` no longer toggles its breaker,
but still listens to `EmpPulseEvent` for updating visuals.
- `C.S/Power/EntitySystems/ChargerSystem.cs` was refactored to add a
`ChargingComponent` flag to power cells instead of `ActiveCharger` on
itself. Battery and Charger communicate through this flag. Listens to
`EmpPulseEvent` for updating its state machine. New
`ChargerUpdateStatusEvent` allows batteries to update the charger's
status.
- `C.S/Power/EntitySystems/BatterySystem.cs` can now be disabled, and
checks for disabling before updating its charge. Raises
`ChargerUpdateStatusEvent` when hearing `EmpDisabledRemoved` to tell its
charger to start charging again.
- `C.S/Power/PowerWireAction.cs` checks for `EmpDisabledComponent`
before turning power back on.
- `C.S/SurveillanceCamera/Systems/SurveillanceCameraSystem.cs` and
`C.S/VendingMachines/VendingMachineSystem.cs` had redundant
`EmpPulseEvent` listeners culled.
- `Resources/Prototypes/Entities/Objects/Weapons/Throwable/grenades.yml`
buffed EMP grenade.

## Media
<!-- 
PRs which make ingame changes (adding clothing, items, new features,
etc) are required to have media attached that showcase the changes.
Small fixes/refactors are exempt.
Any media may be used in SS14 progress reports, with clear credit given.

If you're unsure whether your PR will require media, ask a maintainer.

Check the box below to confirm that you have in fact seen this (put an X
in the brackets, like [X]):
-->
https://www.youtube.com/embed/rSVph6OIg1s?si=8o4bx9Vx16B6usuu - outdated
video demonstrating changes on a wizden map
https://www.youtube.com/embed/B3iPhLcfs-0?si=trB1HY2ccjMf96Bj -
electrical anomaly crit with updated emp

- [x] I have added screenshots/videos to this PR showcasing its changes
ingame, **or** this PR does not require an ingame showcase

**Changelog**
<!--
Make players aware of new features and changes that could affect how
they play the game by adding a Changelog entry. Please read the
Changelog guidelines located at:
https://docs.spacestation14.io/en/getting-started/pr-guideline#changelog
-->

🆑
- tweak: EMP Grenades can now disable basically any electrical device,
and stack in disable duration.

---------

Signed-off-by: VMSolidus <evilexecutive@gmail.com>
Co-authored-by: VMSolidus <evilexecutive@gmail.com>
2024-08-06 16:47:49 -04:00

320 lines
13 KiB
C#

using Content.Server.Administration.Logs;
using Content.Server.Audio;
using Content.Server.Power.Components;
using Content.Server.Emp;
using Content.Shared.Database;
using Content.Shared.Gravity;
using Content.Shared.Interaction;
using Robust.Server.GameObjects;
using Robust.Shared.Player;
namespace Content.Server.Gravity
{
public sealed class GravityGeneratorSystem : EntitySystem
{
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
[Dependency] private readonly AmbientSoundSystem _ambientSoundSystem = default!;
[Dependency] private readonly GravitySystem _gravitySystem = default!;
[Dependency] private readonly SharedAppearanceSystem _appearance = default!;
[Dependency] private readonly SharedPointLightSystem _lights = default!;
[Dependency] private readonly UserInterfaceSystem _uiSystem = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<GravityGeneratorComponent, ComponentInit>(OnCompInit);
SubscribeLocalEvent<GravityGeneratorComponent, ComponentShutdown>(OnComponentShutdown);
SubscribeLocalEvent<GravityGeneratorComponent, EntParentChangedMessage>(OnParentChanged); // Or just anchor changed?
SubscribeLocalEvent<GravityGeneratorComponent, InteractHandEvent>(OnInteractHand);
SubscribeLocalEvent<GravityGeneratorComponent, SharedGravityGeneratorComponent.SwitchGeneratorMessage>(
OnSwitchGenerator);
SubscribeLocalEvent<GravityGeneratorComponent, EmpPulseEvent>(OnEmpPulse);
}
private void OnParentChanged(EntityUid uid, GravityGeneratorComponent component, ref EntParentChangedMessage args)
{
if (component.GravityActive && TryComp(args.OldParent, out GravityComponent? gravity))
{
_gravitySystem.RefreshGravity(args.OldParent.Value, gravity);
}
}
private void OnComponentShutdown(EntityUid uid, GravityGeneratorComponent component, ComponentShutdown args)
{
if (component.GravityActive &&
TryComp<TransformComponent>(uid, out var xform) &&
TryComp(xform.ParentUid, out GravityComponent? gravity))
{
component.GravityActive = false;
_gravitySystem.RefreshGravity(xform.ParentUid, gravity);
}
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<GravityGeneratorComponent, ApcPowerReceiverComponent>();
while (query.MoveNext(out var uid, out var gravGen, out var powerReceiver))
{
var ent = (uid, gravGen, powerReceiver);
if (!gravGen.Intact)
continue;
// Calculate charge rate based on power state and such.
// Negative charge rate means discharging.
float chargeRate;
if (gravGen.SwitchedOn)
{
if (powerReceiver.Powered)
{
chargeRate = gravGen.ChargeRate;
}
else
{
// Scale discharge rate such that if we're at 25% active power we discharge at 75% rate.
var receiving = powerReceiver.PowerReceived;
var mainSystemPower = Math.Max(0, receiving - gravGen.IdlePowerUse);
var ratio = 1 - mainSystemPower / (gravGen.ActivePowerUse - gravGen.IdlePowerUse);
chargeRate = -(ratio * gravGen.ChargeRate);
}
}
else
{
chargeRate = -gravGen.ChargeRate;
}
var active = gravGen.GravityActive;
var lastCharge = gravGen.Charge;
gravGen.Charge = Math.Clamp(gravGen.Charge + frameTime * chargeRate, 0, gravGen.MaxCharge);
if (chargeRate > 0)
{
// Charging.
if (MathHelper.CloseTo(gravGen.Charge, gravGen.MaxCharge) && !gravGen.GravityActive)
{
gravGen.GravityActive = true;
}
}
else
{
// Discharging
if (MathHelper.CloseTo(gravGen.Charge, 0) && gravGen.GravityActive)
{
gravGen.GravityActive = false;
}
}
var updateUI = gravGen.NeedUIUpdate;
if (!MathHelper.CloseTo(lastCharge, gravGen.Charge))
{
UpdateState(ent);
updateUI = true;
}
if (updateUI)
UpdateUI(ent, chargeRate);
if (active != gravGen.GravityActive &&
TryComp<TransformComponent>(uid, out var xform) &&
TryComp<GravityComponent>(xform.ParentUid, out var gravity))
{
// Force it on in the faster path.
if (gravGen.GravityActive)
{
_gravitySystem.EnableGravity(xform.ParentUid, gravity);
}
else
{
_gravitySystem.RefreshGravity(xform.ParentUid, gravity);
}
}
}
}
private void SetSwitchedOn(EntityUid uid, GravityGeneratorComponent component, bool on,
ApcPowerReceiverComponent? powerReceiver = null, ICommonSession? session = null)
{
if (!Resolve(uid, ref powerReceiver))
return;
if (session is { AttachedEntity: { } })
_adminLogger.Add(LogType.Action, on ? LogImpact.Medium : LogImpact.High, $"{session:player} set ${ToPrettyString(uid):target} to {(on ? "on" : "off")}");
component.SwitchedOn = on;
UpdatePowerState(component, powerReceiver);
component.NeedUIUpdate = true;
}
private static void UpdatePowerState(
GravityGeneratorComponent component,
ApcPowerReceiverComponent powerReceiver)
{
powerReceiver.Load = component.SwitchedOn ? component.ActivePowerUse : component.IdlePowerUse;
}
private void UpdateUI(Entity<GravityGeneratorComponent, ApcPowerReceiverComponent> ent, float chargeRate)
{
var (_, component, powerReceiver) = ent;
if (!_uiSystem.IsUiOpen(ent, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key))
return;
var chargeTarget = chargeRate < 0 ? 0 : component.MaxCharge;
short chargeEta;
var atTarget = false;
if (MathHelper.CloseTo(component.Charge, chargeTarget))
{
chargeEta = short.MinValue; // N/A
atTarget = true;
}
else
{
var diff = chargeTarget - component.Charge;
chargeEta = (short) Math.Abs(diff / chargeRate);
}
var status = chargeRate switch
{
> 0 when atTarget => GravityGeneratorPowerStatus.FullyCharged,
< 0 when atTarget => GravityGeneratorPowerStatus.Off,
> 0 => GravityGeneratorPowerStatus.Charging,
< 0 => GravityGeneratorPowerStatus.Discharging,
_ => throw new ArgumentOutOfRangeException()
};
var state = new SharedGravityGeneratorComponent.GeneratorState(
component.SwitchedOn,
(byte) (component.Charge * 255),
status,
(short) Math.Round(powerReceiver.PowerReceived),
(short) Math.Round(powerReceiver.Load),
chargeEta
);
_uiSystem.TrySetUiState(
ent,
SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key,
state);
component.NeedUIUpdate = false;
}
private void OnCompInit(Entity<GravityGeneratorComponent> ent, ref ComponentInit args)
{
ApcPowerReceiverComponent? powerReceiver = null;
if (!Resolve(ent, ref powerReceiver, false))
return;
UpdatePowerState(ent, powerReceiver);
UpdateState((ent, ent.Comp, powerReceiver));
}
private void OnInteractHand(EntityUid uid, GravityGeneratorComponent component, InteractHandEvent args)
{
if (!EntityManager.TryGetComponent(args.User, out ActorComponent? actor))
return;
ApcPowerReceiverComponent? powerReceiver = default!;
if (!Resolve(uid, ref powerReceiver))
return;
// Do not allow opening UI if broken or unpowered.
if (!component.Intact || powerReceiver.PowerReceived < component.IdlePowerUse)
return;
_uiSystem.TryOpen(uid, SharedGravityGeneratorComponent.GravityGeneratorUiKey.Key, actor.PlayerSession);
component.NeedUIUpdate = true;
}
public void UpdateState(Entity<GravityGeneratorComponent, ApcPowerReceiverComponent> ent)
{
var (uid, grav, powerReceiver) = ent;
var appearance = EntityManager.GetComponentOrNull<AppearanceComponent>(uid);
_appearance.SetData(uid, GravityGeneratorVisuals.Charge, grav.Charge, appearance);
if (_lights.TryGetLight(uid, out var pointLight))
{
_lights.SetEnabled(uid, grav.Charge > 0, pointLight);
_lights.SetRadius(uid, MathHelper.Lerp(grav.LightRadiusMin, grav.LightRadiusMax, grav.Charge), pointLight);
}
if (!grav.Intact)
{
MakeBroken((uid, grav), appearance);
}
else if (powerReceiver.PowerReceived < grav.IdlePowerUse)
{
MakeUnpowered((uid, grav), appearance);
}
else if (!grav.SwitchedOn)
{
MakeOff((uid, grav), appearance);
}
else
{
MakeOn((uid, grav), appearance);
}
}
private void MakeBroken(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
_ambientSoundSystem.SetAmbience(ent, false);
_appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Broken);
}
private void MakeUnpowered(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
_ambientSoundSystem.SetAmbience(ent, false);
_appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Unpowered, appearance);
}
private void MakeOff(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
_ambientSoundSystem.SetAmbience(ent, false);
_appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.Off, appearance);
}
private void MakeOn(Entity<GravityGeneratorComponent> ent, AppearanceComponent? appearance)
{
_ambientSoundSystem.SetAmbience(ent, true);
_appearance.SetData(ent, GravityGeneratorVisuals.State, GravityGeneratorStatus.On, appearance);
}
private void OnSwitchGenerator(
EntityUid uid,
GravityGeneratorComponent component,
SharedGravityGeneratorComponent.SwitchGeneratorMessage args)
{
SetSwitchedOn(uid, component, args.On, session:args.Session);
}
private void OnEmpPulse(EntityUid uid, GravityGeneratorComponent component, EmpPulseEvent args)
{
/// i really don't think that the gravity generator should use normalised 0-1 charge
/// as opposed to watts charge that every other battery uses
ApcPowerReceiverComponent? powerReceiver = null;
if (!Resolve(uid, ref powerReceiver, false))
return;
var ent = (uid, component, powerReceiver);
// convert from normalised energy to watts and subtract
float maxEnergy = component.ActivePowerUse / component.ChargeRate;
float currentEnergy = maxEnergy * component.Charge;
currentEnergy = Math.Max(0, currentEnergy - args.EnergyConsumption);
// apply renormalised energy to charge variable
component.Charge = currentEnergy / maxEnergy;
// update power state
UpdateState(ent);
}
}
}