Back to Projects

City Simulation

100,000-agent city simulation in Rust with emergent economy, social dynamics, political systems, and multi-resolution level-of-detail.

RustBevy ECSRayonRatatuiSimulationEmergence

What Happens When You Scale Agents

Most agent simulations cap out at a few hundred entities before performance degrades or behavior becomes incoherent. This project asks: what happens at 100,000? At that scale, you stop scripting behavior and start designing the conditions for emergence.

Each agent maintains its own needs hierarchy, personality traits, memories, and social relationships. They work jobs, trade goods, form communities, spread gossip, create political factions, and occasionally banish each other. None of these macro-behaviors are explicitly programmed — they emerge from simple per-agent rules running in parallel on Bevy's ECS architecture.

The technical challenge is keeping 100K agents coherent while running at interactive frame rates. The solution combines Bevy's data-oriented ECS with Rayon's work-stealing thread pool and a custom multi-resolution LOD system that adjusts simulation fidelity based on what the observer is focused on.

System Architecture

The simulation is organized in three layers. The core Bevy ECS runtime handles scheduling, parallelism, and data storage. The simulation systems — economy, social, and political — operate on entity queries and communicate through events. At the top, individual agents make decisions based on their local state, creating feedback loops that drive emergent behavior.

City Simulation Architecture100K Agents · Emergent Behavior · Multi-ResolutionLOD ENGINEMulti-resolutionSpatial partitioningDetail streamingAGENT LAYERAgent Decision EngineNeeds hierarchy (Maslow-inspired)Personality traits & memoryGoal planning & pathfindingSocial relationship graph100K agentsAgent ArchetypesWorkers — labor & productionMerchants — trade & pricingOfficials — governance & policyCitizens — consumption & socialEmergent Phenomena↳ Spontaneous market formation↳ Social stratification↳ Political resistance movements↳ Economic boom/bust cyclesSIMULATION SYSTEMS$Economic EngineSupply/demand pricingResource extraction chainsLabor market dynamicsCurrency & inflation modelSocial DynamicsRelationship graph (trust/influence)Community formationCultural norm propagationInformation diffusion modelPolitical SystemPolicy creation & enforcementTaxation & public servicesFaction & coalition dynamicsResistance as feedback loopsStability indexUnrest levelCORE ENGINEBevy ECS Runtime· Rust · Data-oriented · ParallelizedComponentsSystemsResourcesEventsSchedulesArchetypesQueriesEMERGENT COMPLEXITY FROM SIMPLE RULES

Engineering Decisions

01

Data-Oriented Design via ECS

Traditional OOP agent architectures scatter data across heap-allocated objects, destroying cache coherence. Bevy's ECS stores components in contiguous arrays (archetypes), so iterating over 100K agents' positions or needs is a sequential memory scan — not 100K pointer chases. This alone yields a 10-20x speedup over naive approaches.

02

Multi-Resolution Level-of-Detail

Not all agents need full simulation fidelity at all times. The LOD system partitions space into regions and adjusts tick rates based on observer focus: foreground agents run full decision trees every frame, mid-ground agents run simplified heuristics at half rate, and background agents are statistically approximated. This makes 100K agents feasible on consumer hardware.

03

Emergent Economics via Simple Rules

The economy isn't a top-down simulation with equilibrium targets. Agents set prices based on local supply/demand signals, creating organic markets. Price information propagates through the social graph as gossip, so distant markets can diverge — producing realistic trade routes, arbitrage opportunities, and boom/bust cycles without any explicit modeling of these phenomena.

04

Political Systems as Feedback Loops

Political behavior emerges from agent dissatisfaction. When needs go unmet, agents form factions. Factions with enough influence enact policies (taxation, resource redistribution). Policies affect the economy, which changes agent satisfaction, which reshapes political coalitions. The system naturally oscillates between stability and upheaval.

Technical Challenges

Parallel Decision Making

Agent decisions depend on shared world state (nearby agents, market prices, faction standings). Naive parallelism creates data races. The solution splits decision-making into a read phase (parallel queries) and a write phase (batched mutations), using Bevy's system ordering to guarantee consistency without locks.

Observability at Scale

Debugging emergent behavior requires seeing macro patterns, not individual agents. Ratatui provides a terminal UI with real-time dashboards: economic indicators, social network metrics, faction power distributions, and spatial heatmaps. You can drill down to any individual agent without pausing the simulation.

Memory Budget

100K agents with full personality, memory, and relationship data would consume gigabytes. Agent memory uses a bounded ring buffer — old memories decay unless reinforced by repeated events. Relationships are stored as sparse adjacency lists with a max connection cap, keeping total memory under 2GB.

Deterministic Replay

Reproducing emergent phenomena requires deterministic execution. All random number generation uses seeded PRNGs per agent. Combined with fixed-step simulation ticks and ordered system execution, any simulation run can be replayed identically from its seed — critical for debugging why a specific economic crash occurred.