Skip to content
Daan van Yperen edited this page Sep 24, 2016 · 30 revisions

About

What happens when a component refers to an entity and that entity gets deleted? A mess! This optional module will manage your entity references for you and can deal with complicated relationships easily.

Uses

  • Prevent dangling references to entities.
  • Remove referencing components when target entity dies.
  • Remove child entities when parent dies.

Usage

  1. Register EntityLinkManager.class with the World/WorldConfiguration.
  2. (Recommended) Setup artemis-odb-plugin to avoid slow reflection.

Components with fields referencing other entities will be automatically managed.

@PooledWeaver
public class Anchor extends Component {
    @EntityId public int target = -1; // managed
    public Entity target2; // managed
}

Set target and target2 like you would normally. Whenever the entity referenced by target is removed it will automatically be set to -1 (or null for Entity).

Advanced usage

per-field listeners can supplement the system with additional logic.

Remove component with dangling reference completely

// register the LinkAdapter - LinkAdapter provides stubs for the LinkListener
world.getSystem(EntityLinkManager.class).register(InheritScale.class, new LinkAdapter() {
    // LinkListeners are subject to dependency injection upon registration
    private ComponentMapper<InheritScale> mapper;

    @Override
    public void onTargetDead(int sourceId, int deadTargetId) {
        // target is dead - better remove the component
        mapper.remove(sourceId);
    }
});
world.delete(targetId); // targetId from snippet above
world.process(); // fires onTargetDead

Exclude reference from management

public class Anchor extends Component {
    @EntityId @LinkPolicy(SKIP)
    public int target;
}

Undigested

Default link behavior and Tuning with @LinkPolicy

default policy note
@EntityId int CHECK_SOURCE_AND_TARGETS
Entity CHECK_SOURCE_AND_TARGETS
@EntityId IntBag CHECK_SOURCE Even with CHECK_SOURCE_AND_TARGETS, never calls #onTargetChanged
Bag<Entity> CHECK_SOURCE Even with, CHECK_SOURCE_AND_TARGETS, never calls #onTargetChanged

Assert entity references in containers are alive

public class ChildRenderable extends PooledComponent {
    @EntityId @LinkPolicy(CHECK_SOURCE_AND_TARGETS)
    public IntBag children = new IntBag();

    @Override
    protected void reset() {
        children.setSize(0);
    }
}
Clone this wiki locally