Field Command: RTS Selection, Formations, Fog of War and AI Opponents Kit
README.md
fogOfWarKit: fog of war for strategy, stealth and exploration games
Fog of war you can drop into any Zero world. Ground nobody has explored is hidden, ground you explored but cannot see right now is dimmed, and enemies stay hidden until one of your units, buildings, players or towers can see them. It comes in four looks you switch live with one setting: classic black and grey, drifting mist, an old parchment map, and chunky pixel tiles. Optional line of sight makes walls block vision for stealth games, and a minimap texture and visibility queries are included. It runs on every player's screen with no networking, and it is fast enough for a real-time strategy game with hundreds of units.
Version 1.0.3 (require("fogOfWarKit.api").VERSION).
Install
Install fogOfWarKit from ZeroMind into your world: search for "fogOfWarKit" (or "fog of war") in the ZeroMind panel and press Install, or run zeromind.install with the package guid bb87faea-e77e-47aa-9bae-f0b76d801268. It needs nothing else. (It also comes with rtsKit, which uses it for its fog of war.)
Try it
Paste this into the console of any world while playing (or into a scene entrypoint) and walk around:
-- One fog for the scene, 200 x 200 m around the origin, drawn as drifting mist.
local fog = entity.spawn("Fog of War")
fog.component.add("FogOfWar", { size = { x = 200, y = 200 }, look = "mist" })
-- The local player sees 15 m around them, and their screen draws team 1's fog.
-- (It waits for your body if it is not there yet, and follows you after a respawn.)
local Fog = require("fogOfWarKit.api")
Fog.followLocalPlayer({ team = 1, radius = 15 })
-- Optional: an enemy that hides in the fog until you get close.
local enemy = entity.spawn("Enemy", { position = { 30, 1, 0 } })
enemy.component.add("Model", { model = "@builtin::meshes.cube" })
enemy.component.add("FogHideable", { team = 2 })
Change the look live: require("fogOfWarKit.api").setLook("parchment"), or set look on the FogOfWar entity in the Inspector.
What it does
- Unexplored ground is hidden, explored ground you cannot see right now is dimmed in the look's style, and what one of the viewing team's sources (units, buildings, players, towers) sees is drawn untouched.
- It is drawn as one full-screen GPU pass that rebuilds every pixel's world position from the depth buffer, so terrain, trees, buildings and units are all fogged by the cell they stand in. It runs before the UI, so HUDs and menus are never fogged, and it is correct in offscreen captures and render-to-texture cameras.
- Cells fade in when revealed and fade slowly back to memory when sight leaves; they never pop.
- Enemies hide (
FogHideable/Fog.track) on screens whose team cannot see them. - Optional line of sight for stealth games: walls and tall colliders block vision.
- A minimap texture (
Fog.texture()) and queries for AI (Fog.isVisible,isExplored,state).
Looks
One setting switches between them, live:
| id | look |
|---|---|
classic | Pitch-black unexplored ground; explored ground drained of colour and darkened; soft feathered rims. The RTS default. |
mist | Unexplored ground lies under a 10 m deep bank of drifting, layered blue-white cloud (raymarched, with parallax); explored ground keeps a thin cold haze. |
parchment | An old map: unexplored ground is aged paper with inked contours and a survey grid, burnt and charred where it meets the known world; explored ground is drawn in sepia ink. |
pixel | Chunky square cells with stepped edges: dark bevelled tiles for unexplored, a posterised checker dither for explored, dithered fades over time. |
Fog.looks() returns { {id, label, description, tags} } for a picker.
Components
| Component | Put it on | Fields |
|---|---|---|
FogOfWar | one entity per scene | center (x, z), size (w, d), cellSize, look, viewerTeam, active, revealAll, lineOfSight, scanColliders, blockerHeight, updateRate, groundY, revealSpeed, hideSpeed |
FogSource | players, units, buildings, towers | team, radius, active, localViewer (on: the local player's own team becomes this screen's viewer), revealOnStart |
FogHideable | enemies, loot, traps | team: hidden on screens of other teams unless they can see it |
FogBlocker | walls, buildings, doors | refresh: its footprint blocks line of sight |
API
local Fog = require("fogOfWarKit.api")
Fog.setup({ center = {x, z}, size = {w, d}, cellSize = 1, look = "classic", viewer = 1, updateRate = 8, lineOfSight = false })
-- more setup keys: groundY = 0, enabled = true, revealAll = false, revealSpeed = 7, hideSpeed = 2.5, mistHeight = 10, blockerHeight = 1.5
Fog.setLook("classic" | "mist" | "parchment" | "pixel") ; Fog.look() ; Fog.looks()
Fog.setViewer(team) ; Fog.viewer() -- which team's fog THIS screen draws
Fog.setSources(team, { {x, z, r}, ... }) -- fast batched path, replaces that team's batch (call ~10x/s)
Fog.addSource(key, { team, x, z, radius, entity?, enabled? }) -- keyed; with `entity` it follows that entity
Fog.moveSource(key, x, z) ; Fog.updateSource(key, { radius?, team?, enabled? }) ; Fog.removeSource(key)
Fog.isVisible(team, x, z) ; Fog.isExplored(team, x, z) ; Fog.state(team, x, z) -- 0 unexplored, 1 explored, 2 visible
Fog.reveal(team, x, z, r) -- permanently explore (map start, scouting)
Fog.exploredFraction(team) -- 0..1, for "map explored: 63%"
Fog.setRevealAll(on) -- spectator / debug: no fog drawn (queries stay honest)
Fog.reset(team?) -- forget explored
Fog.setEnabled(on) ; Fog.enabled()
Fog.track(entity, team) ; Fog.untrack(entity) -- hide on this screen unless the viewer sees it
Fog.setLineOfSight(on) ; Fog.setBlocker(key, {x0, z0}, {x1, z1}) ; Fog.removeBlocker(key) ; Fog.clearBlockers()
Fog.addBlockerEntity(entity, key?) ; Fog.scanBlockers({ minHeight = 1.5 }) ; Fog.isBlocked(x, z)
Fog.on("updated", fn) -> disconnect -- after each grid update
Fog.texture() ; Fog.bounds() -- minimap texture + its world rectangle
Fog.stats() -- { cells, sources, updateMs, updateMsAvg, uploadMs, hideMs, updates, uploads, tracked, ... }
Fog.update() -- force a grid update now
Fog.clear() -- drop all sources, blockers, tracked entities and memory
Fog.VERSION -- "1.0.2"
Queries answer from the last grid update, at most 1 / updateRate seconds old; Fog.update() forces a fresh one.
Minimap texture
Fog.texture() is a cols x rows rgba8 texture: R = visible and G = explored, both feathered and eased over time exactly as the screen draws them, B = crisp visible and A = crisp explored. Texel (i, j) is the cell centred at x = x0 + (i + 0.5) * cellSize, z = z0 + (j + 0.5) * cellSize, and row 0 is the map's minimum z. Fog.bounds() gives x0, z0, x1, z1, cellSize, cols, rows.
Line of sight (stealth)
Set lineOfSight = true. Walls come from FogBlocker entities, Fog.setBlocker(key, min, max) rectangles, or Fog.scanBlockers() (the FogOfWar component's scanColliders), which casts a ray down every cell once and marks every collider standing taller than blockerHeight above groundY. Sources then see by casting rays across the blocker grid: you see the face of a wall but not behind it, and closed diagonal corners stay closed. It costs more than plain discs (rays instead of row fills), so it is meant for tens of sources, not hundreds.
Performance
Measured on desktop with 200 moving batched sources of radius 8-14 m on a 160 x 120 m map at 1 m cells (19,200 cells), with sources fed 10 times a second, while the engine was running other heavy work:
- Grid update: 0.6 ms average per update at 8 Hz, which comes to about 0.07 ms per frame at 60 fps. In isolation, update plus feeding all 200 sources takes about 0.95 ms.
- Upload: about 0.03 ms per update (one
writeBytesof the packed grid, 4 cells per byte-lane; nothing is converted). - GPU:
fog_smoothabout 0.01 ms,fog_applyabout 0.13 ms (the full-screen pass, median).
How: each source is stamped as one native buffer.fill per row span of its disc, into a byte buffer laid out exactly as the GPU reads it. All teams update at updateRate, not every frame, and the drawn fog eases between updates on the GPU.
Multiplayer
The fog is computed locally on every peer for that screen's viewer team, from positions every peer already has (synced units, avatars, buildings). Nothing is networked: there is no fog state to replicate, FogOfWar fields are local (NoSync), and hide/show from FogHideable change only this screen. Each player draws their own team's fog: set Fog.setViewer(myTeam) per peer, or let a FogSource with localViewer on the local player's avatar do it. The fog is for presentation and AI queries; it is not anti-cheat, since every peer still has every position.
Changes
-
1.0.3: documentation only. The README opens with what the kit gives you, then Install and Try it. No change to how the fog works.
-
1.0.2: a fog of a different size now draws after another one in the same session (a second map, a new play session). Before, the old GPU buffer kept its name and size, and the new fog was never drawn.
-
1.0.1:
Fog.followLocalPlayerlets the local player see; the README example runs as written.
Notes
- One fog per engine:
Fog.setupreconfigures the one shared grid. Changingcenter,sizeorcellSizerebuilds the grid and forgets explored ground; every other key changes in place. - Sky pixels follow their view ray down to
groundY; a ray that never comes down keeps the sky. Ground outside the map is unexplored. - For tall structures in
mist, raisemistHeightso the bank covers them. - Guide:
how-to-add-fog-of-war-to-a-strategy-or-stealth-game. Tests:tools.use("tests", "run", { suite = "fogOfWarKit" }).