Code Patterns

Copy-paste examples for common plugin tasks. Commands, events, ECS, GUI, and more.

← Back to Patterns
ecs

archetypes-pattern

Archetypes group entities with the same component signature for cache-efficient iteration. Entities with components [A,B] are stored together, separate from [A,B,C]. This enables fast system processing.

Example Code

java
// ARCHETYPE CONCEPT:
// An archetype is a unique combination of components
// Entities with the same components share an archetype

// Example archetypes:
// Archetype 1: [Position, Health, AI]           -> All mobs
// Archetype 2: [Position, Health, PlayerInput]  -> All players
// Archetype 3: [Position, Velocity]             -> Projectiles

// WHY ARCHETYPES MATTER:
// 1. Memory Layout - Components stored contiguously in memory
// 2. Cache Efficiency - Iterating entities is cache-friendly
// 3. Fast Queries - Finding entities with specific components is O(1)

// In EntityTickingSystem:
@Override
public void processTick(float deltaTime, int index,
                       ArchetypeChunk<EntityStore> archetypeChunk,
                       Store<EntityStore> store,
                       CommandBuffer<EntityStore> commandBuffer) {

    // archetypeChunk contains entities of the SAME archetype
    // index is your position within this chunk
    // This allows the system to efficiently process similar entities

    // Get reference to entity at this index
    Ref<EntityStore> ref = archetypeChunk.getReferenceTo(index);

    // All entities in this chunk have the same components
    // So component access is predictable and fast
}

// ADDING/REMOVING COMPONENTS CHANGES ARCHETYPE:
// When you add a component to an entity, it moves to a new archetype
// This is why component changes should be batched when possible

Thread Safety

Archetype operations are handled automatically by the ECS. Adding/removing components will move entities between archetypes.

Common Mistakes

Adding/removing components too frequently causes archetype migrations which can impact performance. Batch component changes when possible.