ItemPlacerSystem.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Content.Shared.Whitelist;
  2. using Robust.Shared.Physics.Events;
  3. using Robust.Shared.Physics.Systems;
  4. namespace Content.Shared.Placeable;
  5. /// <summary>
  6. /// Tracks placed entities
  7. /// Subscribe to <see cref="ItemPlacedEvent"/> or <see cref="ItemRemovedEvent"/> to do things when items or placed or removed.
  8. /// </summary>
  9. public sealed class ItemPlacerSystem : EntitySystem
  10. {
  11. [Dependency] private readonly CollisionWakeSystem _wake = default!;
  12. [Dependency] private readonly PlaceableSurfaceSystem _placeableSurface = default!;
  13. [Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
  14. public override void Initialize()
  15. {
  16. base.Initialize();
  17. SubscribeLocalEvent<ItemPlacerComponent, StartCollideEvent>(OnStartCollide);
  18. SubscribeLocalEvent<ItemPlacerComponent, EndCollideEvent>(OnEndCollide);
  19. }
  20. private void OnStartCollide(EntityUid uid, ItemPlacerComponent comp, ref StartCollideEvent args)
  21. {
  22. if (_whitelistSystem.IsWhitelistFail(comp.Whitelist, args.OtherEntity))
  23. return;
  24. if (TryComp<CollisionWakeComponent>(args.OtherEntity, out var wakeComp))
  25. _wake.SetEnabled(args.OtherEntity, false, wakeComp);
  26. var count = comp.PlacedEntities.Count;
  27. if (comp.MaxEntities == 0 || count < comp.MaxEntities)
  28. {
  29. comp.PlacedEntities.Add(args.OtherEntity);
  30. var ev = new ItemPlacedEvent(args.OtherEntity);
  31. RaiseLocalEvent(uid, ref ev);
  32. }
  33. if (comp.MaxEntities > 0 && count >= (comp.MaxEntities - 1))
  34. {
  35. // Don't let any more items be placed if it's reached its limit.
  36. _placeableSurface.SetPlaceable(uid, false);
  37. }
  38. }
  39. private void OnEndCollide(EntityUid uid, ItemPlacerComponent comp, ref EndCollideEvent args)
  40. {
  41. if (TryComp<CollisionWakeComponent>(args.OtherEntity, out var wakeComp))
  42. _wake.SetEnabled(args.OtherEntity, true, wakeComp);
  43. comp.PlacedEntities.Remove(args.OtherEntity);
  44. var ev = new ItemRemovedEvent(args.OtherEntity);
  45. RaiseLocalEvent(uid, ref ev);
  46. _placeableSurface.SetPlaceable(uid, true);
  47. }
  48. }
  49. /// <summary>
  50. /// Raised on the <see cref="ItemPlacer"/> when an item is placed and it is under the item limit.
  51. /// </summary>
  52. [ByRefEvent]
  53. public readonly record struct ItemPlacedEvent(EntityUid OtherEntity);
  54. /// <summary>
  55. /// Raised on the <see cref="ItemPlacer"/> when an item is removed from it.
  56. /// </summary>
  57. [ByRefEvent]
  58. public readonly record struct ItemRemovedEvent(EntityUid OtherEntity);