spawn

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: GPL-3.0 Imports: 9 Imported by: 0

README ΒΆ

Spawn Engine

The Spawn Engine provides intelligent entity placement capabilities for game spaces, implementing the complete ADR-0013 specification with split-aware architecture, constraint validation, and adaptive room scaling.

Purpose

The spawn engine serves as the intelligent orchestrator for populating game spaces with entities (players, enemies, treasure, environmental objects). It bridges the gap between high-level game design decisions ("spawn some goblins in this dungeon room") and low-level spatial placement mechanics.

Core Responsibilities:

  • Entity Selection: Uses selectables tables for weighted, context-aware entity selection
  • Spatial Placement: Positions entities using spatial constraints and placement patterns
  • Constraint Validation: Ensures line of sight, distance, and area of effect requirements
  • Capacity Management: Integrates with environment package for room sizing and splitting
  • Multi-Room Awareness: Handles spawning across connected room configurations

Scope

βœ… Implemented (Phases 1-4)

Phase 1: Basic Infrastructure

  • Core SpawnEngine interface with all methods
  • BasicSpawnEngine implementation with dependency injection
  • Scattered spawning pattern (random placement)
  • Entity selection using selectables tables
  • Event publishing for spawn operations

Phase 2: Advanced Patterns

  • Formation-based spawning (structured arrangements)
  • Team-based spawning (ally/enemy separation)
  • Player choice spawning (designated spawn zones)
  • Clustered spawning (grouped entity placement)
  • Configuration validation and error handling

Phase 3: Constraint System

  • Spatial constraint validation (minimum distances, wall proximity)
  • Line of sight requirements (required and blocked sight)
  • Area of effect constraints (exclusion zones)
  • Gridless room support with continuous positioning
  • Constraint solver with position finding algorithms

Phase 4: Environment Integration

  • Capacity analysis using environment package queries
  • Adaptive room scaling when entities don't fit
  • Split recommendations as passthrough from environment package
  • Room modification tracking and event publishing

Cross-Cutting Features:

  • Comprehensive event system for observability
  • Split-aware architecture (works with single or connected rooms)
  • Configuration-driven behavior with validation
  • Error handling with detailed failure reporting
🚧 Planned Future Enhancements
  • Advanced Formation Patterns: Complex geometric arrangements, formation rotation
  • Dynamic Constraints: Runtime constraint modification based on game state
  • Performance Optimization: Spatial indexing for large rooms with many entities
  • AI Integration: Smart placement based on tactical considerations

Architecture

The spawn engine follows RPG Toolkit's philosophy of infrastructure, not implementation:

  • Entity Agnostic: Works with any entity type implementing core.Entity
  • Selection Flexible: Uses selectables module for configurable entity selection
  • Spatially Integrated: Leverages spatial module for all positioning operations
  • Environmentally Aware: Integrates with environment package for capacity analysis
  • Event Driven: Publishes events for all operations for external observability
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Game Logic    β”‚    β”‚  Spawn Engine    β”‚    β”‚ Spatial Module  β”‚
β”‚                 │─────                  │─────                 β”‚
β”‚ - Define pools  β”‚    β”‚ - Entity selectionβ”‚    β”‚ - Room mgmt     β”‚
β”‚ - Set patterns  β”‚    β”‚ - Constraint validation β”‚ - Position validation β”‚
β”‚ - Handle events β”‚    β”‚ - Pattern application β”‚ β”‚ - Collision detection β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                β”‚
                       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                       β”‚ Environment Pkg  β”‚
                       β”‚                  β”‚
                       β”‚ - Capacity analysis β”‚
                       β”‚ - Room scaling   β”‚
                       β”‚ - Split recommendations β”‚
                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Usage Examples

Basic Setup
package main

import (
    "context"
    "log"
    
    "github.com/KirkDiggler/rpg-toolkit/core"
    "github.com/KirkDiggler/rpg-toolkit/events"
    "github.com/KirkDiggler/rpg-toolkit/tools/spawn"
    "github.com/KirkDiggler/rpg-toolkit/tools/spatial"
    "github.com/KirkDiggler/rpg-toolkit/tools/environments"
)

func main() {
    // Create dependencies
    eventBus := events.NewBasicEventBus()
    
    // Create spawn engine with dependencies
    engine := spawn.NewBasicSpawnEngine(spawn.BasicSpawnEngineConfig{
        ID:                 "dungeon-spawner",
        SpatialHandler:     spatialHandler,      // Your spatial query handler
        EnvironmentHandler: environmentHandler,  // Your environment query handler  
        SelectablesReg:     selectablesRegistry, // Your entity selection tables
        EventBus:           eventBus,
        EnableEvents:       true,
    })
    
    // Register entity selection tables
    enemies := []core.Entity{
        &GameEntity{ID: "orc1", Type: "enemy"},
        &GameEntity{ID: "goblin1", Type: "enemy"},
        &GameEntity{ID: "skeleton1", Type: "enemy"},
    }
    
    selectablesRegistry.RegisterTable("basic-enemies", enemies)
}
Simple Enemy Spawning
// Basic scattered spawning
config := spawn.SpawnConfig{
    EntityGroups: []spawn.EntityGroup{
        {
            ID:             "room-enemies",
            Type:           "enemy", 
            SelectionTable: "basic-enemies",
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{3}[0]},
        },
    },
    Pattern: spawn.PatternScattered,
}

result, err := engine.PopulateRoom(ctx, "dungeon-room-1", config)
if err != nil {
    log.Fatal(err)
}

log.Printf("Spawned %d entities, %d failures", 
    len(result.SpawnedEntities), len(result.Failures))
Constraint-Based Spawning
// Spawning with spatial constraints
config := spawn.SpawnConfig{
    EntityGroups: []spawn.EntityGroup{
        {
            ID:             "guards",
            Type:           "guard",
            SelectionTable: "elite-enemies", 
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{2}[0]},
        },
        {
            ID:             "treasure",
            Type:           "treasure",
            SelectionTable: "valuable-loot",
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{1}[0]},
        },
    },
    Pattern: spawn.PatternScattered,
    SpatialRules: spawn.SpatialConstraints{
        MinDistance: map[string]float64{
            "guard:treasure": 3.0, // Guards stay close to treasure
        },
        WallProximity: 1.0, // All entities 1 unit from walls
        LineOfSight: spawn.LineOfSightRules{
            RequiredSight: []spawn.EntityPair{
                {From: "guard", To: "treasure"}, // Guards must see treasure
            },
        },
    },
}

result, err := engine.PopulateRoom(ctx, "treasure-room", config)
Team-Based Spawning
// Tactical team placement
config := spawn.SpawnConfig{
    EntityGroups: []spawn.EntityGroup{
        {
            ID:             "defenders",
            Type:           "ally",
            SelectionTable: "town-guards",
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{4}[0]},
        },
        {
            ID:             "attackers", 
            Type:           "enemy",
            SelectionTable: "orc-raiders",
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{6}[0]},
        },
    },
    Pattern: spawn.PatternTeamBased,
    TeamConfiguration: &spawn.TeamConfig{
        Teams: []spawn.Team{
            {
                ID:          "defenders",
                EntityTypes: []string{"ally"},
                Allegiance:  "town",
            },
            {
                ID:          "attackers", 
                EntityTypes: []string{"enemy"},
                Allegiance:  "orc-clan",
            },
        },
        CohesionRules: spawn.TeamCohesionRules{
            KeepFriendliesTogether: true,
            KeepEnemiesTogether:    true,
            MinTeamSeparation:      5.0,
        },
    },
}

result, err := engine.PopulateRoom(ctx, "battlefield", config)
Player Choice Spawning
// Allow players to choose spawn positions
config := spawn.SpawnConfig{
    EntityGroups: []spawn.EntityGroup{
        {
            ID:             "player-characters",
            Type:           "player",
            SelectionTable: "active-players",
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{4}[0]},
        },
    },
    Pattern: spawn.PatternPlayerChoice,
    PlayerSpawnZones: []spawn.SpawnZone{
        {
            ID:          "safe-zone",
            Area:        spatial.Rectangle{Position: spatial.Position{X: 1, Y: 1}, Width: 3, Height: 3},
            EntityTypes: []string{"player"},
            MaxEntities: 4,
        },
    },
    PlayerChoices: []spawn.PlayerSpawnChoice{
        {PlayerID: "hero1", ZoneID: "safe-zone", Position: spatial.Position{X: 2, Y: 2}},
        // Other players auto-assigned to zone
    },
}

result, err := engine.PopulateRoom(ctx, "starting-room", config)
Multi-Room Spawning
// Spawning across connected rooms
connectedRooms := []string{"room-1", "room-2", "room-3"}

config := spawn.SpawnConfig{
    EntityGroups: []spawn.EntityGroup{
        {
            ID:             "distributed-enemies",
            Type:           "enemy",
            SelectionTable: "dungeon-monsters",
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{12}[0]},
        },
    },
    Pattern: spawn.PatternScattered,
}

// Spawn engine automatically distributes entities across connected rooms
result, err := engine.PopulateSplitRooms(ctx, connectedRooms, config)
Adaptive Scaling
// Automatic room scaling when entities don't fit
config := spawn.SpawnConfig{
    EntityGroups: []spawn.EntityGroup{
        {
            ID:             "large-army",
            Type:           "soldier", 
            SelectionTable: "imperial-legion",
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{50}[0]},
        },
    },
    Pattern: spawn.PatternFormation,
    AdaptiveScaling: &spawn.ScalingConfig{
        Enabled:        true,
        ScalingFactor:  1.5,
        PreserveAspect: true,
        EmitEvents:     true,
    },
}

result, err := engine.PopulateRoom(ctx, "throne-room", config)

// Check if room was scaled
for _, modification := range result.RoomModifications {
    if modification.Type == "scaled" {
        log.Printf("Room scaled: %s", modification.Reason)
    }
}

// Check for split recommendations
if len(result.SplitRecommendations) > 0 {
    log.Printf("Consider splitting room into %d parts", len(result.SplitRecommendations))
}
Gridless Room Support

The spawn engine automatically detects gridless rooms and adapts its positioning strategy:

// Create gridless room
gridlessRoom := spatial.NewGridlessRoom(spatial.GridlessConfig{
    Width:  20.0,
    Height: 15.0,
})

// Spawn engine automatically uses continuous positioning
config := spawn.SpawnConfig{
    EntityGroups: []spawn.EntityGroup{
        {
            ID:             "forest-creatures",
            Type:           "animal",
            SelectionTable: "woodland-animals", 
            Quantity:       spawn.QuantitySpec{Fixed: &[]int{8}[0]},
        },
    },
    Pattern: spawn.PatternScattered,
    SpatialRules: spawn.SpatialConstraints{
        WallProximity: 0.5, // Smaller margins for natural environments
    },
}

// Entities placed with smooth, continuous coordinates
result, err := engine.PopulateRoom(ctx, "forest-clearing", config)
Event Handling
// Subscribe to spawn events for game logic integration
eventBus.SubscribeFunc("spawn.entity.spawned", 10, func(ctx context.Context, event events.Event) error {
    entityID := event.Context().Get("entity_id").(string)
    entityType := event.Context().Get("entity_type").(string)
    posX := event.Context().Get("position_x").(float64)
    posY := event.Context().Get("position_y").(float64)
    
    log.Printf("Entity spawned: %s (%s) at (%.2f, %.2f)", entityID, entityType, posX, posY)
    
    // Trigger game-specific logic (AI activation, animations, etc.)
    return gameLogic.HandleEntitySpawn(entityID, entityType, posX, posY)
})

eventBus.SubscribeFunc("spawn.room.scaled", 10, func(ctx context.Context, event events.Event) error {
    roomID := event.Context().Get("room_id").(string)
    scaleFactor := event.Context().Get("scale_factor").(float64)
    
    log.Printf("Room %s scaled by factor %.2f", roomID, scaleFactor)
    
    // Update UI, notify players, etc.
    return gameUI.NotifyRoomScaled(roomID, scaleFactor)
})

Configuration Reference

SpawnConfig Structure

The main configuration object controlling all spawn behavior:

type SpawnConfig struct {
    // What to spawn
    EntityGroups []EntityGroup `json:"entity_groups"`
    
    // How to spawn
    Pattern           SpawnPattern `json:"pattern"`
    TeamConfiguration *TeamConfig  `json:"team_config,omitempty"`
    
    // Constraints  
    SpatialRules SpatialConstraints `json:"spatial_rules"`
    Placement    PlacementRules     `json:"placement"`
    
    // Behavior
    Strategy        SpawnStrategy  `json:"strategy"`
    AdaptiveScaling *ScalingConfig `json:"adaptive_scaling,omitempty"`
    
    // Player spawn zones and choices
    PlayerSpawnZones []SpawnZone         `json:"player_spawn_zones,omitempty"`
    PlayerChoices    []PlayerSpawnChoice `json:"player_choices,omitempty"`
}
EntityGroup Definition

Defines a group of entities to spawn with selection rules:

type EntityGroup struct {
    ID             string       `json:"id"`              // Unique identifier
    Type           string       `json:"type"`            // Entity category
    SelectionTable string       `json:"selection_table"` // Selectables table ID
    Quantity       QuantitySpec `json:"quantity"`        // How many to spawn
}

type QuantitySpec struct {
    Fixed    *int    `json:"fixed,omitempty"`     // Exact count
    DiceRoll *string `json:"dice_roll,omitempty"` // Future: "2d6+1" 
    Min      *int    `json:"min,omitempty"`       // Future: range
    Max      *int    `json:"max,omitempty"`       // Future: range
}
Spawn Patterns

Available placement patterns:

  • PatternScattered: Random placement throughout room
  • PatternFormation: Structured geometric arrangements
  • PatternTeamBased: Team separation with cohesion rules
  • PatternPlayerChoice: Player-selected positions within zones
  • PatternClustered: Grouped placement in clusters
Spatial Constraints

Fine-grained control over entity positioning:

type SpatialConstraints struct {
    MinDistance   map[string]float64  `json:"min_distance"`   // "type1:type2" -> distance
    LineOfSight   LineOfSightRules    `json:"line_of_sight"`  // Visibility requirements
    WallProximity float64             `json:"wall_proximity"` // Distance from walls
    AreaOfEffect  map[string]float64  `json:"area_of_effect"` // Exclusion zones
    PathingRules  PathingConstraints  `json:"pathing_rules"`  // Movement constraints
}

type LineOfSightRules struct {
    RequiredSight []EntityPair `json:"required_sight"` // Must see each other
    BlockedSight  []EntityPair `json:"blocked_sight"`  // Must NOT see each other
}

type EntityPair struct {
    From string `json:"from"` // Source entity type
    To   string `json:"to"`   // Target entity type  
}

Error Handling

The spawn engine provides comprehensive error reporting:

type SpawnResult struct {
    Success              bool               `json:"success"`
    SpawnedEntities      []SpawnedEntity    `json:"spawned_entities"`
    Failures             []SpawnFailure     `json:"failures"`
    RoomModifications    []RoomModification `json:"room_modifications"`
    SplitRecommendations []RoomSplit        `json:"split_recommendations"`
    RoomStructure        RoomStructureInfo  `json:"room_structure"`
}

type SpawnFailure struct {
    EntityType string `json:"entity_type"`
    Reason     string `json:"reason"`
}

Common Error Scenarios:

  • Selection Failures: Entity table not found, insufficient entities in table
  • Constraint Violations: No positions satisfy spatial constraints
  • Capacity Issues: Room too small for requested entities (triggers scaling/splitting)
  • Configuration Errors: Invalid spawn patterns, malformed constraints

Events

Published events for external integration:

  • spawn.entity.spawned: Individual entity placement
  • spawn.operation.completed: Full spawn operation finished
  • spawn.room.scaled: Room dimensions modified
  • spawn.split.recommended: Room splitting suggested
  • spawn.constraint.violation: Placement constraint failed

Implementation Status

This implementation represents Phases 1-4 of ADR-0013:

βœ… Complete:

  • Basic spawn engine infrastructure
  • All spawn patterns (scattered, formation, team-based, player choice, clustered)
  • Spatial constraint system with validation
  • Environment integration for capacity analysis and room scaling
  • Split-aware architecture for multi-room scenarios
  • Comprehensive event system
  • Gridless room support
  • Full test coverage including environment integration tests

πŸ”„ Future Phases:

  • Advanced formation patterns with complex geometries
  • Dynamic constraint modification during gameplay
  • Performance optimization for large-scale scenarios
  • AI-driven tactical placement algorithms

Dependencies

  • core: Base entity interfaces
  • events: Event bus for observability
  • tools/spatial: Room management and positioning
  • tools/environments: Capacity analysis and room scaling
  • tools/selectables: Weighted entity selection tables

For complete implementation details, see ADR-0013: Entity Spawn Engine.

Documentation ΒΆ

Overview ΒΆ

Package spawn provides entity placement capabilities for game spaces. Purpose: Complete spawn engine implementation per ADR-0013 with split-aware architecture, environment integration, capacity analysis, and adaptive room scaling.

Package spawn provides intelligent entity placement and spawning capabilities.

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	// EntitySpawnedTopic publishes events when entities are spawned
	EntitySpawnedTopic = events.DefineTypedTopic[EntitySpawnedEvent]("spawn.entity.spawned")

	// SplitRecommendedTopic publishes events when room splitting is recommended
	SplitRecommendedTopic = events.DefineTypedTopic[SplitRecommendedEvent]("spawn.split.recommended")
	// RoomScaledTopic publishes events when rooms are scaled for capacity
	RoomScaledTopic = events.DefineTypedTopic[RoomScaledEvent]("spawn.room.scaled")
)

Functions ΒΆ

This section is empty.

Types ΒΆ

type BasicSelectablesRegistry ΒΆ

type BasicSelectablesRegistry struct {
	// contains filtered or unexported fields
}

BasicSelectablesRegistry implements SelectablesRegistry. Purpose: Simple entity selection registry for Phase 1 implementation.

func NewBasicSelectablesRegistry ΒΆ

func NewBasicSelectablesRegistry() *BasicSelectablesRegistry

NewBasicSelectablesRegistry creates a new registry. Purpose: Constructor for entity selection table management.

func (*BasicSelectablesRegistry) GetEntities ΒΆ

func (r *BasicSelectablesRegistry) GetEntities(tableID string, quantity int) ([]core.Entity, error)

GetEntities implements SelectablesRegistry.GetEntities

func (*BasicSelectablesRegistry) ListTables ΒΆ

func (r *BasicSelectablesRegistry) ListTables() []string

ListTables implements SelectablesRegistry.ListTables

func (*BasicSelectablesRegistry) RegisterTable ΒΆ

func (r *BasicSelectablesRegistry) RegisterTable(tableID string, entities []core.Entity) error

RegisterTable implements SelectablesRegistry.RegisterTable

type BasicSpawnEngine ΒΆ

type BasicSpawnEngine struct {
	// contains filtered or unexported fields
}

BasicSpawnEngine implements SpawnEngine interface. Purpose: Complete implementation per ADR-0013 with environment integration and split-aware spawning.

func NewBasicSpawnEngine ΒΆ

func NewBasicSpawnEngine(config BasicSpawnEngineConfig) *BasicSpawnEngine

NewBasicSpawnEngine creates a new spawn engine with the specified configuration. Purpose: Standard constructor following toolkit config pattern with proper dependency injection.

func (*BasicSpawnEngine) AnalyzeRoomStructure ΒΆ

func (e *BasicSpawnEngine) AnalyzeRoomStructure(roomID string) RoomStructureInfo

AnalyzeRoomStructure implements SpawnEngine.AnalyzeRoomStructure

func (*BasicSpawnEngine) ConnectToEventBus ΒΆ added in v0.1.1

func (e *BasicSpawnEngine) ConnectToEventBus(bus events.EventBus)

ConnectToEventBus connects all typed topics to the event bus

func (*BasicSpawnEngine) PopulateRoom ΒΆ

func (e *BasicSpawnEngine) PopulateRoom(
	ctx context.Context, roomID string, config SpawnConfig,
) (SpawnResult, error)

PopulateRoom implements SpawnEngine.PopulateRoom

func (*BasicSpawnEngine) PopulateSpace ΒΆ

func (e *BasicSpawnEngine) PopulateSpace(
	ctx context.Context, roomOrGroup interface{}, config SpawnConfig,
) (SpawnResult, error)

PopulateSpace implements SpawnEngine.PopulateSpace

func (*BasicSpawnEngine) PopulateSplitRooms ΒΆ

func (e *BasicSpawnEngine) PopulateSplitRooms(
	ctx context.Context, connectedRooms []string, config SpawnConfig,
) (SpawnResult, error)

PopulateSplitRooms implements SpawnEngine.PopulateSplitRooms

func (*BasicSpawnEngine) ValidateSpawnConfig ΒΆ

func (e *BasicSpawnEngine) ValidateSpawnConfig(config SpawnConfig) error

ValidateSpawnConfig implements SpawnEngine.ValidateSpawnConfig

type BasicSpawnEngineConfig ΒΆ

type BasicSpawnEngineConfig struct {
	ID                 string
	SpatialHandler     spatial.QueryHandler
	EnvironmentHandler *environments.BasicQueryHandler
	SelectablesReg     SelectablesRegistry
	// EventBus removed - use ConnectToEventBus() method after creation
	EnableEvents bool
	MaxAttempts  int
}

BasicSpawnEngineConfig configures a BasicSpawnEngine. Purpose: Configuration struct following toolkit patterns for dependency injection.

type ConstraintSolver ΒΆ

type ConstraintSolver struct {
	// contains filtered or unexported fields
}

ConstraintSolver validates and enforces spatial constraints during spawning. Purpose: Phase 3 implementation of constraint validation per ADR-0013.

func NewConstraintSolver ΒΆ

func NewConstraintSolver() *ConstraintSolver

NewConstraintSolver creates a new constraint solver with default settings. Purpose: Standard constructor for constraint validation system.

func (*ConstraintSolver) FindValidPositions ΒΆ

func (cs *ConstraintSolver) FindValidPositions(
	room spatial.Room, entity core.Entity, constraints SpatialConstraints,
	existingEntities []SpawnedEntity, maxPositions int,
) ([]spatial.Position, error)

FindValidPositions finds all positions that satisfy constraints. Purpose: Generate valid placement options for constraint-aware spawning.

func (*ConstraintSolver) ValidatePosition ΒΆ

func (cs *ConstraintSolver) ValidatePosition(
	room spatial.Room, position spatial.Position, entity core.Entity,
	constraints SpatialConstraints, existingEntities []SpawnedEntity,
) error

ValidatePosition checks if a position satisfies all spatial constraints. Purpose: Core constraint validation for entity placement.

type EntityGroup ΒΆ

type EntityGroup struct {
	ID             string       `json:"id"`
	Type           string       `json:"type"`
	SelectionTable string       `json:"selection_table"`
	Quantity       QuantitySpec `json:"quantity"`
}

EntityGroup represents a group of entities to spawn. Purpose: Defines entity type, selection table, and quantity for spawning.

type EntityPair ΒΆ

type EntityPair struct {
	From string `json:"from"`
	To   string `json:"to"`
}

EntityPair represents a relationship between two entity types

type EntitySpawnedEvent ΒΆ added in v0.1.1

type EntitySpawnedEvent struct {
	EntityID     string           `json:"entity_id"`
	EntityType   string           `json:"entity_type,omitempty"`
	Position     spatial.Position `json:"position"`
	RoomID       string           `json:"room_id"`
	SpawnType    string           `json:"spawn_type"` // "scattered", "formation", "player_choice", "clustered"
	SpawnGroupID string           `json:"spawn_group_id,omitempty"`
	Constraints  []string         `json:"constraints,omitempty"`
	SpawnedAt    time.Time        `json:"spawned_at"`
}

EntitySpawnedEvent contains data for entity spawning events

type FormationConstraints ΒΆ

type FormationConstraints struct {
	MinSpacing    float64 `json:"min_spacing"`
	RequiredSpace float64 `json:"required_space"`
	WallClearance float64 `json:"wall_clearance"`
}

FormationConstraints define requirements for formation placement

type FormationPattern ΒΆ

type FormationPattern struct {
	Name        string               `json:"name"`
	Positions   []RelativePosition   `json:"positions"`
	Scaling     FormationScaling     `json:"scaling"`
	Constraints FormationConstraints `json:"constraints"`
}

FormationPattern defines a structured arrangement of entities. Purpose: Specifies precise positioning patterns for coordinated entity placement.

type FormationScaling ΒΆ

type FormationScaling struct {
	AllowRotation   bool `json:"allow_rotation"`
	AllowStretching bool `json:"allow_stretching"`
	PreserveRatios  bool `json:"preserve_ratios"`
}

FormationScaling controls how formations adapt to space constraints

type LineOfSightRules ΒΆ

type LineOfSightRules struct {
	RequiredSight []EntityPair `json:"required_sight"`
	BlockedSight  []EntityPair `json:"blocked_sight"`
}

LineOfSightRules define visibility requirements between entities

type PathingConstraints ΒΆ

type PathingConstraints struct {
	MaintainExitAccess bool    `json:"maintain_exit_access"`
	MinPathWidth       float64 `json:"min_path_width"`
}

PathingConstraints define movement and accessibility requirements

type PlacementRules ΒΆ

type PlacementRules struct {
	MaintainExitAccess bool     `json:"maintain_exit_access"`
	MinPathWidth       float64  `json:"min_path_width"`
	PreferredAreas     []string `json:"preferred_areas"`
}

PlacementRules define how entities should be positioned

type PlayerSpawnChoice ΒΆ

type PlayerSpawnChoice struct {
	PlayerID string           `json:"player_id"`
	ZoneID   string           `json:"zone_id"`
	Position spatial.Position `json:"position"`
}

PlayerSpawnChoice represents a player's choice of spawn position

type QuantitySpec ΒΆ

type QuantitySpec struct {
	Fixed *int `json:"fixed,omitempty"`
}

QuantitySpec specifies how many entities to spawn. Purpose: Supports fixed quantities, dice expressions, and ranges for flexible spawning.

type RelativePosition ΒΆ

type RelativePosition struct {
	X        float64 `json:"x"`
	Y        float64 `json:"y"`
	Priority int     `json:"priority"`
}

RelativePosition defines a position relative to formation center

type RoomModification ΒΆ

type RoomModification struct {
	Type     string      `json:"type"`
	RoomID   string      `json:"room_id"`
	OldValue interface{} `json:"old_value"`
	NewValue interface{} `json:"new_value"`
	Reason   string      `json:"reason"`
}

RoomModification describes changes made to rooms during spawning. Purpose: Tracks room scaling and other adaptive changes for debugging and rollback.

type RoomScaledEvent ΒΆ added in v0.1.1

type RoomScaledEvent struct {
	RoomID      string    `json:"room_id"`
	OldCapacity int       `json:"old_capacity"`
	NewCapacity int       `json:"new_capacity"`
	ScaleReason string    `json:"scale_reason"`
	ScaleType   string    `json:"scale_type"` // "expand", "contract", "optimize"
	ScaledAt    time.Time `json:"scaled_at"`
}

RoomScaledEvent indicates when a room's capacity has been scaled

type RoomSplit ΒΆ

type RoomSplit struct {
	SuggestedSize      spatial.Dimensions `json:"suggested_size"`
	ConnectionPoints   []spatial.Position `json:"connection_points"`
	SplitReason        string             `json:"split_reason"`
	EntityDistribution map[string]int     `json:"entity_distribution"`
}

RoomSplit describes a recommended room split configuration. Purpose: Passthrough recommendations from environment package for client decision-making.

type RoomStructureInfo ΒΆ

type RoomStructureInfo struct {
	IsSplit        bool     `json:"is_split"`
	ConnectedRooms []string `json:"connected_rooms"`
	PrimaryRoomID  string   `json:"primary_room_id"`
}

RoomStructureInfo describes the room configuration used for spawning. Purpose: Indicates whether spawning used single or split-room configuration.

type ScalingConfig ΒΆ

type ScalingConfig struct {
	Enabled        bool    `json:"enabled"`
	ScalingFactor  float64 `json:"scaling_factor"`
	PreserveAspect bool    `json:"preserve_aspect"`
	EmitEvents     bool    `json:"emit_events"`
}

ScalingConfig controls adaptive room scaling behavior

type SelectablesRegistry ΒΆ

type SelectablesRegistry interface {
	// RegisterTable registers a selection table for use in spawn configurations
	RegisterTable(tableID string, entities []core.Entity) error

	// GetEntities retrieves entities from a registered table
	GetEntities(tableID string, quantity int) ([]core.Entity, error)

	// ListTables returns the IDs of all registered tables
	ListTables() []string
}

SelectablesRegistry manages selection tables for entity spawning. Purpose: Interface for registering and accessing entity selection tables.

type SeparationConstraints ΒΆ

type SeparationConstraints struct {
	MinTeamDistance float64               `json:"min_team_distance"`
	TeamPlacement   TeamPlacementStrategy `json:"team_placement"`
}

SeparationConstraints define minimum distances between teams

type SimpleRoomEntity ΒΆ

type SimpleRoomEntity struct {
	// contains filtered or unexported fields
}

SimpleRoomEntity implements core.Entity for event publishing. Purpose: Minimal entity implementation for spawn event sources.

func (*SimpleRoomEntity) GetID ΒΆ

func (r *SimpleRoomEntity) GetID() string

GetID returns the room entity ID

func (*SimpleRoomEntity) GetType ΒΆ

func (r *SimpleRoomEntity) GetType() string

GetType returns the room entity type

type SpatialConstraints ΒΆ

type SpatialConstraints struct {
	MinDistance   map[string]float64 `json:"min_distance"`
	LineOfSight   LineOfSightRules   `json:"line_of_sight"`
	WallProximity float64            `json:"wall_proximity"`
	AreaOfEffect  map[string]float64 `json:"area_of_effect"`
	PathingRules  PathingConstraints `json:"pathing_rules"`
}

SpatialConstraints define spatial requirements and restrictions

type SpawnConfig ΒΆ

type SpawnConfig struct {
	// What to spawn
	EntityGroups []EntityGroup `json:"entity_groups"`

	// How to spawn
	Pattern           SpawnPattern `json:"pattern"`
	TeamConfiguration *TeamConfig  `json:"team_config,omitempty"`

	// Constraints
	SpatialRules SpatialConstraints `json:"spatial_rules"`
	Placement    PlacementRules     `json:"placement"`

	// Behavior
	Strategy        SpawnStrategy  `json:"strategy"`
	AdaptiveScaling *ScalingConfig `json:"adaptive_scaling,omitempty"`

	// Player spawn zones and choices
	PlayerSpawnZones []SpawnZone         `json:"player_spawn_zones,omitempty"`
	PlayerChoices    []PlayerSpawnChoice `json:"player_choices,omitempty"`
}

SpawnConfig specifies how to spawn entities in a room. Purpose: Complete configuration for entity placement following ADR-0013 patterns.

type SpawnEngine ΒΆ

type SpawnEngine interface {
	// Core spawning - works with single rooms or split room configurations
	PopulateSpace(ctx context.Context, roomOrGroup interface{}, config SpawnConfig) (SpawnResult, error)

	// Legacy single-room interface for backwards compatibility
	PopulateRoom(ctx context.Context, roomID string, config SpawnConfig) (SpawnResult, error)

	// Multi-room spawning for split room scenarios
	PopulateSplitRooms(ctx context.Context, connectedRooms []string, config SpawnConfig) (SpawnResult, error)

	// Configuration validation
	ValidateSpawnConfig(config SpawnConfig) error

	// Room structure analysis for split-awareness
	AnalyzeRoomStructure(roomID string) RoomStructureInfo
}

SpawnEngine provides entity placement capabilities for game spaces. Purpose: Core interface for all entity spawning functionality per ADR-0013. Supports split-aware spawning, capacity analysis, and adaptive room scaling.

type SpawnFailure ΒΆ

type SpawnFailure struct {
	EntityType string `json:"entity_type"`
	Reason     string `json:"reason"`
}

SpawnFailure represents an entity that could not be placed. Purpose: Error tracking for debugging placement issues and constraint violations.

type SpawnPattern ΒΆ

type SpawnPattern string

SpawnPattern defines how entities are arranged in space. Purpose: Categorizes different spatial arrangement strategies per ADR-0013.

const (
	// PatternScattered distributes entities randomly across available space
	PatternScattered SpawnPattern = "scattered"
	// PatternFormation uses structured arrangements
	PatternFormation SpawnPattern = "formation"
	// PatternClustered groups entities with spacing
	PatternClustered SpawnPattern = "clustered"
	// PatternTeamBased separates teams into distinct areas
	PatternTeamBased SpawnPattern = "team_based"
	// PatternPlayerChoice allows players to choose positions
	PatternPlayerChoice SpawnPattern = "player_choice"
)

type SpawnResult ΒΆ

type SpawnResult struct {
	Success              bool               `json:"success"`
	SpawnedEntities      []SpawnedEntity    `json:"spawned_entities"`
	Failures             []SpawnFailure     `json:"failures"`
	RoomModifications    []RoomModification `json:"room_modifications"`
	SplitRecommendations []RoomSplit        `json:"split_recommendations"`
	RoomStructure        RoomStructureInfo  `json:"room_structure"`
}

SpawnResult contains the results of a spawn operation. Purpose: Complete outcome of entity placement including successes, failures, and room modifications.

type SpawnStrategy ΒΆ

type SpawnStrategy string

SpawnStrategy defines the spawning approach. Purpose: Controls randomization vs deterministic behavior in entity placement.

const (
	// StrategyRandomized uses random placement within constraints
	StrategyRandomized SpawnStrategy = "randomized"
	// StrategyDeterministic produces consistent results
	StrategyDeterministic SpawnStrategy = "deterministic"
	// StrategyBalanced optimizes for gameplay balance
	StrategyBalanced SpawnStrategy = "balanced"
)

type SpawnZone ΒΆ

type SpawnZone struct {
	ID          string            `json:"id"`
	Area        spatial.Rectangle `json:"area"`
	EntityTypes []string          `json:"entity_types"`
	MaxEntities int               `json:"max_entities"`
}

SpawnZone defines an area where players can choose spawn positions. Purpose: Restricts player spawn choices to specific rectangular areas with type filtering.

type SpawnedEntity ΒΆ

type SpawnedEntity struct {
	Entity   core.Entity      `json:"entity"`
	Position spatial.Position `json:"position"`
	RoomID   string           `json:"room_id"`
}

SpawnedEntity represents an entity that was successfully placed. Purpose: Contains entity reference, final position, and room assignment.

type SplitRecommendedEvent ΒΆ added in v0.1.1

type SplitRecommendedEvent struct {
	RoomID             string    `json:"room_id"`
	CurrentCapacity    int       `json:"current_capacity"`
	RequiredCapacity   int       `json:"required_capacity"`
	RecommendationType string    `json:"recommendation_type"` // "split", "expand", "redistribute"
	Reason             string    `json:"reason"`
	Timestamp          time.Time `json:"timestamp"`
}

SplitRecommendedEvent indicates when room splitting is recommended for capacity

type Team ΒΆ

type Team struct {
	ID            string            `json:"id"`
	EntityTypes   []string          `json:"entity_types"`
	Formation     *FormationPattern `json:"formation,omitempty"`
	PreferredZone string            `json:"preferred_zone"`
	Cohesion      float64           `json:"cohesion"`
}

Team represents a group of entities that should be placed together. Purpose: Defines entity types, formation, and cohesion settings for a tactical unit.

type TeamCohesionRules ΒΆ

type TeamCohesionRules struct {
	KeepFriendliesTogether bool    `json:"keep_friendlies_together"`
	KeepEnemiesTogether    bool    `json:"keep_enemies_together"`
	MinTeamSeparation      float64 `json:"min_team_separation"`
}

TeamCohesionRules define how teams are kept together

type TeamConfig ΒΆ

type TeamConfig struct {
	Teams           []Team                `json:"teams"`
	CohesionRules   TeamCohesionRules     `json:"cohesion_rules"`
	SeparationRules SeparationConstraints `json:"separation_rules"`
}

TeamConfig configures team-based spawning. Purpose: Defines team separation rules and cohesion constraints for tactical entity placement.

type TeamPlacementStrategy ΒΆ

type TeamPlacementStrategy string

TeamPlacementStrategy defines how teams are positioned relative to each other

const (
	// TeamPlacementCorners places teams in room corners
	TeamPlacementCorners TeamPlacementStrategy = "corners"
	// TeamPlacementOppositeSides places teams on opposite sides
	TeamPlacementOppositeSides TeamPlacementStrategy = "opposite_sides"
	// TeamPlacementRandom places teams randomly with separation
	TeamPlacementRandom TeamPlacementStrategy = "random"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL