Skip to content

Entity Relations - #7000

Open
Roudenn wants to merge 64 commits into
space-wizards:masterfrom
Roudenn:entity-relations
Open

Roudenn wants to merge 64 commits into
space-wizards:masterfrom
Roudenn:entity-relations

Conversation

@Roudenn

@Roudenn Roudenn commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Added Entity Relations - a generic system to automatically clear references to entities that are becoming invalid.
Fixes #6152 (Only provides a solution, but to resolve the issue entirely mechanics have to be ported to use Entity Relations)
Related content PR (not required for merge): space-wizards/space-station-14#45411
Related Docs PR: space-wizards/docs#670

Ready for review!

Patch notes

New Features

  • Added Entity Relations - a system for automatically resetting invalid EntityUid? references back to null. To implement the system, apply AutoGenerateEntityRelations attribute to the component and AutoRelationsField to all of its EntityUid fields. Then replace all assignments to the fields with API calls to the EntityRelationsSystem. For more details and a usage guide, read https://docs.spacestation14.com/en/robust-toolbox/entity-relations.html (TODO the docs PR above must be merged first, also the link must be re-checked after that)

Technical overview

Main usage loop

  1. EntityRelation struct is a wrapper around EntityUid? - to write to it you have to use an EntityManager method (or an EntitySystem proxy). The entity inside if not null is always guaranteed to have at least a single link with another entity.
  2. When you write an entity into a relation, an EntityRelationComponent gets added to both entities, which contains List<EntityRelation> to entities that relate to it - that way a link is formed between 2 entities using a single universal marker component.
  3. When an entity with EntityRelationComponent gets deleted, it raises an event EntityRelationDeleteEvent for all its EntityRelations to handle
  4. Systems can handle the event manually, or component can autogenerate a system using [AutoGenerateEntityRelations] and [AutoRelationField] on a EntityRelation (or a list/set/dictionary) to set it to null (or remove from the collection).

Component shutdown

[AutoGenerateEntityRelations] generates a ComponentRemove event by default for an assignmed component. This means that when porting mechanics to use relations, they will have to resort to using ComponentShutdown instead if they already use it.

When EntityRelationsComponent is itself shutting down while the entity isn't terminating, it will call a EntityRelationShutdownEvent on the entity to clear all of its relations and set them to null values. That is another safety feature that guarantees that the EntityRelation references are always valid even in such weird scenarios.
This however may be useful in the future to make it possible to "cut" entities out of the simulation safely without throwing any errors.

Manual handling

To handle an EntityRelation manually, for example if you use some non-default data structure to store it, or to do something else when removing the relations, you have to subscribe to these events and do the actions manually:

  • EntityRelationDeleteEvent - compare all relations in the component to the removed relation to replace it with an EntityRelation.Null value if found
  • EntityRelationShutdownEvent to set all EntityRelations to null in the component
  • ComponentRemove to call the ClearRelation function on each relation.

Networking

By default, all Relation methods provided by EntityManager are fully networked between the server and client. To set a relation locally either for the server or the client, use Local variations of the API methods (for example SetLocalRelation).
This replicates the normal entity relation pipeline on the local side by storing it in a separate non-networked lit in EntityRelationsComponent.

To use Local Entity Relations together with networked ones on an entity, you have to ensure that its EntityRelationsComponent.RemoveOnEmpty is false. This can be done by using EntityRelationsSystem API.

Other parameters in EntityRelationsComponent

RemoveOnEmpty removes the component if the list of relations becomes empty. It's true by default to retain consistency and minimize changes in entities caused by supporting relations, since an entity that never had any relations will look like an entity that had all relations removed from it. This should be disabled if you are using Local relations together with Networked relations.

Supported types

The autogenerator for relations currently supports the following types:

  • EntityRelation
  • EntityRelation?
  • List<EntityRelation>
  • HashSet<EntityRelation>
  • Dictionary<EntityRelation, T>
  • Dictionary<T, EntityRelation>

The reason why I didn't add more is because ComponentNetworkGenerator is not flexible at all and is almost entirely hardcoded, so adding more types while making them supported by [AutoGenerateComponentState] is impossible.

In general a helper that recursively goes through all fields in a data type to be able to automatically generate code for all fields of a certain type would be super useful for auto-generators and would allow for support of any struct, class, or a collection.

Technical details

EntityRelation struct was added to ComponentNetworkGenerator where it's automatically converted into NetEntity? when generating component state.

EntityRelationsGenerator automatically generates systems for components with [AutoGenerateEntityRelations], handling EntityRelationDeleteEvent for that component. Fields with [AutoRelationField] get set to null when a corresponding relation is found in them.

EntityManager now has public methods to manipulate relations, the most important one being SetRelation. It is used for linking an entity to another owner entity, and storing the relation in a field inside of the owner's component.
ClearRelation can be used to remove a specific link between 2 entities, and if there are no relations anymore in one of them, the component is automatically removed (for consistency so that when there's a component, it means that the entity is linked to other entities)
Other API methods for relations are Network methods for converting collections of EntityRelation into NetEntity.

@Roudenn
Roudenn marked this pull request as ready for review August 15, 2026 14:00
@Roudenn
Roudenn requested a review from DrSmugleaf as a code owner August 15, 2026 14:00

@Tayrtahn Tayrtahn left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This definitely needs some integration tests to show everything works as expected!

Here are a couple of snags that I ran into when I tried to do something like this myself:

  • Imagine entity A has a component containing a relation to entity B. If entity A removes just that component (without the entity terminating), what happens? If this requires subscribing to the shutdown event for the component, does this prevent other systems (like the main one for the component) from subscribing to shutdown?
  • Ideally we would have a way to make networking optional or even player-specific. Otherwise a modified client will be able to detect any entities with relations to a given entity - for example, a homing missile tracking the local player. This is very tricky to balance with the desire for prediction, so I recommend further discussion before trying to implement anything here.

@Roudenn

Roudenn commented Aug 16, 2026

Copy link
Copy Markdown
Contributor Author

Here are a couple of snags that I ran into when I tried to do something like this myself:

  • Imagine entity A has a component containing a relation to entity B. If entity A removes just that component (without the entity terminating), what happens? If this requires subscribing to the shutdown event for the component, does this prevent other systems (like the main one for the component) from subscribing to shutdown?

This implementation auto-generates a system that subscribes to ComponentShutdown automatically, but it can be turned off by adding (shutdownEvent: false) as a constructor parameter to the [AutoGenerateEntityRelations] attribute - this should be used in cases where other code has to subscribe to ComponentShutdown, and to still be able to clear the relations automatically without much poilerplate, components with [AutoGenerateEntityRelations] also have a public method to clear all relations.

I've took that way because Sloth said that adding a new event just to shutdown the relations will make deletion performance even worse, and at the same time clearing the relations on shutdown of a certain component is required to make EntityRelationsComponent consistent (so it can be removed from entities that are no longer related by anything), so I've decided to just force all developers to deal with that manually if they encounter this issue and gave them convenient tools to do it. Sad but unless eventbus will somehow have 0 performance cost, handling the component shutdown properly will remain a responsibility of the developers.

  • Ideally we would have a way to make networking optional or even player-specific. Otherwise a modified client will be able to detect any entities with relations to a given entity - for example, a homing missile tracking the local player. This is very tricky to balance with the desire for prediction, so I recommend further discussion before trying to implement anything here.

This is an issue that isn't that urgent compared to the error spams that still appear on live servers and it can be solved later. The only thing that needs to be checked here is whenever the system is flexible enough to still be backwards compatiable when a generic conditional networking system comes out.

Without standartising all conditional networking usecases, adding that system to EntityRelations will be impossible, because even if you make a bare-bones version that supports a couple features, Content may need something more, and then they're still screwed because the bare-bones conditional networking system for EntityRelations isn't developed enough.

For now my opinion is that solving error spams is far more important than caring about possible minor info cheating opportunities (especially when a lot of them already exist in Content still unfixed).

@metalgearsloth

Copy link
Copy Markdown
Contributor

Imagine entity A has a component containing a relation to entity B. If entity A removes just that component (without the entity terminating), what happens? If this requires subscribing to the shutdown event for the component, does this prevent other systems (like the main one for the component) from subscribing to shutdown?

ComponentRemove is mostly unused / misused but it might cause too much of a blast radius on it. The only component that really needs it is transform and all the others just want ordered startups. If the choice is performance or QOL just because it's component lifecycle related I'm choosing performance.

@Roudenn

Roudenn commented Aug 16, 2026

Copy link
Copy Markdown
Contributor Author

Added the base test for EntityRelations functionality

Still working on splitting the diagnostics from the relations codegen and making a codegen test

@Tayrtahn

Copy link
Copy Markdown
Contributor

This implementation auto-generates a system that subscribes to ComponentShutdown automatically, but it can be turned off by adding (shutdownEvent: false) as a constructor parameter to the [AutoGenerateEntityRelations] attribute - this should be used in cases where other code has to subscribe to ComponentShutdown, and to still be able to clear the relations automatically without much poilerplate, components with [AutoGenerateEntityRelations] also have a public method to clear all relations.

Sounds good to me! Maybe we can have an analyzer that detects manual Shutdown handlers and makes sure they call that clear method - I'd be happy to look into that.

@Roudenn

Roudenn commented Aug 16, 2026

Copy link
Copy Markdown
Contributor Author

Added a test for the code generator and split its analyzers into a proper DiagnosticsAnalyzer class, but I couldn't figure out how to properly make a test for the analyzer unfortunately

Besides the analyzer test, the only other thing left is an integration test for EntityRelation networking

(well technically there's also map saving but it should be trivial enough to just save a post-init map and ensure it gets saved and loaded correctly)

@metalgearsloth metalgearsloth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at it more I think I'd prefer:

  1. No EntityManager code as it really doesn't relate to any of this and bloats the API significantly.
  2. Trim down the API significantly with generics / interfaces and simplify it, and keep it just on the system.
  3. No CompNetworkGenerator code.
  4. No networked relations, client doesn't exactly need to know about this stuff. The only reason we'd ever need to know about it is if we somehow did overrides for some stuff like joints but that would be out of scope I would think. I think we should just be targeting stale entity refs for serialization + getstate in the moment (which are both entirely server side). This also fixes the weird Null bugs / handling.
  5. Sub on general comp remove or whatever that checks if the component implements IRelationComponent or whatever over having to manually handle shutdown events, we can just eat the perf cost to simplify the API.
  6. Make the storage EntityRelationsComponent Unsaved and just re-build on load as we don't need to actually store any bookkeeping for it as we assume the entity refs are valid when saving / loading now (anything else is an exception case from some other bug and not intended).

Then the final thing should be however much boilerplate code on entityrelationssystem + the sourcegen attribute that it calls + the interface, which still fixes stale refs and gives us a much lower API surface to maintain.

@metalgearsloth

Copy link
Copy Markdown
Contributor

@Tayrtahn any thoughts on the above.

@Tayrtahn

Copy link
Copy Markdown
Contributor

It's been a bit since I last did a deep dive with this stuff, but I think what sloth is saying makes sense and sounds good.

GetState definitely should be the main focus, since that's where the bulk of the problems come up.

The simplicity of keeping the relations unnetworked and unsaved is very appealing. I'm a bit wary that it could cause issues with prediction, but I mean, in theory it shouldn't, right?

I highly recommend that for whatever implementation we go with, we take the time to convert one of the Content systems to use it as a test. I've found that this is the quickest way to expose anything that might be missing from the implementation. Jukebox and projectiles are good candidates that I've used before; they have interesting UI and network behaviors to consider.

@Fildrance

Copy link
Copy Markdown
Member

I highly recommend that for whatever implementation we go with, we take the time to convert one of the Content systems to use it as a test.

Experimental content PR is already prepared and open, just waiting for engine.

@Roudenn

Roudenn commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

The requested changes were implemented, however there still may be some issues:

  • XML documentation of EntityRelationsSystem API may be incorrect somewhere
  • Reconstruction of the relations may be done incorrectly (currently it adds the relations on EntityManager.ComponentAdded
  • EntityRelationsSystem API is filled with _netIsClient checks because the system is better to be available in Shared but I didn't want to make a server/client system split just to keep it empty on the client. It needs to be decided later how client entity relations should work
  • Not everything is tested (entity relations analyzer, entity relations + maploader integration test, etc.)

Other than that it should be ready to be tested in game (see the example content PR in this PR's description)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

We need WeakEntityReference or another solution to solve PVS error spam

4 participants