Files
tbd-station-14/Content.Server/GameObjects/Components/Power/ApcNetComponents/PowerReceiverUsers/PoweredLightComponent.cs
Paul Ritter 5c50b1f6ed Serialization v3 content PR (#3491)
* serv3 in shared pt 1

* beginning of deepclone api

* progress in implementing ideepclone & serv3 in content

* adds target

* its cant hurt you it cant hurt you

* more changes to content.server

* adds dataclasses

* almost there

* renamed & edited entry

* finishes refactoring content to use serv3

* gasmixture runtimes, next: reagentunit

* fucin hell that was an annoying one

* adds flags

* fixes some yaml errors

* removes comment

* fixes generic components for now

* removes todo
actually clones values my god paul
fixes bug involving resolving custom data classes from other proj
renames dataclass
fixes spritecomp
adds WithFormat.Constants support

* adds deepclone to ResistanceSet

* adds a bunch of deepclone implementations
adds a deepclone analyzer (TODO)
adds a deep clone fallback for classes & structs

* fixes a bunch of runtimes

* adds deepclone to entityuid

* adds generator to sln

* gets rid of warnings

* fixes

* argh

* componentdata refactors

* more deepclone impl

* heck me i reworked all of content deepclone

* renames custom dataclasstarget

* misc

* reworks prototypes

* deepclone nuke

* renamed customdataclass attribute

* fixes everything

* misc fixed

* the killcommit

* getting there

* changed yamlfieldattribute namespace

* adds back iselfserialize

* renames everything to data(field/definition)

* ouch

* Fix most errors on content

* Fix more errors in content

* Fix some components

* work on tests

* fixes some customdataclasses

* fuggin shit

* yes

* yeas

* Remove data classes

* Data field naming fixes

* arg

* Git resetti RobustToolbox

* Merge fixes

* General fixes

* Fix startup serialization errors

* Fix DamageContainerPrototype when supported classes or types are null

* Implement construction graph step type serializer

* Fix up construction serialization

* Fix up construction serialization part 2

* Fix null list in technology database component

* Fix body serialization

* Fix entity storage serialization

* Fix actions serialization

* Fix AI serialization

* Fix reaction serialization

* Fix body serialization

* Fix grid atmosphere serialization

* Rename IServ3Manager to ISerializationManager

* Convert every non generic serializer to the new format, general fixes

* Serialization and body system fix

* pushinheritance fix

* Update all prototypes to have a parent and have consistent id/parent properties

* Merge fixes

* smh my head

* cuddling slaps

* Content commit for engine PR

* stuff

* more fixes

* argh

* yes even you are fixed

* changelog fixes

* fixes seeds

* argh

* Test fixes

* Add writing for alert order prototype

* Fix alert order writing

* FIX

* its been alot ok

* Fix the rest of the visualizers

* Fix server alerts component tests

* Fix alert prototype tests not using the read value

* Fix alert prototype tests initializing serialization multiple times

* THIS IS AN AMERICAN CODEBASE GOD BLESS THE USA

* Add ImplicitDataDefinitionForInheritors to IMechanismBehavior
Fixes the behaviors not being found

* Fix NRE in strap component
Good night to the 1 buckle optimization

* Fix clothing component slot flags serialization tag

* Fix body component in all components test

* Merge fixes

* ffs

* Make construction graph prototype use serialization hooks

* human yaml linted

* a

* Do the thing for construction

* stuff

* a

* monke see yaml linter

* LINT HARDER

* Remove redundant todo

* yes

* Add skip hook argument to readers and copiers

* we gamin

* test/datafield fixes

* adds more verbose validation

* moves linter to action

* Improve construction graph step type serializer error message

* Fix ammo box component NRE

* gamin

* some updates to the linter

* yes

* removes that test

* misc fixes

* array fix
priority fix
misc fixes

* adds proper info the validation

* adds alwaysrelevant usa

* Make yaml linter take half as long to run (~50% less)

* Make yaml linter 5 times faster (~80% less execution time)

* based vera being based

* fixes mapsaving

* warning cleanup & moves surpressor

* removes old msbuild targets

* Revert "Make yaml linter 5 times faster (~80% less execution time)"

This reverts commit 3e6091359a26252c3e98828199553de668031c63.

* Add -nowarn to yaml linter run configuration

* Improve yaml linter message feedback

* Make dependencies an argument instead of a property on the serialization manager

* yamllinting slaps

* Clean up type serializers

* Move yaml linter code to its own method

* Fix yaml errors

* Change yaml linter action name and remove -nowarn

* yaml linter please shut

* Git resetti robust toolbox

Co-authored-by: Paul <ritter.paul1+git@googlemail.com>
Co-authored-by: DrSmugleaf <DrSmugleaf@users.noreply.github.com>
2021-03-05 01:08:38 +01:00

319 lines
11 KiB
C#

#nullable enable
using System;
using System.Threading.Tasks;
using Content.Server.GameObjects.Components.GUI;
using Content.Server.GameObjects.Components.Items.Storage;
using Content.Server.GameObjects.Components.MachineLinking;
using Content.Server.GameObjects.Components.MachineLinking.Signals;
using Content.Server.GameObjects.Components.Mobs;
using Content.Server.GameObjects.Components.Observer;
using Content.Shared.Actions;
using Content.Shared.Damage;
using Content.Shared.GameObjects.Components.Damage;
using Content.Shared.GameObjects.Components.Power.ApcNetComponents.PowerReceiverUsers;
using Content.Shared.Interfaces;
using Content.Shared.Interfaces.GameObjects.Components;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Power.ApcNetComponents.PowerReceiverUsers
{
/// <summary>
/// Component that represents a wall light. It has a light bulb that can be replaced when broken.
/// </summary>
[RegisterComponent]
public class PoweredLightComponent : Component, IInteractHand, IInteractUsing, IMapInit, ISignalReceiver<bool>, ISignalReceiver<ToggleSignal>, IGhostBooAffected
{
[Dependency] private readonly IGameTiming _gameTiming = default!;
public override string Name => "PoweredLight";
private static readonly TimeSpan _thunkDelay = TimeSpan.FromSeconds(2);
// time to blink light when ghost made boo nearby
private static readonly TimeSpan ghostBlinkingTime = TimeSpan.FromSeconds(10);
private static readonly TimeSpan ghostBlinkingCooldown = TimeSpan.FromSeconds(60);
[ComponentDependency]
private readonly AppearanceComponent? _appearance;
private TimeSpan _lastThunk;
private TimeSpan? _lastGhostBlink;
[DataField("hasLampOnSpawn")]
private bool _hasLampOnSpawn = true;
[ViewVariables] [DataField("on")]
private bool _on = true;
[ViewVariables]
private bool _currentLit;
[ViewVariables]
private bool _isBlinking;
[ViewVariables] [DataField("ignoreGhostsBoo")]
private bool _ignoreGhostsBoo;
[DataField("bulb")]
private LightBulbType BulbType = LightBulbType.Tube;
[ViewVariables] private ContainerSlot _lightBulbContainer = default!;
[ViewVariables]
private LightBulbComponent? LightBulb
{
get
{
if (_lightBulbContainer.ContainedEntity == null) return null;
_lightBulbContainer.ContainedEntity.TryGetComponent(out LightBulbComponent? bulb);
return bulb;
}
}
// TODO CONSTRUCTION make this use a construction graph
async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs)
{
return InsertBulb(eventArgs.Using);
}
bool IInteractHand.InteractHand(InteractHandEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent(out IDamageableComponent? damageableComponent))
{
Eject();
return false;
}
if(eventArgs.User.TryGetComponent(out HeatResistanceComponent? heatResistanceComponent))
{
if(CanBurn(heatResistanceComponent.GetHeatResistance()))
{
Burn();
return true;
}
}
Eject();
return true;
bool CanBurn(int heatResistance)
{
if (LightBulb == null)
return false;
return _currentLit && heatResistance < LightBulb.BurningTemperature;
}
void Burn()
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("You burn your hand!"));
damageableComponent.ChangeDamage(DamageType.Heat, 20, false, Owner);
var audioSystem = EntitySystem.Get<AudioSystem>();
audioSystem.PlayFromEntity("/Audio/Effects/lightburn.ogg", Owner);
}
void Eject()
{
EjectBulb(eventArgs.User);
UpdateLight();
}
}
/// <summary>
/// Inserts the bulb if possible.
/// </summary>
/// <returns>True if it could insert it, false if it couldn't.</returns>
private bool InsertBulb(IEntity bulb)
{
if (LightBulb != null) return false;
if (!bulb.TryGetComponent(out LightBulbComponent? lightBulb)) return false;
if (lightBulb.Type != BulbType) return false;
var inserted = _lightBulbContainer.Insert(bulb);
lightBulb.OnLightBulbStateChange += UpdateLight;
lightBulb.OnLightColorChange += UpdateLight;
UpdateLight();
return inserted;
}
/// <summary>
/// Ejects the bulb to a mob's hand if possible.
/// </summary>
private void EjectBulb(IEntity user)
{
if (LightBulb == null) return;
var bulb = LightBulb;
bulb.OnLightBulbStateChange -= UpdateLight;
bulb.OnLightColorChange -= UpdateLight;
if (!_lightBulbContainer.Remove(bulb.Owner)) return;
if (!user.TryGetComponent(out HandsComponent? hands)
|| !hands.PutInHand(bulb.Owner.GetComponent<ItemComponent>()))
bulb.Owner.Transform.Coordinates = user.Transform.Coordinates;
}
/// <summary>
/// For attaching UpdateLight() to events.
/// </summary>
public void UpdateLight(object? sender, EventArgs? e)
{
UpdateLight();
}
/// <summary>
/// Updates the light's power drain, sprite and actual light state.
/// </summary>
public void UpdateLight()
{
var powerReceiver = Owner.GetComponent<PowerReceiverComponent>();
if (LightBulb == null) // No light bulb.
{
_currentLit = false;
powerReceiver.Load = 0;
_appearance?.SetData(PoweredLightVisuals.BulbState, PoweredLightState.Empty);
return;
}
switch (LightBulb.State)
{
case LightBulbState.Normal:
if (powerReceiver.Powered && _on)
{
_currentLit = true;
powerReceiver.Load = LightBulb.PowerUse;
_appearance?.SetData(PoweredLightVisuals.BulbState, PoweredLightState.On);
_appearance?.SetData(PoweredLightVisuals.BulbColor, LightBulb.Color);
var time = _gameTiming.CurTime;
if (time > _lastThunk + _thunkDelay)
{
_lastThunk = time;
EntitySystem.Get<AudioSystem>().PlayFromEntity("/Audio/Machines/light_tube_on.ogg", Owner, AudioParams.Default.WithVolume(-10f));
}
}
else
{
_currentLit = false;
_appearance?.SetData(PoweredLightVisuals.BulbState, PoweredLightState.Off);
}
break;
case LightBulbState.Broken:
_currentLit = false;
_appearance?.SetData(PoweredLightVisuals.BulbState, PoweredLightState.Broken);
break;
case LightBulbState.Burned:
_currentLit = false;
_appearance?.SetData(PoweredLightVisuals.BulbState, PoweredLightState.Burned);
break;
}
}
public override void Initialize()
{
base.Initialize();
_lightBulbContainer = ContainerHelpers.EnsureContainer<ContainerSlot>(Owner, "light_bulb");
}
public override void HandleMessage(ComponentMessage message, IComponent? component)
{
base.HandleMessage(message, component);
switch (message)
{
case PowerChangedMessage:
UpdateLight();
break;
case DamageChangedMessage msg:
TryDestroyBulb(msg);
break;
}
}
private void TryDestroyBulb(DamageChangedMessage msg)
{
if (!msg.TookDamage)
return;
if (LightBulb == null || LightBulb.State == LightBulbState.Broken)
return;
LightBulb.State = LightBulbState.Broken;
LightBulb.PlayBreakSound();
UpdateLight();
}
void IMapInit.MapInit()
{
if (_hasLampOnSpawn)
{
var prototype = BulbType switch
{
LightBulbType.Bulb => "LightBulb",
LightBulbType.Tube => "LightTube",
_ => throw new ArgumentOutOfRangeException()
};
var entity = Owner.EntityManager.SpawnEntity(prototype, Owner.Transform.Coordinates);
_lightBulbContainer.Insert(entity);
UpdateLight();
}
}
public void TriggerSignal(bool signal)
{
_on = signal;
UpdateLight();
}
public void TriggerSignal(ToggleSignal signal)
{
_on = !_on;
UpdateLight();
}
public void ToggleBlinkingLight(bool isNowBlinking)
{
if (_isBlinking == isNowBlinking)
return;
_isBlinking = isNowBlinking;
_appearance?.SetData(PoweredLightVisuals.Blinking, _isBlinking);
}
public bool AffectedByGhostBoo(InstantActionEventArgs args)
{
if (_ignoreGhostsBoo)
return false;
// check cooldown first to prevent abuse
var time = _gameTiming.CurTime;
if (_lastGhostBlink != null)
{
if (time <= _lastGhostBlink + ghostBlinkingCooldown)
return false;
}
_lastGhostBlink = time;
ToggleBlinkingLight(true);
Owner.SpawnTimer(ghostBlinkingTime, () => {
ToggleBlinkingLight(false);
});
return true;
}
}
}