Files
Delta-v/Content.Server/Salvage/SalvageSystem.Magnet.cs
T
29e55b9464 Upstream Merge (June / July) attempt 2 electric boogaloo (#4607)
* Fix the sensor monitoring console forcing a GC every 3 seconds (#38146)

* Optimize sensor monitoring window graph drawing

* Add shared static Vector2 pool for all GraphView instances

* Address requested changes

* remove lock

* Update submodule to 264.0.0 (#38629)

* Toy/Plushie Inhands and Wearables (#38514)

* Fixed dependency injection and some other issues in a few places.

* More issue fixes

* patchfor broken NetworkConfiguratorLinkMenu (#38632)

fix

* Fix solutions flickering when transferring contents (#34838)

* Use Solution clones when applying SolutionComponent states

* Revert "Use Solution clones when applying SolutionComponent states"

This reverts commit 013fd111cf92b22562e00f98a7aaa49bc4b4ed62.

* Make Solution implement ICloneable and rename Clone method.

* Copy CanReact value when cloning a Solution

* Convert to IRobustCloneable

* Fix typos in guidebook: Buisness → Business (#38636)

* Fix typo in `MinorAntagonists.xml`

Buisness → Business

* Fix typo in `YourFirstCharacter.xml`

Buisness → Business

* Various Headphones Fixes and Tweaks (#38479)

* sprites, wearables

* neck

* icon-on sprite

* Cleanup prototype instantiation in `DamageTest` (#38639)

Cleanup prototype instantiation in DamageTest

* Cleanup prototype instantiation in `ExplosionSystem` (#38642)

Cleanup prototype instantiation in ExplosionSystem

* AddBodyPartCommand localization. (#38612)

commit

* fix ItemSlotsSystem debug assert (#38655)

* Allow the Command & Super door remotes to use the access of their user. (Re-creation of PR due to changes to game balance) (#35536)

* Added directional beacons (#38284)

* Added directional beacons

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* Fixed names

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

---------

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* Power stat and nuke codes commands get some LEC love. (#38585)

* commit

* requested changes.

* Dsay Dirty and Follow commands converted to LEC and localized. (#38666)

* commit

* whoopwhoopwhoop

* Retro laser sprite fix (#38676)

* Fixed everything except the icon

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* fixed icon

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

---------

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* fix water coolers (#38681)

* Monochromacy typo fix (#38686)

* fixes the typo

* Fixed cloning looking for the trait, not the component, RE https://github.com/space-wizards/space-station-14/pull/38686#issuecomment-3025093504

* Apply suggestions from code review

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Validate `CloningSettingsPrototype`s (#38688)

* Validate CloningSettingsPrototypes

* Update Content.IntegrationTests/Tests/Cloning/CloningSettingsPrototypeTest.cs

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Check EventComponents too

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Add test of objective-related console commands (#36400)

* Add test of objective add/list/remove commands

* Not sure why we're validating test prototypes, but sure

* We don't need a map

* Improvements and fixups for New Status Effect API (#38660)

* Predict healing and bloodstream (#38690)

* initial commit

* reapply 38126

* fix rootable

* someone missed an important minus sign here

* try this

* fix

* fix

* reenable crit hits

* cleanup

* fix status time dirtying

* fix

* camelCase

* Healing and bloodstream prediction fixes.

* Resolving Wizard casting recall on nuke disk making it impossible to disarm (#38661)

* Resolving Wizard Recall on Nuke disk making it impossible to disarm
- Adding a DisarmBomb case to nuke status update loop
- Changing a few methods and parameters to properly follow formatting standards
- Updating some names to follow camelCase

* Updating missed tag

* Reverting DataField change

Should prevent this preventative bugfix being a breaking change.

* Switch HSV to the default colorspace for character customization (#38434)

* Made HSV default for character editor

* Adds/fixes comments to HSV defaulting

* Added dropbox fix, potentially cursed

* Revert "Added dropbox fix, potentially cursed"

This reverts commit a709883366fbee813e839742125e70844672af29.

---------

Co-authored-by: TrixxedHeart <46364955+TrixxedBit@users.noreply.github.com>

* Fix: Don't deploy foldables when clicking on items inside containers (#38709)

* Fix

* Apply suggestions from code review

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Pressure Relief Valve (#36708)

* initial system (this math is probably WRONG)

* General code cleanup and OnExamined support
(holy moly this code sucks)

* UICode and related events foundation
TODO:
- Actually write the XAML UI and the underlying system
- Un-shitcode the entire thing
- Actually test everything...

* Working UI code
TODO: Make predicted, as this certainly isn't predicted. Even though I said it was. It isn't.

* Remove one TODO for unshitcoding the examine code

* Add reminder
yea

* Make predicted (defenitely isn't)
(also defenitely isn't a copypaste from pressure pump code)

* It's predicted!
TODO:
- Give it snazzy predicted visuals!
- Have a different field for pressure entry, lest it gets bulldozed every UI update.

* Improve gas pressure relief valve UI
TODO: Reminder to reduce amount of dirties using deltafields

* Implement DirtyField prediction

* Entity<T> cleanup
A lot of Entity<T> conversions and lukewarm cleanup.

Also got caught copy pasting code in 4K UHD but it's not like you couldn't tell.

* More cleanup and comments

* Remove TODO comment on bulldozing window title

* """refactoring"""
- Move appearance out of shared and finally fix it. Pointless to predict appearance in this instance.
- More Entity<T> conversions because I like them.
- Move UI creation handling over entirely to the ActivatableUI system.
- Fix a hardcoded locale string (why????).

* Add visuals

* Revert debugging variable replacememt
yea

* Revert skissue

* Remove unused using directives and remove TODO

* Localize, cleanup, document

* Fix adminlogging discrepancy

* Add ability to construct, add guidebook entry

* Clear up comment

* Add guidebook tooltip to valve

* Convert GasPressureReliefValveBoundUserInterface declaration into primary constructor

* Adds more input handling and adds autofill on open

* Un-deepfry input validator shitcode
Genuinely what was I smoking

* improve visuals logic

* Refactor again
- Update math to the correct implementation
- Moved code that could be re-used in the future into a helper method under AtmosphereSystem.Gases.cs

* I'm sorry but I hate warnings

* Remove unused using directive in AtmosphereSystem.Gases.cs

* Review and cleanup

* Lukewarm UI glossup

* Maintainer for the upstream project btw

* Remove redundant state sets and messy logic

* Unduplicate valve updater code

* Redo UI (im sorry Slarti)

* run tests

* Test refactored UI messaging

* Second round of UI improvements
- God please find a way to improve this system. Feels bad.

* Update loop implementation

* Further predict UI

* Clear up SetToCurrentThreshold

* cleanup

* Update to master + pipe layers and bug fixes
want to run tests

* fixes

* Deploy rename pipebomb

* Documentation and requested changes

* Rename the method that wiggled away

* Undo rounding changes

* Fix comment

* Rename and cleanup

* Apply suggestions from code review

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Fix TextLinkTag (#32203)

* Adjust uplink buy button to be under item icon (#38596)

* Adjusted uplink buy button to be under item icon

* Put the discount subtext under the icon

* Indent fixes, added margin

---------

Co-authored-by: TrixxedHeart <46364955+TrixxedBit@users.noreply.github.com>

* Scurrets - Audio Improvements (#38482)

* Scurret audio tuning

* Add new sfx

* Update sneezing sfx

* YAML support

* Rename a folder

* make telesci wreck easier (#37569)

rel

* Validate `ShaderPrototype` IDs (#38728)

* Convert all shader prototype string literals to protoids in overlays

* Convert more shader prototype literal strings to protoids

* Convert ValidatePrototypeId to ProtoId

* Later

* [BUGFIX] Fixed revenant malfunction ability not working properly only MediBots and Stasis bed (#38664)

* fixed

* clean up

* orks fix smart

* review fix 1

* more requested changes

* less cursed

* more descriptive description

* better wording

* Tiny Tiny Cleanup of the EyeClosingSystem. (#38734)

Update EyeClosingSystem.cs

* Fix human skin tone distribution (#38701)

* fix: Use PredictedQueueDel for gib spell (#38729)

* fix: don't default to uncharged sprite state for cells (#38730)

* Fix Hristov description - remove inaccurate technical specs (#38746)

- Removes inaccurate 'armor piercing 14.5mm shells' reference
- Replaces it with a more funny description, matching the style of the other snipers and guns
- Keeps ammunition type '.60 anti-materiel ammo' specification
- Fixes issue #38590

Co-authored-by: Arthur Fiorese de Andrade <aandrade@cmcxs.gov.br>

* feat: allow mopping evaporating puddles (#38743)

* Validate remaining `ProtoId` strings (#38747)

Validate remaining ProtoId strings

* Validate `ProtoId`s in tests (#38745)

* Convert string literals to protoids in Content.Tests

* Convert string literals to protoids or consts in Content.IntegrationTests

* Fix linter failures
Tricksy static using misled me

* Cleanup warning in StomachSystem (#38748)

you did not see this

* Vox scars (#38592)

* Added vox scars n'stuff, renamed vox_tattoos.ftl to just vox.ftl

* Revert "Added vox scars n'stuff, renamed vox_tattoos.ftl to just vox.ftl"

This reverts commit c73da55ba3b39ddf93b493aecd85604c54dd8a15.

* locale key fix

* Changed top surgery scar names to be more generalized

* Adjusted face scars

* Formatting fixes

---------

Co-authored-by: TrixxedHeart <46364955+TrixxedBit@users.noreply.github.com>

* UnlockNode command to LEC. (#38751)

* commit

* Update UnlockNodeCommand.cs

* commit

* move command locale to its own file.

* Update Content.Server/Xenoarchaeology/Artifact/UnlockNodeCommand.cs

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Typofixes for figurine dialogue (#38737)

* Typofixes for figurine dialogue

* Forgot two

* Janitor Tool: Wire Brush (#38667)

* Wow! It's -brush-

* spacing.

* Update Resources/Prototypes/Entities/Objects/Specific/Janitorial/janitor.yml

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Update Resources/Prototypes/Entities/Objects/Specific/Janitorial/janitor.yml

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* fixed changes

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Minor escape menu UX improvements (#38650)

* fix: spellbooks can have infinite charges (#38376)

* fix: spellbooks can have infinite charges

* refactor: indicate infinite spellbook charges with null

Not sure if I like this much better...
2025-11-06 18:22:39 +00:00

470 lines
17 KiB
C#

using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using Content.Server.Salvage.Magnet;
using Content.Shared.Mobs.Components;
using Content.Shared.Procedural;
using Content.Shared.Radio;
using Content.Shared.Salvage.Magnet;
using Robust.Shared.Exceptions;
using Robust.Shared.Map;
using Robust.Shared.Prototypes;
namespace Content.Server.Salvage;
public sealed partial class SalvageSystem
{
[Dependency] private readonly IRuntimeLog _runtimeLog = default!;
private static readonly ProtoId<RadioChannelPrototype> MagnetChannel = "Supply";
private EntityQuery<SalvageMobRestrictionsComponent> _salvMobQuery;
private EntityQuery<MobStateComponent> _mobStateQuery;
private List<(Entity<TransformComponent> Entity, EntityUid MapUid, Vector2 LocalPosition)> _detachEnts = new();
private void InitializeMagnet()
{
_salvMobQuery = GetEntityQuery<SalvageMobRestrictionsComponent>();
_mobStateQuery = GetEntityQuery<MobStateComponent>();
SubscribeLocalEvent<SalvageMagnetDataComponent, MapInitEvent>(OnMagnetDataMapInit);
SubscribeLocalEvent<SalvageMagnetTargetComponent, GridSplitEvent>(OnMagnetTargetSplit);
SubscribeLocalEvent<SalvageMagnetComponent, MagnetClaimOfferEvent>(OnMagnetClaim);
SubscribeLocalEvent<SalvageMagnetComponent, ComponentStartup>(OnMagnetStartup);
SubscribeLocalEvent<SalvageMagnetComponent, AnchorStateChangedEvent>(OnMagnetAnchored);
}
private void OnMagnetClaim(EntityUid uid, SalvageMagnetComponent component, ref MagnetClaimOfferEvent args)
{
var station = _station.GetOwningStation(uid);
if (!TryComp(station, out SalvageMagnetDataComponent? dataComp) ||
dataComp.EndTime != null)
{
return;
}
var index = args.Index;
var user = args.Actor; // DeltaV
async void TryTakeMagnetOffer()
{
try
{
await TakeMagnetOffer((station.Value, dataComp), index, (uid, component), user); // DeltaV: pass the user
}
catch (Exception e)
{
_runtimeLog.LogException(e, $"{nameof(SalvageSystem)}.{nameof(TakeMagnetOffer)}");
}
}
TryTakeMagnetOffer();
}
private void OnMagnetStartup(EntityUid uid, SalvageMagnetComponent component, ComponentStartup args)
{
UpdateMagnetUI((uid, component), Transform(uid));
}
private void OnMagnetAnchored(EntityUid uid, SalvageMagnetComponent component, ref AnchorStateChangedEvent args)
{
if (!args.Anchored)
return;
UpdateMagnetUI((uid, component), args.Transform);
}
private void OnMagnetDataMapInit(EntityUid uid, SalvageMagnetDataComponent component, ref MapInitEvent args)
{
CreateMagnetOffers((uid, component));
}
private void OnMagnetTargetSplit(EntityUid uid, SalvageMagnetTargetComponent component, ref GridSplitEvent args)
{
// Don't think I'm not onto you people splitting to make new grids.
if (TryComp(component.DataTarget, out SalvageMagnetDataComponent? dataComp))
{
foreach (var gridUid in args.NewGrids)
{
dataComp.ActiveEntities?.Add(gridUid);
}
}
}
private void UpdateMagnet()
{
var dataQuery = EntityQueryEnumerator<SalvageMagnetDataComponent>();
var curTime = _timing.CurTime;
while (dataQuery.MoveNext(out var uid, out var magnetData))
{
// Magnet currently active.
if (magnetData.EndTime != null)
{
if (magnetData.EndTime.Value < curTime)
{
EndMagnet((uid, magnetData));
}
else if (!magnetData.Announced && (magnetData.EndTime.Value - curTime).TotalSeconds < 59) //DeltaV: was 31 seconds. Increased to give time to actually fulton a crate out.
{
var magnet = GetMagnet((uid, magnetData));
if (magnet != null)
{
Report(magnet.Value.Owner, MagnetChannel,
"salvage-system-announcement-losing",
("timeLeft", (magnetData.EndTime.Value - curTime).Seconds));
}
magnetData.Announced = true;
}
}
if (magnetData.NextOffer < curTime)
{
CreateMagnetOffers((uid, magnetData));
}
}
}
/// <summary>
/// Ends the magnet attachment and deletes the relevant grids.
/// </summary>
private void EndMagnet(Entity<SalvageMagnetDataComponent> data)
{
if (data.Comp.ActiveEntities != null)
{
// Handle mobrestrictions getting deleted
var query = AllEntityQuery<SalvageMobRestrictionsComponent, MobStateComponent>();
while (query.MoveNext(out var salvUid, out var salvMob, out var salvMobState))
{
if (data.Comp.ActiveEntities.Contains(salvMob.LinkedEntity) && _mobState.IsAlive(salvUid, salvMobState))
{
QueueDel(salvUid);
}
}
// Uhh yeah don't delete mobs or whatever
var mobQuery = AllEntityQuery<MobStateComponent, TransformComponent>();
_detachEnts.Clear();
while (mobQuery.MoveNext(out var mobUid, out _, out var xform))
{
if (xform.GridUid == null || !data.Comp.ActiveEntities.Contains(xform.GridUid.Value) || xform.MapUid == null)
continue;
if (_salvMobQuery.HasComp(mobUid))
continue;
bool CheckParents(EntityUid uid)
{
do
{
uid = _transform.GetParentUid(uid);
if (_mobStateQuery.HasComp(uid))
return true;
} while (uid != xform.GridUid && uid != EntityUid.Invalid);
return false;
}
if (CheckParents(mobUid))
continue;
// Can't parent directly to map as it runs grid traversal.
_detachEnts.Add(((mobUid, xform), xform.MapUid.Value, _transform.GetWorldPosition(xform)));
_transform.DetachEntity(mobUid, xform);
}
// Go and cleanup the active ents.
foreach (var ent in data.Comp.ActiveEntities)
{
Del(ent);
}
foreach (var entity in _detachEnts)
{
_transform.SetCoordinates(entity.Entity.Owner, new EntityCoordinates(entity.MapUid, entity.LocalPosition));
}
data.Comp.ActiveEntities = null;
}
data.Comp.EndTime = null;
UpdateMagnetUIs(data);
}
private void CreateMagnetOffers(Entity<SalvageMagnetDataComponent> data)
{
data.Comp.Offered.Clear();
for (var i = 0; i < data.Comp.OfferCount; i++)
{
var seed = _random.Next();
// Fuck with the seed to mix wrecks and asteroids.
seed = (int) (seed / 10f) * 10;
if (i >= data.Comp.OfferCount / 2)
{
seed++;
}
data.Comp.Offered.Add(seed);
}
data.Comp.NextOffer = _timing.CurTime + data.Comp.OfferCooldown;
UpdateMagnetUIs(data);
}
// Just need something to announce.
private Entity<SalvageMagnetComponent>? GetMagnet(Entity<SalvageMagnetDataComponent> data)
{
var query = AllEntityQuery<SalvageMagnetComponent, TransformComponent>();
while (query.MoveNext(out var magnetUid, out var magnet, out var xform))
{
var stationUid = _station.GetOwningStation(magnetUid, xform);
if (stationUid != data.Owner)
continue;
return (magnetUid, magnet);
}
return null;
}
private void UpdateMagnetUI(Entity<SalvageMagnetComponent> entity, TransformComponent xform)
{
var station = _station.GetOwningStation(entity, xform);
if (!TryComp(station, out SalvageMagnetDataComponent? dataComp))
return;
_ui.SetUiState(entity.Owner, SalvageMagnetUiKey.Key,
new SalvageMagnetBoundUserInterfaceState(dataComp.Offered)
{
Cooldown = dataComp.OfferCooldown,
Duration = dataComp.ActiveTime,
EndTime = dataComp.EndTime,
NextOffer = dataComp.NextOffer,
ActiveSeed = dataComp.ActiveSeed,
});
}
private void UpdateMagnetUIs(Entity<SalvageMagnetDataComponent> data)
{
var query = AllEntityQuery<SalvageMagnetComponent, TransformComponent>();
while (query.MoveNext(out var magnetUid, out var magnet, out var xform))
{
var station = _station.GetOwningStation(magnetUid, xform);
if (station != data.Owner)
continue;
_ui.SetUiState(magnetUid, SalvageMagnetUiKey.Key,
new SalvageMagnetBoundUserInterfaceState(data.Comp.Offered)
{
Cooldown = data.Comp.OfferCooldown,
Duration = data.Comp.ActiveTime,
EndTime = data.Comp.EndTime,
NextOffer = data.Comp.NextOffer,
ActiveSeed = data.Comp.ActiveSeed,
});
}
}
private async Task TakeMagnetOffer(Entity<SalvageMagnetDataComponent> data, int index, Entity<SalvageMagnetComponent> magnet, EntityUid user) // DeltaV: add user param
{
var seed = data.Comp.Offered[index];
var offering = GetSalvageOffering(seed);
// Begin DeltaV Addition: make wrecks cost mining points to pull
if (offering.Cost > 0 && !(_points.TryFindIdCard(user) is {} idCard && _points.RemovePoints(idCard, offering.Cost)))
return;
// End DeltaV Addition
var salvMap = _mapSystem.CreateMap();
var salvMapXform = Transform(salvMap);
// Set values while awaiting asteroid dungeon if relevant so we can't double-take offers.
data.Comp.ActiveSeed = seed;
data.Comp.EndTime = _timing.CurTime + data.Comp.ActiveTime;
data.Comp.NextOffer = data.Comp.EndTime.Value;
UpdateMagnetUIs(data);
switch (offering)
{
case AsteroidOffering asteroid:
var grid = _mapManager.CreateGridEntity(salvMap);
await _dungeon.GenerateDungeonAsync(asteroid.DungeonConfig, grid.Owner, grid.Comp, Vector2i.Zero, seed);
break;
case DebrisOffering debris:
var debrisProto = _prototypeManager.Index<DungeonConfigPrototype>(debris.Id);
var debrisGrid = _mapManager.CreateGridEntity(salvMap);
await _dungeon.GenerateDungeonAsync(debrisProto, debrisGrid.Owner, debrisGrid.Comp, Vector2i.Zero, seed);
break;
case SalvageOffering wreck:
var salvageProto = wreck.SalvageMap;
if (!_loader.TryLoadGrid(salvMapXform.MapID, salvageProto.MapPath, out _))
{
Report(magnet, MagnetChannel, "salvage-system-announcement-spawn-debris-disintegrated");
_mapSystem.DeleteMap(salvMapXform.MapID);
return;
}
break;
default:
throw new ArgumentOutOfRangeException();
}
Box2? bounds = null;
if (salvMapXform.ChildCount == 0)
{
Report(magnet.Owner, MagnetChannel, "salvage-system-announcement-spawn-no-debris-available");
return;
}
var mapChildren = salvMapXform.ChildEnumerator;
while (mapChildren.MoveNext(out var mapChild))
{
// If something went awry in dungen.
if (!_gridQuery.TryGetComponent(mapChild, out var childGrid))
continue;
var childAABB = _transform.GetWorldMatrix(mapChild).TransformBox(childGrid.LocalAABB);
bounds = bounds?.Union(childAABB) ?? childAABB;
// Update mass scanner names as relevant.
if (offering is AsteroidOffering or DebrisOffering)
{
_metaData.SetEntityName(mapChild, Loc.GetString("salvage-asteroid-name"));
_gravity.EnableGravity(mapChild);
}
}
var magnetXform = _xformQuery.GetComponent(magnet.Owner);
var magnetGridUid = magnetXform.GridUid;
var attachedBounds = new Box2Rotated();
var mapId = MapId.Nullspace;
Angle worldAngle;
if (magnetGridUid != null)
{
var magnetGridXform = _xformQuery.GetComponent(magnetGridUid.Value);
var (gridPos, gridRot) = _transform.GetWorldPositionRotation(magnetGridXform);
var gridAABB = _gridQuery.GetComponent(magnetGridUid.Value).LocalAABB;
attachedBounds = new Box2Rotated(gridAABB.Translated(gridPos), gridRot, gridPos);
worldAngle = (gridRot + magnetXform.LocalRotation) - MathF.PI / 2;
mapId = magnetGridXform.MapID;
}
else
{
worldAngle = _random.NextAngle();
}
if (!TryGetSalvagePlacementLocation(magnet, mapId, attachedBounds, bounds!.Value, worldAngle, out var spawnLocation, out var spawnAngle))
{
Report(magnet.Owner, MagnetChannel, "salvage-system-announcement-spawn-no-debris-available");
_mapSystem.DeleteMap(salvMapXform.MapID);
return;
}
// I have no idea if we want to return on failure or not
// but I assume trying to set the parent with a null value wouldn't have worked out anyways
if (!_mapSystem.TryGetMap(spawnLocation.MapId, out var spawnUid))
return;
data.Comp.ActiveEntities = null;
mapChildren = salvMapXform.ChildEnumerator;
// It worked, move it into position and cleanup values.
while (mapChildren.MoveNext(out var mapChild))
{
var salvXForm = _xformQuery.GetComponent(mapChild);
var localPos = salvXForm.LocalPosition;
_transform.SetParent(mapChild, salvXForm, spawnUid.Value);
_transform.SetWorldPositionRotation(mapChild, spawnLocation.Position + localPos, spawnAngle, salvXForm);
data.Comp.ActiveEntities ??= new List<EntityUid>();
data.Comp.ActiveEntities?.Add(mapChild);
// Handle mob restrictions
var children = salvXForm.ChildEnumerator;
while (children.MoveNext(out var child))
{
if (!_salvMobQuery.TryGetComponent(child, out var salvMob))
continue;
salvMob.LinkedEntity = mapChild;
}
}
Report(magnet.Owner, MagnetChannel, "salvage-system-announcement-arrived", ("timeLeft", data.Comp.ActiveTime.TotalSeconds));
_mapSystem.DeleteMap(salvMapXform.MapID);
data.Comp.Announced = false;
var active = new SalvageMagnetActivatedEvent()
{
Magnet = magnet,
};
RaiseLocalEvent(ref active);
}
private bool TryGetSalvagePlacementLocation(Entity<SalvageMagnetComponent> magnet, MapId mapId, Box2Rotated attachedBounds, Box2 bounds, Angle worldAngle, out MapCoordinates coords, out Angle angle)
{
var attachedAABB = attachedBounds.CalcBoundingBox();
var magnetPos = _transform.GetWorldPosition(magnet) + worldAngle.ToVec() * bounds.MaxDimension;
var origin = attachedAABB.ClosestPoint(magnetPos);
var fraction = 0.50f;
// Thanks 20kdc
for (var i = 0; i < 20; i++)
{
var randomPos = origin +
worldAngle.ToVec() * (magnet.Comp.MagnetSpawnDistance * fraction) +
(worldAngle + Math.PI / 2).ToVec() * _random.NextFloat(-magnet.Comp.LateralOffset, magnet.Comp.LateralOffset);
var finalCoords = new MapCoordinates(randomPos, mapId);
angle = _random.NextAngle();
var box2 = Box2.CenteredAround(finalCoords.Position, bounds.Size);
var box2Rot = new Box2Rotated(box2, angle, finalCoords.Position);
// This doesn't stop it from spawning on top of random things in space
// Might be better like this, ghosts could stop it before
if (_mapManager.FindGridsIntersecting(finalCoords.MapId, box2Rot).Any())
{
// Bump it further and further just in case.
fraction += 0.1f;
continue;
}
coords = finalCoords;
return true;
}
angle = Angle.Zero;
coords = MapCoordinates.Nullspace;
return false;
}
}
[ByRefEvent]
public record struct SalvageMagnetActivatedEvent
{
public EntityUid Magnet;
}