Flatland Wiki & Encyclopedia
> Landing Page: /
> Source Repositories: flws (Backend) · flws-web (Web Frontend) · flws-page (Landing Page)
> Developed by Long Phan ([email protected] · Demo: /demo/)
> Built and refined using OpenCode and Antigravity · Developed from the core ideas of *Edwin A. Abbott's Flatland: A Romance of Many Dimensions*** (1884).
Flatland is an autonomous 2D artificial life and world simulation developed from the foundational mathematical and spatial ideas of Edwin A. Abbott's 1884 classic Flatland.
Design Philosophy
This project is developed from the Flatland idea rather than mimicking the book literally. It adopts Abbott's core premises — 2D planar constraints, geometric vertex hierarchies, atmospheric perception, and higher-dimensional observation — as a foundation to create a living, evolutionary artificial life ecosystem that organically changes and expands over time.
Core Architecture & Systems
- The Sphere (God Model): The Sphere (God) sets global laws of nature (carrying capacity, food growth, metabolism, disease, climate) from Spaceland, never intervening in individual lives. Configured via a dedicated 🎯 Presets selector and 6 streamlined ⚖️ Macro Domains with live search and dual sliders. Organisms navigate continuously via 16-sensor raycasts and Micro-RNN neural actuators.
- Botanical Ecology & Functional Nutrition: 6 diverse plant species (
grass,grain,berry,medicinal_herb,mushroom,poisonous) with distinct caloric densities, decay clocks, infection remedy effects, and targeted health-based foraging preferences. - Cognitive Agency & Clan Social Intelligence: Multi-objective utility AI replaces rigid if/else trees (evaluating survival, duty, traits, and kin needs); spatial waypoint mental maps; tactical soldier phalanxes, line kiting maneuvers, interpersonal trust-based buddy pairing, autonomous clan task boards (dynamic labor division), governance archetypes (Monarchy, Theocracy, Junta, Republic), adaptive bylaws (winter rationing, martial law), calculated Casus Belli, inter-clan trade caravans, and annual autumn harvest festivals.
- Autonomous Evolution & Culture: 6 heritable personality archetypes (
brave,cautious,altruistic,greedy,explorer,builder), craftable tools (spears, baskets, herb poultices, chieftain crowns), 4 mastery skills (Farming 🌾, Combat ⚔️, Foraging 🦴, Healing 🌿), earned dynamic titles, oral lore passed from elders to youth in houses, and live thought bubbles. - Realistic Energy & Metabolism: Infant low metabolism ($0.45\times$ energy decay), combat stamina expenditure, and autonomous field food reserve management via baskets.
- Settlements & Diplomacy: Walled houses with creature-sized doors, multi-house clan territories, settlement food larders, mutual coalitions, tributary pacts, and schisms.
- Geometric Physics & Morphological Evolution (K∈[3,24]): Polar genomes $(r_i,\phi_i)$ $K\in[3,24]$ (
KMAX 24,morphology_engine.py) with SoAphysical_traitstrait baking ($A,P,I_{zz},\theta_{\min},asym,D_{mult}$) and SAT narrowphase (broadphase $r_{\max}$ + circle fallback $K\ge24$ & $asym<0.05$ + edge normals); annealing $\lambda(g)$ blends Abbott templates → free evolution, energetic asymmetry, neural courtship, and extinction safeguards ($\eta(N)$, Tier1/2/3 genesis, mercy). - Evolutionary Genome Mirror : Dynamic visual phenotype rendering where each creature's body, corolla aura, and chromatic luminescence directly mirror its living genome, generational depth (Gen 0 → 2000+), and physical mutations across millennia.
- Real-Time Synchronization: Deterministic fixed-rate engine loop streaming state over WebSocket (
/ws) at ~30–60 FPS with durable SQLite historical chronicle storage.
Flatland: The Novella vs. The Simulation
A comparative study between *Edwin A. Abbott’s 1884 satirical classic Flatland: A Romance of Many Dimensions*** and this autonomous artificial life simulation.
---
1. Caste, Geometry & Social Hierarchy
| Dimension | Abbott’s Book (Flatland, 1884) | Our Application (Flatland Simulator) |
| :--- | :--- | :--- |
| Hierarchy Principle | "Configuration makes the man." Social status is strictly determined by the number of sides and regularity of angles. | Entities inherit exact geometric castes based on vertex count (N-gons) and regularity. |
| Women (Lines) | Straight lines with no angular width. Because they are practically invisible head-on and razor-sharp, they are legally required to make a continuous "peace cry" and use dedicated side doors. | Rendered as 1D segments (shape: 'line'). Distinct agility, movement, and domestic shelter dynamics. |
| Working Class / Soldiers | Isosceles triangles with narrow, sharp vertex angles (dangerous, volatile, prone to rebellions). | Soldiers (#ff7b72): Sharp combatants with boosted attack, military discipline, and perimeter defense behavior. |
| Artisans & Middle Class | Equilateral triangles (3 equal sides) — stable and respectable tradespeople. | Artisans (3–4 sides, #f2cc60): Farmers, foragers, and builders responsible for harvesting and maintaining houses. |
| Gentlemen & Professionals | Squares (4 sides) and Pentagons (5 sides) — the middle/upper administrative classes. | Gentlemen (4 sides, #ffa657) and Professionals (5 sides, #d2a8ff): Administrative and specialized roles. |
| Nobility | Hexagons (6 sides) and higher polygons — aristocrats and statesmen. | Nobles (6–8 sides, #79c0ff): High influence and lineage priority. |
| Priesthood (Circles) | Polygons with so many sides (≥ 24 to hundreds) that their vertices are imperceptible, forming smooth circles. They govern religion, law, and morality. | Priests (≥ 24 sides, #e6edf3): Emit soothing auras, heal injured or infected clanmates, and resist disease. |
---
2. The "Law of Nature" & Generational Ascent
- In the Book:
- In the App:
- Abbott establishes the "Law of Upward Development": A male child of a regular polygon almost always inherits one more side than his father (e.g., a Square fathers a Pentagon, whose son becomes a Hexagon), lifting the lineage toward circular Priesthood over generations.
- Rare "Irregulars" (whose sides/angles do not match) are viewed as societal threats and sent to state institutions or executed.
- Generational Evolution: Offspring inherit ancestral traits with a probabilistic side increment (sides += 1), simulating the gradual generational ascent toward circular perfection.
- Irregularity & Demotion: Entities that develop genetic irregularity or undergo trauma have their irregularity tracked and are judged/demoted or marked with distinct visual indicators.
- Dynastic Lineage: The Family Tree tracks mother, father, and generational pedigree across decades of world history.
---
3. Sight Recognition, Weather & Perception
- In the Book:
- In the App:
- In a 2D world, all inhabitants look like flat lines from the edge!
- In the Foggy South, Flatlanders rely on "Sight Recognition" — judging the angle and distance of an approaching polygon by how quickly its edges fade into the atmospheric fog.
- In the Clear North, they must rely on "Feeling" (touching vertices with fingertips).
- Dynamic Weather Engine: Simulates Clear, Fog, Rain, and Storm states.
- Atmospheric Vision: Fog and storms dynamically restrict creature vision radii (sight_radius), forcing entities to rely on local spatial queries and nearby auditory alarms (signals).
- Day/Night & Lighting: The ambient illuminance curves shift through dawn, noon, dusk, and pitch-black night, restricting wandering and driving creatures into their shelters.
---
4. Housing, Settlements & Territorial Architecture
- In the Book:
- In the App:
- Houses are strictly pentagonal or hexagonal, with specific entrances: a smaller rear entrance for lines (women) and a main entrance for polygons.
- Settlement Economy: Houses are physical 2D structures with precise interior boundaries, oriented doors (north, east, south, west), and bed capacities.
- Single Main House Invariant: Each clan establishes exactly one Main House / HQ (the Leader's residence) with surrounding outpost shelters.
- Shelter Dynamics: Creatures seek refuge inside houses to sleep at night, protect against winter frostbite, heal from chills, and educate infant offspring.
- Doorway Entry & Exit Navigation: Creatures calculate vector standoff waypoints to transition smoothly through doorway openings when entering shelter at dusk or exiting to forage and explore at dawn, preventing indoor wall trapping.
---
5. Clan Diplomacy, Totems & Autonomous Society
While Abbott’s book portrays a centralized Victorian government, our app layers an evolutionary social simulation:
- Sacred Avatars & Specialization: Each clan bears one of the 8 Sacred Avatars of the Sphere (⭕ Radiant Circle, ⚡ Celestial Strike, 👁️ All-Seeing Vertex, 🛡️ Indomitable Monolith, 🌿 Sacred Spiral, ⚖️ Cosmic Scales, 🌀 Dimensional Rift, 🕯️ Eternal Hearth), each granting a distinct divine buff and biasing the clan's balance of warriors, farmers, and scavengers.
- Diplomacy, Tributes & War: Dynamic clan relations with wars, peace treaties, tribute subjugation, and schisms.
- Personal Autonomy & Inventory: Independent personality archetypes (Brave, Cautious, Altruistic, Greedy, Explorer, Builder) with personal foraging baskets, tools (spears, crowns, herb poultices), and emergency self-preservation eating.
---
6. The Higher Dimension: The User as "The Sphere"
The most profound connection between the app and the book is the role of the user:
- In Flatland, the protagonist A Square is visited by A Sphere from the 3D Spaceland, who can look down from the Z-axis, see into locked rooms, view internal organs, and manipulate the 2D world with god-like omnipresence.
- In our App:
- You are the Sphere (God): As the observer on your screen, you look down on Flatland from Spaceland (the third dimension).
- The Sphere Panel: You hold the power of The Sphere to alter the "Laws of Nature" in real-time — toggling famine, changing food growth multipliers, curing or spreading plagues, introducing winter freezes, or blessing clans with prosperity.
Configuration & ops
Env vars (FLATWORLD_*)
| Variable | Default | Description |
|---|---|---|
| FLATWORLD_WIDTH | 400 | World width (grid units) |
| FLATWORLD_HEIGHT | 300 | World height |
| FLATWORLD_BOUNDARY | wrap | wrap or clamp |
| FLATWORLD_SEED | 42 | RNG seed |
| FLATWORLD_TICK_RATE | 10 | Ticks per second |
| FLATWORLD_DB | backend/flatworld.db | SQLite path |
| FLATWORLD_GOD_KEY | — | Seed/override the god passkey at boot |
God passkey (auth)
POST /api/laws, POST /api/presets/{name}, POST /api/control and WebSocket control messages need the god passkey (X-God-Key header, key field on the socket). No credential yet → any god call answers 409 and the web UI asks to create one (POST /api/auth/setup). Lost it? Recover on the server only: cd backend && uv run python -m app.godkey reset <new> (or clear). The TUI takes no prompt: ./run.sh tui ws://host/ws <passkey> or export FLATWORLD_GOD_KEY. Only a PBKDF2 hash is stored.
Persistence (db.py:20)
SQLite flatworld.db (WAL, thread lock). Tables:
worlds(id, seed, width, height, boundary, started_at, ended_at)events(id, world_id, tick, type, entity_id, caste, cause, x, y, payload, created_at)law_changes(id, world_id, tick, name, value, created_at)creatures(id, world_id, entity_id, caste, clan_id, generation, mother_id, father_id, born_tick, died_tick)snapshots(id, world_id, tick, payload, created_at)
History survives restarts; reset closes old world row and opens new.
Concurrency stance & SimEngine
The simulation core is strictly deterministic (one seeded RNG stream, one fixed tick order). Run uvicorn with 1 worker (more workers = several disconnected worlds, not a faster one). Under SimEngine (main.py:446), simulation advancement runs on its own dedicated background OS thread. State stepping occurs under RT.lock while JSON snapshot serialization runs outside the lock (advance_world_lockless), so heavy state dumps and WebSocket broadcasts never block REST endpoints or hold the GIL. Key operational & diagnostic endpoints:
GET /healthz— Live server health, current TPS, memory usage, uptime, and active WebSocket client count.GET /api/perf/telemetry— Rolling telemetry rings: tick duration, lock wait time, and broadcast latencies.GET /api/analytics/summary— High-level macro demographics, biomass, and trophic distribution.
How the world works
The Sphere (God model): The Sphere (God) sets laws from Spaceland, never touches individual creatures. Everything else emerges.
The deterministic tick
s = Simulation(Config(seed)) → s.step() is fully deterministic (one random.Random per world). Same seed ⇒ same world. Tick loop (backend/app/simulation/core.py Simulation.step()) order: weather → plants → rebuild index → creatures → disease → war → reproduce → relations → food law → corpses → settlements → tick+=1. Simulation advances on a dedicated OS thread (SimEngine) with lockless serialization, streaming snapshots over WebSocket state every tick.
Life cycle & stages (§A)
Creature.age ticks + caste-based lifespan (Woman 4800 → Priest 9000). Stage by age/lifespan: infant <15%, juvenile <30%, adult <75%, else elder. Stage scales speed & sight (infant 0.6×, elder 0.85×) and fertility (elder ×0.5). Death causes: starvation, old_age, euthanasia, disease.
Health core (§AT-4 H-0)
Health is a resource, not a constant. Regeneration demands an energy surplus: below 40% of energy_max (HEALTH_REGEN_MIN_ENERGY) wounds stop closing — awake or asleep; sheltered rest heals at 0.15×rest_recovery_mult, waking regen is 0.1/tick (+Indomitable Monolith defense). Below 20% energy the body cannibalizes itself: −0.05 health/tick (HEALTH_SELF_DRAIN_*) until death by starvation — famine now kills twice. Weakness slows every stride (HEALTH_SPEED_TIERS): health <80 ×0.95, <60 ×0.85, <40 ×0.70, <20 ×0.50. Sickly bodies cannot beget children: mating requires health ≥ REPRO_MIN_HEALTH (50), so a plague suppresses births without touching birth laws.
Damage variety & healing economy (§AT-4 H-1)
Chronic hunger gnaws: below 20% energy for more than EXHAUSTION_TICKS 30 ticks drains EXHAUSTION_DRAIN 0.08 health/tick (death cause exhaustion). Age withers: elders lose ELDER_DECAY_RATE 0.02/tick passively. Sickness dims the eyes (HEALTH_SIGHT_TIERS: <60 ×0.90, <30 ×0.75) and blunts the harvest (_forage_mult: −20% under 60 HP, −50% under 30) so decline feeds on itself. The badly wounded (<30 HP) or grievously wounded never start a duel, though they can still be attacked; blows above WOUND_MIN_DAMAGE 15 leave a lingering wound (50–100 ticks, severity 1–2 by damage ≥40) that halves or quarters regen and hobbles speed (×0.85/×0.70). Where a body stands decides how fast it mends: waking regen runs at ×0.5 outdoors (REGEN_OUTDOOR_MULT) vs ×0.8 sheltered-awake vs full strength asleep indoors. And supper keeps working: berries set +0.3 health/tick for 20 ticks, grain +0.2×30, medicinal herbs +0.8×40 (FOOD_HEAL_BONUS) — a hurt creature even seeks herbs on a full stomach (herb targeting ignores the sated gate under 60 HP). Bodies differ in depth, too (CASTE_MAX_HP): Soldiers/Artisans pool 130 HP, Nobles/Predators 120, Women 110, Gentlemen/Herbivores 100, Professionals/Priests a delicate 90 — regeneration and healing cap at each body's own pool.
Physics axioms (§AQ PH-0)
Energy is the universal currency. Sunlight is the world's only income: _sun_factor() follows the day cycle — zero through the night, full strength at noon — and gates both plant growth and seed spread, so nothing grows for free in the dark (winter's bite remains the season table). Every body pays upkeep by its geometric complexity (METABOLIC_COST): triangles 1.0×, squares 1.1×, pentagons 1.2×, hexagons/nobles 1.3×, women and priests 1.5× (a priest burns energy maintaining the aura) — applied to the per-tick decay on top of stage/lifestyle multipliers. And mending is a conversion, not a miracle: each point of regenerated health costs HEALING_ENERGY_COST 0.5 energy (charged only when healing actually happens).
Thermodynamics & heat (§AQ PH-1)
A coarse ambient heat field (TEMP_CELL 25-unit cells, _update_temperature) relaxes toward a target each tick: the seasonal base (SEASON_BASE_TEMP spring 12° / summer 24° / autumn 8° / winter −4°) swept across the map from an edge — cold fronts enter from the west, warm fronts from the east — plus the day cycle (DAY_HEAT_AMPLITUDE ±5°), weather (rain −2°, storm −3°, fog −1°) and open flame (FIRE_HEAT 60° within 8 units). Every creature carries body_temp (on the wire) that drifts toward the local ambient at BODY_TEMP_DRIFT; standing indoors replaces ambient with indoor_ambient(), where the house material insulates (INSULATION_BY_MATERIAL: straw 0.15 < wood 0.35 < stone 0.55) toward HOUSE_COMFORT_TEMP 18°, and larger floors shed heat faster (HOUSE_REF_SIDE/size). Extreme heat is always physics: past HYPERTHERMIA_TEMP 36° health drains with the excess (HYPERTHERMIA_DRAIN) until death by hyperthermia. Extreme cold feeds §R chill below HYPOTHERMIA_TEMP 2° when the weather-sickness law is on.
Wind (§AQ PH-2)
The sky has a breath: a wind vector (wind_angle/wind_speed, on every snapshot payload) whose strength follows the weather — calm 0.25, rain 0.55, storm howls at 1.0 (WIND_*_SPEED, relaxed each tick) — and whose direction re-rolls near the season's prevailing bearing whenever the weather turns (WIND_SEASON_BIAS). Fire obeys it: both random ignition and plant-to-plant spread multiply by a tailwind factor (WIND_FIRE_MULT × speed × alignment), so flame races downwind while upwind groves stand longer.
Nature's Law inheritance (§B)
Sex: polygons male, lines female (entities.py:137). Sons sides = father.sides+1 capped at max_sides (24→Priest per new spec; K∈[3,24]); daughters lines. Mutation mutation_rate ±1 side → irregularity 0.3–1.0. Isosceles triangles: iso_angle+0.5° per generation, ≥60° promotes Soldier→Artisan. Fertility: per-caste table × crowding carrying_capacity/max_population. When morphology_annealing_enabled (morphology_engine), polar $(r_i,\phi_i)$ annealing supersedes side-count: $\lambda(g)$ blends Abbott template $K\in[3,24]$ with parental noisy genome, topo $p\cdot(1-\lambda)$.
Geometric Physics (Morphology Engine, K∈[3,24])
Polar genomes $K\in[3,24]$ SoA morph_radii/morph_angles/morph_k/physical_traits (A,P,I_{zz},\theta_{\min},asym,Dmult) — vectorized morphology_engine.py KMAX 24 (morphology.py shim). $\lambda(g)=morph\_lambda\_override ?? clamp(1-(g-g_{start})/g_{decay})$ (g_start 50 g_decay 150, override -1.0 = auto). Baking $E_{\max}\cdot clamp(A/A_{ref},0.5,2.5)$ $decay\cdot clamp(P/P_{ref},0.7,2.0)$ $steer\Delta\theta$ $D_{mult}$ $asym$→$irregularity$ with safeguard_morph_mercy ($\eta>0.3$ suspends euthanasia), SAT broadphase $r_{\max}$ + circle fallback ($K\ge24$ & $asym<0.05$) + edge normals + $D_{mult}$ impulse. Telemetry /api/metrics/morphology and /api/metrics/safeguards (N,\eta,tier,miracles,mercy) live.
World History, Chronicle & AI Storytelling (§BM)
Flatland features an end-to-end multi-era historiography, timeline analytics, and AI storytelling suite:
- Major Moments & Chronicle Jumps: Top dramatic days (casualties, conquests, schisms) are automatically highlighted as jump chips above the chronicle feed. Users can jump directly to any specific tick timestamp.
- Epoch Bar & Population Sparkline: Interactive temporal navigation with color-coded world epochs (Genesis, Age of Tribes, Feudal Era, Classical Zenith, Era of Ruin) and population curves overlaid with war and plague crisis markers.
- Records & Legends Leaderboard: Hall of fame for Sovereign of War, Deadliest Single Day, Greatest Realm, Divine Architects, Largest Schism, and Hero/Villain notables.
- History Analytics: Clan Rivalry Heatmap Matrix, Mortality Breakdown (combat, famine, disease, age) across 10-day eras, and Faith Devotion Index over time.
- In-App AI Story Generator: Integrated browser-based LLM narrative generator using Google Gemini 1.5 Flash or OpenAI GPT-4o-mini with client-side API keys in localStorage. Supports 4 narrative styles (Saga, Chronicle, Mythos, Tragedy) in EN, VI, and FR.
- Deep Linking: Shareable URLs with
?history=42to auto-open specific world days or?clan=7to auto-open clan biographies.
Irregularity & caste (§C)
Mutated children's irregularity judged at adult_age: ≥euthanasia_threshold → consumed (euthanasia), else demoted to Soldier. CASTE_TRAITS (entities.py:39) gives lifespan/speed/sight_mult/fertility. BC maps $asymmetry$ → $irregularity$ for same gate.
Disease (§D)
disease_enabled, disease_outbreak_rate starts new disease_id, spreads within disease_radius at disease_rate (winter ×1.5), drains disease_energy_drain + health 2×disease_lethality, recovers recovery_rate. Disabling freezes instantly.
Environment (§E)
Clock from tick: time_of_day (day_length cycle, starts sunrise), day, season (season_length). Night night_sight_mult, fog fog_sight_mult stack. SEASON_FOOD_MULT spring 1.0/summer 1.2/autumn 1.0/winter 0.5; spring ×1.25 birth, winter ×1.5 disease. Weather FSM clear/rain/fog/storm at weather_change_rate: rain/storm rain_speed_mult, storm storm_wander_bonus.
Clans & social order (§C/I/P/V)
Settlements seed clans (§V): every non-ruin house founds a clan led by the founding creature nearest its centre, and every founding creature joins its nearest house's clan — soldiers, women, nobles and priests mix inside one settlement (simulation/settlement.py _found_founding_clans, deterministic given the seed). God law max_clans caps society granularity: -1 = one clan per house; N ≥ 1 clusters the founders into N spatial clans (greedy k-centre) instead — a pinned value applies at world creation. A clan's settlement IS its anchor house: claims match the clustering (_assign_house_claims/_claim_house_for_clan pick the free house nearest a clan's people, never round-robin), and territory/totem/crest anchor there. Children inherit mother's clan_id; orphans found new clans that settle at the nearest free house (or build one, §L). Procedural name (CLAN_ADJECTIVES/NOUNS) + Sacred Avatar of the Sphere (§AP: ⭕ Radiant Circle, ⚡ Celestial Strike, 👁️ All-Seeing Vertex, 🛡️ Indomitable Monolith, 🌿 Sacred Spiral, ⚖️ Cosmic Scales, 🌀 Dimensional Rift, 🕯️ Eternal Hearth — emoji on the map) if totems_enabled (config.py:59, simulation/theology.py AVATARS/TOTEM_BUFF, renderCore.tsx pole + shrine). Clan crest color on snapshot, totem pole + glowing shrine beside the main house, StateMessage.clans carries name/totem/faith/shrine_level/leader_id/color. Clan stats & history (§P): GET /api/clans roster with leader_id/population/house/war_wins/losses/territory_radius, polled by ClanPanel.tsx under trophic chart. Relations −100..+100 drift relation_drift_rate →0, threshold alliance_threshold/rivalry_threshold → alliance/rivalry events; shared feeding within flock_radius +2. Boids cohesion_weight/alignment_weight/separation_weight blended after food-seeking; social yielding YIELD_RADIUS 2.5. Territory (§P): each settlement anchors a territory_radius 14 circle (config.py:49, simulation/society.py _update_territory, CanvasRenderer.tsx:514) — members steer home when outside (0.35×steer), trespass inside a rival's circle sours relations trespass_decay (protocol.py:127) via _bump_relation. Totem buffs (§AP): eight Sacred Avatars with divine aspects — ⭕ Radiant Circle +30% harvest/+20% fertility, ⚡ Celestial Strike +25% warrior damage, 👁️ All-Seeing Vertex +40% sight + nocturnal clarity, 🛡️ Indomitable Monolith −30% damage/cold immunity, 🌿 Sacred Spiral herbs ×2/plague recovery/composting, ⚖️ Cosmic Scales reliable peace/refuses kin-eating, 🌀 Dimensional Rift faster promotion/adaptive mutation/elder lore, 🕯️ Eternal Hearth nocturnal calm. Theology (§AP): settled clans consecrate a shrine beside the main house (_update_faith); the devout tithe tithe_rate at dawn & dusk into the clan faith pool; the aura mends the faithful; faith overflowing at a season turn works a miracle (bloom + mending); temple_faith_cost raises a Temple whose aura covers all territory (temple event); when God sets laws every shrine chimes and priests preach doctrinal sermons (on_law_change from POST /api/laws); same/complementary-avatar clans sympathise (+1 relation, holy alliances); crisis ages convene the Great synod (+relations, sacred truce); and rarely an elder priest receives the 3D epiphany — all strife stills (truce_ticks). Leadership (§P): founder is leader_id (simulation/society.py), death triggers succession to oldest living member → succession event (protocol.py:129, simulation/lifecycle.py) if succession_enabled (config.py:54).
Food economy (§H/N/O)
Food is a living plant growth 0.15→1.0 (plant_growth_rate), spreads plant_spread_rate within SPREAD_RADIUS 6.0 if below seasonal bounty food_count×SEASON_FOOD_MULT. Winter die-back removes youngest first. A meal whose straight path is blocked by a rock circle or a house wall is abandoned for food_giveup_ticks — the hungry give up and seek food somewhere else instead of grinding against the obstacle until they starve; eating anything clears the grudge, 0 disables giving up (_segment_hits_circle, _give_up_on). Death leaves Corpse (corpse_ttl, corpse_energy) edible like food; decay boosts nearby plants NUTRIENT_BOOST×nutrient_cycle_rate within NUTRIENT_RADIUS. §O biodiversity: Food.variant grass/berry/mushroom/poisonous (entities.py:169) — plant_variants_enabled/poison_rate (config.py:44), VARIANT_ENERGY grass 32/berry 48/mushroom 24/poison 8 and VARIANT_HEALTH berry +1/poison -30 (simulation/constants.py), growth VARIANT_GROWTH_MULT×VARIANT_SEASON_MULT (simulation/ecology.py), spawn picks berry burst in autumn / mushroom on corpses/rocks (simulation/ecology.py), poisonous mutates via poison_rate; bloom carries variant (simulation/ecology.py). Wild herbivores (§O): Herbivore clanless grazers (entities.py:40, is_herbivore) spawn area×density×beast_ratio (config.py:46, simulation/lifecycle.py), graze plants and are hunted by predators (plants → herbivores → predators); beast_ratio/diet_strictness GodLaws (protocol.py:123). Diet & preference (§O): diet_strictness (config.py:46) filters perceived meals (simulation/creature_update.py) — herbivore ignores corpse when strict, predator ignores food, higher castes skip low-energy grass when strict (berry preferred), herbivore avoids poisonous; test_synergies.py:test_diet_preference_respects_strictness verifies.
Communication & knowledge (§Q/X)
Signals (§Q): food calls and alarm calls ripple within signal_radius; clan-mates respond strongly, strangers weakly. Knowledge (§X): creatures learn typed facts from experience — food spots seen/eaten, danger at predator sightings, safe roofs while sheltered, enemy clans that struck them (Creature.facts, decay after knowledge_ttl). Teaching: knowledge_share_rate chance/tick to broadcast the freshest fact to clan-mates; heard facts land at half confidence — retold knowledge is vaguer than firsthand sighting, only better news overwrites. Mobbing: an attacked creature emits a help call; clan-mates within help_radius converge on the attacker (warriors first via caste rank, the peaceful lag behind, high castes only when bold), and every defender inside earshot softens the attacker's blows by defense_weight. Clan memory: /api/clans surfaces each clan's remembered enemies/danger zones/food spots (clan_knowledge()), and clans that remember each other as enemies plot wars faster (§S foreshadowing). Full history (§AT-1): GET /api/clans/{id}/history?page=&size= paginates the clan's entire filtered event stream (newest first, total/has_more) alongside the internal milestone log; the durable chronicle filters by clan at the SQL level — GET /api/history?clan_id=N matches any clan-bearing payload key (a/b/clan_id/conquest/schism/takeover pairs) so events stay queryable after rolling off the in-memory deque; ClanDetails renders a lazy "Full History" panel with load older. Senses interact (§AR S-0): sleeping bodies are fully deaf — a sleeper never processes signals and never counts as a mob defender (_mob_defenders skips the asleep), so predators may stalk a silent village. Ripe plants smell through the dark: a hungry or starving creature with no visual target catches the scent of any mature plant (growth 1.0) within FOOD_SCENT_RADIUS 8.0 at night — blind starvation is cured by the nose. And starvation dulls fear: _effective_fear_radius halves fear_radius for the starving (traits paranoid +4 / bold −2.5 still apply first), so the desperate walk toward death chasing scented food.
Politics (§AB)
Coalitions: a leader folds friendly unaligned clans (relation ≥ coalition_threshold) into a named bloc (coalition_formed/coalition_joined); soured or shrunken blocs dissolve (coalition_dissolved). Mutual defence — strike one member and every mate's relations with the attacker sour −12, dragging them into the war. Leader agency: leaders act on their heritable trait — bold declares war on a remembered enemy (§X), peaceful sues for peace when weakened (peace event), paranoid betrays an ally (betrayal event + treason: false enemy knowledge seeded into nearby third clans). Strong clans demand tribute: vassals pay from their larder every 240 ticks (tribute events). Resource sharing: each settlement keeps a larder capped by larder_capacity — well-fed members deposit surplus, starving members withdraw; full-bellied allies top up starving allies at aid_rate. Defection: unhappy members (starving or homeless) walk to the healthiest nearby banner, even a rival's (defection events). /api/clans exposes coalition_id, larder, tribute_to; ClanPanel shows 🤝 pact / 🛡️ vassal / 🏺 larder chips. The leader is leverage (§AS L-0): kin within LEADER_AURA_RADIUS 15 of the living leader gain +10% sight (LEADER_SIGHT_BONUS), −5% energy burn (LEADER_DECAY_MULT) and a calmer hand (fear radius −1); with no living leader the whole clan glooms — sight −10%, burn +5% (LEADERLESS_DECAY_MULT), food gain ×0.85 (LEADERLESS_GAIN_MULT), bylaws and task boards pause, war declarations stop, and members drift cautious at LEADERLESS_CAUTIOUS_CHANCE. The death itself shocks: every member instantly loses 10 energy (LEADER_SHOCK_ENERGY), panics for 20 ticks (+0.3 flee urge), the larder loses 20% to looting, and a grey grief ripple marks the spot.
Desperation cannibalism (§AC)
Only the desperate eat the living: below cannibalism_hunger_ratio energy a creature perceives eligible prey — enemy-clan members (negative relation) and the weak (starving, elder, wounded) of any clan; never predators, wild beasts, infants or indoor refugees. On contact within eat_radius the prey dies (cause cannibalism), the eater gains cannibalism_energy and leaves a partial corpse, and a cooldown separates kills. Kin-eating carries a terrible price (eat_kin_enabled): the kin-slayer is exiled (exile_on_kin_eat) to found a one-being outcast band, witnesses remember the band as an enemy (§X), and relations between former clan and band sink by kin_stigma — rivalry, plots, war.
Food decay (§AE)
Nothing lasts forever: a mature plant lives food_lifespan_ticks × its variant's pace (mushroom 0.4×, grass ×1, berry 1.5×, poisonous 3×) before it withers — sprouts and growing plants never rot. Withered plants fade brown in the renderer, release half a corpse's nutrient boost to nearby plants (§H death feeds life), then vanish (wither events stay in-memory like blooms, never the DB). The bounty law respawns replacement growth, so plant counts now churn instead of freezing.
Shelter & Settlements (§L/N)
Houses (entities.py:184) squares with doorway; walls block except door — doorway too small for Carnivore predators (§L refuge) so houses are safe havens. Exposure exposure_drain outdoors in rain/storm or night unless indoors. Beds scale with floor area: house_capacity counts beds in an average 8×8 hall (HOUSE_REF_AREA), small huts have fewer beds, and large houses are strictly capped at 16 beds max (HOUSE_MAX_BEDS). Clans can settle across multiple houses, with the leader residing in the primary Main House marked with a golden crown. Abandoned houses decay to ruins (is_ruin). One house, one clan (§AT-2/AT-3): a creature sleeps only under its own clan's roof or an unclaimed one — _house_for() never returns a foreign house, so rival bodies cannot poison occupancy caps. A growing clan with no free roof may take over a weak rival's spare house (non-main, nobody sleeping there tonight, rival population under half its bed count — _try_house_takeover): the invader claims it outright, relations sour −25 and a takeover event hits the chronicle with an expanding crest-ring flash on the map; conquest-by-war transfers houses too (winner repoints the loser's seat). An audit pass each settlement tick (_audit_house_claims) clears claims whose clan died so no house ends a tick owned by a ghost.
Autonomous Evolution & Tools (§AG)
Evolution emerges 100% autonomously without god interventions:
- Personality Archetypes:
brave,cautious,altruistic,greedy,explorer,builder(65% heritability). Altruistic creatures feed starving kin with basket food. - Dynamic Equipment & Tools: Soldiers/Predators wield Spears (+20% combat damage & reach); Farmers/Artisans/Herbivores carry Baskets (haul up to 3 food units for field snacks or clan larder deposits); Priests carry Herb Poultices (+25 HP healing & infection cure); Chieftains wear the golden Crown.
- Skill Mastery & Dynamic Titles: 4 skills (Farming 🌾, Combat ⚔️, Foraging 🦴, Healing 🌿) progress from Novice to Master, unlocking titles (the Slayer, the Fearless Champion, the Grand Harvester, the Wise Shaman, the Pathfinder).
- Oral Lore: Elders sleeping in houses transmit their highest skill mastery XP to resting youth.
- Floating Emote Thoughts: Real-time mood balloons (
🍖,❤️,⚔️,🌿,🏆,💤,🧺,😱) above creature heads.
Energy Dynamics & Stage Metabolism (§AH)
- Stage-Aware Metabolism: Born infants burn 55% less energy per tick (
0.45x), juveniles burn 25% less (0.75x), adults standard (1.0x), elders0.85x. - Combat Stamina: Duels and war clashes expend energy (winner -6, loser -10); low energy (<20%) causes an exhaustion penalty (30% less damage).
- Food Reserves & Field Eating: Roaming creatures with <45 energy autonomously eat carried food from their basket. Full creatures (>85% energy) never eat or destroy food plants.
Cognitive Agency & Clan Social Intelligence (§AL)
- Multi-Objective Utility AI Engine: Dynamic utility scoring evaluating survival energy, caste duty, personality weights, and kin emergency signals.
- Mental Map & Purposeful Waypoints: Coordinates for
home,rich_food,danger, andpatrolenable purposeful foraging and perimeter circuits over random Brownian noise. - Tactical Combat Formations: Allied Soldiers in combat align into disciplined phalanxes; 1D lines (women) execute evasive tangential kiting; outnumbered creatures execute organized retreats to shelter.
- Interpersonal Trust Matrix: Pairs develop affinity from healing (+15) and feeding (+20), forming loyal buddy pairs for shared foraging.
- Clan Division of Labor & Task Board: Dynamic macro priorities (
balanced,food_security,defense,quarantine_healing) boost harvester (2.0×) and guard (2.5×) action weights. - Governance Archetypes: Distinct institutional succession models (
Monarchyroyal dynasty,Theocracypriest succession,Juntacombat mastery,Republiccouncil of elders). - Dynamic Bylaws: Automated policies including winter food rationing (<35 energy threshold) and wartime martial law curfews.
- Macro Geopolitics & Casus Belli: Intentional war declarations based on famine food raids, blood feuds, and territorial friction with documented Casus Belli.
- Inter-Clan Trade Caravans: Economic specialization barter transferring surplus grain from agrarian clans to martial clans in exchange for combat training and diplomatic goodwill (+12 relations).
- Tribal Traditions & Harvest Festivals: Annual autumn celebrations at clan Main Houses boosting energy (+25), mood emotes, leader trust (+10), and oral lore transmission (+2.0 skill XP).
Food & Botanical Ecology (§AM)
- Crop Diversity & Botanical Variants: 6 distinct flora species (
grass,grain,berry,medicinal_herb,mushroom,poisonous). - Functional Nutrition:
- Targeted Dietary Selection: Injured and infected creatures actively seek medicinal herbs (0.2× effective distance weighting); starving creatures seek golden grain (0.4× distance weighting).
- Golden Grain: Dense calorie staple (+45 Energy), slow decay rate ($2.5\times$ lifespan), foundational for settlement security.
- Sun Berry: Energy burst (+48 Energy) and +15% movement speed surge.
- Medicinal Herb: Healing remedy (+18 Energy, $+30\text{ HP}$), cures infections, grants heal emotes.
- Fungi / Mushroom: Decomposer thriving near corpses, rocks, and during winter (+24 Energy).
Terminal User Interface (§AI)
A complete Textual terminal interface (backend/tui/) attaches to running worlds with:
- Camera follow mode (
w) tracking moving creatures. - Category-filtered Chronicle (
t) (All, Birth, Death, War, Politics, Settlement). - Full creature dossier inspector (
enter/i) and clan details modal (c). - God laws manager (
g) and ASCII/half-block renderer (a/f).
Micro-Neural Network & Evolutionary Engine (BA)
Every creature carries a micro Elman RNN (16 → 12 → 7, 295 float32 weights, fixed) evolved by selection — always on. Sensors (16): vitals, three raycasts ±35°, audio, scent, collision, slope and hidden state. Outputs (7): thrust/steer (movement + energy drain), interact (consume/attack), social (mating readiness replaces §B gating), vocal_amp/vocal_freq, recurrent_out (writes hidden_state). Physics 60 Hz, inference at nn_inference_hz (default 15 Hz, every 4th tick latched, zero-alloc inputs_buf/outputs_buf). Genomes init N(0,0.5) clipped [-4,4]; mating via spatial query when energy > mate_energy_min and social > 0.5; uniform crossover 50/50 + Gaussian mutation N(0,0.08²) p=0.03 (mutation_sigma/crossover_rate laws). Always-on 295. See backend/app/agent_soa.py, neural_engine.py, agent_pipeline.py, evolution.py, sim_loop.py, spatial_grid.py.
Sustainability — Multi-Generational Balance
The world self-balances across hundreds of days and multi-generational dynastic flourishing under tuned ecological and social equilibrium.
Curated Presets
- balance ⚖️ (Default) — Goldilocks harmony tuned for 200–350 inhabitants with 380 food, carrying capacity 400 (max 500), gentle wars, rare predation, agriculture, density damping ($\xi$), extinction safeguards ($\eta$), and flourishing multi-generational clans.
- sustainable 🌿 — 1000-day prosperous peace: abundant food (550), carrying capacity 550 (max 600), rich granaries, harvest festivals, banquets, and gentle damping.
- theocracy 🔮 — Age of the Sphere: sacred avatars, glowing temples, avatar miracles, 3D epiphanies, holy synods, and divine tithes.
- warlords ⚔️ — Clash of clans: imperial conquests, granary raids, house takeovers, territorial expansion, and defensive coalitions.
- chaos 🔥 — High predator ratio, lethal wars, wildfires, earthquakes, frequent plagues, and fast seasonal turnover.
- extinction 💀 — Severe famine (120 food), harsh winter (0.30×), high exposure decay, testing societal resilience under collapse.
- boom 🚀 — High reproduction, 440 food, carrying capacity 800 (max 850) for monumental metropolis testing.
Use: curl -X POST localhost:8000/api/presets/balance?reset=true or use The Sphere (God Panel) preset selector.
Dynamic Homeostasis & Extinction Prevention
Flatland includes two complementary closed-loop homeostatic feedback engines:
1. Density-Dependent Soft-Cap Damping ($\xi$)
When population $N$ exceeds carrying capacity $K_{cap}$, the overshoot ratio $\xi = (N - K_{cap}) / K_{cap}$ acts as a non-linear brake:
- Birth Suppression: $R_{birth} = R_0 / (1 + \text{damping\_steepness} \cdot \xi^2)$
- Crowding Metabolic Stress: $M_{decay} = M_0 \cdot (1 + \text{crowding\_stress\_mult} \cdot \xi)$
- Resource Strain: Plant growth and spread slow down proportionally to ecosystem saturation.
2. Extinction Safeguards & Genesis Miracles ($\eta$)
When population drops below $K_{safe} = K_{cap} \times \text{safeguard\_relief\_ratio}$, emergency relief kicks in:
- Tier 1 ($\eta \le 0.5$): Famine relief, metabolic energy discount up to 40%, plant growth acceleration up to 60%.
- Tier 2 ($\eta > 0.5$): Critical relief, reproduction cooldown halved, infant euthanasia suspended (
safeguard_morph_mercy). - Tier 3 ($N \le K_{crit}$): The Sphere intervenes with a Genesis Miracle, creating
safeguard_genesis_batchpristine regular beings to ensure species survival.
Performance & Scale — 1000+ head @ 60 FPS
- Zero-Allocation Spatial Hash: Pre-allocated 1D bucket list in
world.pyeliminates tuple allocations and dictionary re-hashing per tick;query_radiususes squared-distance early-exit withoutmath.hypot. - Fast Mate Discovery: Spatial index queries nearby partners in $O(1)$ instead of $O(N^2)$ nested roster scans.
- Snapshot Caching: Static terrain and obstacles are pre-cached, eliminating redundant dictionary list copies on every broadcast frame.
- Batched Canvas 2D Rendering: Batches drawing passes by caste, plant variant, and house primitives with inline trigonometric vertex transforms, completely eliminating per-creature
ctx.save()/ctx.restore()overhead (draw calls reduced from 20,000+ to ~30-50). - Dynamic Level of Detail (LOD): Zoom-dependent rendering skips fine-grained glyph text and ripples when zoomed out, maintaining 60 FPS even with dense populations.
- Decoupled React State: High-frequency simulation snapshots stream directly into mutable refs at 60 FPS for canvas rendering, while React virtual DOM reconciliation (HUD stats, charts) is throttled to ~6 Hz to keep the main browser thread light and responsive.
Codebase map
Tri-Repository Architecture & Single-System Deployment (§BP)
Flatland is decoupled into three dedicated GitHub repositories with unified same-system deployment:
flws(github.com/longphanmn/flws): Backend simulation engine (FastAPI, SimEngine thread, NumPy SoA, micro-Elman RNN, polar geometry SAT, TUI, SQLite WAL). Listens on host port:8000.flws-web(github.com/longphanmn/flws-web): Standalone web frontend simulation client (React 18, Vite, TypeScript, Canvas2D/WebGL 60 FPS viewport, Macro Observatory). Deployed to GitHub Pages (https://longphanmn.github.io/flws-web/) and runs on:5173/:80(Nginx reverse-proxying to backend).flws-page(github.com/longphanmn/flws-page): Official project landing page and showcase (interactive canvas, audio synthesizer badge, lore). Deployed to independent GitHub Pages (https://longphanmn.github.io/flws-page/).- Same-System Orchestration:
docker-compose.ymlanddeploy.shdeploy and run both backend and frontend on the same host system.
Backend (backend/app/)
config.py:13—Configdataclass: world geometry, densities, food, corpses, behaviour, life, reproduction, disease, environment, shelter, terrain, society, houses, chronicle.from_env()+tick_interval.entities.py:1—CasteTraits,CASTE_TRAITS,YIELD_RANK,caste_name(),Creature(shape/sides/caste/age/lifespan/health/infected/clan_id/sleeping...),Food(growth),Corpse,House(size/door/clan).world.py:32—Worldregistry + uniform spatial hash (cell_size,rebuild_index),delta/distancewrap-aware,query_radius.simulation/— Modular simulation package (§BI, replacing legacysimulation.py:335):agent_soa.py— SoA buffers (pos/vel/genomes + morph_radii/angles/k/traits) vectorized.agent_pipeline.py— Vectorized batch sensory raycasting and movement physics.neural_engine.py— Micro-Elman RNN forward inference (16→12→7, 295 weights).morphology_engine.py— Polar geometry SAT collision & physical trait baking.evolution_manager.py— Annealing λ(g), Abbott templates K3..64, polar crossover.spatial_grid.py— Vectorized spatial grid for fast proximity queries.analytics.py— TelemetryRing, macro metrics, demography, biodiversity, timeseries.safeguard_engine.py— Extinction safeguards & Genesis miracles.density_damping.py— Soft-cap density damping (ξ).auth.py:1—require_godFastAPI dependency for God passkey PBKDF2 verification (X-God-Key).protocol.py:7— Pydantic wire schemas:ControlAction,ControlMessage,EntityState,StateMessage,HistoryEvent,HelloMessage,GodLaws.db.py:1— SQLite WAL persistence for worlds, events, lineage, and snapshots with write buffer.main.py:1— FastAPIapp,SimEnginededicated tick thread,Hubbroadcaster, REST & WebSocket routes.
- core.py — Simulation class, deterministic step loop, SoA slot sync, and cache refreshes.
- creature_update.py — Decomposed 7-phase agent loop (_creature_movement, _creature_feeding, etc.).
- settlement.py — Housing economy, construction, claims, takeovers, and wall collision.
- lifecycle.py — Spawning, reproduction, birth, death, skill titles, and disease propagation.
- ecology.py — Flora lifecycle, farming, banquets, corpse decomposition, and nutrient cycling.
- theology.py — Faith pools, Sacred Avatars, shrines, miracles, synods, and epiphanies.
- society.py — Clans, diplomacy, war, coalitions, larders, trade caravans, and cannibalism.
- serialization.py — Wire snapshot and delta payload generation.
- environment.py — Weather FSM, wind, temperature grid, elevation, and wildfires.
- constants.py — Lookups, multipliers, names, and avatar configurations.
Frontend (frontend/src/)
App.tsx— Main application layout, HUD, WebSocket synchronization, mobile drawer tabs.analytics/— Macro Analytics Engine & Observatory:render/CanvasRenderer.tsx— High-performance 60 FPS batched HTML5 Canvas renderer.render/ClanPanel.tsx— Live clan settlements, totems, and war records.render/ChronicleFeed.tsx— Filterable, scrollable real-time event log.render/PlotsPanel.tsx— Multi-metric population, caste, and trophic sparklines.clan/ClanDetails.tsx— Clan profile, leader residence, founded day & casualty tracking.history/WorldHistoryModal.tsx— Daily chronicle digest, major wars, and AI Story export.god/GodPanel.tsx— Interactive Laws of Nature drawer across 6 macro domains.god/auth.tsx— God passkey modal dialog and authenticated fetch wrapper (godFetch).inspect/Inspector.tsx— Creature dossier, polar morphology radar, vitals & family tree.wiki/Wiki.tsx— In-app interactive wiki & API playground.types.ts— TypeScript definitions mirroring backend protocol schemas.websocket.ts— Auto-reconnecting WebSocket client.
- Observatory.tsx — Full-screen macro dashboard container with tabbed views.
- MacroOverview.tsx — Demographics, vital health, biomass & speed sparklines.
- SociologyTab.tsx — Clan hegemony, trade caravans, wars & succession tracking.
- EcologyTab.tsx — Botanical diversity, soil health & trophic pyramid.
- CrisisTab.tsx — Epidemic spread, starvation alerts & disaster log.
- MutationLab.tsx — Morphological phylogeny tree & 2D morphospace scatterplot.
- MetricCard.tsx / Sparkline.tsx — Lightweight SVG time-series visualizers.
Data flow
SimEngine (dedicated thread) → sim.step() → sim.snapshot() (lockless serialization) → HUB.broadcast → ws → CanvasRenderer + App state. Client → ControlMessage → apply_control → RT.config/RT.sim → DB law_changes. Events → DB.add_events + genealogy.
Data model & protocol
Entities (in-memory)
Creature(entities.py:95):id,x,y,angle,shapepolygon|line,sides,caste,radius,age,lifespan,stageinfant|juvenile|adult|elder,irregularity,health0–100,infected,sexmale|female,mother_id/father_id,clan_id/clan_color,sleeping/indoors,generation,born_tick,energy,statushungry/starving,meals.Food(entities.py:158):x,y,growth0–1.Corpse(entities.py:170):x,y,ttl,energy.House(entities.py:184):x,y,size,door_width/door_side/door_offset,clan_id/clan_color(settlement),is_ruin/abandoned_ticks,takeover_tick(last hostile takeover, §AT-3 render flash); ruin afterhouse_decay_ticks(config.py:113),settlement/ruin/takeoverevents.- Terrain:
fertile: [{x,y,r}],rocks: [{x,y,r}]in snapshot.
Wire schemas (protocol.py)
EntityState(protocol.py:27):id,kindcreature|food|house|corpse,x/y/angle, plus optional fields above.StateMessage(protocol.py:62):tick,seed,width/height/boundary,population,entities,clans,creatures_alive/creatures_dead/dead_by_cause,infected_count,time_of_day/day/season/weather,terrain_fertile/terrain_rocks,relations,events, plus periodic 1 Hzanalyticsframe (coalesced macro metrics).HistoryEvent(protocol.py:86):typedeath|birth|promotion|demotion|outbreak|recovery|bloom|alliance|rivalry|predation|war|ruin|settlement,tick,entity_id,caste,cause,x/y,payload(parents/sides/generation/clan_id etc).HelloMessage(protocol.py:99):seed,tick_rate,width/height/boundary.ControlMessage(protocol.py:22):actionpause|resume|step|reset|set_speed +value.
WebSocket flow
Server → client: {"type":"hello", ...} then {"type":"state", ...} each tick (with coalesced 1 Hz analytics frames for the Observatory). Client → server: {"action":"pause"|"resume"|"step"|"reset"|"set_speed", "value":...} (main.py).
Laws of the Sphere
Every law in GodLaws (protocol.py:108) with type/range/default. Set via POST /api/laws or presets.
| Law | Type | Range | Default | Hint + docs |
|---|---|---|---|---|
boundary | typing.typing.Literal'wrap', 'clamp' | — | wrap | World border topology: wrap (seamless toroidal loop) vs clamp (solid collision walls). md |
food_count | typing.int | ≥0, ≤2000 | 210 | Living food plants maintained across the world (summer ×1.2, winter ×0.5). md |
energy_max | typing.float | >1, ≤10000 | 100.0 | Maximum metabolic energy capacity an organism can store (10–500). md |
energy_decay_per_tick | typing.float | ≥0, ≤2 | 0.025 | Baseline metabolic burn rate per tick without food (0.025). md |
energy_from_food | typing.float | ≥0, ≤1000 | 32.0 | Base energy yield from harvesting a mature plant (berry 48, grass 32, mushroom 24, poison 8). md |
plant_variants_enabled | typing.bool | — | True | Master switch enabling botanical biodiversity across 6 distinct functional plant species. md |
plant_growth_rate | typing.float | ≥0, ≤1 | 0.05 | How fast sprouted plants mature into harvestable food (0.045). md |
plant_spread_rate | typing.float | ≥0, ≤1 | 0.006 | Probability per tick that a mature plant drops seeds into adjacent fertile ground (0.006). md |
nutrient_cycle_rate | typing.float | ≥0, ≤10 | 0.65 | Acceleration of plant growth near decomposing corpses (0.65) — death nourishes new life. md |
poison_rate | typing.float | ≥0, ≤1 | 0.01 | Probability a new wild sprout is poisonous (-30 HP damage on ingestion). md |
food_decay_enabled | typing.bool | — | True | Enables mature plants to naturally wither over time and fertilize the living soil. md |
food_lifespan_ticks | typing.int | ≥100, ≤1000000 | 9000 | Ticks a mature plant lives before naturally withering into the living soil grid (8000). md |
agriculture_enabled | typing.bool | — | True | Enables seed gathering, cultivated farm plots (2× growth, 2.5× yield), irrigation furrows, and tending. md |
granaries_enabled | typing.bool | — | True | Enables communal settlement granaries to stockpile grain and berries against winter. md |
granary_capacity | typing.float | ≥0, ≤100000 | 400.0 | Units of food a settlement granary can store (400) — feasts fire at ≥80% capacity. md |
perceive_radius | typing.float | >0.5, ≤60 | 20.0 | Base perception sight radius (16) — scaled by caste (Woman 0.8×, Priest 1.35×), night (0.6×), and fog (0.6×). md |
eat_radius | typing.float | >0.1, ≤10 | 1.4 | Physical contact distance required to consume a plant, corpse, or prey item (1.4). md |
hungry_ratio | typing.float | >0, ≤1 | 0.35 | Energy threshold (≤35%) feeding normalized energy into neural network input slot 0 to trigger foraging. md |
starving_ratio | typing.float | >0, ≤1 | 0.15 | Severe energy threshold (≤15%) triggering desperation sprint and pulsing survival distress. md |
steer_turn | typing.float | ≥0, ≤3.2 | 0.45 | Maximum heading angular turn agility per tick, scaled by creature moment of inertia Izz. md |
birth_enabled | typing.bool | — | True | Master switch enabling reproduction, mating, and generational ascendance. md |
lifespan_mult | typing.float | ≥0.01, ≤100 | 1.0 | Multiplier scaling all caste lifespans (Woman: 4,800 ticks → Priest: 9,000 ticks). md |
adult_age | typing.float | ≥0, ≤100000 | 600.0 | Ticks required for an infant/juvenile to mature into a sexually fertile adult (220). md |
birth_rate | typing.float | ≥0, ≤1 | 0.05 | Base reproduction probability per eligible adult mating pair per tick (0.28). md |
carrying_capacity | typing.int | ≥-1, ≤10000 | -1 | Population density threshold above which fertility gradually fades (-1 = auto). md |
max_population | typing.int | ≥-1, ≤15000 | -1 | Hard global population cap preventing any new births until density declines (-1 = auto). md |
mutation_rate | typing.float | ≥0, ≤1 | 0.05 | Probability a newborn son deviates ±1 side from classical caste inheritance (0.05). md |
mutation_heritability | typing.float | ≥0, ≤1 | 0.35 | — |
sex_ratio | typing.float | ≥0, ≤1 | 0.5 | Probability a newborn child is a son (ascending polygon) vs daughter (agile line) (0.50). md |
max_sides | typing.int | ≥3, ≤64 | 24 | Upper limit on regular polygon vertex ascendance (up to Priest / Circle status) (24). md |
euthanasia_threshold | typing.float | ≥0, ≤1 | 0.7 | Irregularity threshold; deformed infants exceeding this are consumed at adulthood (0.70). md |
mutation_sigma | typing.float | ≥0, ≤1 | 0.08 | Gaussian mutation standard deviation (σ) applied to genome weights during crossover (0.08). md |
crossover_rate | typing.float | ≥0, ≤1 | 0.5 | Probability of uniform 50/50 parental genome blending during sexual reproduction (0.50). md |
morphology_annealing_enabled | typing.bool | — | True | Master switch for geometric physics — polar (r,φ) annealing, SAT polygon collision, and trait baking. md |
annealing_start_generation | typing.int | ≥0, ≤1000 | 15 | — |
annealing_decay_generations | typing.int | ≥1, ≤5000 | 250 | Generations over which polar morphology annealing decays from Abbott templates to free evolution (150). md |
morph_lambda_override | typing.float | ≥-1.0, ≤1.0 | None | — |
vertex_mutation_std | typing.float | ≥0, ≤0.5 | 0.025 | — |
angle_mutation_std | typing.float | ≥0, ≤0.5 | 0.012 | — |
topological_mutation_rate | typing.float | ≥0, ≤0.2 | 0.008 | — |
safeguard_enabled | typing.bool | — | True | — |
safeguard_critical_pop | typing.int | ≥2, ≤50 | 12 | — |
safeguard_relief_ratio | typing.float | ≥0.05, ≤0.5 | 0.3 | — |
safeguard_genesis_batch | typing.int | ≥1, ≤20 | 6 | — |
safeguard_morph_mercy | typing.bool | — | True | — |
safeguard_max_miracles | typing.int | ≥1 | 1 | — |
soft_cap_enabled | typing.bool | — | True | — |
damping_steepness | typing.float | ≥1.0, ≤20.0 | 12.0 | — |
crowding_stress_mult | typing.float | ≥0.0, ≤1.0 | 1.0 | — |
resource_strain_mult | typing.float | ≥0.0, ≤2.0 | 2.0 | — |
boom_ramp_days | typing.float | ≥0, ≤100 | 1.2 | — |
boom_birth_floor | typing.float | ≥0, ≤1.0 | 0.4 | — |
boom_cooldown_mult | typing.float | ≥1.0, ≤10.0 | 1.0 | — |
boom_energy_mult | typing.float | ≥1.0, ≤10.0 | 1.0 | — |
initial_season_offset | typing.int | ≥0, ≤3 | 0 | — |
disease_enabled | typing.bool | — | True | Master switch for infectious pathogen outbreaks and contagion transmission. md |
disease_outbreak_rate | typing.float | ≥0, ≤1 | 6e-05 | Spontaneous plague outbreak probability per tick during crowded conditions (0.00006). md |
disease_rate | typing.float | ≥0, ≤1 | 0.035 | Contagion transmission probability per tick within contact range (0.035). md |
disease_energy_drain | typing.float | ≥0, ≤10 | 0.05 | Metabolic energy drained per tick from actively infected creatures (0.05). md |
disease_lethality | typing.float | ≥0, ≤1 | 0.18 | Direct health (HP) damage dealt per tick to actively diseased creatures (0.18). md |
weather_enabled | typing.bool | — | True | Master switch for dynamic meteorological cycles (sun, rain, fog, storms). md |
sleep_enabled | typing.bool | — | True | Enables diurnal sleep cycles, house resting, and oral lore transfer after dark. md |
day_length | typing.int | ≥2, ≤200000 | 1200 | Total duration in ticks of a single diurnal day/night cycle (1200). md |
season_length | typing.int | ≥2, ≤1000000 | 14400 | Duration in ticks of each season (Spring, Summer, Autumn, Winter) (12000). md |
winter_food_mult | typing.float | ≥0.1, ≤2 | 0.5 | Winter seasonal food abundance multiplier (0.70 gentle, 0.50 harsh, 0.30 extinction). md |
night_sight_mult | typing.float | ≥0.05, ≤2 | 0.6 | Perception radius multiplier during night ticks for non-nocturnal castes (0.60). md |
weather_change_rate | typing.float | ≥0, ≤1 | 0.002 | Frequency of meteorological transitions between clear, rain, fog, and storm (0.002). md |
weather_sickness_enabled | typing.bool | — | False | Enables exposure chill and hypothermia when caught unsheltered in wet or freezing weather. md |
chill_drain | typing.float | ≥0, ≤5 | 0.18 | Direct health drain per tick when chilled outdoors without shelter (0.18). md |
shelter_enabled | typing.bool | — | True | Master switch for house claiming, door navigation, and roof protection. md |
exposure_drain | typing.float | ≥0, ≤10 | 0.03 | Health and energy drain per tick when outdoors during harsh weather (0.025). md |
house_capacity | typing.int | ≥1, ≤64 | 12 | Bed capacity inside a settlement hall (12); excess members sleep outdoors. md |
house_decay_ticks | typing.int | ≥100, ≤100000 | 2400 | Ticks before an abandoned, roofless house crumbles into ruins (10000). md |
rest_recovery_mult | typing.float | ≥0, ≤10 | 2.0 | Health regeneration multiplier when sleeping indoors under a roof (2.0). md |
territory_enabled | typing.bool | — | True | Enables clan boundary markings, territory defence, and trespass penalties. md |
territory_radius | typing.float | ≥1, ≤50 | 14.0 | Radius of clan territorial influence around settlement houses (16). md |
trespass_decay | typing.float | ≥0, ≤5 | 0.25 | Diplomatic relation points lost per tick when a rival clan enters marked territory (0.15). md |
max_clans | typing.int | ≥-1, ≤64 | -1 | Maximum number of sovereign clans spawned during world initialization (-1 = auto). md |
totems_enabled | typing.bool | — | True | Enables Sacred Avatar totem blessings for each clan settlement. md |
succession_enabled | typing.bool | — | True | Enables dynamic governance leadership transfers on chieftain death. md |
communication_enabled | typing.bool | — | True | Enables vocalizations, alarm chirps, peace hums, and emotional thought bubbles. md |
knowledge_enabled | typing.bool | — | True | Enables spatial memory, waypoint mapping, and rumor broadcasting among kin. md |
schism_enabled | typing.bool | — | True | Enables internal clan fractures when members starve or lack shelter. md |
schism_threshold | typing.float | ≥0, ≤1 | 0.5 | Dissatisfaction fraction (hunger, homelessness) triggering a factional clan schism (0.40). md |
war_enabled | typing.bool | — | True | Enables inter-clan warfare, tactical raids, and territorial conquest. md |
attack_damage | typing.float | ≥0, ≤1000 | 30.0 | Base damage dealt by soldiers and warriors in inter-clan battles (32.0). md |
predation_enabled | typing.bool | — | False | Enables carnivorous predator-prey ecology and hunting dynamics. md |
predator_ratio | typing.float | ≥0, ≤1 | 0.0 | Fraction of population spawned as predatory carnivores hunting prey (0.02). md |
hunt_radius | typing.float | ≥1, ≤40 | 8.0 | Aggro detection radius within which carnivores and war parties acquire targets (16.0). md |
bite_damage | typing.float | ≥0, ≤1000 | 28.0 | Combat damage dealt per carnivore attack or predatory strike (28.0). md |
energy_from_prey | typing.float | ≥0, ≤1000 | 40.0 | Caloric energy extracted from slaying and eating a prey creature (45.0). md |
fear_radius | typing.float | ≥1, ≤40 | 12.0 | Distance at which herbivores and vulnerable castes detect threats and execute evasion (12.0). md |
coalitions_enabled | typing.bool | — | True | Enables mutual defensive alliances and diplomatic treaties between friendly clans. md |
coalition_threshold | typing.int | ≥-100, ≤100 | 40 | Diplomatic trust score required for two friendly clans to form a defensive coalition (40). md |
leader_decisions_enabled | typing.bool | — | True | Enables chieftain governance bylaws (rationing, martial law, war declarations). md |
resource_sharing_enabled | typing.bool | — | True | Enables communal settlement larders and altruistic basket food sharing. md |
larder_capacity | typing.float | ≥0, ≤5000 | 300.0 | Energy capacity of settlement communal food stores where surplus is shared (300). md |
cannibalism_enabled | typing.bool | — | True | Enables desperate consumption of the living during extreme starvation. md |
eat_kin_enabled | typing.bool | — | True | Allows consumption of deceased or weak clanmates at the cost of tribal exile and feuds. md |
cannibalism_energy | typing.float | ≥0, ≤1000 | 35.0 | Energy gained by starving creatures resorting to eating fallen kin or rivals (45.0). md |
theology_enabled | typing.bool | — | True | Enables the 8 Sacred Avatars, shrines, temples, miracles, and divine tithes. md |
tithe_rate | typing.float | ≥0, ≤1 | 0.04 | Fraction of energy devout worshippers offer at shrines each dawn & dusk to build clan faith (0.04). md |
temple_faith_cost | typing.float | ≥0, ≤100000 | 400.0 | Faith points required to consecrate a glowing Temple of the Sphere (400.0). md |
age_enabled | typing.bool | — | True | Enables historical epoch progression (Golden Age, Ice Age, Age of Chaos, Age of Plague). md |
age_length | typing.int | ≥100, ≤1000000 | 12000 | Duration in ticks per world historical epoch (50000). md |
culture_enabled | typing.bool | — | True | Enables traditions, governance archetypes, and cultural diffusion. md |
culture_spread_rate | typing.float | ≥0, ≤1 | 0.005 | Rate at which allied clans sharing borders adopt common cultural traits and beliefs (0.0005). md |
rivers_enabled | typing.bool | — | True | Enables water channels, fords, water currents, bridges, and dams. md |
river_count | typing.int | ≥0, ≤8 | 2 | Number of procedural river channels carved across the terrain at world generation (2). md |
relief_enabled | typing.bool | — | True | Enables topographical elevation, slope inertia, cliffs, and road packing. md |
structural_enabled | typing.bool | — | True | Enables weather wear on buildings, builder repairs, and roof collapse into rubble. md |
earthquake_enabled | typing.bool | — | False | Enables seismic tremors that shake terrain and damage weakened structures. md |
earthquake_rate | typing.float | ≥0, ≤0.01 | 8e-05 | Frequency of seismic quakes that crack buildings and shake terrain (0.00008). md |
lightning_enabled | typing.bool | — | True | Enables real lightning strikes during storms that ignite fires and damage creatures. md |
lightning_strike_rate | typing.float | ≥0, ≤0.05 | 0.0015 | Frequency of deadly electrical arc strikes during thunder storms (0.0015). md |
wildfire_enabled | typing.bool | — | True | Enables combustive flame propagation across dense vegetation and forests. md |
fire_rate | typing.float | ≥0, ≤0.05 | 8e-05 | Probability per tick that a mature plant ignites during dry spells or lightning strikes (0.00008). md |
disaster_enabled | typing.bool | — | True | Enables cataclysmic meteors, floods, and natural world disturbances. md |
disaster_rate | typing.float | ≥0, ≤0.05 | 4e-05 | Stochastic probability of catastrophic environmental disasters (0.0003). md |
anomaly_count | typing.int | ≥0, ≤8 | 3 | Number of mysterious spatial anomaly zones altering local physics (3). md |
door_clearance | typing.float | ≥1, ≤5 | 1.5 | Width multiplier for house doorways relative to the largest creature size (1.5). md |
house_min_size | typing.float | ≥3, ≤60 | 5.5 | — |
house_max_size | typing.float | ≥3, ≤80 | 8.0 | — |
aid_rate | typing.float | ≥0, ≤1 | 0.05 | — |
alarm_call_rate | typing.float | ≥0, ≤1 | 0.12 | — |
alignment_weight | typing.float | ≥0, ≤10 | 0.0 | — |
alliance_threshold | typing.int | ≥-100, ≤100 | 50 | — |
attack_radius | typing.float | ≥0, ≤10 | 1.8 | — |
banquets_enabled | typing.bool | — | True | — |
beast_ratio | typing.float | ≥0, ≤1 | 0.0 | — |
betrayal_enabled | typing.bool | — | True | — |
birth_energy_cost | typing.float | ≥0, ≤1000 | 20.0 | — |
bite_cooldown | typing.int | ≥0, ≤1000 | 15 | — |
cannibalism_hunger_ratio | typing.float | ≥0, ≤1 | 0.08 | — |
chill_rate | typing.float | ≥0, ≤10 | 0.04 | — |
chill_threshold | typing.float | ≥0, ≤1000 | 12.0 | — |
coalition_min_size | typing.int | ≥1, ≤100 | 2 | — |
cohesion_weight | typing.float | ≥0, ≤10 | 0.0 | — |
corpse_energy | typing.float | ≥0, ≤1000 | 25.0 | — |
corpse_ttl | typing.int | ≥0, ≤100000 | 600 | — |
corpses_enabled | typing.bool | — | True | — |
creature_density | typing.float | ≥0, ≤10 | 0.0013 | — |
defection_enabled | typing.bool | — | True | — |
defense_weight | typing.float | ≥0, ≤10 | 0.5 | — |
desperate_perceive_mult | typing.float | ≥1, ≤10 | 1.6 | — |
desperate_speed_mult | typing.float | ≥1, ≤10 | 1.35 | — |
dialect_drift_enabled | typing.bool | — | True | — |
diet_strictness | typing.float | ≥0, ≤1 | 0.0 | — |
disease_radius | typing.float | ≥0, ≤100 | 3.0 | — |
eat_enemy_enabled | typing.bool | — | True | — |
energy_start | typing.float | ≥0, ≤1000 | 85.0 | — |
envoys_enabled | typing.bool | — | True | — |
exile_on_kin_eat | typing.bool | — | True | — |
fertile_food_bias | typing.float | ≥0, ≤10 | 0.7 | — |
fertile_patches | typing.int | ≥-1, ≤1000 | -1 | — |
fire_spread_rate | typing.float | ≥0, ≤10 | 0.035 | — |
flock_radius | typing.float | ≥0, ≤100 | 6.0 | — |
fog_mushroom_mult | typing.float | ≥0, ≤10 | 1.35 | — |
fog_sight_mult | typing.float | ≥0, ≤10 | 0.6 | — |
food_call_rate | typing.float | ≥0, ≤1 | 0.08 | — |
food_giveup_ticks | typing.int | ≥0, ≤100000 | 240 | — |
hearths_enabled | typing.bool | — | True | — |
height | typing.float | ≥10, ≤10000 | 300.0 | — |
help_call_enabled | typing.bool | — | True | — |
help_radius | typing.float | ≥0, ≤100 | 12.0 | — |
history_max | typing.int | ≥0, ≤1000000 | 200 | — |
house_claim_enabled | typing.bool | — | True | — |
house_density | typing.float | ≥0, ≤1 | 0.00065 | — |
house_gap | typing.float | ≥0, ≤100 | 6.0 | — |
hungry_perceive_mult | typing.float | ≥1, ≤10 | 1.3 | — |
kin_stigma | typing.float | ≥0, ≤1000 | 40 | — |
knowledge_share_rate | typing.float | ≥0, ≤1 | 0.05 | — |
knowledge_ttl | typing.int | ≥0, ≤1000000 | 600 | — |
markets_enabled | typing.bool | — | True | — |
mate_energy_min | typing.float | ≥0, ≤1000 | 30.0 | — |
mate_radius | typing.float | ≥0, ≤100 | 10.0 | — |
nn_inference_hz | typing.int | ≥1, ≤1000 | 15 | — |
num_hexagons | typing.int | ≥-1, ≤100 | -1 | — |
num_houses | typing.int | ≥-1, ≤100 | -1 | — |
num_pentagons | typing.int | ≥-1, ≤100 | -1 | — |
num_priests | typing.int | ≥-1, ≤100 | -1 | — |
num_squares | typing.int | ≥-1, ≤100 | -1 | — |
num_triangles | typing.int | ≥-1, ≤100 | -1 | — |
num_women | typing.int | ≥-1, ≤100 | -1 | — |
omens_enabled | typing.bool | — | True | — |
omp_enabled | typing.bool | — | True | — |
omp_threshold | typing.int | ≥0, ≤10000 | 100 | — |
rain_growth_mult | typing.float | ≥0, ≤10 | 1.25 | — |
rain_speed_mult | typing.float | ≥0, ≤10 | 0.85 | — |
recovery_rate | typing.float | ≥0, ≤1 | 0.03 | — |
relation_drift_rate | typing.float | ≥0, ≤10 | 2.2 | — |
reproduction_cooldown | typing.int | ≥0, ≤100000 | 600 | — |
rivalry_threshold | typing.int | ≥-100, ≤100 | -75 | — |
rock_count | typing.int | ≥-1, ≤1000 | -1 | — |
rubble_blocking_enabled | typing.bool | — | True | — |
scent_enabled | typing.bool | — | True | — |
schism_min_pop | typing.int | ≥1, ≤1000 | 6 | — |
seed | typing.int | ≥0 | 42 | — |
separation_weight | typing.float | ≥0, ≤10 | 0.0 | — |
signal_radius | typing.float | ≥0, ≤100 | 12.0 | — |
signal_speed | typing.float | ≥0, ≤100 | 8.0 | — |
sleep_energy_mult | typing.float | ≥0, ≤10 | 0.5 | — |
soil_depletion_enabled | typing.bool | — | True | — |
spawn_variance | typing.float | ≥0, ≤100 | 0.25 | — |
storm_plant_damage | typing.float | ≥0, ≤10 | 0.02 | — |
storm_wander_bonus | typing.float | ≥0, ≤10 | 0.35 | — |
tick_rate | typing.float | ≥0.1, ≤1000 | 10.0 | — |
trait_mutation_rate | typing.float | ≥0, ≤1 | 0.02 | — |
tribute_enabled | typing.bool | — | True | — |
vocalizations_enabled | typing.bool | — | True | — |
wander_turn | typing.float | ≥0, ≤10 | 0.35 | — |
wet_disease_mult | typing.float | ≥0, ≤10 | 1.5 | — |
width | typing.float | ≥10, ≤10000 | 400.0 | — |
Presets — one-click worlds
Sustainable is the 1000-day gentle world. Apply via The Sphere panel or POST /api/presets/{name}?reset.
| Preset | Key laws | Apply |
|---|---|---|
balance ACTIVE | boundary=wrap, door_clearance=1.5, food_count=380, plant_growth_rate=0.065, plant_spread_rate=0.008, nutrient_cycle_rate=0.65 … +179 more | Via the app UI or TUI |
sustainable | boundary=wrap, door_clearance=1.5, food_count=550, plant_growth_rate=0.08, plant_spread_rate=0.01, nutrient_cycle_rate=0.85 … +179 more | Via the app UI or TUI |
chaos | boundary=wrap, door_clearance=1.5, food_count=320, plant_growth_rate=0.045, plant_spread_rate=0.006, nutrient_cycle_rate=0.65 … +179 more | Via the app UI or TUI |
extinction | boundary=wrap, door_clearance=1.5, food_count=120, plant_growth_rate=0.025, plant_spread_rate=0.003, nutrient_cycle_rate=0.5 … +179 more | Via the app UI or TUI |
boom | boundary=wrap, door_clearance=1.5, food_count=440, plant_growth_rate=0.06, plant_spread_rate=0.012, nutrient_cycle_rate=0.85 … +179 more | Via the app UI or TUI |
theocracy | boundary=wrap, door_clearance=1.5, food_count=400, plant_growth_rate=0.055, plant_spread_rate=0.007, nutrient_cycle_rate=0.7 … +179 more | Via the app UI or TUI |
warlords | boundary=wrap, door_clearance=1.5, food_count=340, plant_growth_rate=0.05, plant_spread_rate=0.006, nutrient_cycle_rate=0.65 … +179 more | Via the app UI or TUI |
API reference
Live routes from app.routes + Swagger at /docs. Try curl examples below.
| Route | Name |
|---|---|
/ws | |
GET /api/analytics/hegemony | get_analytics_hegemony |
GET /api/analytics/summary | get_analytics_summary |
GET /api/analytics/timeseries | get_analytics_timeseries |
GET /api/analytics/trophic | get_analytics_trophic |
GET /api/analytics/warnings | get_analytics_warnings |
GET /api/annals | get_annals |
GET /api/auth/status | auth_status |
GET /api/clan/{clan_id}/biography | get_clan_biography |
GET /api/clans/{clan_id}/history | get_clan_history |
GET /api/clans/{clan_id} | get_clan |
GET /api/clans | get_clans |
GET /api/config | get_config |
GET /api/creature/{creature_id} | get_creature |
GET /api/history/summary | get_history_summary |
GET /api/history | get_history |
GET /api/laws | read_laws |
GET /api/metrics/damping | get_damping_metrics |
GET /api/metrics/morphology | get_morphology_metrics |
GET /api/metrics/safeguards | get_safeguards_metrics |
GET /api/perf/telemetry | get_telemetry |
GET /api/presets | list_presets |
GET /api/state | get_state |
GET /api/version | get_version |
GET /api/wiki | get_wiki_json |
GET /api/worlds | get_worlds |
GET /guide | get_guide |
GET /health.html | health_dashboard |
GET /health | health_dashboard |
GET /healthz | healthz |
GET /robots.txt | get_robots_txt |
GET /sitemap.xml | get_sitemap_xml |
GET /wiki | get_wiki |
POST /api/auth/setup | auth_setup |
POST /api/control | post_control |
POST /api/laws | write_laws |
POST /api/presets/{name} | apply_preset |
Curl playground
# laws
curl localhost:8000/api/laws
curl -X POST localhost:8000/api/laws -H 'content-type: application/json' -d '{"food_count": 90}'
# presets (1000-day one click)
curl -X POST localhost:8000/api/presets/sustainable?reset=true
curl -X POST localhost:8000/api/presets/chaos
curl -X POST localhost:8000/api/presets/extinction?reset=true
# state & history
curl localhost:8000/api/state | jq .tick
curl localhost:8000/api/history?limit=5 | jq
curl localhost:8000/api/worlds | jq
curl localhost:8000/api/clans | jq
# control
curl -X POST localhost:8000/api/control -H 'content-type: application/json' -d '{"action":"pause"}'
curl -X POST localhost:8000/api/control -d '{"action":"reset"}'
# websocket (live)
# ws://localhost:8000/ws → {"type":"hello"} then {"type":"state"} throttled ~30Hz
# send {"action":"pause"} / {"action":"set_speed","value":20}
Configuration & ops
Env vars (FLATWORLD_*)
| Variable | Default | Description |
|---|---|---|
| FLATWORLD_WIDTH | 400 | World width (grid units) |
| FLATWORLD_HEIGHT | 300 | World height |
| FLATWORLD_BOUNDARY | wrap | wrap or clamp |
| FLATWORLD_SEED | 42 | RNG seed |
| FLATWORLD_TICK_RATE | 10 | Ticks per second |
| FLATWORLD_DB | backend/flatworld.db | SQLite path |
| FLATWORLD_GOD_KEY | — | Seed/override the god passkey at boot |
God passkey (auth)
POST /api/laws, POST /api/presets/{name}, POST /api/control and WebSocket control messages need the god passkey (X-God-Key header, key field on the socket). No credential yet → any god call answers 409 and the web UI asks to create one (POST /api/auth/setup). Lost it? Recover on the server only: cd backend && uv run python -m app.godkey reset <new> (or clear). The TUI takes no prompt: ./run.sh tui ws://host/ws <passkey> or export FLATWORLD_GOD_KEY. Only a PBKDF2 hash is stored.
Persistence (db.py:20)
SQLite flatworld.db (WAL, thread lock). Tables:
worlds(id, seed, width, height, boundary, started_at, ended_at)events(id, world_id, tick, type, entity_id, caste, cause, x, y, payload, created_at)law_changes(id, world_id, tick, name, value, created_at)creatures(id, world_id, entity_id, caste, clan_id, generation, mother_id, father_id, born_tick, died_tick)snapshots(id, world_id, tick, payload, created_at)
History survives restarts; reset closes old world row and opens new.
Concurrency stance & SimEngine
The simulation core is strictly deterministic (one seeded RNG stream, one fixed tick order). Run uvicorn with 1 worker (more workers = several disconnected worlds, not a faster one). Under SimEngine (main.py:446), simulation advancement runs on its own dedicated background OS thread. State stepping occurs under RT.lock while JSON snapshot serialization runs outside the lock (advance_world_lockless), so heavy state dumps and WebSocket broadcasts never block REST endpoints or hold the GIL. Key operational & diagnostic endpoints:
GET /healthz— Live server health, current TPS, memory usage, uptime, and active WebSocket client count.GET /api/perf/telemetry— Rolling telemetry rings: tick duration, lock wait time, and broadcast latencies.GET /api/analytics/summary— High-level macro demographics, biomass, and trophic distribution.
Run & deploy
./run.sh
# or
cd backend && uv run uvicorn app.main:app --reload --port 8000
cd frontend && npm run dev
Tests
cd backend && uv run pytest -q
cd backend && uv run pytest tests/test_synergies.py -q
Roadmap
See TODO.md (active) + docs/roadmap-archive.md (completed) — 13 sections + 213 laws + 42 routes + 7 presets. Wiki extends Guide with presets, sustainability & playground.
Generated from live code — Config defaults + GodLaws + app.routes. Official living documentation & encyclopedia for Flatland. · Developed by Long Phan — [email protected] · Demo: Demo ↗ · Landing: Landing ↗ · GitHub: flws / flws-web · Built with OpenCode & Antigravity