# cityGen
A city generator for Zero's procGen. A world hands it a **template** (a table that describes one city: its ground,
its arterials, its districts and their rules, its landmarks) and gets back a planned city: the terrain, a road graph,
blocks, lots that front their streets, and a building programme for every lot, as procGen geometry with attributes
that any graph can read or rewrite between two stages, and as one baked record a game reads at run time.
Nothing in the package knows a particular city. The first template is Verrane (a fictional Lisbon) in the Painted
Metropolis world, `/zero/source/metropolis/verrane/template.module` + `templatePlan.module`.
## The stages
Every stage is a node of the `city` family (`city.nodebox`); the work of each is in the module of the same name,
run on the CPU through `io.luau`. What flows between stages is geometry with attributes, so a builtin node can
stand anywhere in the chain (`attribute.set` on the districts to restyle one, a filter on the lots, ...).
| node | takes | answers |
|-|-|-|
| `city.terrain` | `template.terrain` | a Raster: `height`, `water`, `land`, surface layers |
| `city.survey` | the raster | `survey` (a grid of points, `P.y` the ground) and `shore` (the shoreline, land on its left) |
| `city.arterials` | survey, `anchors`, `arterials`, `places` | `ways`: the skeleton. Each arterial routed over the ground for its class (grade limits, water closed except declared spans), rounded to the class's least radius; places as closed ways |
| `city.districts` | survey, ways, shore, `districts` | one closed curve per district, pulled onto the ways and shore that bound it, carrying EVERY rule as an attribute |
| `city.streets` | survey, ways, shore, districts, `streets`, seed | the local streets, grown per district from its pattern (tensor-field streamlines) |
| `city.network` | survey, ways, streets, shore, `places`, seed | `nodes`, `edges` (one planar graph), `roads` (the `pathNetwork` `fromPlan` record) |
| `city.blocks` | survey, nodes, edges, districts, `places` | one closed curve per block: the building line |
| `city.lots` | survey, blocks, nodes, edges, districts, `landmarks`, seed | one point per lot with the lot record |
| `city.massing` | lots, districts, `sectors`, `skyline`, `landmarks`, seed | the lots with their building programme |
| `city.plan` | all of it + `meta` | ONE record for run-time code |
A graph that plans a city (this is `/zero/source/metropolis/verrane/PlanDebug.procGraph`, less its debug drawing):
```luau
local T = require("metropolis.verrane.template") -- the terrain section
local P = require("metropolis.verrane.templatePlan") -- the plan sections
return proc.define(function(g)
local ground = g.city.terrain({ template = T.terrain, resolution = 4 })
local sv = g.city.survey({ raster = ground, step = 8 })
local skeleton = g.city.arterials({ survey = sv.survey, anchors = P.anchors, arterials = P.arterials, places = P.places })
local districts = g.city.districts({ survey = sv.survey, ways = skeleton.ways, shore = sv.shore, districts = P.districts })
local streets = g.city.streets({ survey = sv.survey, ways = skeleton.ways, shore = sv.shore,
districts = districts.districts, designs = P.streets, seed = P.seed })
local network = g.city.network({ survey = sv.survey, skeleton = skeleton.ways, streets = streets.streets,
shore = sv.shore, places = P.places, seed = P.seed })
local blocks = g.city.blocks({ survey = sv.survey, nodes = network.nodes, edges = network.edges,
districts = districts.districts, places = P.places })
local lots = g.city.lots({ survey = sv.survey, blocks = blocks.blocks, nodes = network.nodes, edges = network.edges,
districts = districts.districts, landmarks = P.landmarks, seed = P.seed })
local massing = g.city.massing({ lots = lots.lots, districts = districts.districts, sectors = P.sectors,
skyline = P.skyline, landmarks = P.landmarks, seed = P.seed })
local plan = g.city.plan({ survey = sv.survey, nodes = network.nodes, edges = network.edges, blocks = blocks.blocks,
lots = massing.lots, districts = districts.districts, meta = { name = T.name, seed = P.seed, places = P.places } })
return { plan = plan, lots = massing.lots, edges = network.edges }
end)
```
## The template
Frame: world metres, +X east, +Z south, +Y up. A point is `{ x, z }`. Every section is optional: a template with no
water, no hills, no places still plans a city.
**`terrain`**: see `city.terrain` (`rect`, `base`, `seaLevel`, `relief` spot heights and ridge lines, `shapes`, `land`).
**`seed`**: a number. Every draw is keyed by it and by what the draw is for (a district's name, a lot's place), so
editing one district leaves the others as they were.
**`anchors`**: named points, `{ rossio = { 40, 60 }, ... }`.
**`arterials`**: `{ name, class, via = { waypoint, ... }, straight = false, tram = false }`. A waypoint is an anchor's
name, a point `{ x, z }`, or `{ x, z | at = "anchor", span = "bridge" | "viaduct", deck = y, straight = true, pier = true }`.
Between waypoints the route is found over the ground and then SET OUT: the found route is reduced to the points
where it really turns, and one smooth curve (centripetal Catmull-Rom) is drawn through them and every waypoint,
rounded to the class's least radius; its heights are the ground eased along the way (longer for grander classes).
A `straight` leg (or arterial) is ruled. A `span` leg is a declared bridge: allowed over water, its deck running
between the `deck` heights stated (the ground's at its ends where none is); span waypoints in a row are ONE span
drawn as a smooth curve through them (a curved viaduct), unless a waypoint is its own `pier` (an anchorage, where
the span really breaks). An arterial that ends within 40 m of another ends on it.
**`places`**: two sorts.
- Designed outlines that are ways of their own and faces of the graph:
`{ name, kind = "square" | "roundabout" | "precinct", at, size = { w, d } | radius | outline = { ... }, yaw, class, width, closed = true, level }`.
Arterials are cut where they would run through a closed place; no street is grown inside one. `width` restates
the class's right of way (Verrane's waterfront square states 18.44: its arcade stands on the square's own way,
so the blocks behind begin at the arcade's back wall). `level` makes it a pad (below).
- Small named places, `{ name, kind = "largo" | "parvis" | "miradouro" | "market" | ..., at, maxArea = 6000, ground }`:
each takes the BLOCK it is stated in (the nearest within 40 m when stated on a way), which becomes kind `square`
(or `ground`, e.g. "park") and nobody's building ground. The streets round it are whatever the district grew.
**`streets`**: designed streets ruled before anything is grown: `{ name, class, width, district, via = { { x, z }, ... } }`.
A whole quarter can be designed this way (state `grow = 0` for its district: Verrane's Lowmarket grid).
**`districts`**: `{ name, code, pattern, outline = { { x, z }, ... }, anchor = { x, z }, snap = 60, rules = { ... } }`.
The outline is rough: points within `snap` metres of an arterial or place go onto it, points drawn over water go to
the shore, points on the map's rim stay there (the district runs off the map; no street is laid along the rim),
the rest is a free edge (an edge street, unless `edgeStreets = 0`). Neighbours that share a free edge state the
same points for it. `code` is the district's number in every stable key (below): state it and never change it.
Patterns: `grid`, `organic`, `radial`, `terraces`, `yards`, `villas`, `towers`, `waterfront`, `garden` (a garden
suburb), `farms` (the city's edge: lanes, a house here and there, more along the roads that leave), `campus`,
`allotments`, `cemetery`, `park`, `ground` (ONE use on one piece of ground: a street round it, nothing grown
inside: the district states `ground = "reservoir" | "stadium" | "railyard" | "quarry" | ...`), `none`. A pattern is
a set of rule values (`classes.module`, `Classes.patterns`); `rules` restates what differs. A district is also how
a large single use is stated: its `ground` becomes the `kind` of its blocks and a place of the baked plan.
The rules (`Classes.rules`, `Classes.ruleTexts`):
| rule | default | meaning |
|-|-|-|
| `angle` | 0 | heading of the grain, degrees clockwise from north |
| `radial` | 0 | 0..1: the grain is rays and rings about the anchor |
| `contour` | 0 | 0..1: the grain follows the contours where the ground slopes |
| `align`, `alignReach` | 0.6, 120 | how strongly, and from how far, ways and edges turn the grain to run along and square to them |
| `wander`, `wanderSize` | 0, 220 | noise that turns the grain (radians, metres) |
| `blockDepth`, `blockLength` | 50, 90 | metres between streets of the grain / between cross streets |
| `jitter` | 0.15 | unevenness of that spacing |
| `crossRate` | 1 | share of cross streets built |
| `tee`, `stopAt` | 0, 0 | share of streets leaving to one side only / chance a street ends on one it meets |
| `deadEnds` | 0 | share of dead ends kept as closes |
| `maxGrade`, `stairsGrade` | 0.18, 0.45 | steeper than the first a street becomes steps; steeper than the second nothing is built |
| `edgeStreets`, `quay` | 1, 10 | lay edge streets on free edges; metres of open quay along the shore |
| `grow` | 1 | 0 grows no streets inside (a designed quarter, a single-use ground) |
| `names` | "" | the word pools its grown streets are named from (`cityGen.names`: `trades pigments saints old sea trees works hills grand`; a template may add pools) |
| `streetClass`, `crossClass`, `edgeClass` | street | class of each family of streets |
| `lotWidth`, `lotDepth`, `lotJitter` | 12, 16, 0.2 | frontage and depth of a lot, unevenness of the cuts |
| `setback`, `gap`, `coverage` | 0, 0, 1 | metres back from the building line, metres between neighbours (0 = party walls), share of the plot built. All three at their defaults = a wall-to-wall district: its blocks are TILED (below) |
| `yard` | 6 | metres of private yard a plot keeps behind its building where the block is deep enough (tiled blocks) |
| `built`, `fill`, `ribbon` | 1, 1, 1 | 0 marches no lots; the share of lot slots built; how many times likelier than `fill` a slot on a street or grander way is built |
| `ground` | "" | what the district's blocks are when not plain building ground (free text: the block's `kind`) |
| `storeysMin`, `storeysMax`, `cornerBoost`, `mainBoost` | 3, 5, 1, 1 | storeys, and what a corner or a main street adds |
| `storeyHeight`, `groundHeight` | 3.3, 4.2 | metres |
| `shops`, `use` | 0.3, housing | share of shopfronts; the use lots take otherwise |
| `roof`, `kit`, `palette`, `palettes` | tile, "", "", 6 | texts the world's building generator reads; how many colours of the palette lots draw from |
Classes of way (`Classes.ways`): `highway boulevard avenue street lane track` (driven), `pedestrian quay alley path
stairs` (walked), `tramway`; `shore` and `limit` are edges that close blocks. `width` is the whole right of way.
**`landmarks`**: `{ name, kind, at, size = { w, d }, yaw, storeys | height, clear = 4, fixed, overhead, level }`: ground
reserved in the block that holds `at` (moved in from a building line it crosses), emitted as a lot with
`use = "landmark"`. `fixed = true`: it stands EXACTLY where stated (an arch on a square's edge, a church on its
terrace, a tower in the water): every block it reaches keeps clear of it and no street is grown across it
(`overhead = true`: streets may pass under: a walkway). `level` makes its ground a pad. Sizes should be the
delivered models' footprints: the template is bent to the models, not the reverse.
**`sectors`**: `{ name, outline, rules = { ... } }`: rules laid over the district's for the lots inside the outline.
**`skyline`**: `{ kind = "ring" | "peak", at, radius, width, storeys, only = district }`: storeys added round a place.
## Lots: tiled blocks and the lot record
Where a district builds wall to wall (`gap = 0`, `setback = 0`, `coverage = 1`: an old town, a downtown, terraces)
its blocks are TILED by `cityGen.parcels` (`Parcels.tile(poly, fronts, opt)`), not marched with rectangles:
- a sharp outward corner between two streets takes a corner lot that WRAPS it: a kite whose two outer sides are
its two street fronts and whose inner sides stand square to them;
- between corners the frontage is cut by walls square to it, always at a kink of the building line, so a front
never bends inside a lot and follows any curve without steps or wedges;
- a lot runs back `lotDepth`, or to the middle of a shallow block where it meets the lot fronting the other street;
- neighbours share the two ends of their common wall exactly (party walls coincide; no gaps, no overlaps);
- behind each building its plot keeps a yard strip (`yard`), and what no plot takes is the block's COURT; one lot
per court is marked `passage` (the archway in).
Districts of detached buildings (villas, towers, yards, garden, farms, campus, waterfront) keep rectangles marched
along each street side.
One point per lot (`P` = the middle of the box round its footprint at the level it is built at):
`id` (STABLE, below), `yaw`, `fx`, `fz` (unit vector to the street), `orient` (turns a +Z facade to the street),
`width`, `depth` (the box round the footprint, square to its front), the FOOTPRINT `pn`, `px1..8`, `pz1..8`,
`py1..8` (ground at each corner), `pk1..8`: a convex polygon, counter-clockwise seen from above (north up), corner
1 -> 2 the main street front with corner 1 on the left as seen from that street; `pk<i>` says what the side leaving
corner i is (1 street, 2 party wall, 3 yard). The yard strip `yn`, `yx1..4`, `yz1..4`. `front` (metres of main
frontage), `footprint` (m2), `frontFall` (how much the ground falls along the front: a level front takes a shop
floor or a room to enter), `passage`; `g0..g3` (ground at the box's corners), `low`, `high`, `parcelWidth`,
`parcelDepth`, `setback`, `edge` (graph edge fronted), `edge2`, `corner`, `cornerSide` (the second street of a
corner lot: 1 to its right, -1 to its left, as seen from the street), `partyL`, `partyR`, `block`, `district`,
`use`, `frontClass`, `storefront`, `landmark`; and from massing: `storeys`, `groundHeight`, `storeyHeight`,
`height`, `tiers`, `tier2At`, `tier3At`, `tierInset`, `roof`, `kit`, `palette`, `colour`, `seed`, `sector`.
`Lots.shape(lot)` gives `poly, kinds, yard` back from the columns; the ground is reported, not flattened.
`city.lots` also answers `courts`: closed curves (`block`, `district`, `area`).
## Stable ids: what a re-plan preserves
`id` of a node, edge or block is its place in this plan's lists (what the plan's own columns refer to one another
by) and may change whenever anything is re-planned. What a save, a baked mesh or a mission keys on is:
- a district's `code` (stated in the template; never reuse one);
- a block's `key` = code * 1000 + its number among that district's blocks (north to south, then west to east);
- a lot's `id` = its block's key * 1000 + its number round the block (clockwise from due north of the block's
middle); a landmark's lot is 90,000,000 + its place in the template's list;
- an edge's `key` = its line's key * 128 + the n-th stretch of that line. A line is an arterial or designed street
(keyed by its NAME) or a grown street (its district's code * 4096 + its number in that district's growth);
- a node's `key` = the smallest key of the edges that meet there, * 2, + 1 at that edge's far end.
So: editing one district re-keys that district's blocks, lots and grown streets, and nothing in any other district;
within it, blocks keep their keys while the count of blocks before them (in reading order) is unchanged, and a
block's lots keep their ids while that block's lots are unchanged. Adding a street to an arterial re-keys the
arterial's stretches after the new junction. A change of the template's `seed` re-grows everything grown.
Every grown street has a NAME (deterministic: seed, district, the street's number there; no name twice).
## Run time: the baked plan and `cityGen.query`
A Generator does not cook in play. Bake the plan at edit time and read it as data:
```luau
-- a bake script (edit mode)
local plan = asset.resolve("/zero/source/metropolis/verrane/PlanDebug.procGraph"):eval("plan")
require("cityGen.export").write(plan, "metropolis/verrane", "cityPlan") -- three generated modules
-- the game
local Query = require("cityGen.query")
local city = Query.new(require("metropolis.verrane.cityPlan"))
local district = city:districtAt(x, z) -- { name, pattern, rules, ... } | nil
local hit = city:nearestEdge(x, z, { drive = true }) -- { edge, s, distance, x, y, z, tx, tz, side }
local lane = city:nearestLane(x, z, hx, hz) -- { edge, direction, lane, x, y, z, tx, tz }
local route = city:route(x0, z0, x1, z1, { mode = "drive" }) -- { edges, nodes, length, points }
local px, py, pz = city:randomPavementPoint(rng, { district = "Lowmarket" })
local lot = city:lot(city:lotAt(x, z)) -- the lot record, texts resolved
local roads = require("@builtin::modules.pathNetwork").fromPlan(city:roadPlan(), { terrain = false })
local poly, kinds, yard = city:lotShape(i) -- the footprint polygon, what each side is, the yard strip
```
The record's shape (version 2) is stated at the top of `export.module`; `query.module` states every question.
Beyond roads, blocks and lots it carries `courts` (block interiors), `places` (with `outline` and `block` where a
place has ground: squares, small places, the large grounds, landmarks, bridgeheads, tram stops, points of interest)
and `pads` (`{ name, kind, level, outline }`: ground a designed place or landmark needs level).
Bake from a script that calls `cityGen.export` itself (a graph's `io.luau` may hold an older instance of a module
after a module-only edit):
```luau
local all = asset.resolve("<your plan graph>"):eval("all")
local plan = require("cityGen.export").plan(all.survey, all.nodes, all.edges, all.blocks, all.lots, all.districts, meta, all.courts)
require("cityGen.export").write(plan, "metropolis/verrane", "cityPlan")
```
## Designed ground: beds, pads and what covers them
A city does not stand on the ground as found. `city.terrain` takes a second, optional input beside the template's
terrain: `design`, the ground the PLAN asks for, laid over the landform in the same cook (`cityGen.beds`):
```luau
design = {
rect = { x0, z0, x1, z1 }, -- where it applies (left out: the bounds of what it states)
shoulder = 6, drop = 0.12, -- metres designed ground takes to ease into the natural; metres the ground lies under a stated surface
beds = { { pts = { x, y, z, ... }, width, shoulder?, drop?, cover? } }, -- a strip along a 3D polyline: level across
pads = { { outline = { x, z, ... }, level?, shoulder?, drop?, cover? } }, -- a polygon at one level (no level: cover only)
cells = { step, x0, z0, scale, rows = { { j, i, { h, ... } } } }, -- a surface stated lattice point by point
over = { pads laid last: the ground under each building },
}
```
Shapes lay over one another in that order. Each cell of designed ground takes the stated height (minus `drop`); the
height then spreads outwards ring by ring over the shoulder, its hold on the natural ground easing to nothing, so
a road bed has eased shoulders, a terrace a bank, and two building pads at different levels a STEP between them
(a hill town is terraced). `cover` says what the ground is: `paved` (the default: ways, squares, quays, steps, the
ground under buildings) or `earth` (yards, courts). Every raster of `city.terrain` carries the layers `paved`,
`earth` and `bare` (either), zero where nothing is designed, and `meadow` / `cliff` exclude `bare`: a world's
vegetation reads growth = 0 there and its ground material paves it.
The design is DATA, baked from the plan once the streets are meshed (Verrane: `metropolis/verrane/groundDesign.module`,
written by the bake script `plan2/lua/design.luau` of the job folder; the recipe for another world):
- `cells` = the street mesher's own finished surface on the terrain's lattice
(`cityGen.streetscape.bed(model, rect, { step, origin = the terrain's cell centres })` packed by `Beds.cells`),
so the ground under a street is that street's surface and nothing else;
- `pads` = the plan's `pads` (squares and terraces at their `level`), quays and squares as cover, courts as `earth`;
- `over` = every lot's footprint at the lot's DESIGN LEVEL (`lots.level`: the street surface at the middle of its
front; the pad lies 0.10 under it), and its yard strip at the same level as `earth`.
The terrain graph passes it on: `g.city.terrain({ template = Template.terrain, resolution = 2, design = Design })`.
The grid is built in Luau when the graph is built, on the raster's own cell centres (a cell reads exactly its own
sample); a 600 x 500 m rect at 2 m is 78,000 cells. A whole 4 km map at 2 m is 3 million: that needs the design
as a baked texture or in tiles (not done yet).
## Use in another world
1. Install the package (or copy `cityGen.package` to the world root).
2. Write a template module: start from `templatePlan.module` of Verrane. Draw the anchors and arterials first,
cook, look; then the districts.
3. Write a graph like the one above (requiring YOUR template), spawn it on a Generator in edit mode to look at it,
or evaluate it from a script (`ref:eval("plan")`).
4. Bake the plan with `export.write` and read it in the game through `cityGen.query`.
`cityGen.pipeline.run(S, template)` runs every plan stage back to back in Luau on a survey table (for tests, tools,
a profile); `cityGen.debug` draws plan pictures and debug boxes for generator QA (never the city's art).
## Checks
`cityGenPlan.testSuite` plans a small city on a made ground and checks determinism, one connected road graph, dry
ground ways, no overlapping lots, every lot on its way, sectors, and a template with no water.