1
0

SharedActionsSystem.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Linq;
  3. using Content.Shared.ActionBlocker;
  4. using Content.Shared.Actions.Events;
  5. using Content.Shared.Administration.Logs;
  6. using Content.Shared.Database;
  7. using Content.Shared.Hands;
  8. using Content.Shared.Interaction;
  9. using Content.Shared.Inventory.Events;
  10. using Content.Shared.Mind;
  11. using Content.Shared.Rejuvenate;
  12. using Content.Shared.Whitelist;
  13. using Robust.Shared.Audio.Systems;
  14. using Robust.Shared.GameStates;
  15. using Robust.Shared.Map;
  16. using Robust.Shared.Timing;
  17. using Robust.Shared.Utility;
  18. namespace Content.Shared.Actions;
  19. public abstract class SharedActionsSystem : EntitySystem
  20. {
  21. [Dependency] protected readonly IGameTiming GameTiming = default!;
  22. [Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
  23. [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!;
  24. [Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!;
  25. [Dependency] private readonly RotateToFaceSystem _rotateToFaceSystem = default!;
  26. [Dependency] private readonly SharedAudioSystem _audio = default!;
  27. [Dependency] private readonly SharedTransformSystem _transformSystem = default!;
  28. [Dependency] private readonly ActionContainerSystem _actionContainer = default!;
  29. [Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
  30. public override void Initialize()
  31. {
  32. base.Initialize();
  33. SubscribeLocalEvent<InstantActionComponent, MapInitEvent>(OnActionMapInit);
  34. SubscribeLocalEvent<EntityTargetActionComponent, MapInitEvent>(OnActionMapInit);
  35. SubscribeLocalEvent<WorldTargetActionComponent, MapInitEvent>(OnActionMapInit);
  36. SubscribeLocalEvent<EntityWorldTargetActionComponent, MapInitEvent>(OnActionMapInit);
  37. SubscribeLocalEvent<InstantActionComponent, ComponentShutdown>(OnActionShutdown);
  38. SubscribeLocalEvent<EntityTargetActionComponent, ComponentShutdown>(OnActionShutdown);
  39. SubscribeLocalEvent<WorldTargetActionComponent, ComponentShutdown>(OnActionShutdown);
  40. SubscribeLocalEvent<EntityWorldTargetActionComponent, ComponentShutdown>(OnActionShutdown);
  41. SubscribeLocalEvent<ActionsComponent, ActionComponentChangeEvent>(OnActionCompChange);
  42. SubscribeLocalEvent<ActionsComponent, RelayedActionComponentChangeEvent>(OnRelayActionCompChange);
  43. SubscribeLocalEvent<ActionsComponent, DidEquipEvent>(OnDidEquip);
  44. SubscribeLocalEvent<ActionsComponent, DidEquipHandEvent>(OnHandEquipped);
  45. SubscribeLocalEvent<ActionsComponent, DidUnequipEvent>(OnDidUnequip);
  46. SubscribeLocalEvent<ActionsComponent, DidUnequipHandEvent>(OnHandUnequipped);
  47. SubscribeLocalEvent<ActionsComponent, RejuvenateEvent>(OnRejuventate);
  48. SubscribeLocalEvent<ActionsComponent, ComponentShutdown>(OnShutdown);
  49. SubscribeLocalEvent<ActionsComponent, ComponentGetState>(OnActionsGetState);
  50. SubscribeLocalEvent<InstantActionComponent, ComponentGetState>(OnInstantGetState);
  51. SubscribeLocalEvent<EntityTargetActionComponent, ComponentGetState>(OnEntityTargetGetState);
  52. SubscribeLocalEvent<WorldTargetActionComponent, ComponentGetState>(OnWorldTargetGetState);
  53. SubscribeLocalEvent<EntityWorldTargetActionComponent, ComponentGetState>(OnEntityWorldTargetGetState);
  54. SubscribeLocalEvent<InstantActionComponent, GetActionDataEvent>(OnGetActionData);
  55. SubscribeLocalEvent<EntityTargetActionComponent, GetActionDataEvent>(OnGetActionData);
  56. SubscribeLocalEvent<WorldTargetActionComponent, GetActionDataEvent>(OnGetActionData);
  57. SubscribeLocalEvent<EntityWorldTargetActionComponent, GetActionDataEvent>(OnGetActionData);
  58. SubscribeAllEvent<RequestPerformActionEvent>(OnActionRequest);
  59. }
  60. public override void Update(float frameTime)
  61. {
  62. base.Update(frameTime);
  63. var worldActionQuery = EntityQueryEnumerator<WorldTargetActionComponent>();
  64. while (worldActionQuery.MoveNext(out var uid, out var action))
  65. {
  66. if (IsCooldownActive(action) || !ShouldResetCharges(action))
  67. continue;
  68. ResetCharges(uid, dirty: true);
  69. }
  70. var instantActionQuery = EntityQueryEnumerator<InstantActionComponent>();
  71. while (instantActionQuery.MoveNext(out var uid, out var action))
  72. {
  73. if (IsCooldownActive(action) || !ShouldResetCharges(action))
  74. continue;
  75. ResetCharges(uid, dirty: true);
  76. }
  77. var entityActionQuery = EntityQueryEnumerator<EntityTargetActionComponent>();
  78. while (entityActionQuery.MoveNext(out var uid, out var action))
  79. {
  80. if (IsCooldownActive(action) || !ShouldResetCharges(action))
  81. continue;
  82. ResetCharges(uid, dirty: true);
  83. }
  84. }
  85. private void OnActionMapInit(EntityUid uid, BaseActionComponent component, MapInitEvent args)
  86. {
  87. component.OriginalIconColor = component.IconColor;
  88. if (component.Charges == null)
  89. return;
  90. component.MaxCharges ??= component.Charges.Value;
  91. Dirty(uid, component);
  92. }
  93. private void OnActionShutdown(EntityUid uid, BaseActionComponent component, ComponentShutdown args)
  94. {
  95. if (component.AttachedEntity != null && !TerminatingOrDeleted(component.AttachedEntity.Value))
  96. RemoveAction(component.AttachedEntity.Value, uid, action: component);
  97. }
  98. private void OnShutdown(EntityUid uid, ActionsComponent component, ComponentShutdown args)
  99. {
  100. foreach (var act in component.Actions)
  101. {
  102. RemoveAction(uid, act, component);
  103. }
  104. }
  105. private void OnInstantGetState(EntityUid uid, InstantActionComponent component, ref ComponentGetState args)
  106. {
  107. args.State = new InstantActionComponentState(component, EntityManager);
  108. }
  109. private void OnEntityTargetGetState(EntityUid uid, EntityTargetActionComponent component, ref ComponentGetState args)
  110. {
  111. args.State = new EntityTargetActionComponentState(component, EntityManager);
  112. }
  113. private void OnWorldTargetGetState(EntityUid uid, WorldTargetActionComponent component, ref ComponentGetState args)
  114. {
  115. args.State = new WorldTargetActionComponentState(component, EntityManager);
  116. }
  117. private void OnEntityWorldTargetGetState(EntityUid uid, EntityWorldTargetActionComponent component, ref ComponentGetState args)
  118. {
  119. args.State = new EntityWorldTargetActionComponentState(component, EntityManager);
  120. }
  121. private void OnGetActionData<T>(EntityUid uid, T component, ref GetActionDataEvent args) where T : BaseActionComponent
  122. {
  123. args.Action = component;
  124. }
  125. public bool TryGetActionData(
  126. [NotNullWhen(true)] EntityUid? uid,
  127. [NotNullWhen(true)] out BaseActionComponent? result,
  128. bool logError = true)
  129. {
  130. result = null;
  131. if (uid == null || TerminatingOrDeleted(uid.Value))
  132. return false;
  133. var ev = new GetActionDataEvent();
  134. RaiseLocalEvent(uid.Value, ref ev);
  135. result = ev.Action;
  136. if (result != null)
  137. return true;
  138. if (logError)
  139. Log.Error($"Failed to get action from action entity: {ToPrettyString(uid.Value)}. Trace: {Environment.StackTrace}");
  140. return false;
  141. }
  142. public bool ResolveActionData(
  143. [NotNullWhen(true)] EntityUid? uid,
  144. [NotNullWhen(true)] ref BaseActionComponent? result,
  145. bool logError = true)
  146. {
  147. if (result != null)
  148. {
  149. DebugTools.AssertOwner(uid, result);
  150. return true;
  151. }
  152. return TryGetActionData(uid, out result, logError);
  153. }
  154. public void SetCooldown(EntityUid? actionId, TimeSpan start, TimeSpan end)
  155. {
  156. if (!TryGetActionData(actionId, out var action))
  157. return;
  158. action.Cooldown = (start, end);
  159. Dirty(actionId.Value, action);
  160. }
  161. public void SetCooldown(EntityUid? actionId, TimeSpan cooldown)
  162. {
  163. var start = GameTiming.CurTime;
  164. SetCooldown(actionId, start, start + cooldown);
  165. }
  166. public void ClearCooldown(EntityUid? actionId)
  167. {
  168. if (!TryGetActionData(actionId, out var action))
  169. return;
  170. if (action.Cooldown is not { } cooldown)
  171. return;
  172. action.Cooldown = (cooldown.Start, GameTiming.CurTime);
  173. Dirty(actionId.Value, action);
  174. }
  175. /// <summary>
  176. /// Sets the cooldown for this action only if it is bigger than the one it already has.
  177. /// </summary>
  178. public void SetIfBiggerCooldown(EntityUid? actionId, TimeSpan? cooldown)
  179. {
  180. if (cooldown == null ||
  181. cooldown.Value <= TimeSpan.Zero ||
  182. !TryGetActionData(actionId, out var action))
  183. {
  184. return;
  185. }
  186. var start = GameTiming.CurTime;
  187. var end = start + cooldown;
  188. if (action.Cooldown?.End > end)
  189. return;
  190. action.Cooldown = (start, end.Value);
  191. Dirty(actionId.Value, action);
  192. }
  193. public void StartUseDelay(EntityUid? actionId)
  194. {
  195. if (actionId == null)
  196. return;
  197. if (!TryGetActionData(actionId, out var action) || action.UseDelay == null)
  198. return;
  199. action.Cooldown = (GameTiming.CurTime, GameTiming.CurTime + action.UseDelay.Value);
  200. Dirty(actionId.Value, action);
  201. }
  202. public void SetUseDelay(EntityUid? actionId, TimeSpan? delay)
  203. {
  204. if (!TryGetActionData(actionId, out var action) || action.UseDelay == delay)
  205. return;
  206. action.UseDelay = delay;
  207. UpdateAction(actionId, action);
  208. Dirty(actionId.Value, action);
  209. }
  210. public void ReduceUseDelay(EntityUid? actionId, TimeSpan? lowerDelay)
  211. {
  212. if (!TryGetActionData(actionId, out var action))
  213. return;
  214. if (action.UseDelay != null && lowerDelay != null)
  215. action.UseDelay = action.UseDelay - lowerDelay;
  216. if (action.UseDelay < TimeSpan.Zero)
  217. action.UseDelay = null;
  218. UpdateAction(actionId, action);
  219. Dirty(actionId.Value, action);
  220. }
  221. private void OnRejuventate(EntityUid uid, ActionsComponent component, RejuvenateEvent args)
  222. {
  223. foreach (var act in component.Actions)
  224. {
  225. ClearCooldown(act);
  226. }
  227. }
  228. #region ComponentStateManagement
  229. public virtual void UpdateAction(EntityUid? actionId, BaseActionComponent? action = null)
  230. {
  231. // See client-side code.
  232. }
  233. public void SetToggled(EntityUid? actionId, bool toggled)
  234. {
  235. if (!TryGetActionData(actionId, out var action) ||
  236. action.Toggled == toggled)
  237. {
  238. return;
  239. }
  240. action.Toggled = toggled;
  241. UpdateAction(actionId, action);
  242. Dirty(actionId.Value, action);
  243. }
  244. public void SetEnabled(EntityUid? actionId, bool enabled)
  245. {
  246. if (!TryGetActionData(actionId, out var action) ||
  247. action.Enabled == enabled)
  248. {
  249. return;
  250. }
  251. action.Enabled = enabled;
  252. UpdateAction(actionId, action);
  253. Dirty(actionId.Value, action);
  254. }
  255. public void SetCharges(EntityUid? actionId, int? charges)
  256. {
  257. if (!TryGetActionData(actionId, out var action) ||
  258. action.Charges == charges)
  259. {
  260. return;
  261. }
  262. action.Charges = charges;
  263. UpdateAction(actionId, action);
  264. Dirty(actionId.Value, action);
  265. }
  266. public int? GetCharges(EntityUid? actionId)
  267. {
  268. if (!TryGetActionData(actionId, out var action))
  269. return null;
  270. return action.Charges;
  271. }
  272. public void AddCharges(EntityUid? actionId, int addCharges)
  273. {
  274. if (!TryGetActionData(actionId, out var action) || action.Charges == null || addCharges < 1)
  275. return;
  276. action.Charges += addCharges;
  277. UpdateAction(actionId, action);
  278. Dirty(actionId.Value, action);
  279. }
  280. public void RemoveCharges(EntityUid? actionId, int? removeCharges)
  281. {
  282. if (!TryGetActionData(actionId, out var action) || action.Charges == null)
  283. return;
  284. if (removeCharges == null)
  285. action.Charges = removeCharges;
  286. else
  287. action.Charges -= removeCharges;
  288. if (action.Charges is < 0)
  289. action.Charges = null;
  290. UpdateAction(actionId, action);
  291. Dirty(actionId.Value, action);
  292. }
  293. public void ResetCharges(EntityUid? actionId, bool update = false, bool dirty = false)
  294. {
  295. if (!TryGetActionData(actionId, out var action))
  296. return;
  297. action.Charges = action.MaxCharges;
  298. if (update)
  299. UpdateAction(actionId, action);
  300. if (dirty)
  301. Dirty(actionId.Value, action);
  302. }
  303. private void OnActionsGetState(EntityUid uid, ActionsComponent component, ref ComponentGetState args)
  304. {
  305. args.State = new ActionsComponentState(GetNetEntitySet(component.Actions));
  306. }
  307. #endregion
  308. #region Execution
  309. /// <summary>
  310. /// When receiving a request to perform an action, this validates whether the action is allowed. If it is, it
  311. /// will raise the relevant <see cref="InstantActionEvent"/>
  312. /// </summary>
  313. private void OnActionRequest(RequestPerformActionEvent ev, EntitySessionEventArgs args)
  314. {
  315. if (args.SenderSession.AttachedEntity is not { } user)
  316. return;
  317. if (!TryComp(user, out ActionsComponent? component))
  318. return;
  319. var actionEnt = GetEntity(ev.Action);
  320. if (!TryComp(actionEnt, out MetaDataComponent? metaData))
  321. return;
  322. var name = Name(actionEnt, metaData);
  323. // Does the user actually have the requested action?
  324. if (!component.Actions.Contains(actionEnt))
  325. {
  326. _adminLogger.Add(LogType.Action,
  327. $"{ToPrettyString(user):user} attempted to perform an action that they do not have: {name}.");
  328. return;
  329. }
  330. if (!TryGetActionData(actionEnt, out var action))
  331. return;
  332. DebugTools.Assert(action.AttachedEntity == user);
  333. if (!action.Enabled)
  334. return;
  335. // check for action use prevention
  336. // TODO: make code below use this event with a dedicated component
  337. var attemptEv = new ActionAttemptEvent(user);
  338. RaiseLocalEvent(actionEnt, ref attemptEv);
  339. if (attemptEv.Cancelled)
  340. return;
  341. var curTime = GameTiming.CurTime;
  342. if (IsCooldownActive(action, curTime))
  343. return;
  344. // TODO: Replace with individual charge recovery when we have the visuals to aid it
  345. if (action is { Charges: < 1, RenewCharges: true })
  346. ResetCharges(actionEnt, true, true);
  347. BaseActionEvent? performEvent = null;
  348. if (action.CheckConsciousness && !_actionBlockerSystem.CanConsciouslyPerformAction(user))
  349. return;
  350. // Validate request by checking action blockers and the like:
  351. switch (action)
  352. {
  353. case EntityTargetActionComponent entityAction:
  354. if (ev.EntityTarget is not { Valid: true } netTarget)
  355. {
  356. Log.Error($"Attempted to perform an entity-targeted action without a target! Action: {name}");
  357. return;
  358. }
  359. var entityTarget = GetEntity(netTarget);
  360. var targetWorldPos = _transformSystem.GetWorldPosition(entityTarget);
  361. _rotateToFaceSystem.TryFaceCoordinates(user, targetWorldPos);
  362. if (!ValidateEntityTarget(user, entityTarget, (actionEnt, entityAction)))
  363. return;
  364. _adminLogger.Add(LogType.Action,
  365. $"{ToPrettyString(user):user} is performing the {name:action} action (provided by {ToPrettyString(action.Container ?? user):provider}) targeted at {ToPrettyString(entityTarget):target}.");
  366. if (entityAction.Event != null)
  367. {
  368. entityAction.Event.Target = entityTarget;
  369. Dirty(actionEnt, entityAction);
  370. performEvent = entityAction.Event;
  371. }
  372. break;
  373. case WorldTargetActionComponent worldAction:
  374. if (ev.EntityCoordinatesTarget is not { } netCoordinatesTarget)
  375. {
  376. Log.Error($"Attempted to perform a world-targeted action without a target! Action: {name}");
  377. return;
  378. }
  379. var entityCoordinatesTarget = GetCoordinates(netCoordinatesTarget);
  380. _rotateToFaceSystem.TryFaceCoordinates(user, _transformSystem.ToMapCoordinates(entityCoordinatesTarget).Position);
  381. if (!ValidateWorldTarget(user, entityCoordinatesTarget, (actionEnt, worldAction)))
  382. return;
  383. _adminLogger.Add(LogType.Action,
  384. $"{ToPrettyString(user):user} is performing the {name:action} action (provided by {ToPrettyString(action.Container ?? user):provider}) targeted at {entityCoordinatesTarget:target}.");
  385. if (worldAction.Event != null)
  386. {
  387. worldAction.Event.Target = entityCoordinatesTarget;
  388. Dirty(actionEnt, worldAction);
  389. performEvent = worldAction.Event;
  390. }
  391. break;
  392. case EntityWorldTargetActionComponent entityWorldAction:
  393. {
  394. var actionEntity = GetEntity(ev.EntityTarget);
  395. var actionCoords = GetCoordinates(ev.EntityCoordinatesTarget);
  396. if (actionEntity is null && actionCoords is null)
  397. {
  398. Log.Error($"Attempted to perform an entity-world-targeted action without an entity or world coordinates! Action: {name}");
  399. return;
  400. }
  401. var entWorldAction = new Entity<EntityWorldTargetActionComponent>(actionEnt, entityWorldAction);
  402. if (!ValidateEntityWorldTarget(user, actionEntity, actionCoords, entWorldAction))
  403. return;
  404. _adminLogger.Add(LogType.Action,
  405. $"{ToPrettyString(user):user} is performing the {name:action} action (provided by {ToPrettyString(action.Container ?? user):provider}) targeted at {ToPrettyString(actionEntity):target} {actionCoords:target}.");
  406. if (entityWorldAction.Event != null)
  407. {
  408. entityWorldAction.Event.Entity = actionEntity;
  409. entityWorldAction.Event.Coords = actionCoords;
  410. Dirty(actionEnt, entityWorldAction);
  411. performEvent = entityWorldAction.Event;
  412. }
  413. break;
  414. }
  415. case InstantActionComponent instantAction:
  416. if (action.CheckCanInteract && !_actionBlockerSystem.CanInteract(user, null))
  417. return;
  418. _adminLogger.Add(LogType.Action,
  419. $"{ToPrettyString(user):user} is performing the {name:action} action provided by {ToPrettyString(action.Container ?? user):provider}.");
  420. performEvent = instantAction.Event;
  421. break;
  422. }
  423. // All checks passed. Perform the action!
  424. PerformAction(user, component, actionEnt, action, performEvent, curTime);
  425. }
  426. public bool ValidateEntityTarget(EntityUid user, EntityUid target, Entity<EntityTargetActionComponent> actionEnt)
  427. {
  428. var comp = actionEnt.Comp;
  429. if (!ValidateEntityTargetBase(user,
  430. target,
  431. comp.Whitelist,
  432. comp.Blacklist,
  433. comp.CheckCanInteract,
  434. comp.CanTargetSelf,
  435. comp.CheckCanAccess,
  436. comp.Range))
  437. return false;
  438. var ev = new ValidateActionEntityTargetEvent(user, target);
  439. RaiseLocalEvent(actionEnt, ref ev);
  440. return !ev.Cancelled;
  441. }
  442. private bool ValidateEntityTargetBase(EntityUid user,
  443. EntityUid? targetEntity,
  444. EntityWhitelist? whitelist,
  445. EntityWhitelist? blacklist,
  446. bool checkCanInteract,
  447. bool canTargetSelf,
  448. bool checkCanAccess,
  449. float range)
  450. {
  451. if (targetEntity is not { } target || !target.IsValid() || Deleted(target))
  452. return false;
  453. if (_whitelistSystem.IsWhitelistFail(whitelist, target))
  454. return false;
  455. if (_whitelistSystem.IsBlacklistPass(blacklist, target))
  456. return false;
  457. if (checkCanInteract && !_actionBlockerSystem.CanInteract(user, target))
  458. return false;
  459. if (user == target)
  460. return canTargetSelf;
  461. if (!checkCanAccess)
  462. {
  463. // even if we don't check for obstructions, we may still need to check the range.
  464. var xform = Transform(user);
  465. var targetXform = Transform(target);
  466. if (xform.MapID != targetXform.MapID)
  467. return false;
  468. if (range <= 0)
  469. return true;
  470. var distance = (_transformSystem.GetWorldPosition(xform) - _transformSystem.GetWorldPosition(targetXform)).Length();
  471. return distance <= range;
  472. }
  473. return _interactionSystem.InRangeAndAccessible(user, target, range: range);
  474. }
  475. public bool ValidateWorldTarget(EntityUid user, EntityCoordinates coords, Entity<WorldTargetActionComponent> action)
  476. {
  477. var comp = action.Comp;
  478. if (!ValidateWorldTargetBase(user, coords, comp.CheckCanInteract, comp.CheckCanAccess, comp.Range))
  479. return false;
  480. var ev = new ValidateActionWorldTargetEvent(user, coords);
  481. RaiseLocalEvent(action, ref ev);
  482. return !ev.Cancelled;
  483. }
  484. private bool ValidateWorldTargetBase(EntityUid user,
  485. EntityCoordinates? entityCoordinates,
  486. bool checkCanInteract,
  487. bool checkCanAccess,
  488. float range)
  489. {
  490. if (entityCoordinates is not { } coords)
  491. return false;
  492. if (checkCanInteract && !_actionBlockerSystem.CanInteract(user, null))
  493. return false;
  494. if (!checkCanAccess)
  495. {
  496. // even if we don't check for obstructions, we may still need to check the range.
  497. var xform = Transform(user);
  498. if (xform.MapID != coords.GetMapId(EntityManager))
  499. return false;
  500. if (range <= 0)
  501. return true;
  502. return coords.InRange(EntityManager, _transformSystem, Transform(user).Coordinates, range);
  503. }
  504. return _interactionSystem.InRangeUnobstructed(user, coords, range: range);
  505. }
  506. public bool ValidateEntityWorldTarget(EntityUid user,
  507. EntityUid? entity,
  508. EntityCoordinates? coords,
  509. Entity<EntityWorldTargetActionComponent> action)
  510. {
  511. var comp = action.Comp;
  512. var entityValidated = ValidateEntityTargetBase(user,
  513. entity,
  514. comp.Whitelist,
  515. null,
  516. comp.CheckCanInteract,
  517. comp.CanTargetSelf,
  518. comp.CheckCanAccess,
  519. comp.Range);
  520. var worldValidated
  521. = ValidateWorldTargetBase(user, coords, comp.CheckCanInteract, comp.CheckCanAccess, comp.Range);
  522. if (!entityValidated && !worldValidated)
  523. return false;
  524. var ev = new ValidateActionEntityWorldTargetEvent(user,
  525. entityValidated ? entity : null,
  526. worldValidated ? coords : null);
  527. RaiseLocalEvent(action, ref ev);
  528. return !ev.Cancelled;
  529. }
  530. public void PerformAction(EntityUid performer, ActionsComponent? component, EntityUid actionId, BaseActionComponent action, BaseActionEvent? actionEvent, TimeSpan curTime, bool predicted = true)
  531. {
  532. var handled = false;
  533. var toggledBefore = action.Toggled;
  534. // Note that attached entity and attached container are allowed to be null here.
  535. if (action.AttachedEntity != null && action.AttachedEntity != performer)
  536. {
  537. Log.Error($"{ToPrettyString(performer)} is attempting to perform an action {ToPrettyString(actionId)} that is attached to another entity {ToPrettyString(action.AttachedEntity.Value)}");
  538. return;
  539. }
  540. if (actionEvent != null)
  541. {
  542. // This here is required because of client-side prediction (RaisePredictiveEvent results in event re-use).
  543. actionEvent.Handled = false;
  544. var target = performer;
  545. actionEvent.Performer = performer;
  546. actionEvent.Action = (actionId, action);
  547. if (!action.RaiseOnUser && action.Container != null && !HasComp<MindComponent>(action.Container))
  548. target = action.Container.Value;
  549. if (action.RaiseOnAction)
  550. target = actionId;
  551. RaiseLocalEvent(target, (object) actionEvent, broadcast: true);
  552. handled = actionEvent.Handled;
  553. }
  554. if (!handled)
  555. return; // no interaction occurred.
  556. // play sound, reduce charges, start cooldown, and mark as dirty (if required).
  557. if (actionEvent?.Toggle == true)
  558. {
  559. action.Toggled = !action.Toggled;
  560. }
  561. _audio.PlayPredicted(action.Sound, performer, predicted ? performer : null);
  562. var dirty = toggledBefore != action.Toggled;
  563. if (action.Charges != null)
  564. {
  565. dirty = true;
  566. action.Charges--;
  567. if (action is { Charges: 0, RenewCharges: false })
  568. action.Enabled = false;
  569. }
  570. action.Cooldown = null;
  571. if (action is { UseDelay: not null, Charges: null or < 1 })
  572. {
  573. dirty = true;
  574. action.Cooldown = (curTime, curTime + action.UseDelay.Value);
  575. }
  576. if (dirty)
  577. {
  578. Dirty(actionId, action);
  579. UpdateAction(actionId, action);
  580. }
  581. var ev = new ActionPerformedEvent(performer);
  582. RaiseLocalEvent(actionId, ref ev);
  583. }
  584. #endregion
  585. #region AddRemoveActions
  586. public EntityUid? AddAction(EntityUid performer,
  587. string? actionPrototypeId,
  588. EntityUid container = default,
  589. ActionsComponent? component = null)
  590. {
  591. EntityUid? actionId = null;
  592. AddAction(performer, ref actionId, out _, actionPrototypeId, container, component);
  593. return actionId;
  594. }
  595. /// <summary>
  596. /// Adds an action to an action holder. If the given entity does not exist, it will attempt to spawn one.
  597. /// If the holder has no actions component, this will give them one.
  598. /// </summary>
  599. /// <param name="performer">Entity to receive the actions</param>
  600. /// <param name="actionId">Action entity to add</param>
  601. /// <param name="component">The <see cref="performer"/>'s action component of </param>
  602. /// <param name="actionPrototypeId">The action entity prototype id to use if <see cref="actionId"/> is invalid.</param>
  603. /// <param name="container">The entity that contains/enables this action (e.g., flashlight).</param>
  604. public bool AddAction(EntityUid performer,
  605. [NotNullWhen(true)] ref EntityUid? actionId,
  606. string? actionPrototypeId,
  607. EntityUid container = default,
  608. ActionsComponent? component = null)
  609. {
  610. return AddAction(performer, ref actionId, out _, actionPrototypeId, container, component);
  611. }
  612. /// <inheritdoc cref="AddAction(Robust.Shared.GameObjects.EntityUid,ref System.Nullable{Robust.Shared.GameObjects.EntityUid},string?,Robust.Shared.GameObjects.EntityUid,Content.Shared.Actions.ActionsComponent?)"/>
  613. public bool AddAction(EntityUid performer,
  614. [NotNullWhen(true)] ref EntityUid? actionId,
  615. [NotNullWhen(true)] out BaseActionComponent? action,
  616. string? actionPrototypeId,
  617. EntityUid container = default,
  618. ActionsComponent? component = null)
  619. {
  620. if (!container.IsValid())
  621. container = performer;
  622. if (!_actionContainer.EnsureAction(container, ref actionId, out action, actionPrototypeId))
  623. return false;
  624. return AddActionDirect(performer, actionId.Value, component, action);
  625. }
  626. /// <summary>
  627. /// Adds a pre-existing action.
  628. /// </summary>
  629. public bool AddAction(EntityUid performer,
  630. EntityUid actionId,
  631. EntityUid container,
  632. ActionsComponent? comp = null,
  633. BaseActionComponent? action = null,
  634. ActionsContainerComponent? containerComp = null
  635. )
  636. {
  637. if (!ResolveActionData(actionId, ref action))
  638. return false;
  639. if (action.Container != container
  640. || !Resolve(container, ref containerComp)
  641. || !containerComp.Container.Contains(actionId))
  642. {
  643. Log.Error($"Attempted to add an action with an invalid container: {ToPrettyString(actionId)}");
  644. return false;
  645. }
  646. return AddActionDirect(performer, actionId, comp, action);
  647. }
  648. /// <summary>
  649. /// Adds a pre-existing action. This also bypasses the requirement that the given action must be stored in a
  650. /// valid action container.
  651. /// </summary>
  652. public bool AddActionDirect(EntityUid performer,
  653. EntityUid actionId,
  654. ActionsComponent? comp = null,
  655. BaseActionComponent? action = null)
  656. {
  657. if (!ResolveActionData(actionId, ref action))
  658. return false;
  659. DebugTools.Assert(action.Container == null ||
  660. (TryComp(action.Container, out ActionsContainerComponent? containerComp)
  661. && containerComp.Container.Contains(actionId)));
  662. if (action.AttachedEntity != null)
  663. RemoveAction(action.AttachedEntity.Value, actionId, action: action);
  664. if (action.StartDelay && action.UseDelay != null)
  665. SetCooldown(actionId, action.UseDelay.Value);
  666. DebugTools.AssertOwner(performer, comp);
  667. comp ??= EnsureComp<ActionsComponent>(performer);
  668. action.AttachedEntity = performer;
  669. comp.Actions.Add(actionId);
  670. Dirty(actionId, action);
  671. Dirty(performer, comp);
  672. ActionAdded(performer, actionId, comp, action);
  673. return true;
  674. }
  675. /// <summary>
  676. /// This method gets called after a new action got added.
  677. /// </summary>
  678. protected virtual void ActionAdded(EntityUid performer, EntityUid actionId, ActionsComponent comp, BaseActionComponent action)
  679. {
  680. // See client-side system for UI code.
  681. }
  682. /// <summary>
  683. /// Grant pre-existing actions. If the entity has no action component, this will give them one.
  684. /// </summary>
  685. /// <param name="performer">Entity to receive the actions</param>
  686. /// <param name="actions">The actions to add</param>
  687. /// <param name="container">The entity that enables these actions (e.g., flashlight). May be null (innate actions).</param>
  688. public void GrantActions(EntityUid performer, IEnumerable<EntityUid> actions, EntityUid container, ActionsComponent? comp = null, ActionsContainerComponent? containerComp = null)
  689. {
  690. if (!Resolve(container, ref containerComp))
  691. return;
  692. DebugTools.AssertOwner(performer, comp);
  693. comp ??= EnsureComp<ActionsComponent>(performer);
  694. foreach (var actionId in actions)
  695. {
  696. AddAction(performer, actionId, container, comp, containerComp: containerComp);
  697. }
  698. }
  699. /// <summary>
  700. /// Grants all actions currently contained in some action-container. If the target entity has no action
  701. /// component, this will give them one.
  702. /// </summary>
  703. /// <param name="performer">Entity to receive the actions</param>
  704. /// <param name="container">The entity that contains thee actions.</param>
  705. public void GrantContainedActions(Entity<ActionsComponent?> performer, Entity<ActionsContainerComponent?> container)
  706. {
  707. if (!Resolve(container, ref container.Comp))
  708. return;
  709. performer.Comp ??= EnsureComp<ActionsComponent>(performer);
  710. foreach (var actionId in container.Comp.Container.ContainedEntities)
  711. {
  712. if (TryGetActionData(actionId, out var action))
  713. AddActionDirect(performer, actionId, performer.Comp, action);
  714. }
  715. }
  716. /// <summary>
  717. /// Grants the provided action from the container to the target entity. If the target entity has no action
  718. /// component, this will give them one.
  719. /// </summary>
  720. /// <param name="performer"></param>
  721. /// <param name="container"></param>
  722. /// <param name="actionId"></param>
  723. public void GrantContainedAction(Entity<ActionsComponent?> performer, Entity<ActionsContainerComponent?> container, EntityUid actionId)
  724. {
  725. if (!Resolve(container, ref container.Comp))
  726. return;
  727. performer.Comp ??= EnsureComp<ActionsComponent>(performer);
  728. if (TryGetActionData(actionId, out var action))
  729. AddActionDirect(performer, actionId, performer.Comp, action);
  730. }
  731. public IEnumerable<(EntityUid Id, BaseActionComponent Comp)> GetActions(EntityUid holderId, ActionsComponent? actions = null)
  732. {
  733. if (!Resolve(holderId, ref actions, false))
  734. yield break;
  735. foreach (var actionId in actions.Actions)
  736. {
  737. if (!TryGetActionData(actionId, out var action))
  738. continue;
  739. yield return (actionId, action);
  740. }
  741. }
  742. /// <summary>
  743. /// Remove any actions that were enabled by some other entity. Useful when unequiping items that grant actions.
  744. /// </summary>
  745. public void RemoveProvidedActions(EntityUid performer, EntityUid container, ActionsComponent? comp = null)
  746. {
  747. if (!Resolve(performer, ref comp, false))
  748. return;
  749. foreach (var actionId in comp.Actions.ToArray())
  750. {
  751. if (!TryGetActionData(actionId, out var action))
  752. return;
  753. if (action.Container == container)
  754. RemoveAction(performer, actionId, comp);
  755. }
  756. }
  757. /// <summary>
  758. /// Removes a single provided action provided by another entity.
  759. /// </summary>
  760. public void RemoveProvidedAction(EntityUid performer, EntityUid container, EntityUid actionId, ActionsComponent? comp = null)
  761. {
  762. if (!Resolve(performer, ref comp, false) || !TryGetActionData(actionId, out var action))
  763. return;
  764. if (action.Container == container)
  765. RemoveAction(performer, actionId, comp);
  766. }
  767. public void RemoveAction(EntityUid? actionId)
  768. {
  769. if (actionId == null)
  770. return;
  771. if (!TryGetActionData(actionId, out var action))
  772. return;
  773. if (!TryComp(action.AttachedEntity, out ActionsComponent? comp))
  774. return;
  775. RemoveAction(action.AttachedEntity.Value, actionId, comp, action);
  776. }
  777. public void RemoveAction(EntityUid performer, EntityUid? actionId, ActionsComponent? comp = null, BaseActionComponent? action = null)
  778. {
  779. if (actionId == null)
  780. return;
  781. if (!ResolveActionData(actionId, ref action))
  782. return;
  783. if (action.AttachedEntity != performer)
  784. {
  785. DebugTools.Assert(!Resolve(performer, ref comp, false)
  786. || comp.LifeStage >= ComponentLifeStage.Stopping
  787. || !comp.Actions.Contains(actionId.Value));
  788. if (!GameTiming.ApplyingState)
  789. Log.Error($"Attempted to remove an action {ToPrettyString(actionId)} from an entity that it was never attached to: {ToPrettyString(performer)}. Trace: {Environment.StackTrace}");
  790. return;
  791. }
  792. if (!Resolve(performer, ref comp, false))
  793. {
  794. DebugTools.Assert(action.AttachedEntity == null || TerminatingOrDeleted(action.AttachedEntity.Value));
  795. action.AttachedEntity = null;
  796. return;
  797. }
  798. if (action.AttachedEntity == null)
  799. {
  800. // action was already removed?
  801. DebugTools.Assert(!comp.Actions.Contains(actionId.Value) || GameTiming.ApplyingState);
  802. return;
  803. }
  804. comp.Actions.Remove(actionId.Value);
  805. action.AttachedEntity = null;
  806. Dirty(actionId.Value, action);
  807. Dirty(performer, comp);
  808. ActionRemoved(performer, actionId.Value, comp, action);
  809. if (action.Temporary)
  810. QueueDel(actionId.Value);
  811. }
  812. /// <summary>
  813. /// This method gets called after an action got removed.
  814. /// </summary>
  815. protected virtual void ActionRemoved(EntityUid performer, EntityUid actionId, ActionsComponent comp, BaseActionComponent action)
  816. {
  817. // See client-side system for UI code.
  818. }
  819. public bool ValidAction(BaseActionComponent action, bool canReach = true)
  820. {
  821. if (!action.Enabled)
  822. return false;
  823. if (action.Charges.HasValue && action.Charges <= 0)
  824. return false;
  825. var curTime = GameTiming.CurTime;
  826. if (action.Cooldown.HasValue && action.Cooldown.Value.End > curTime)
  827. return false;
  828. return canReach || action is BaseTargetActionComponent { CheckCanAccess: false };
  829. }
  830. #endregion
  831. private void OnRelayActionCompChange(Entity<ActionsComponent> ent, ref RelayedActionComponentChangeEvent args)
  832. {
  833. if (args.Handled)
  834. return;
  835. var ev = new AttemptRelayActionComponentChangeEvent();
  836. RaiseLocalEvent(ent.Owner, ref ev);
  837. var target = ev.Target ?? ent.Owner;
  838. args.Handled = true;
  839. args.Toggle = true;
  840. if (!args.Action.Comp.Toggled)
  841. {
  842. EntityManager.AddComponents(target, args.Components);
  843. }
  844. else
  845. {
  846. EntityManager.RemoveComponents(target, args.Components);
  847. }
  848. }
  849. private void OnActionCompChange(Entity<ActionsComponent> ent, ref ActionComponentChangeEvent args)
  850. {
  851. if (args.Handled)
  852. return;
  853. args.Handled = true;
  854. args.Toggle = true;
  855. var target = ent.Owner;
  856. if (!args.Action.Comp.Toggled)
  857. {
  858. EntityManager.AddComponents(target, args.Components);
  859. }
  860. else
  861. {
  862. EntityManager.RemoveComponents(target, args.Components);
  863. }
  864. }
  865. #region EquipHandlers
  866. private void OnDidEquip(EntityUid uid, ActionsComponent component, DidEquipEvent args)
  867. {
  868. if (GameTiming.ApplyingState)
  869. return;
  870. var ev = new GetItemActionsEvent(_actionContainer, args.Equipee, args.Equipment, args.SlotFlags);
  871. RaiseLocalEvent(args.Equipment, ev);
  872. if (ev.Actions.Count == 0)
  873. return;
  874. GrantActions(args.Equipee, ev.Actions, args.Equipment, component);
  875. }
  876. private void OnHandEquipped(EntityUid uid, ActionsComponent component, DidEquipHandEvent args)
  877. {
  878. if (GameTiming.ApplyingState)
  879. return;
  880. var ev = new GetItemActionsEvent(_actionContainer, args.User, args.Equipped);
  881. RaiseLocalEvent(args.Equipped, ev);
  882. if (ev.Actions.Count == 0)
  883. return;
  884. GrantActions(args.User, ev.Actions, args.Equipped, component);
  885. }
  886. private void OnDidUnequip(EntityUid uid, ActionsComponent component, DidUnequipEvent args)
  887. {
  888. if (GameTiming.ApplyingState)
  889. return;
  890. RemoveProvidedActions(uid, args.Equipment, component);
  891. }
  892. private void OnHandUnequipped(EntityUid uid, ActionsComponent component, DidUnequipHandEvent args)
  893. {
  894. if (GameTiming.ApplyingState)
  895. return;
  896. RemoveProvidedActions(uid, args.Unequipped, component);
  897. }
  898. #endregion
  899. public void SetEntityIcon(EntityUid uid, EntityUid? icon, BaseActionComponent? action = null)
  900. {
  901. if (!Resolve(uid, ref action))
  902. return;
  903. action.EntityIcon = icon;
  904. Dirty(uid, action);
  905. }
  906. /// <summary>
  907. /// Checks if the action has a cooldown and if it's still active
  908. /// </summary>
  909. protected bool IsCooldownActive(BaseActionComponent action, TimeSpan? curTime = null)
  910. {
  911. curTime ??= GameTiming.CurTime;
  912. // TODO: Check for charge recovery timer
  913. return action.Cooldown.HasValue && action.Cooldown.Value.End > curTime;
  914. }
  915. protected bool ShouldResetCharges(BaseActionComponent action)
  916. {
  917. return action is { Charges: < 1, RenewCharges: true };
  918. }
  919. }