ViF
vi-style motions meet a roguelike terminal shooter: here, in a terminal or on a phone, solo or multiplayer
About
ViF (short for vi-fighter) is a real-time game where vi-style editing moves are the
controls: hjkl, w/b/e, f/t, counts, operators, registers, search and
macros, across Normal, Insert, Visual, Search, Command and Overlay modes. You type,
shoot and survive procedural encounters against enemies that learn, to music the
game writes as you play. Keyboard, mouse, or both.
Nine scenarios ship with it: main, the default (survive storms, lure Krakens
through mazes, defend the tower); td, two towers to hold in a sprawling maze;
cave, which scrolls past you and crushes you against its left edge; armada,
a vertical scroller of diving ranks and circling squadrons; magic, a magic square whose rows and columns you turn to fend off swarms; recall, a sequence to repeat; tutorial,
the motions a lesson at a time; dummy, a range of every weapon and a target to
try them on; and blank, an empty arena to build in.
It is written in Go, without cgo, on an engine of its own: an entity-component-system, a fixed-step simulation loop that processes events in a deterministic order, and scenarios written as TOML state machines. The same binary plays solo, hosts or joins a multiplayer game, runs as a dedicated server, replays recorded games, and runs without a display for deterministic tests.
A terminal, a desktop window, an Android phone and a browser page all draw the same grid of character cells, each through the terminal library, and the game’s code does not depend on which one it runs in.
Media














Play
The browser build is the Go game compiled to WebAssembly, running in a Web Worker while the page draws its screen on a canvas. It opens in its own tab, because it takes the keyboard and mouse while it has focus. It plays the main scenario solo, or joins a multiplayer game started in the lobby, over a WebSocket on this site; the lobby starts any scenario, and a native build plays them all.
- Requires
- A modern browser with JavaScript and WebAssembly. WebGL draws the screen; without it a 2D canvas does, slower on big maps, and the page says so.
- Download
- Nightly builds of the main branch, rebuilt every night:
Linux (amd64, arm64) and FreeBSD for a terminal or, with
-g, a desktop window; an app for Android 11 and newer; and an experimental Windows build that plays in Windows Terminal, without sound. Not releases: flags and files can change from one night to the next. - Phones
- Tap to move and fire; tap and hold the status bar, the strip along the bottom edge, for the menu, drawn with the page's own controls, and tap it three times, or use the strip on top, for the keyboard; pinch to zoom the screen. Or install the Android app from the nightly builds.
- Audio
- Music and effects are synthesized as you play, on from the press that
starts the game.
Ctrl-S, or the speaker on a phone's strip, cycles effects and music, and the menu sets them and the volume; this browser keeps the choice for the next visit. - Performance
- Close to native on a laptop; the largest maps still cost more in a browser.
- Multiplayer
- Start a game in the lobby, then join it from the browser, or from a native
build with the command the lobby hands back,
vif -join vif://lixen.com:7777/<game>: every game has its own name, and joining needs it. A native build can also start a new game of its own withvif -join https://lixen.com, which asks this site for one.
Engine
ViF is a single Go binary with an engine of its own. One package, the app, builds every other part for the chosen mode and runs the main loop. The game’s state lives in one world, beside the scenario’s state machine, and one lock guards both. In a solo game three goroutines take turns on them: the main goroutine handles input and draws frames, the scheduler advances the simulation in fixed steps called ticks, and an event goroutine processes events raised between ticks. A tick is 50 ms (20 a second) by default and can be set from 10 to 100 ms; durations given in seconds assume the default. Each player controls a cursor, their piece on the map: they type and fire from it, enemies hit it, and the view follows it. Select a part in the diagram to read how it works. Multiplayer attaches beside the simulation and has its own tab.
Select a part to read about it below
Appstartup and the main loop
cmd/vif reads the command-line flags, finds the configuration directories and picks a mode; internal/app then assembles the game for that mode. It initializes the services (files, the texts to type, display, sound, network), creates the world and its global resources, constructs the systems and renderers from the generated manifest (the build's declared list of components, systems and renderers), sets up the input parser and the mode router (which applies input according to the input mode, such as Normal or Insert), creates the scheduler and loads the scenario into its state machine. Only the app constructs parts, and no part depends on the app: it owns the world and the lock over it, and runs the loop.
0one tick, 50 ms100 ms
- Main goroutine waits for display events (keys, mouse, resizes), the 16 ms input timer and the frame timer. A key is parsed and applied under the lock, and the events it raises are processed at once, so the next frame shows the result
- Scheduler goroutine runs a tick every 50 ms, then waits up to two ticks for the frame that shows it, so the simulation does not outrun the screen; above real-time speed it skips the wait
- Event goroutine processes events raised between ticks, and keeps doing so while the game is paused
- Service goroutines read the terminal, mix audio and move network data. They pass what they read to the loop through bounded channels and never modify the world
- Play
- normal play: display, input, sound and, if asked, multiplayer; the clock can pause
- Server
-serve: a dedicated multiplayer host with no screen, sound or cursor of its own- Headless
- no display; the clock advances only when its caller, such as a test, a script or a bot, steps it
- Replay
-r: plays back a recorded journal, with display and sound- Script
- a scripted or bot-driven game, shown on screen
- One lock
- The tick, event processing, input and frame drawing take turns holding the world's one mutex; the component stores and the spatial grid have no locks of their own. Frames are written out, and blocking calls made, after the lock is released; only a few commands typed on the
:command line, such as:log onopening its log file, block under it. - Determinism
- Headless, replay and script modes start no scheduler or event goroutine: the caller runs each tick and event pass itself. For a solo run on one build, the outcome then depends only on the seed, the configuration and the input events.
- Build profiles
- Parts can be left out at compile time. A build for dedicated servers has no display, renderers or audio, yet the same simulation fingerprint (a hash of its simulation definitions) as a full build, so the two can share a session.
- File lookup
- A path given by flag, then
-config-dir, the user's directory, a source checkout'swad/, the system directories, and finally the copies built into the binary.
Inputfrom a key press to the world
Every display (a terminal, a desktop window, a browser page or the Android view) reports keys, mouse input, resizes and close requests in one format, defined by the terminal library. The input parser turns them into intents: plain data describing a command, such as "delete three words", with no reference to the engine, so the vi grammar is tested without a world. The mode router tracks the current mode (Normal, Insert, Visual and so on) and applies each intent under the world lock: it moves the local cursor, runs operators and searches, and raises the events that combat and the scenario respond to.
3dwcount 3 · operator delete · motion word
- Parser handles counts, operators, motions, keys that wait for a character (as after
fort),gprefixes, search and command-line text, overlays (screens over the game, such as help or the menu) and macro recording. It keeps only its parsing state and the last change, which.repeats - Router keeps the state that needs the world: undo history, the register, marks, macros, the last search and find, command history, and the last fire times that held buttons and auto-fire share, so their shots do not stack
- Captured keys a scenario can take printable keys for its own on-screen buttons. These are sent as key presses rather than commands, so in multiplayer every instance's scenario receives them
- Modes
- Normal, Insert, Visual, Search, Command and Overlay. Command and Overlay pause a solo game; a multiplayer game keeps running.
- Input timer
- Every 16 ms, independent of frames and ticks, so held fire and macro playback keep their pace when frames slow down.
- One path
- The router moves only the local cursor, through the cursor system, which moves every cursor the same way, whether live input, a replay, a bot or a remote player drives it.
- Keymaps
- TOML files over the built-in defaults; the player's file is brought up to date when the game starts.
- Pointer
- A mouse or a finger aims and fires. Selecting a cell draws the cursor there at once; the simulation then places it there in one step.
Botscomputer-controlled players
A bot is a player controlled by a state machine instead of a person. It is written in the same TOML format as scenarios: states, conditions (guards) on what the bot perceives, and actions that queue intents, the same parsed commands a person's keys and mouse produce. A driver releases the queued intents at the bot's rate, 16 or 20 a second for the shipped bots, through the same mode router a person's input goes through. A bot takes a player slot and a cursor under the same rules as a person and plays alongside people against the game's enemies.
- Perception a bot sees only the current state of its own copy of the world and the events its last step handled; never the event queue, the position of a random number stream, or actions a multiplayer session has not yet applied
- Seats a bot added beside a player keeps its own copy of the world in the same process and joins through the player's instance over an in-process stream
- Score a measure each bot's file defines, weighing characters typed, errors, bonus text typed, kills and distance travelled, so a script can compare a new bot against the default bot over several seeds on two scenarios
- Playing with bots
vif -bot 2, or:bot addin a running game; with-hostor-join, the bots enter the session too.- Bots alone
-bot -watchshows a bot playing;-bot -headless -speed maxruns one as fast as possible and prints its score.- Recording
- A journal records the events the router produced from a bot's commands, so replaying it does not need the bot's state machine.
- Validation
-checkvalidates every bot file it finds, together with the rest of the configuration.
Schedulerwhat each tick runs
The scheduler advances the simulation one tick at a time. A tick is a fixed step of game time: 50 ms by default, configurable from 10 to 100 ms, and constant for the life of a game. Game time is computed from the tick number rather than read from a clock, so every instance in a session, and every replay, sees the same time at the same tick. At normal speed or slower, the scheduler waits after each tick, up to a limit, for the frame that shows it; at higher speeds it does not wait, so the simulation can outrun the display.
- Eventsprocess those raised since the last tick
- Clockset the tick number and game time
- Networkqueue every player's actions due this tick, this instance's own included
- Scenarioadvance each running region (parallel part) of the state machine that scripts the game
- Systemsrun each, in priority order
- Eventsprocess until the queue is empty
- Committick count, actions per minute, counters
- Sendthis tick's actions to the other instances; when due, a checksum of the world into the replay journal
All eight steps run under the world lock. After releasing it, the scheduler touches only atomic or internally synchronized state: it checks run-until requests and breakpoints, takes the status snapshot and the flight recorder's sample, and, when due, repeats the run's settings in the journal.
- Complete ticks
- Unless events keep raising events for sixteen passes, the tick's last event step empties the queue, so nothing raised by the steps before it is still pending when the tick's actions are sent, its world is captured or its checksum is taken.
- Late ticks
- A tick that takes longer than a frame delays that frame. If the next tick then starts late, the one after it is scheduled from that late start, so ticks stay evenly spaced.
- Pause
- Stops ticks, not the process: input, event processing and the pause screen continue, and sound fades out.
- Speed
- From 1/8 to 8 times normal, kept as exact fractions.
:stepruns a given number of ticks, and run-until runs, optionally at another speed, until a named event or the next state machine transition, then restores the previous speed and, if asked, pauses. - Reset
:newrebuilds entities, resources and the state machine. In multiplayer, a reset that happens during a tick ends that tick at the same point on every instance.
Eventshow the parts communicate
Systems, the scenario's state machine (the scenario is the TOML script that drives a game), input and multiplayer do not call each other; they push events. The queue is a lock-free ring buffer of 2,048 slots that any goroutine can push to; reading from it requires the world lock, so there is only ever one reader. Processing the queue, a settle, works in passes: each event goes first to the scenario's state machine, then to every system registered for its type. Events those handlers push are handled in the next pass, up to sixteen passes, so a chain of consequences completes before anything else reads the world.
push→queue→state machine→handlers↺
- When at the start and the end of each tick, immediately after an input that raised events, and between ticks on the event goroutine
- Classes besides its domain (shared or player), every event type has a class, which decides whether it is sent. Local: affects only this instance, such as sound, display or the player's own state. Shared: computed identically by every instance in a session, so never sent. Bus: a player's action that changes shared state; the instance that made it sends it to the others. Stamped: a few types, such as a kill, whose producer marks each event with the domain it affects, so one that affects shared state is handled as Bus and any other as Local
- Catalog about two hundred event types, most with a typed payload; the high-volume payloads are pooled. Code generation produces from it the event registry, the names TOML files use for events, and the binary encoding used on the network and in the journal
- Overflow
- When the ring is full, a new event evicts the oldest unread one, which is counted and logged as lost state.
- Loops
- A settle that reaches its sixteenth pass with events still queued stops and is counted, so an accidental event loop cannot hang a goroutine.
- Observers
- The journal records each event that enters the simulation from outside as it is pushed; a bot is shown the events dispatched during its last step and reacts to them at its next step.
- Requests
- Mechanics are triggered by request events, such as a spawn or an attack, so the scenario, a script and a console command all trigger them the same way.
Worldentities, components and resources
Apart from the state machine that scripts the game, which the scheduler keeps under the same lock, the world holds all mutable simulation state as an entity-component-system (ECS): an entity is only an ID, components are plain data attached to entities, and systems hold the logic that reads and writes them. An entity ID is 64 bits: 8 bits for its domain (shared or player-owned, below) and a 56-bit counter. Each component type is stored in a sparse set: packed arrays of the components and of their entity IDs, plus a paged index from entity ID to array position. A lookup is two array reads, a removal moves the last element into the gap, and iteration walks contiguous memory.
- Generated code the component stores, entity destruction, and the code that captures, compares and hashes the world for multiplayer are generated from one manifest, the build's declared list of components (nearly sixty), systems and renderers
- Position the one special store: moving an entity updates the store and the spatial grid together. The grid has one 16-byte cell per map coordinate, holding one entity directly or a group of up to 31, so the lookups behind collision, typing (matching a typed key to the character under the cursor) and targeting allocate no memory
- Composites a large actor, such as a Kraken, a storm, a snake or a tower, is a header entity grouping member entities that form its visible, collidable cells; a Kraken takes damage on its header, while a tower or a storm loses its cells one by one
- Resources global state beside the stores: time, game state, the list of up to 16 cursors, seeded random number streams, targets, route graphs and the genetic algorithm's registry
- Two domains
- Every entity, event and random stream is either Shared, the same on every instance in a session (cursors, most enemies, bonus text any player can type, walls, towers, the map, game time), or Player, owned by one player (the text that player types, projectiles, the basic enemies that chase only that player, collectibles, effects).
- Queries
- What occupies a cell or an area, free space found by spiral or pattern, line of sight and rays. A presence bit per cell lets a scan skip empty cells 64 at a time, and a bit plane per wall type answers a wall test with one bit.
- Motion
- Positions, velocities and accelerations are
float64, measured in cells; integers are used only for grid cells. - Pointers
- A pointer into a store stays valid only until that store next gains or loses a component, and never past the locked operation that obtained it.
Scenario machinewhen things happen
When things happen is data, not code. A scenario is written in TOML and run by a generic hierarchical state machine: states nest inside other states, and several regions run in parallel, each in one state at a time with its own timer and delayed actions. Responsibilities are strictly separated: the TOML decides when an encounter starts, repeats, pauses or escalates; the state machine executes transitions deterministically; events request mechanics without knowing which state sent them; and systems implement mechanics without knowing the scenario. The main scenario, for example, escalates through these phases:
3 storms→Kraken→3 storms→Kraken→tower defense
- Each tick every running region advances its timer, runs the delayed actions now due and its
on_updatehooks, then takes the first tick-triggered transition whose condition holds, checking from the innermost state outward - Each event reaches the state machine before any system. Each region may take one transition on it; a bitmask of the events its active states listen for rejects all others with one test
- A transition copies event fields into variables, exits states up to the nearest common ancestor, runs its actions, then enters states down to the target. Its actions can set variables, start, pause or end regions, switch systems on or off, and emit events, now or after a delay
- System switching the scenario sets which systems run by default, and while a region runs it switches the systems it names on or off; a system switched off stays built but inactive until switched back on. Switching one off is checked against the other systems' declared dependencies
- Scenarios
- Nine ship:
main, the endless campaign, built into the binary, andtd,cave,armada,recall,tutorial,dummy,blankandmagic. - Generic
- The state machine package imports no game systems, only the game's event types; its standard actions and conditions reach the game through callbacks the game supplies, and bots run the same state machine over their own view of the game.
- Tools
-checkloads the chosen scenario (the main campaign by default) and every bot file it finds, and checks the scenario's systems and their dependencies against this build;-schemaprints, as JSON, the vocabulary a scenario is written in: every event with its fields, and every action and condition with its arguments.- In multiplayer
- A world capture, the snapshot of the shared game state that a joining player installs, includes each region's state, variables and pending delayed actions, and every region follows the host's transitions, so a phase changes once, at the same tick, on every screen.
Systemsthe mechanics
A system implements one mechanic: typing, heat, the shield, a weapon, an enemy type, walls, navigation, loot. Each tick the scheduler runs every active system in priority order; systems also handle the event types they registered for, within ticks and between them. Systems are constructed from the manifest, the build's declared list of components and systems, which also gives, for each system, its domain (state shared by all players, or one player's own) and the systems it requires. Systems never call each other; they interact only through components, the world's global resources and events. For example, an enemy that must ignore hits sets a status that the combat system checks.
- Cursor, typing and loot the cursor, energy, heat, shield, boost, weapons, typing, the text to type, bonus text, collectibles and loot
- Map walls, towers, gateways (enemy spawners), composites (entities that span several cells), timers, death and its effects, and wind
- Combat one table of attack effects indexed by kind, plus lightning, missiles, pulses, bullets, explosions and soft collision
- Species the enemy types: drain, quasar, swarm, storm, Kraken, pylon, snake and eye, plus any a scenario defines in data
- Order
- Priority alone orders the tick; dependencies do not. They order initialization instead, at startup and on every reset; whatever a running system requires is kept switched on, and an unknown name or a cycle stops startup.
- Domains
- A system can also be declared for both domains, and a test checks each system's code against its declaration.
- Per-kind tables
- What differs by kind is one table indexed by kind: weapon specifications, the combat table, collision and mass profiles. A new kind adds a row, not a new code branch.
- Tuning
- Gameplay timing and balance constants are in one package; the characters, palettes and gradients the renderers use are in another beside it.
Speciesbehaviour, navigation, adaptation
A species is an enemy type. In several species, each enemy runs its own small state machine, whose whole state (the current state, the time spent in it and its duration) is stored as plain integers in the species' component, so world captures (snapshots of the shared game state that joining players install), checksums and the host's corrections handle it like any other data. The swarm, quasar and storm define their state machines in Go. A scenario can add species of its own as behaviour programs: TOML compiled at load time, against the actions the game provides, into the same state machine type. A new species is therefore one TOML program, holding its body and its state machine, not new code, and nothing is interpreted during a tick.
- Flow fields for pathfinding, a Dijkstra search spreads outward from a group of target cells and records in every open cell the direction of its shortest path to the target, as drawn above. Step costs follow a terminal cell's 2:1 shape (10 across, 20 down, 22 diagonally), in eight directions without cutting corners. A ring of distance buckets replaces the usual heap, and a field is cached per target group and recomputed at a limited rate
- Route learning a gateway, an enemy spawner, computes several distinct routes to its target, each penalized for overlapping the ones before, with a flow field for each. A learner chooses each spawned enemy's route by multiplicative weights over each route's average score (how far its enemies got along it, discounted for longer routes), with one choice in ten made at random to keep exploring
- Evolution the choice of eye a gateway spawns, one of seven types with fixed hit points and speed, evolves in the steady-state engine of the genetic library, which replaces individuals continuously rather than generation by generation, scored by how close each eye gets and how much damage its self-destruct deals
- Large bodies
- A multi-cell enemy follows a field computed only over the positions where its whole body fits, so its path always leaves it room, and a target blocked by walls seeds the field from the first open ring around it.
- Lifetime
- Learned route weights last as long as their gateway's current routes, and evolved populations one game;
:newstarts every species afresh. - In multiplayer
- A world capture includes each genetic engine's exact state, its random generator's position and pending work included, so guests evolve what the host does.
- Libraries
- Navigation takes grids, cells and callbacks and reads no world; the per-enemy state machine package uses only the standard library.
Renderfrom the world to a frame
The screen is a grid of character cells. Renderers read the world and write cells into a buffer, never to the screen. Each frame starts from a copy of the time, screen size, camera and local cursor. The render loop clears the buffer, takes the world lock, runs the visible renderers in priority order, each clipped to the playfield or the screen, and releases the lock. Compositing then finishes without the lock: cells nothing drew get the background colour, the area outside the map is filled, and in TrueColor the background under text is dimmed. The finished frame goes to a surface, an interface with a colour mode and Flush and Sync methods, which is all a display has to implement to show frames.
- Overlayshelp, menu, console, telemetry
- Interfaceheat meter, status bar, cursors, start screen
- Passesgrayout, strobe, dim
- Markslanding marks, buttons, large text such as countdowns
- Weaponsshield, orbs, lightning, missiles, rays, bullets
- Tracerstracers, materialize, teleport lines
- Actorsstorm, Kraken, eye, snake, swarm, towers
- Particlesflashes, explosions, flying characters
- Textsymbols for pickups and particles, the text to type, bonus text
- Fieldthe cursor's crosshair lines, walls
- Frame rate
- A frame every third of a tick, 60 a second; 24 inside tmux or screen, which drop faster output. A frame cap the player sets replaces it.
- Smooth motion
- Drifting background text and a scrolling cave's rock and walls are drawn where they stand at each frame, carried forward from the last tick, so they move smoothly at 60 frames a second instead of stepping 20 times a second.
- Colour
- 24-bit TrueColor; on a terminal that does not announce it, a final pass maps each cell onto sixteen colours: on a text console, the console's own palette; on a 256-colour terminal, its first sixteen, except the game's status bar and overlays, which keep all 256.
- Slow terminals
- The terminal is written by a goroutine of its own that keeps only the newest frame, so a terminal that reads slowly never delays a tick.
- Output size
- Fast effects round their background colours so neighbouring cells share one colour change: a 240 by 66 frame fell from 27.8 to 20.6 KB.
Audioeffects, music, the mixer
Sound comes from the audio library: pure-Go synthesis, cached pre-rendered sounds, voices, harmony, patterns and a sequencer, mixed on one goroutine into 44.1 kHz stereo. The library knows nothing about the game; two systems drive it. The audio system plays the one-shot effects the game requests by event, and applies mute and pause. The music system reads the player's actions per minute (APM) over the last five seconds and maps them to an intensity tier and a tempo of 100 + 100·√(APM/480) beats per minute; the sequencer takes a new tempo on the next beat, and a new tier's rhythm, melody and bass at a bar line.
- Calmunder 60 APM100 BPM
- Normal60 APM135 BPM
- Elevated140 APM154 BPM
- Intense220 APM168 BPM
- Peak300 APM179 BPM
- Transitions
- Tempo rises by at most 12 BPM a second and falls by at most 6. The tier rises no sooner than four seconds after its last change, straight to the tier the APM has reached, and falls one tier at a time.
- Outputs
pacat,pw-cat,aplay, SoX'splay,ffplayor FreeBSD's OSS; WAV and null outputs for tests; Android's AudioTrack; the browser's AudioWorklet.- No output
- The game runs silent rather than failing. Audio output needs no cgo.
- Controls
Ctrl-Scycles effects and music; the menu turns each on or off and sets the effects volume.- Server builds
- The audio library is left out, and small stand-in systems consume the audio events, so the telemetry and the simulation fingerprint (a hash of the simulation's definitions that instances in one session must share) stay the same.
Sessionwhere multiplayer attaches
Multiplayer is three parts outside the simulation, each reaching the game through one narrow interface, so the world stays owned by the app. Membership handles this instance's place in a session: hosting and joining, the lobby, admission, the player list, the keys players reconnect with, bots and spectators. The corrector captures the shared world (the state every instance must agree on), and checks, stages and applies corrections, the host's repairs to a guest's copy. The authority protocol decides which instance hosts, how often the host sends corrections over each connection and who takes over when the host is lost; it holds no world, so its tests run it against a stub.
- In the tick a network system takes in, at the same point in every tick, every player's actions due that tick, this instance's own included, and, as the tick ends, sends the actions this instance made during it; network goroutines only fill a bounded channel
- Between ticks a correction is first applied to a staging world, a headless copy of the game with the same seed and scenario, then written into the live world between two ticks
- Every mode
- A player, a dedicated server, a script and a bot use one implementation: correction scheduling, the player list and host succession do not depend on how the session was started.
- Compatibility
- The build's manifest, its declared list of components and systems, yields a simulation fingerprint; a joiner whose protocol version, fingerprint, formats, tick length, seed or scenario differ from the host's is refused before it takes a slot.
Journalrecording and replay
The journal is a JSON Lines file recording every event that enters the simulation from outside (a key, a macro, a command, a remote player's action) as it is pushed. Each record is stamped with its run (a counter that increases with each reset), its tick, and its group: 0 if it was applied inside that tick, otherwise which round of event processing after that tick handled it. A headless recording fed back at the same points into a fresh headless game reproduces the world bit for bit on the same build. The tests rely on this, and vif -r <file> -headless stops at the first periodic world checksum the replay does not reproduce. A recording of live play reproduces the player's input but not necessarily the world, since in live play the three goroutines race for the lock.
run0tick198group0, inside the tick
- Replay
vif -r <file>plays a journal back with display and sound. It keeps checkpoints, so:r tick Nseeks forward or backward, and stepping works in both directions - Scripts a hand-written schedule of commands (intents) and events by tick, run headless or on screen; the ViF picture on this site's home page is tick 214 of one
- Fuzzing seeded random input that the test suite plays for long stability runs
- Mid-game
:journal startbegins recording from the current point, writing the current world first.- Independent
- Recording, loading, replay ordering, the fuzzer and the script format do not import the app; they drive a game through narrow interfaces.
- Not guaranteed
- Identical results across platforms: floating-point differences rule that out.
Diagnosticsobserving the game without slowing it
Metrics, the periodic snapshot, the flight recorder and the profiler never take the world lock. Every metric is a registered atomic value that its system updates through a cached pointer. The periodic status snapshot and the flight recorder's sample are taken after the tick releases the lock, so neither lengthens a tick. With logging on, the flight recorder keeps the last 200 ticks of every metric in an in-memory ring buffer and writes them out only when something triggers it, such as a dropped event, a lock held too long, a breakpoint, a crash or a command. The log is structured JSON Lines, and every entry carries its run (a counter that increases with each reset) and its tick, so it lines up with the journal.
- In the game a telemetry overlay with pinned metrics, and breakpoints that stop on an event's dispatch, on entering a scenario state, or when a metric passes a threshold
- Profiler wall time per module on the tick, event and render paths; pprof CPU, heap and mutex profiles and execution traces on request
- Dedicated servers can be set by flags to answer
/healthand/metricsand to end themselves: when no guest joins in time, after a grace period once empty, or after draining on a termination signal
- Log filtering
- The log has one level for the whole process, and each subsystem can be switched off, so networking alone can be logged at debug level; errors from every subsystem are still logged.
- Go runtime output
- With
-dev, what the Go runtime writes to standard error goes to a file beside the log, and a log record points to each report; a panic in the main, scheduler or event goroutine is logged with its stack. - Browser
- The WebAssembly build compiles logging out.
Servicesfiles, displays, sound, network
The files the game reads, the content (the texts to type), the display, sound output and the network are each a service with one lifecycle: registered according to mode and build, initialized in dependency order, made available to the world through a typed interface, started only once the whole game is assembled, and stopped in reverse order. A service goroutine therefore never sees a partly built world, and never modifies one: it passes what it reads to a bounded channel, drained by the main loop or, for network data, by the tick. The display differs by platform, and the game does not know which one it has.
Terminalraw mode and the alternate screen; TrueColor, 256 colours or a console's 16
Desktop windowXlib, EGL and OpenGL ES 2, loaded at run time without cgo
Androidthe game runs inside the app, drawing to a SurfaceView, with sound through AudioTrack
BrowserWebAssembly in a Web Worker; cells drawn on a WebGL canvas, sound through an AudioWorklet
All four displays come from the terminal library: each provides a surface for the cell grid and reports input in the same format, so the game draws the same grid everywhere; on Android the app's own drawer paints the frames the library hands it. The window and Android draw the cells in the library's font, Hack, from bitmaps at three sizes; a browser draws the same font at any size.
- Files
- Scenarios, the typing texts, keymaps, bots and sound overrides are looked up in an ordered list of directories, with built-in copies of what the game cannot run without.
- Network
- Framed TCP, TLS or WebSocket streams; a browser joins through this site's WebSocket route, the only kind of connection a page can open.
- Platforms
- Linux and FreeBSD in a terminal or a window, Android, the browser, and an experimental Windows build; 64-bit only.
- Libraries
- Terminal, TOML, colour, logging, authentication, audio and genetics are separate Go modules, listed on the Build tab; another, ascimage, reads the wall images and fits the logo's cells.
Netcode
A ViF multiplayer session holds up to 16 players, people and bots, on one shared map. Each player controls a cursor, their piece on the map: they type and fire from it, enemies hit it, and the view follows it. Each copy of the game taking part is an instance, and one instance can carry a person, bots or both. One instance is the host: its copy of the shared world is the authoritative one. Every other instance is a guest. The simulation advances in fixed steps called ticks, 50 ms (20 a second) by default; a host can set 10 to 100 ms, and durations given in seconds below assume the default. Each instance simulates the shared world itself, so a player’s input takes effect on their own screen at once instead of waiting for the network, and the host regularly checks each guest’s copy against its own and repairs whatever differs. The network carries the players’ actions and those repairs, not a full copy of the world every tick. The diagram shows how instances connect; the topics under it are grouped by what they cover: keeping the copies in agreement, players joining and leaving, how instances connect, and what it all costs.
- Terminal, desktop window, Android app
- Can join over TCP, TLS or WebSocket, host over TCP or WebSocket, and relay over TCP. The Android app relays only in a session it may take over as host.
- Browser tab
- Can only join, over WebSocket. A web page can neither open a TCP connection nor accept any connection, so a tab cannot host, relay or take over when the host fails or leaves.
- Dedicated server
- Can only host. It runs the game, and any bots it is given, with no screen or player of its own.
Each host or guest box is one instance of the game, a copy running on a player's device or on a server, with the players it carries. A guest connects to the host directly or, if it cannot reach the host, through a relaying guest: a guest that also accepts connections from other guests and forwards their traffic (). Relays can be chained. Toward the host, a link carries the actions of the players on that instance and on every instance behind it (). Away from the host, it carries every player's actions in the order the host accepted them, and the host's corrections (). Viewers only watch and are not part of the session ().
Select a topic to read it below
Synchronizationhow every instance computes the same game
Simulation modelprediction and correction
Every instance, the host and each guest, runs the full simulation of the shared world. A guest's copy is a prediction: the guest computes it from the same rules and the same player actions as the host, except for the scenario's phase changes, which only the host decides and sends like actions. The host corrects the guest's copy where it differs from its own. This is neither lockstep, where every instance waits each tick for every player's input, nor a thin client, which only draws what a server sends. Input takes effect locally at once, and no instance stalls because a packet is late. Within one build the simulation is deterministic, meaning the same inputs produce the same world, so a guest's prediction is usually exact, and confirming that two copies match costs one hash comparison.
- Shared state what all players see and interact with: cursors, enemies, bonus text any player can type, walls, towers, the map, the scenario's current phase and game time. The host's copy is authoritative, except for a few values on each cursor, such as energy, heat and shield, that only its player's instance computes (); a guest's copy is provisional until the next correction
- Player state what belongs to one player and is simulated only on that player's instance: the text they type, the shots their weapons fire, the enemies and pickups only they see, and visual effects. It is never sent, and no other instance reconstructs it
- Actions what is sent: the effect of a player's input on the shared state, in its smallest form (a cursor move, a hit, a kill), never the raw keystrokes, except those of keys the scenario has taken over as its own controls
- No rewinds
- A correction never moves the clock back and never reverses an event that every instance applied at the same tick, so a kill, a knockback or a phase change happens exactly once on every screen.
- Roles
- Hosting, relaying and playing are independent. A dedicated server hosts without a player of its own; a relaying guest forwards traffic but is still a guest, and decides nothing for the instances behind it.
- Players
- Up to 16 per session, people and bots alike.
- Determinism
- Guaranteed only within one build. Builds for different platforms can compute slightly different
float64results, so corrections, not determinism alone, keep the copies in agreement.
Player inputlocal prediction, the lead, acceptance
A keystroke takes effect on the player's screen at once: their instance moves the cursor and fires weapons from the predicted position, without waiting for the network. The change it makes to the shared world is sent as an action stamped with an apply tick a few ticks in the future; that margin is the lead. Every instance, the sender included, applies the action at its apply tick, and applies the actions due at one tick in a fixed order: by player, then by sequence number. The lead gives the action time to reach every instance before that tick, so every copy of the world applies it at the same point.
key at tick T→stamped T + lead→host accepts→all apply at T + lead
- Acceptance the host applies an action that arrives in time at its stamped tick and a late one at the host's next tick, and drops one more than 20 ticks late, which the next correction (the host's regular check and repair of a guest's copy) then undoes on the sender. The host forwards only its accepted copy, with the tick it chose, to every other instance, and tells the sender how many ticks its actions took to be accepted ()
- Each guest's lead is set from how many ticks the guest's recent batches (one per player each tick, holding that player's actions, sent even when empty) took to be accepted by the host, between 1 and 20 ticks. It rises at once after a delay spike and falls only when the spike leaves a window of the last 300 ticks (15 seconds). The host's own lead is one tick
- Clock pacing a guest runs its ticks up to 8% faster or slower until the host's batches arrive just before the guest reaches their tick
- Isolation
- A slow or stalling guest delays only its own players' actions; when the host applies them late, only that guest's copy needs correcting.
- Structural changes
- A join, a departure, a reset, a pause, a speed change or a spawn applies at one agreed tick on every instance, including the one that requested it.
- Rewards
- A kill a guest predicts is shown at once; its loot and boost (a short timed bonus) are granted only after the host's world confirms it.
Correctionsfinding and repairing differences
The host regularly checks each guest's copy of the shared world against its own and repairs what differs. The check uses a hash tree of the shared world. The tree has one section per component type (position, combat and so on) and one per other kind of shared state, such as the random-number streams and the scenario's state machine. Each section's rows, one per entity or item, are grouped into up to 64 pages, and one root hash covers everything. The host sends only the root hash. The guest builds the same tree over its own world at the tick the host names and compares the roots. Equal roots prove the two copies identical, except for the cursor values sent separately (), and the guest replies only that they match. If they differ, the guest replies at once with its page hashes, and the host returns only the pages that differ, so a repair takes one round trip. When those pages would cost more than the whole world, the host sends a keyframe instead: a compressed copy of the entire shared world.
root hash→page hashes→differing pagesorkeyframe
- Verified every page received is checked against its hash, and the full set against the host's root hash. A repair is applied entirely or not at all, and never mixes pages from two ticks
- Staged a correction is first applied to a staging world, a separate copy of the game that is not displayed, and moved into the live world between two ticks, under the world's lock
- Brought forward a correction usually describes a tick the guest has already passed. The staging world replays the actions the guest applied since then until it reaches the current tick, and the result is written into the live world at that tick, so the clock never moves back. A correction for a tick up to 4 ticks ahead waits for that tick; one further ahead means the guest has fallen behind, so it is applied at once and the clock jumps forward to its tick
- No lost actions each correction records, for every player, the last action the host's world contains. Later actions are re-applied on top of the correction, so an action is not undone just because it had not reached the host when the host's world was captured
- Cadence
- The number of ticks between two checks on one link. It is 4 ticks (five checks a second) by default; 2 while the corrections the guest applies are growing, or while it has at least twice the guests' average number of moving entities near its cursor; and 8 while nothing near its cursor is moving and the last correction it applied changed no entity. When probes (timing messages each end sends five times a second) show the link is saturated, the host first sends keyframes less often, then lengthens the cadence, up to 60 ticks, until corrections fit within 75% of the link's measured throughput.
- Floor
- Whatever the cadence, every guest receives a keyframe, or proves with a matching root hash that it needs none, at least once every 60 ticks (3 seconds). A guest whose link cannot carry that is refused when it joins; if its link later falls below that, both ends report it.
- Agreement rate
- On the repository's socket test harness, all but a few checks were answered with a matching root hash; on a jittery connection to this site, 82% were.
- Caching
- Every instance keeps each row's serialized bytes and hash beside a copy of its value, so building the hash tree serializes and hashes again only the rows whose values changed.
Wire formatwhat a link carries
A link between two instances is one reliable, ordered byte stream in each direction, divided into frames that each start with a 12-byte header. It carries four kinds of message. Tick batches: every tick, one batch per player, and one from a dedicated server, holding the actions made during that tick, sent even when empty. Cursor state: every six ticks, the values of a player's cursor that only that player's instance computes, such as energy, heat and shield. Corrections: the host's checks and repairs of a guest's copy of the world (). Control: a timing probe and its reply five times a second, the player list, and the list of guests that may take over as host ().
tick 124 ticks, 1.2 s
While the copies agree, each check is a short message carrying a hash of the whole shared world (the small marks), answered by a short reply that the hashes match; the wide mark is a repair of the parts that differ.
- Binary encoding each action is written as its type's index, then its sequence number and the tick it takes effect at as variable-length deltas, and its data as a bitmask of the fields present followed by those fields: 79 to 89% fewer bytes than the text encoding it replaced, and 10 to 26% less traffic once the link compresses it
- Stream compression each direction of a link is one continuous deflate stream, so every message is compressed against the stream's last 32 KiB, and tick batches and cursor states shrink about 3 times
- No double compression keyframes (copies of the whole shared world) and repair pages (the parts of it a repair replaces) are compressed when they are created, and the link sends them unchanged
- Bundling a link's tick batches and cursor states go out packed in one frame when the instance forwards what it received and in another when the tick closes, so a receiver reads one or two frames a tick, however many players there are
- Confirmation the host sends each guest's batches back to it once accepted, so the guest learns how many ticks each one took to be accepted (). A guest with no other instances behind it receives only that count, not the batches
- Cursor state
- Each of these values has one writer, the owning player's instance, and travels as a plain value that the host's checks leave out: other instances hold copies up to six ticks old, which would otherwise show as a difference during every fight.
- Empty batches
- A tick with no actions still sends its batch, because instances measure timing by when batches arrive: guests pace their clocks by the host's ().
Session lifecyclehow players join, disconnect and leave, and what happens if the host fails
Joiningentering a game in progress
A game in progress starts accepting players with the :host command, which opens a listening address; guests can then join at any time. Connecting first shows a preview of the session. The joining instance downloads the scenario if it does not have it, builds its world and checks it against the host's, and by default takes a player slot only when its player presses a key, clicks or taps to join. The host admits the new link before copying its world for the guest, so actions the other players make during the transfer are queued, not lost. The world arrives compressed and in chunks; the guest loads it into a staging world, a separate copy of the game that is not displayed, writes it into its live world, and then simulates the ticks the transfer took, applying the queued actions, before starting its clock.
- Compatibility the protocol version, the simulation fingerprint (a hash of the build's list of data components and update systems), the world and replay journal formats, the tick length, the random seed, the number of the current game and the scenario's hash must all match the host's; a joiner that differs is refused before it takes a slot
- Admission every connection proves the key its player's slot is tied to (). A host can also require a passphrase, checked by an Argon2id SCRAM exchange in which both sides prove they know it without sending it; over WSS the exchange is bound to the server's certificate. On this site, the router that forwards each connection to its game issues single-use admission tickets in place of a passphrase
- Limits connection attempts are rate-limited per address, each handshake runs outside the accepting loop under a time limit, and every buffer an incoming frame can fill has a size cap
- Cost
- Grows with the size of the world, not with how long the session has been running.
- Paused sessions
- A guest that joins a paused session starts paused and resumes with everyone else on the host's next tick.
- Local network
- Players on the same network can find a host without typing an address, through a UDP beacon and probe; off by default.
- Bots
- A bot joins through the instance that runs it, over an in-process connection, and leaves with it.
Disconnectiona dropped connection and reconnecting
A player whose connection drops is not removed from the session. The host records the departure at one tick on every instance, and the player's cursor becomes a Wraith: it stays where it was, drawn pale, and nothing can hit it or collide with it. Each player slot is tied to an Ed25519 key pair generated by the player's own instance; the session's player list holds the public key. Reconnecting and proving possession of the private key restores the same slot and cursor, with the energy, heat, health and weapon loadout the player had.
connection drops→Wraith, up to 2 min→key proven→same slot, same state
- Reconnection the guest stops its clock and redials the host with its key for up to 5 seconds; if that fails, it continues as after a host failure (). Reconnecting is an ordinary join: the current world arrives the same way
- Across restarts the key is kept after the game closes: in this site's browser storage for a tab, in a file in the user's state directory for a terminal or desktop window, and in the app's own storage on Android. After a closed tab, a crash or a reboot, a player who rejoins within the two-minute wait gets the same slot back
- Pass the host's signed statement that this key was admitted, valid for 24 hours and renewed by a reconnect after the first 12, so a returning player needs no passphrase and, on this site, no new admission ticket
- The wait
- A Wraith waits two minutes of game time, and the player's bots wait with it; then the player is removed ().
- Replay protection
- A key proof is valid for one challenge at one address, and the player list holds only public keys, so nothing read from it lets anyone take a slot.
Host failuremigrating the host
The host decides what happens if it disappears. By default nobody takes over: the session exists only at the host's address, and once reconnecting fails, each remaining instance continues on its own, except that players who joined through a relay (a guest that forwards other guests' traffic) continue together in that relay's session. With -authority migrate, hosting, meaning the right to accept actions and repair each guest's copy of the world, can pass to a guest whose player offered to take over: a candidate. A candidate opens a listening address of its own when it joins, and the host sends every instance the succession list: the candidates in the order they joined, with their addresses. Every instance except a browser tab, which cannot open a TCP connection, keeps a connection open to the first candidate.
- Freezeevery remaining instance stops its clock
- Redialthe old host, for up to 5 s
- Walkthe list, one candidate every 5 s
- Take overcandidate k becomes host with term T + k
- Announcethe others accept its signed takeover record
- Resumeon the new host's first tick
- No election every instance works out the same list of candidates from what it already holds: the succession list without the lost host and anyone who has left or lost their connection. The session's term is a number that increases with each change of host; candidate k may take over only at its turn, and only with term T + k, where T was the lost host's term. A record for that term from anyone else is refused, so two hosts can never share a term. A majority vote would not work for the smallest session: one instance left out of two is not a majority
- No duplicated actions each guest resends to the new host the actions it never saw accepted; the new host discards, by sequence number, any it already has, and drops any more than 20 ticks late, as any host does
- Split sessions an instance that reaches no candidate continues in a session of its own, keeping every other player's cursor as a Wraith (a pale, inert stand-in that holds their place), and can open it to others with
:host. Split sessions are never merged
- Opt-in at both ends
- Off unless the host enabled it and the guest's player offered, because a candidate's address is shown to every other player.
- Term
- Carried on everything a host sends; an instance rejects anything carrying a lower term than its own.
- Timing
- Each wait is 5 seconds of wall-clock time, since game time is frozen. A host that went silent costs a full wait; a host that quit refuses the redial at once.
- Never candidates
- Bots, which belong to their instance; browser tabs, which cannot accept connections; guests that joined through a relay, unless their player gives a listening address with
-listen; and guests whose player did not offer.
Leavingleaving a session, and removal
A player leaves with :leave and keeps playing the current world in a session of their own. The others see the same as for a dropped connection: the player's cursor stays as a Wraith, a pale, inert stand-in that keeps their slot in the session (). A host that leaves is handled as a host failure (), and a dedicated server cannot leave the session it serves. Removal is final: it frees the player's slot and takes the player's bots with it. Disconnection is not: the cursor waits as a Wraith, and the player can reconnect. A player is removed or disconnected in these cases:
- By command
:player dropremoves a player and bars their key (the key pair their slot was tied to) at every entry point of the session: the host, any later host and every relay (a guest that forwards other guests' traffic). A guest can remove its own bots with:bot drop - Timeout a Wraith is removed after waiting two minutes of game time. A full session gives the slot of whoever has been away longest to a new player instead of turning the new player away
- Late or excess traffic the host disconnects a player whose batches (their actions, one batch a tick) keep arriving late while their link is still delivering data, or a link that sends more than 64 KiB a second for each player it carries
- Overload a host that keeps missing its own ticks removes the newest bot in the session, or the newest player once no bot is left, one at a time, and tells everyone why
- No news the host treats a player behind a lost relay as disconnected once it has had no news of them for 15 seconds ()
- Thresholds
- Late means at least 5 late batches a second over 20 seconds, on a link carrying at least 8 KiB a second; overload means more than 10% of the host's ticks missed over 10 seconds. A host can change or turn off both checks.
- Grace
- The first 20 seconds after a player arrives, or after the host changes the game's speed, are not checked for late batches.
- Session end
- A dedicated server can end itself when no guest joins in time, once it has been empty for a grace period, or on a termination signal. On this site both waits are 90 seconds.
Connectionshow instances reach each other
Transportsthe byte streams a link runs over
A link can run over any reliable, ordered byte stream: TCP, TLS, or WebSocket with or without TLS; native builds use ViF's own WebSocket implementation. Everything above the transport (the handshake, admission, world transfer) is the same code on all of them. What an instance can do depends on which of them it can open and accept.
- Native builds the terminal, desktop and Android builds can open connections on all of them, host on TCP, WebSocket or WSS, and relay on TCP, accepting other guests' connections and forwarding their traffic to the host. They can also use WebSocket on a network that allows only HTTPS
- Browser tabs a web page can open only a WebSocket, which ViF wraps so the same protocol runs over it unchanged, and it cannot accept connections, so a tab can join but never host or relay
- On this site each game's host is a dedicated server in its own Kubernetes pod. Native builds connect to port 7777 and browser tabs to
wss://lixen.com/vif/ws/<game>; the router forwards each connection to its game by the name in its first frame (Deploy)
- Why not UDP
- Stream compression, the handshake, multi-part world transfers and the order of actions all depend on in-order delivery. Over UDP the protocol would have to rebuild that ordering itself, only to recover from packet loss faster than TCP does, and corrections (the host's repairs of a guest's copy of the world) already absorb the delay a loss causes.
- Certificates
- A WSS listener uses a certificate it is given, or one it generates and signs itself, which a native joiner can pin by its fingerprint; a browser has to be told to trust it first.
- Encryption
- TLS and WSS links are encrypted; plain TCP and plain WebSocket links are not, those to this site's port 7777 included ().
Relaysjoining through another guest
A relay is a guest, started with -relay, that also accepts connections from players who cannot reach the host directly, for example because the host is behind NAT. Players who join through it are ordinary guests with slots of their own: their actions travel up the relay's link to the host, and the host's accepted actions and corrections (its repairs of each guest's copy of the world) travel back down. When one of those guests asks for the parts of its copy of the world that differ from the host's, the relay answers from the host's corrections it has kept, but decides nothing: the host still accepts their actions. Relays can be chained, so a session's instances form a tree with the host at its root.
- Opt-in an instance relays only if its player chose to, so no traffic passes through an instance that did not offer
- Tunnels through this site a relay behind NAT can accept players through this site's router, the service that forwards each connection to its game by name. The relay keeps a control connection open to the router; the router gives the relay a name of its own and, for each incoming connection, asks the relay to open a second connection back, then joins the two. The relay opens no port to the internet, and the router never connects to an address a caller supplies
- Bots an instance carries its own bots the same way, over in-process connections: to the host, each bot is one more player behind that instance's link
- Depth
- Any number of guests may relay, and relays can be chained up to 16 levels deep. A browser tab cannot relay.
- Lost relay
- Players behind a relay that disconnects keep their slots and try to reconnect through that relay or another; the host treats a player it has had no news of for 15 seconds as disconnected ().
- No hole punching
- It needs a rendezvous server and UDP or WebRTC, which the restrictive networks that most need relaying are the first to block.
Spectatorswatching without playing
A viewer watches a session without taking part: it has no slot or identity and sends nothing. While anyone is watching, the host writes everything it accepts into one feed: each tick's batches of player actions, the cursor values that only each player's own instance computes (such as energy and heat) and an end-of-tick marker, grouped ten ticks to a record, plus a keyframe of the whole world every 30 seconds. Every viewer receives the same bytes, so the feed is encoded once however many are watching, and not at all when nobody is. A viewer simulates a tick only after the feed has delivered everything the host accepted for it, so it computes the same shared world as the host, and each later keyframe would repair any drift.
- Delay one record plus a four-tick margin: 13 to 14 ticks, about 0.7 seconds behind the host
- What is shown the shared world, following one player's cursor at a time. The text a player types, the shots their weapons fire and their loot exist only on that player's instance and are not shown
- On this site the router, the service that forwards each connection to its game by name, subscribes once to a game's feed and copies it to every viewer, so the game server sends one stream however many watch
- How to watch
vif -spectate <link>, or:spectate <link>from a running game.- Limit
- Eight viewers per session by default, which a host can change. On this site the router admits up to 256 per game, at most four from one address.
- Privacy
- A viewer sees the game and the players' names, but nothing that could be used to take or reclaim a slot. Players are not told who is watching.
Performance and limitswhat poor links and large sessions cost, and what is not supported
Latency and losswhat a poor connection costs
The protocol assumes links that are slow, jittery and sometimes silent, and limits what each failure can cost. Streams are reliable and ordered, so a lost packet only arrives late. Lateness is absorbed in three ways: a guest's lead (how many ticks ahead it schedules its players' actions) covers its worst recent delay, an action that still arrives late is applied at the host's next tick unless it is more than 20 ticks late, and the next correction repairs whatever a guest predicted wrongly in the meantime.
- Delay spike raises that guest's lead at once, up to 20 ticks (one second). Other guests' leads do not change
- Dropped correction (one refused by a full send queue, for example) is not resent: each correction supersedes the previous one, so a loss only delays the next repair. A keyframe (a compressed copy of the whole world) or a repair is sent in 4 KiB chunks, released only as the link drains, so on a slow link a tick batch (one player's actions for one tick) waits behind a few chunks, not a whole world
- Low bandwidth how often a link receives corrections follows the throughput it actually delivers. A link that cannot deliver a keyframe within half a second receives root-hash checks (one hash of the whole world, compared with the guest's) instead, and a keyframe only when it asks for one
- Silence every link is probed every 200 ms and closed after 5 seconds without a frame; the player's slot then waits for them ()
- Measured at this site
- Over a link with a 107 to 202 ms round trip, 14 to 85 ms of jitter and stalls of a second or more up to 1% of the time, a guest running in a terminal used 12 kB/s down and 3 kB/s up; its lead varied between 4 and 11 ticks.
- Simulated links
- A test harness runs a host and a guest, both moving and firing at the game's enemies, over a link with added latency, jitter and dropped frames. Over 1,200 ticks, each of its four link profiles has 1 to 3 actions accepted late.
- No lag compensation
- Nothing rewinds the world to check a hit against what the shooter saw.
Measurementswhat a session costs
These figures come from a test harness in the repository: a host and its guests connected over real sockets in one process, each running at the normal tick rate, with every player moving on one tick in three and firing on one in six. They are the host's outgoing traffic per second of game time on a 159 by 46 map, after compression.
- 2 players1.5 kB/s
- 4 players6.4 kB/s
- 16 players75 kB/s
- Compression the link sends about a third of the bytes it frames: before compression, the figures are 5, 20 and 231 kB/s
- Quadratic growth in a star, the host forwards every player's tick batches (their actions, one batch a tick) and cursor state (energy, heat and other values only their own instance computes) to every other player, so its traffic grows with the square of the player count. The topology causes this, not the encoding
- Map size limits a host before the number of players does: on a 500 by 250 map, the harness used about as much CPU with 4 players as with 16 on the 159 by 46 map
- Checks
- Five checks a second per guest in each of these runs, all but a few answered with a matching root hash (a single hash of the whole world), which proves no repair is needed.
- Keyframe size
- A keyframe, a compressed copy of the whole world, is about 20 kB on a 500 by 250 map; large sections that did not change are reused rather than compressed again.
- CPU
- The whole process, host and guests together, used 0.08, 0.14 and 0.47 CPU-seconds per second of game time at 2, 4 and 16 players.
- Caveat
- Measured on one machine on one day: rely on how the figures scale, not on their absolute values.
Limitswhat it does not do
The game is in development and its protocol has no compatibility guarantee: each change raises the protocol version or a format version. Some limits are deliberate; others are not built yet.
- Trusted guests admission is the security boundary. Once admitted, a guest is trusted; nothing detects a guest that lies about what it saw
- Unencrypted links plain TCP and plain WebSocket links are not encrypted, including those to this site's port 7777, whether they reach a game server or a relaying guest behind NAT (); TLS and WSS links, such as a browser tab's link to this site, are. The key pair a player's instance generates for them proves the right to a slot (a place in the session), not who the person is
- Whole world everywhere every instance receives the whole shared world, since any candidate may have to take over as host (); nothing is filtered by what a player can see
- No merging the parts of a session that split when its host was lost continue separately; a part that meets a host with a higher term (a number that rises with each change of host) refuses it and reports why
- Exact match a joiner's protocol and format versions and its simulation definitions must match the host's exactly; versions are not negotiated
- Background
- The protocol was designed after an incident in which determinism alone did not keep two copies of the world in agreement. The repository's design notes record the alternatives it was chosen over.
- Read more
- Multiplayer and Netcode design in the repository.
Build
Runtime
- Platforms: Linux and FreeBSD, in a terminal or a window; Android; WebAssembly in the browser; experimental Windows
- Toolchain: Go 1.27, no CGO
- Libraries: Terminal, Color, TOML, Log, Auth, Audio and Genetic
- Data: TOML scenarios, species, visuals, audio and keymaps, with embedded fallbacks
- Modes: interactive, dedicated server, headless simulation, journal replay
- Multiplayer: framed TCP, or WebSocket for browsers and blocked networks
- License: BSD-3-Clause
Build
- Download
- Or skip the build: nightly builds for Linux, FreeBSD, Android and Windows
- Clone
git clone https://github.com/lixenwraith/vif --depth 1- Build
cd vif && make release- Play
./bin/vif- Window
./bin/vif -gon Linux and FreeBSD- Scenario
./bin/vif -s td, orcave,armada,magic,recall,tutorial,dummy,blank- Online
./bin/vif -join vif://lixen.com:7777/<game>, a game's name from the lobby;-join https://lixen.comstarts a new one
Deploy
The site and the game run on one FreeBSD machine. An nginx jail terminates TLS
for lixen.com and serves this site; an Arch Linux guest under bhyve runs a
single-node K3s cluster whose only workload is game servers, one per game,
created on demand by the router and gone when the last player leaves. From
the internet the guest takes one port, 7777, for the game; everything else goes
through the jail. Everything in the guest comes from the repository’s deploy/
and moves with one command; the host, the jail and the forwarding between them
are configured outside it.
FreeBSD host bare metal
- From the internet, forwards the web to the jail and the game's one port, TCP 7777, to the guest, the source address kept; nothing else reaches either
- Runs the jail and the guest; nothing of the site or the game runs on the host itself
nginx jail
- Terminates TLS for lixen.com
- This site: a static Hugo build, assets under content hashes, precompressed
/vif/api/sessions,/vif/api/logs(SSE) and/vif/ws/<game>(WebSocket upgrade) proxied to the router in the guest- Exact routes only; nothing else of the guest is published
Arch Linux guest bhyve VM, the K3s node
vif-router systemd, Go
- The lobby's API: lists games, creates one (a Job and a Service), relays the log stream, answers the browser's WebSocket and splices it to the pod
- The front door, the game's public port: reads the game's name a native client sends first, runs its admission, then splices bytes to its pod
- Relay tunnels: a player's game that relays for others from behind NAT holds a connection open to the router, which names it; each dial on that name at the front door is spliced to a connection the game opens back, so it is reached by name, as a pod is
- Ceilings a request can pick within: players, scenario, screen, log level; a budget for each address
LogWisp systemd, built from upstream main
- Tails every game's JSONL log, rate-limited, with TRACE and address-bearing records left out
- One SSE stream, which only the router can read
Node pieces deploy/guest
- A tmpfs for the games' logs, swept by a timer; the scenario volume, read-only, replaced by atomic rename
- A packet filter of its own: the front door from anywhere, the API from the jail alone, nothing else
- Docker for builds alone: the session image, imported into K3s
./deploy/update.sh: diffs every component against the checkout and replaces what changed
K3s single node, namespace vif
- Pod Security restricted; a ResourceQuota of ten games and their memory; NetworkPolicy denying all but the game port in and a probe from monitoring; no egress
- The router's Role: create and delete Jobs and Services, watch readiness, read no logs
Game a Job and its Service
vif -serve -name <game>in ascratchimage: one static binary, non-root, read-only root, no shell- An init container checks the scenario; mounts: the scenario volume and the log tmpfs, nothing else
- Ends itself: 90 s without a first player, 90 s after the last leaves, an hour at most
up to ten, none between games
- Pages. A browser reaches nginx over TLS and gets this site; the lobby's script polls
/vif/api/sessionsevery few seconds. - Starting a game. The lobby posts to
/vif/api/sessions; nginx hands it to the router, which creates the Job and its Service, waits for the pod to answer ready, and returns the game's two links. - Playing in the browser.
wss://lixen.com/vif/ws/<game>is upgraded by nginx and terminated by the router, which splices the socket's bytes to the pod's game port. - Playing in a terminal.
vif -join vif://lixen.com:7777/<game>is raw TCP, never through nginx: the host forwards 7777 to the guest, the router reads the game's name and splices the bytes to its pod. One port for every game. - Logs. Each pod writes its own JSONL to the tmpfs; LogWisp tails the files and serves one SSE stream to the router, which relays it as
/vif/api/logs, through nginx, to the lobby's Log tab. - Updates.
git pull && ./deploy/update.shon the guest: the filter, the cluster objects, the scenarios, the image, the router and LogWisp, each replaced only when it differs, the last three only with no game running.