# World Simulation A browser-based world simulation with a Rust server and a Leptos/Wasm UI. The server runs the simulation and exposes its state over HTTP and WebSockets. You can edit terrain and resources, manage people and animals, and customize agent behavior with the included Rune script. Every person, rabbit, wolf, and partnership is a Picard actor that owns its state and applies its own rules: people age, get hungry, eat, and starve; animals spend and gain energy, breed, and die; partnerships track when they last had a child. The world keeps only world-level state (terrain, resources, the shared stockpile, houses, and the calendar) and talks to entities exclusively through messages: each step it asks the actors for their state, decides movement and opportunities with the Rune behavior scripts, and sends the actors the outcome. Behavior decisions stay on the simulation thread because Rune's VM is not `Send`, and replies are processed in entity order so runs stay deterministic. Picard's tracing and runtime statistics features are enabled: actor lifecycle events are logged (configure verbosity with `RUST_LOG`, for example `RUST_LOG=picard=trace`), and cumulative actor/message counters are shown in the UI. ## Cluster The world is split into vertical strips of columns called shards. Each shard is a separate process with its own Picard actor system and its own database. `sim` starts as a gateway: by default, it spawns `SIM_SHARDS` (default 3) copies of itself with the `shard` subcommand; when `SIM_SHARD_ADDRS` is set, it connects to externally managed shards instead. The gateway steps shards in lockstep and merges their views so the UI sees one world. Edits from the UI are routed to the shard that owns them. People, animals and carts that cross a shard border are migrated with their whole state and inventory into the neighbouring shard's Picard actor system. A cluster-wide directory maps each entity address to its current shard and actor path, so world messages continue to reach it after migration without actor-owned forwarding timers or transfer messages. Shards connect directly through Picard's authenticated remoting endpoint (`/remoting`); the gateway continues to use `/control` for simulation coordination. The gateway generates a shared token when it launches shard processes; external shard deployments supply the same `SIM_CLUSTER_TOKEN` to the gateway and every shard. ## Public access Clients outside localhost can view the simulation but cannot edit it: the UI hides editing controls, and the server rejects remote write requests and WebSocket edit commands. When exposing the app through a reverse proxy, keep the published port bound to host loopback and ensure the proxy sets `X-Forwarded-For` or `X-Real-IP`. Compose enables `SIM_TRUST_PROXY_HEADERS=1` for this setup. Docker-host requests to `localhost` remain editable, while forwarded requests are classified by their client IP. ## Economy Every shard founds markets and workplaces: farms, woodcutters, quarries, hunters, toolmakers and cartwrights. Adults are hired, commute to their job site each day, work their shift, sell the goods at a market, get paid and go home. Farmers sow fields that ripen into crops; gatherers fell trees, quarry stone and hunt; crafters buy materials and make tools and carts. Markets are actors with their own coins and stock; prices follow supply and demand, and buyers and sellers haggle. Merchants carry surplus goods to markets on other shards. Markets, workplaces, carts and crop fields are drawn on the map, and the side panel shows each person's job and coins. ## Actor Console The server enables Picard's console by default and exposes its JSON request/response protocol over `ws://127.0.0.1:7878/api/actors/ws`. The connection reaches shard 0; use `?shard=N` to connect to shard `N`. Every shard registers the others as console peers named `shard-N`: `peers` lists them, `@shard-1 actors` forwards a command, and `send @shard-1 PATH JSON` sends a message to a remote actor through Picard remoting. Send one JSON request per text frame; each receives one response. For example, `{"id":1,"op":"actors"}` lists actors, and `{"id":2,"op":"inspect","path":"/user/person-1"}` inspects one (actors are named `person-`, `rabbit-`, `wolf-`, and `partnership-`). Other operations include `messages`, `pause`, `resume`, `clear`, `stop`, `restart`, and `send`. Console requests are handled by the selected shard's Picard console. `cargo run --no-default-features` disables the endpoint; `--features console` enables it explicitly. The simulation script is the root [config.rn](./config.rn), a single Rune file. Its `pub const` items hold defaults and tuning values: map dimensions and terrain generation, initial population and resources, calendar and life-stage defaults, hunger, gathering, construction, partnerships and births, animal behavior, and edit limits. Its `pub fn person`, `pub fn rabbit`, and `pub fn wolf` items are the agent behaviours, and they can use the constants directly. Every constant the server reads must be defined; missing or invalid values are reported at startup. `SIM_CONFIG` can point to a different Rune file. Docker Compose mounts the repository's `config.rn` read-only into the gateway and each shard container. The in-browser script editor edits the same file contents. Applied edits take effect immediately for behaviours and tuning values, while map dimensions, initial population, and calendar defaults apply when the world is reset. Editor changes are not written back to disk: on restart, `config.rn` from disk replaces them, even when a saved world snapshot is restored. The **Calendar and life-stage durations** panel configures ticks per day and the number of days, weeks, and months in larger calendar units. Each human life stage has an inclusive minimum/maximum duration in in-game days; the world samples within that range when a person enters the stage. These runtime settings are stored with the world snapshot and take precedence over the config defaults until the world is reset. New people, including babies, start as toddlers and age through child, teen, young adult, adult, older adult, elderly, and death. By default, the 192×128 world starts with 180 people (60 of them young adults), 1200 rabbits, 80 wolves and 1200 food, shared between the shards. People pathfind around blocked terrain when travelling home for food. Unpartnered people from young adulthood onward can form a single partnership with a nearby eligible person. Each partnership can have one toddler per calendar week when both partners are in stages marked fertile, the stockpile has enough food, and housing capacity permits it. By default, the village has capacity for 12 people, with each additional house increasing capacity by three; these values are configurable. Young adult and adult stages are fertile by default; fertility can be changed per stage in the calendar panel. Partnerships, markets, workplaces and carts are Picard actors as well as people and animals. The UI is built automatically as part of `cargo run` and embedded in the server binary. There is no separate manual UI build step. ## Getting Started ### Local run with SQLite Install Rust with `rustup`. The build script installs the `wasm32-unknown-unknown` target if it is missing. Start locally with SQLite using: ```sh just dev ``` Open [http://127.0.0.1:7878](http://127.0.0.1:7878). Each shard keeps a SQLite database `sim-shard-N.db` in the current directory, and the initial seed is `42`. You can also run directly with `cargo run`. To choose a seed on the first run: ```sh cargo run -- 123 ``` Existing shard snapshots take precedence on later runs, including over a new command-line seed. If the shards' snapshots don't match (for example after changing `SIM_SHARDS`), all shards start fresh. Use the UI's **Reset** button to start a fresh world with its current seed, or **Regenerate** to choose a different seed. ### Run with Just Install [Just](https://just.systems/), then list the project recipes: ```sh just ``` Useful recipes: ```sh just run # Build images, then recreate the gateway and SQLite shards just stop # Stop Compose services; keep shard data volumes just dev # Run locally with SQLite ``` ### Run with Docker Compose and SQLite shards Install Docker with the Compose plugin, then run `just run`. It builds the images while the current stack is still running, then asks Compose to recreate changed services and remove obsolete service containers. This minimizes downtime by keeping the build outside the service interruption. The stack consists of one gateway container and three shard containers; each shard stores its snapshot in its own SQLite database and persistent volume. You can also use the equivalent Docker commands directly: ```sh docker compose build docker compose up -d --remove-orphans ``` Open [http://localhost:7878](http://localhost:7878). The `shard_0_data`, `shard_1_data`, and `shard_2_data` volumes survive container restarts, `just stop`, and `docker compose down`. Compose now uses SQLite instead of Postgres. Existing Postgres snapshots are not migrated; the old Postgres volume is left untouched, and the SQLite shards start fresh. To remove all shard volumes and saved simulation data as well: ```sh docker compose down -v ``` ## Database Configuration Each shard selects its database through `SHARD_DATABASE_URL`. `{shard}` in the URL is replaced with the shard index and is required when there is more than one shard: | Backend | Example URL | | ---------------- | ------------------------------------------------- | | SQLite (default) | `sqlite://sim-shard-{shard}.db?mode=rwc` | | Postgres | `postgres://USER:PASSWORD@localhost:5432/sim_shard_{shard}` | For example, run locally against a reachable Postgres server that has the shard databases with: ```sh SHARD_DATABASE_URL='postgres://USER:PASSWORD@localhost:5432/sim_shard_{shard}' cargo run ``` Every shard saves its part of the world as a snapshot about once per second and restores it at startup. Compose uses a separate SQLite database and volume for each shard; Postgres remains available for deployments that configure it explicitly. `SIM_SHARDS` sets the number of shards (default 3). `SIM_SHARD_ADDRS` optionally provides comma-separated shard control addresses in index order; set `SIM_CLUSTER_TOKEN` to the same cluster token on the gateway and every external shard. `SIM_ADDR` sets the gateway's listen address. It defaults to `127.0.0.1:7878`; containers set it to `0.0.0.0:7878`. ## Project Layout - `src/world.rs` contains the simulation and snapshot serialization; `src/world/` holds the actors, shard routing and economy. - `src/main.rs` runs the gateway's Axum server and HTTP/WebSocket API, and the `shard` subcommand. - `src/cluster/` contains the gateway, the shard node, the inter-shard transport and the control protocol. - `src/storage.rs` provides SQLite and Postgres snapshot storage. - `config.rn` is the Rune simulation script: `pub const` defaults and tuning values plus `pub fn` behaviours. - `ui/` contains the Leptos frontend, compiled to Wasm by `build.rs`. - `Dockerfile`, `compose.yaml`, and `Justfile` provide container and developer workflows. ## Tests Run the server tests with: ```sh cargo test --workspace --no-default-features ``` `tests/cluster.rs` starts a real multi-process cluster.