Files
Emil c7e86663d8
MVP checks / mvp (push) Canceled after 0s
Expand voxel gameplay, lighting, full-height streaming and world imports
Add shared Rust/WASM physics, worker meshing and diagnostics, 64-chunk full-height streaming, atlas texture support, and baseline world import. Document the current implementation and include the supplied in-game lobby screenshot.
2026-09-17 02:10:53 +03:00

93 lines
15 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# MVP server, protocol, and operation
## Running the server
Rust 1.96+ and a modern browser with WebGL2 are required. Java is not needed to run Shacraft: the verified catalog is included in the source tree. Node 22+ is used for client and network checks.
```sh
cargo build --release --locked --workspace
bash scripts/run.sh --data data --listen 127.0.0.1:4000
```
Open http://127.0.0.1:4000. To let friends connect over a local network, use `--listen 0.0.0.0:4000`; browser SHA-256 verification requires HTTPS for addresses other than localhost. External access requires a standard HTTPS/WSS reverse proxy. The MVP has no account service; a player name is not an authenticated identity. Only the server owner receives the control token; it is never sent to the client.
`--data` selects the WorldStore directory; `--cache-sections` sets the shared cache capacity (64 by default). `--client` and `--packages` specify the static client and verified package directories. The startup script explicitly resolves these paths relative to the extracted project. Stop the server with Ctrl+C; already acknowledged edits do not depend on a clean process shutdown.
The first launch creates a lobby, the `gallery` world, an immutable Spleef base, and two independent arenas. The catalog contains every Java 26.2 block state and an original trampoline. The server can also open an imported WorldStore; imported worlds appear in the world selector alongside the demo worlds. The gallery contains 1,197 default-state samples on a 128×128 floor, spaced 3 blocks apart. It provides an overview of all block types, rather than all 32 thousand state variants. The gallery spawn is `[-50,2,58]`; the client loads the world in parts as the player moves.
## State ownership
One dedicated thread owns WorldStore, physics, and game state. HTTP and WebSocket handlers enqueue bounded commands. The shared Rust/WASM movement solver runs at 20 ticks per second with measured Java 26.2 acceleration, friction, gravity, jump, fluid and collision behavior. Position specifies the center of the player's feet. Standing, crouching and swimming/crawling use different body and eye heights. +Y points up, yaw increases to the right, and pitch increases upward; the viewing direction is `[sin(yaw)*cos(pitch),sin(pitch),-cos(yaw)*cos(pitch)]`. See [player physics](PHYSICS.md) for reference evidence and limits.
Player positions, spawn points, physics and action rays use double precision. Procedural worlds support horizontal gameplay through ±29,999,872 and build layers Y=64…319; section-local rendering preserves distant geometry. Nonprocedural arena configuration and entity administration retain their ±32,700 bounds. Storage and conversion retain their ±30,000,000 contract. See [procedural worlds and diagnostics](WORLD_STREAMING.md) for the bounded CPU worker pool, durable natural baselines and streaming limits.
Input expresses movement intent rather than position. The server checks the 6-block reach, the nearest shape intersection, the placement cell, intersections with players, and arena rules. Stale input is cleared after one second. Gameplay physics reads a bounded region of neighboring blocks for each tick; independent worlds without players need no array of loaded sections.
`worlds.sqlite3` stores blocks and their history. `server.sqlite3` stores configuration and persistent entities, with a separate revision. These are two transaction domains: creating a world and adding its settings are not claimed to form one shared transaction. If saving settings fails after world creation, the world remains available with safe defaults; the error must not be interpreted as permission to create the same world again. A failed entity or settings write restores state from the last saved version. If even reading SQLite fails, the operation returns an error; a storage failure is never acknowledged as success.
## HTTP and authorization
Public GET endpoints: `/api/health`, `/api/manifest`, `/api/worlds`, `/api/catalog`, `/api/entities`, `/api/metrics`. The catalog accepts `query`, `offset`, `limit` (1256), `ids` with at most 128 runtime IDs, or `states` containing canonical states separated by commas outside property brackets. Obtain runtime IDs from the response; they do not match Minecraft's numeric IDs.
`POST /api/control` accepts `{ "method": "world.read", "params": {...} }` and returns `{ "result": ... }`, or HTTP 400 with `{ "error": "..." }`. It requires `Authorization: Bearer <token>`. On the first launch, `control.token` is created with Unix mode 0600. Operation parameters are available in the separate MCP server's `tools/list` schemas. Control API names use a dot: `world.edit`, `build.plan`, `camera.capture`, and so on.
The token is not secret from the local machine's administrator. The manifest hash confirms resource compatibility; it does not prove that the client's executable code is unmodified. Game state protection relies on server-side validation. Browser WebSocket and Control API requests are subject to Origin checks; cross-site access is not enabled.
## WebSocket, snapshots, and edits
The current client prefers **`chunk_stream_v2`** with **`view_buffer_v1`**, documented in [section protocol v2](WORLD_STREAMING.md#section-protocol-v2). It receives an incremental view (405 sections by default, configurable from 245 to 1,805) and palette/RLE batches with generation IDs. The loaded radius includes one extra chunk ring; horizontal view anchors move only after a two-chunk displacement. Older v2 clients without the buffer feature retain 245 sections by default, configurable from 125 to 1,445. Procedural worlds require v2. The descriptions below of full snapshots and `chunks` apply to the retained v1/legacy paths.
Send the first message to `/ws` within 10 seconds:
```json
{"type":"join","protocol":1,"manifest_hash":"from /api/manifest","name":"Player","world":"lobby","features":["chunk_stream_v1","movement_prediction_v1"]}
```
`welcome` contains `id`, `world`, `revision`, `blocks:[{pos,block}]`, definitions of the `materials` in use, `players`, `entities`, `spawn`, `view_center`, and `manifest_hash`. The view center uses world coordinates rounded down to multiples of 16, including negative coordinates. A client requesting `chunk_stream_v1` receives that feature in `features`, plus inclusive `view_min` and `view_max` bounds. Its full snapshot covers `[centerX-32, centerY-16, centerZ-32]…[centerX+31, centerY+31, centerZ+31]`: 4×3×4 complete 16³ sections.
As the negotiated client's center moves, the server sends `chunks` updates at most once every 250 ms. Each contains `world`, the current `revision`, `from_center`, `view_center`, `view_min`, `view_max`, `unload:[[sectionX,sectionY,sectionZ]]`, `sections:[{section:[sectionX,sectionY,sectionZ],blocks:[{pos,block}]}]`, and `materials`. Section addresses are integer section coordinates; block positions and view centers are world coordinates. Only newly visible sections are read and sent, including empty ones, while retained sections keep their existing client geometry. Unloaded sections are removed. A jump with no view overlap sends every entering section through the same message. Chunk messages do not change the spawn, players, or world revision: they contain a view of the current revision. Initial joins, world switches, and explicit resyncs still send a complete snapshot.
Clients that omit `chunk_stream_v1` retain protocol 1's original bounds, `[centerX-32, centerY-8, centerZ-32]…[centerX+31, centerY+31, centerZ+31]`, and receive replacement `snapshot` messages on movement at most once every 2 seconds. Unknown feature names are ignored.
Snapshots do not include the full string registry. `materials` is limited to 256 entries and 128 KiB; chunk updates include only definitions used by entering blocks. The client requests any remaining definitions sequentially through `/api/catalog?ids=1,2,...&limit=128`. This allows players to join worlds with large palettes without overflowing the outbound queue.
The client sends `input` with `seq,yaw,pitch,forward,strafe,jump,sprint,sneak,fly_toggle`; `break` with `pos`; `place` with `pos,block` or `state`; and `switch_world`, `resync`, `respawn`, `start_match`, `chat`, and `ping`. The three added movement flags default to false for older clients. A `state` response contains authoritative positions, `tick`, the processed input `ack`, and match state. Public players also contain velocity in blocks per tick, pose, height, eye height, sprinting and flying. Blocks arrive in `blocks` messages with a new revision. If a revision is missing, the client requests a snapshot. Subscription and snapshot creation are serialized with edits on the same thread, so an edit made between those steps cannot be lost.
Clients negotiating `movement_prediction_v1` send one movement command every 50 ms. At most 32 commands are queued, and one is consumed per server tick; packet bursts never create additional simulation ticks. Duplicate sequence numbers are ignored. When the queue is empty the last controls remain held, with flight toggles consumed once. Stale controls clear after one second. `welcome`, `snapshot` and `state` include `motion:{body,ack,tick,epoch,settings}`. The body is the complete shared solver state, including velocity, pose, contact flags and jump cooldown. Settings are chosen by the server, including creative flight permission and arena countdown freeze. The client restores this state and replays unacknowledged commands through the shipped `/physics.wasm` module.
`input_reset` clears queued and held controls, acknowledges discarded commands and advances the motion epoch. Respawn and world/arena teleports also advance the epoch so prediction discards obsolete input. `look` with `yaw,pitch` updates the action ray without consuming a movement sequence; the browser uses it immediately before a block action. Final client positions, velocities and flight permission are never accepted as authority. Clients without the movement feature keep the earlier latest-input behavior and authoritative state updates.
Control edits retain the core contract: an expected revision, a unique `operation_id`, a durable acknowledgment, replay of the same request without a second write, and rejection on conflict. A build plan covers at most 32,768 cells and is retained for 5 minutes, with at most 16 plans stored; preview does not change the world. Plans are ephemeral and disappear after a restart; accepted edits remain on disk. `camera.capture` returns a PNG of the server's isometric projection and the exact revision; it is not a frame from the player's WebGL camera.
## Spleef rules
A match follows `waiting → countdown → active → finished → waiting`. Defaults are 2 required players, a 3-second countdown, and a round lasting up to 180 seconds. Only `minecraft:snow_block` may be broken during an active round; block placement and boundary destruction are forbidden. Falling below Y=6 eliminates a player. The last remaining participant wins; if time expires with multiple participants remaining, the result is a draw. Five seconds after the result, the world returns to its pinned template and players return to spawn. Arenas are independent. Disconnecting or leaving the world removes a participant; rejoining during the round admits them as a spectator. After a restart, an interrupted match resets to its template.
`arena.configure` persists world settings. They can be changed between matches; attempts during countdown/active/finished are rejected. Available fields are `mode`, `spawn`, and:
- `countdown_seconds`: integer 1…30, default 3; `round_seconds`: integer 1…3600, default 180.
- `min_players`: integer 2…32, default 2.
- `elimination_y`: a finite coordinate within ±32,700, default 6.
- `spawn_points`: up to 32 `[x,y,z]` points. An empty list uses a circle of radius 7 around X/Z=0 at height `spawn[1]`. A nonempty list must accommodate the minimum player count and, at match start, every player who has joined; points must be at least 0.8 blocks apart.
- `spectator_spawn`: spectator position, default `[13,2,0]`.
- `floor_block`: a known canonical state with collision that participants are allowed to break. Default: `minecraft:snow_block`. The pinned map's floor must already contain this material; configure does not repaint or rebuild the map.
All spawn points must be within the gameplay range, with Y above `elimination_y + 0.5`. The optional `expected_revision` checks the shared metadata revision available through `entity.list`/`metrics`; this is separate from world block revisions. Rules are returned in `match.rules`. Older settings containing only `mode/spawn` are read using the defaults above.
The core idempotency journal covers block edits, undo/reset, and build commits. Entity operations and arena configuration do not yet have such a journal: repeating `entity.spawn` creates another instance. After an uncertain network result, read the current state first.
## Limits and observability
- 32 WebSocket sessions, including those waiting to join; 16 concurrently served HTTP requests; a 64-command queue.
- WebSocket input messages up to 64 KiB, with at most 80 messages/s per connection; block actions no more often than every 110 ms, chat every 700 ms, explicit resync every 500 ms, and world switches every second. Negotiated chunk updates run at most every 250 ms on section changes; legacy automatic snapshots retain their 2-second interval. Movement streaming uses a separate timer and does not delay explicit resyncs or world switches.
- Control API JSON up to 2 MiB; standard edits up to 32,768 cells; reads up to 262,144 cells and 6 MiB of response data. Exceeding the byte limit requires a smaller region.
- Each client's outbound queue holds up to 16 messages and 8 MiB. A slow connection is closed if its queue overflows or sending times out. The aggregate queue bound depends on the number of clients; these bytes are separate from the section cache.
- Server metadata up to 8 MiB, at most 4096 entities, and up to 16 KiB of properties per entity. Gameplay snapshots contain compact representations without arbitrary property JSON; full properties are available through `entity.list` with offset and limit (default 64, maximum 128).
- Process RAM in `/api/metrics` is the actual Linux VmRSS; `storage.cache_payload_bytes` counts only the payload bytes of encoded sections. The catalog, strings, SQLite, network buffers, temporary reads, and allocator memory are separate allocations.
The maximum allowed configuration is not the measured target load profile. Benchmark conditions and results are published in VERIFICATION; no advantage over Paper is claimed without a comparable run.
## Entities and compatibility
The 158 entity definitions have measured dimensions and original procedural models. Persistent instances can be created, moved, and deleted through MCP. Full vanilla AI, redstone, fluids, inventories, and Minecraft gameplay logic are not implemented. Context-dependent block shapes are explicitly marked in the catalog. The converter handles modified and unknown data according to `docs/interop.md`, without silently claiming lossless compatibility.