1
0

AnimalHusbandrySystem.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. using Content.Server.Administration.Logs;
  2. using Content.Server.Popups;
  3. using Content.Shared.Database;
  4. using Content.Shared.IdentityManagement;
  5. using Content.Shared.Interaction.Components;
  6. using Content.Shared.Mind.Components;
  7. using Content.Shared.Mobs.Systems;
  8. using Content.Shared.NameModifier.EntitySystems;
  9. using Content.Shared.Nutrition.AnimalHusbandry;
  10. using Content.Shared.Nutrition.Components;
  11. using Content.Shared.Nutrition.EntitySystems;
  12. using Content.Shared.Storage;
  13. using Content.Shared.Whitelist;
  14. using Robust.Shared.Audio.Systems;
  15. using Robust.Shared.Player;
  16. using Robust.Shared.Random;
  17. using Robust.Shared.Timing;
  18. namespace Content.Server.Nutrition.EntitySystems;
  19. /// <summary>
  20. /// This handles logic and interactions related to <see cref="ReproductiveComponent"/>
  21. /// </summary>
  22. public sealed class AnimalHusbandrySystem : EntitySystem
  23. {
  24. [Dependency] private readonly EntityLookupSystem _entityLookup = default!;
  25. [Dependency] private readonly HungerSystem _hunger = default!;
  26. [Dependency] private readonly IAdminLogManager _adminLog = default!;
  27. [Dependency] private readonly IGameTiming _timing = default!;
  28. [Dependency] private readonly IRobustRandom _random = default!;
  29. [Dependency] private readonly MobStateSystem _mobState = default!;
  30. [Dependency] private readonly PopupSystem _popup = default!;
  31. [Dependency] private readonly SharedAudioSystem _audio = default!;
  32. [Dependency] private readonly SharedTransformSystem _transform = default!;
  33. [Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
  34. [Dependency] private readonly NameModifierSystem _nameMod = default!;
  35. private readonly HashSet<EntityUid> _failedAttempts = new();
  36. private readonly HashSet<EntityUid> _birthQueue = new();
  37. /// <inheritdoc/>
  38. public override void Initialize()
  39. {
  40. SubscribeLocalEvent<ReproductiveComponent, MindAddedMessage>(OnMindAdded);
  41. SubscribeLocalEvent<InfantComponent, RefreshNameModifiersEvent>(OnRefreshNameModifiers);
  42. }
  43. // we express EZ-pass terminate the pregnancy if a player takes the role
  44. private void OnMindAdded(EntityUid uid, ReproductiveComponent component, MindAddedMessage args)
  45. {
  46. component.Gestating = false;
  47. component.GestationEndTime = null;
  48. }
  49. private void OnRefreshNameModifiers(Entity<InfantComponent> entity, ref RefreshNameModifiersEvent args)
  50. {
  51. // This check may seem redundant, but it makes sure that the prefix is removed before the component is removed
  52. if (_timing.CurTime < entity.Comp.InfantEndTime)
  53. args.AddModifier("infant-name-prefix");
  54. }
  55. /// <summary>
  56. /// Attempts to breed the entity with a valid
  57. /// partner nearby.
  58. /// </summary>
  59. public bool TryReproduceNearby(EntityUid uid, ReproductiveComponent? component = null)
  60. {
  61. if (!Resolve(uid, ref component))
  62. return false;
  63. var xform = Transform(uid);
  64. var partners = new HashSet<Entity<ReproductivePartnerComponent>>();
  65. _entityLookup.GetEntitiesInRange(xform.Coordinates, component.BreedRange, partners);
  66. if (partners.Count >= component.Capacity)
  67. return false;
  68. foreach (var comp in partners)
  69. {
  70. var partner = comp.Owner;
  71. if (TryReproduce(uid, partner, component))
  72. return true;
  73. // exit early if a valid attempt failed
  74. if (_failedAttempts.Contains(uid))
  75. return false;
  76. }
  77. return false;
  78. }
  79. /// <summary>
  80. /// Attempts to breed an entity with
  81. /// the specified partner.
  82. /// </summary>
  83. public bool TryReproduce(EntityUid uid, EntityUid partner, ReproductiveComponent? component = null)
  84. {
  85. if (!Resolve(uid, ref component))
  86. return false;
  87. if (uid == partner)
  88. return false;
  89. if (!CanReproduce(uid, component))
  90. return false;
  91. if (!IsValidPartner(uid, partner, component))
  92. return false;
  93. // if the partner is valid, yet it fails the random check
  94. // invalidate the entity from further attempts this tick
  95. // in order to reduce total possible pairs.
  96. if (!_random.Prob(component.BreedChance))
  97. {
  98. _failedAttempts.Add(uid);
  99. _failedAttempts.Add(partner);
  100. return false;
  101. }
  102. // this is kinda wack but it's the only sound associated with most animals
  103. if (TryComp<InteractionPopupComponent>(uid, out var interactionPopup))
  104. _audio.PlayPvs(interactionPopup.InteractSuccessSound, uid);
  105. _hunger.ModifyHunger(uid, -component.HungerPerBirth);
  106. _hunger.ModifyHunger(partner, -component.HungerPerBirth);
  107. component.GestationEndTime = _timing.CurTime + component.GestationDuration;
  108. component.Gestating = true;
  109. _adminLog.Add(LogType.Action, $"{ToPrettyString(uid)} (carrier) and {ToPrettyString(partner)} (partner) successfully bred.");
  110. return true;
  111. }
  112. /// <summary>
  113. /// Checks if an entity satisfies
  114. /// the conditions to be able to breed.
  115. /// </summary>
  116. public bool CanReproduce(EntityUid uid, ReproductiveComponent? component = null)
  117. {
  118. if (_failedAttempts.Contains(uid))
  119. return false;
  120. if (Resolve(uid, ref component, false) && component.Gestating)
  121. return false;
  122. if (HasComp<InfantComponent>(uid))
  123. return false;
  124. if (_mobState.IsIncapacitated(uid))
  125. return false;
  126. if (TryComp<HungerComponent>(uid, out var hunger) && _hunger.GetHungerThreshold(hunger) < HungerThreshold.Okay)
  127. return false;
  128. if (TryComp<ThirstComponent>(uid, out var thirst) && thirst.CurrentThirstThreshold < ThirstThreshold.Okay)
  129. return false;
  130. return true;
  131. }
  132. /// <summary>
  133. /// Checks if a given entity is a valid partner.
  134. /// Does not include the random check, for sane API reasons.
  135. /// </summary>
  136. public bool IsValidPartner(EntityUid uid, EntityUid partner, ReproductiveComponent? component = null)
  137. {
  138. if (!Resolve(uid, ref component))
  139. return false;
  140. if (!CanReproduce(partner))
  141. return false;
  142. return _whitelistSystem.IsWhitelistPass(component.PartnerWhitelist, partner);
  143. }
  144. /// <summary>
  145. /// Gives birth to offspring and
  146. /// resets the parent entity.
  147. /// </summary>
  148. public void Birth(EntityUid uid, ReproductiveComponent? component = null)
  149. {
  150. if (!Resolve(uid, ref component))
  151. return;
  152. // this is kinda wack but it's the only sound associated with most animals
  153. if (TryComp<InteractionPopupComponent>(uid, out var interactionPopup))
  154. _audio.PlayPvs(interactionPopup.InteractSuccessSound, uid);
  155. var xform = Transform(uid);
  156. var spawns = EntitySpawnCollection.GetSpawns(component.Offspring, _random);
  157. foreach (var spawn in spawns)
  158. {
  159. var offspring = Spawn(spawn, xform.Coordinates.Offset(_random.NextVector2(0.3f)));
  160. _transform.AttachToGridOrMap(offspring);
  161. if (component.MakeOffspringInfant)
  162. {
  163. var infant = AddComp<InfantComponent>(offspring);
  164. infant.InfantEndTime = _timing.CurTime + infant.InfantDuration;
  165. // Make sure the name prefix is applied
  166. _nameMod.RefreshNameModifiers(offspring);
  167. }
  168. _adminLog.Add(LogType.Action, $"{ToPrettyString(uid)} gave birth to {ToPrettyString(offspring)}.");
  169. }
  170. _popup.PopupEntity(Loc.GetString(component.BirthPopup, ("parent", Identity.Entity(uid, EntityManager))), uid);
  171. component.Gestating = false;
  172. component.GestationEndTime = null;
  173. }
  174. public override void Update(float frameTime)
  175. {
  176. base.Update(frameTime);
  177. _birthQueue.Clear();
  178. _failedAttempts.Clear();
  179. var query = EntityQueryEnumerator<ReproductiveComponent>();
  180. while (query.MoveNext(out var uid, out var reproductive))
  181. {
  182. if (reproductive.GestationEndTime != null && _timing.CurTime >= reproductive.GestationEndTime)
  183. {
  184. _birthQueue.Add(uid);
  185. }
  186. if (_timing.CurTime < reproductive.NextBreedAttempt)
  187. continue;
  188. reproductive.NextBreedAttempt += _random.Next(reproductive.MinBreedAttemptInterval, reproductive.MaxBreedAttemptInterval);
  189. // no.
  190. if (HasComp<ActorComponent>(uid) || TryComp<MindContainerComponent>(uid, out var mind) && mind.HasMind)
  191. continue;
  192. TryReproduceNearby(uid, reproductive);
  193. }
  194. foreach (var queued in _birthQueue)
  195. {
  196. Birth(queued);
  197. }
  198. var infantQuery = EntityQueryEnumerator<InfantComponent>();
  199. while (infantQuery.MoveNext(out var uid, out var infant))
  200. {
  201. if (_timing.CurTime < infant.InfantEndTime)
  202. continue;
  203. RemCompDeferred(uid, infant);
  204. // Make sure the name prefix gets removed
  205. _nameMod.RefreshNameModifiers(uid);
  206. }
  207. }
  208. }