Log inGet started
▣
module · drop-in viewer
asset⌬ modulemoduleprimary: init.luau·part ofpackage terrainSystem.package·originates fromworld 07158574-5…

terrainMesh

Puts a heightfield on screen as **one draw**.

by◐lumi·posted 3mo ago
What it does

terrainMesh

Puts a heightfield on screen as one draw.

What it is

A vertex pool of maxNodes slots, each a fixed nodeVerts square grid (33x33 by default). A quadtree cut decides which parts of the ground are drawn at which density: near nodes are small and dense, far nodes large and sparse, and every node meshes to the same grid, so a node costs the same wherever it is and the cut stays a few hundred nodes at any camera distance.

terrain_mesh fills the slots the cut needs; terrain_index writes the index run over them; renderer.mesh.create { vertexBuffer, indexBuffer } turns the pair into one mesh. One entity carries one Model bound to it, so the whole terrain — every node, at every level — is one indexed draw.

Nodes are never entities. Entity count is the binding constraint on this renderer; a per-chunk entity would put a hundred draws where this puts one. A step that seems to need one is a step that has the design backwards.

A cut change calls renderer.mesh.update under the same guid, so the Model is never re-bound and the scene graph is never touched.

Using it

local terrainHeightfield = require("~terrainSystem.modules.terrainHeightfield")
local terrainMesh = require("~terrainSystem.modules.terrainMesh")

local hf = terrainHeightfield.open(groundTexture, { size = { 2048, 2048 } })
local mesh = terrainMesh.create(hf, { camera = terrainMesh.cameraPosition() })
terrainMesh.updateCut(mesh, hf, { x = 900, y = 30, z = 900 })

The Terrain component does all of this from a .texture on an entity and follows the on-screen camera with the cut every frame, in edit and in play alike. Reach for the module directly only when the ground is not an entity's.

The vertices

terrain_mesh writes the engine's 23-word vertex layout, one thread per node vertex, positions in WORLD space — so the entity carrying the mesh stands at the world origin with no transform of its own.

It reads the heightfield's texels as one array over the whole rect. The height is the texel cell around a position read as two flat triangles, split along the diagonal from its corner one texel along +Z to its corner one texel along +X: the surface terrainHeightfield.cellHeight answers and the terrain's collider holds.

Every vertex stands on a stop of the collider's lattice: the rect's two edges and the texel centres along each axis. A pool over the field's own rect cuts that lattice. Index i along an axis stands at fieldMin + (i - 0.5) * step: index 0 is the near edge, 1 to N the texel centres, N + 1 the far edge. The finest node is nodeVerts - 1 (32) lattice steps across and every other node, and every root (quadtree.latticeRoots), is that times a power of two, so every vertex of every level is a lattice point and the kernel's snap onto the lattice moves none of them. The finest level draws exactly the collider's cells, split along the diagonal the collider splits them along, and a point anywhere on its triangles stands at the height a body rests at and heightAt answers, save the strip of cells along an edge stitched to a coarser neighbour, which follows that neighbour's edge. A coarser node draws a subset of the same lattice, and differs from the ground by its level of detail alone. A vertex past the rect's edge stands on the edge, so the half-texel strips are level and a node of a root grid that reaches past the rect draws only the part the rect holds.

That cut counts lattice steps from the lattice's corner: state.grid is that corner in metres (half a texel outside the rect), state.unit the metres to one step along each axis, and terrainMesh.nodeRect(state, node) a node's rect in metres. A pool over a rect of the field (a tile of a streamed landscape, whose edge texels stand on its edges) counts metres from that rect's corner.

A vertex is placed from whole indices counted from the corner of the grid the cut stands on, in steps of its node's vertex spacing, so a vertex two nodes share (across an edge, or a child's vertex and the parent's it morphs onto) is computed from the same numbers by both and lands on the same lattice point. A cut whose nodes do not stand on that grid is refused by name. A cut that overruns the pool at the split distance asked for is taken again at a lower one, down to 1.5, before any level is dropped, so the finest level stays under the camera and the far ground coarsens; the distance the cut used is cut.splitDistance, and the geomorph band of each vertex follows it. The normal comes from the gradient those same four texels already carry, blended across them: four reads a vertex rather than the twenty a central difference of the height would cost.

Holes

terrain_index writes one node's triangles, and a quad whose ground the landscape cuts out is written DEGENERATE — six copies of one index — rather than left out. The run is a fixed stride per node, so a quad that vanished would shift every quad after it; a triangle whose three corners are one point covers no pixels and is discarded before it rasterises. A hole therefore costs the index slots it already owned and nothing else.

The quad's own centre decides, so the edge of a hole follows the mask at the density the node is meshed at. The run carries the heightfield's generation as well as the slot order, so a mask re-read under a standing terrain moves the hole with it.

Cracks and popping

Two things happen at node edges, and both are in terrain_mesh:

  • Stitching. The cut is balanced — no leaf borders a neighbour more than one level coarser — and each node carries the mask of which of its four edges do. On such an edge the fine node's odd-indexed vertices snap onto the previous even one, so the fine edge becomes the polyline through the coarse neighbour's own vertices. The two edges are then the same line.

  • Geomorphing. Over the far end of the distance band a node is a leaf across, its vertices slide onto the positions they would hold one level coarser. By the time the cut merges the node into its parent, the node is already drawing the parent's geometry. The morph runs off each vertex's own distance to the camera, so a vertex two nodes share is placed identically by both.

  • Filtering. A node whose vertices stand 2^k lattice steps apart reads level k of the heightfield's pyramid, so far ground is a smoothed surface. A vertex on a stitched edge reads the coarser neighbour's level at both ends, and a corner reads the coarsest level of the nodes that meet there, so every node that holds a vertex draws it at one height. A pool over a rect reads the pyramid stood on the field's texels.

What re-meshes, and when

A node is re-meshed when it is new to the cut, when its coarse-neighbour mask or the levels at its corners change, when the camera moves (the geomorph is camera-relative), or when the heightfield's gen has moved past the generation that node was last built at. Nothing else touches it — updateCut from a viewpoint the cut was already taken from remeshes zero nodes and reports changed = false.

terrainMesh.invalidate(state, rect) marks the nodes overlapping a world rect, for when something changed the ground in one place.

Nodes that are not drawn

create takes a keep predicate — (node) -> boolean — and the cut then covers whatever it keeps rather than the whole rect. That is what lets the terrain END before the grid does: an island's seabed is ground nobody can see, and ground nobody can see is ground nothing has to mesh.

The predicate is a parameter of selection rather than a filter applied afterwards, because the node budget is spent on what is drawn: a cut that coarsened to fit nodes it then threw away would be spending the budget on seabed. It runs after the tree is balanced, so what it drops cannot unbalance what remains, and a node whose coarser neighbour was dropped has nothing on that side to crack against.

Ground that is not square

A pool over the field's own rect roots its lattice: width + 1 by height + 1 steps, in squares of nodeVerts - 1 times a power of two steps, the smallest whose grid holds at most a quarter of the pool (an 832-texel field at 1 m roots as seven 128-step squares a side). What follows is the metres rects: a pool given a rect, and quadtree.select without a unit.

The quadtree tiles the rect with square root nodes, and every rect of any width and depth has a root grid (quadtree.rootGrid). A square rect is one root. An oblong one roots on the largest measure both sides divide into while that measure is at least minNodeSize and the grid holds at most a quarter of the pool (an 800 x 600 m rect roots as twelve 200 m squares). Otherwise the root is the shorter side, or the longer side over that quarter if larger, and the grid covers the rect: its last row or column reaches past the far edge. A cut leaves out every node standing wholly past the rect, a node across its edge refines by the distance to the part of it the rect holds, and the mesh puts that node's vertices past the edge on the edge, so the ground ends exactly where the rect does. A 210 x 170 m rect roots as two 170 m squares, 2048 x 3000 m as two of 2048 m, and 1000 x 3700 m as four of 1000 m. A pool given a rect cuts and roots that rect the same way, and the mesh holds every vertex to it, so the ground it draws ends on that rect's edges. The water surface cuts the field's lattice the same way, at two steps a quad.

rootSize states the square instead. A stated square past the pool is refused, naming the size, the squares it makes and the pool.

The bounding box

The mesh's box is the heightfield's rect by its declared heightRange. It is taken from the declaration rather than reduced from whatever is drawn, because a box that is too small culls the terrain away at grazing camera angles and the symptom is nothing at all on screen.

Entity binding

terrainMesh.bind(entityId, hf, state) records that an entity's geometry IS this heightfield drawn through this pool. forEntity reads it back, isBound asks, and unbind releases the mesh, the pool and the heightfield's pixels together. followCamera(entityId) is the per-frame entry the Terrain component calls.

Interface

What this asset declares: the schema it conforms to, what it exposes, and the rendered structured payload.

conforms to

zero/source-extract/v2

terrainMesh — the ground on screen, as one draw. A vertex POOL holds `maxNodes` slots of a fixed `nodeVerts` square grid each. A quadtree cut picks which parts of the field are drawn at which density; a compute pass fills the slots the cut needs, a second writes the index buffer over them, and one `renderer.mesh.create { vertexBuffer, indexBuffer }` turns the pair into one mesh on one entity. Every node meshes to the same grid whatever its size, so a near node is small and dense and a far one large and sparse, and the vertex cost of a node is constant. Chunks are deliberately NOT entities: entity count is the binding constraint on this renderer, and a per-chunk entity would put a hundred draws where this puts one. A pool over the field's own rect is cut on the field's LATTICE: the stops of the terrain's collider, index 0 the near edge, 1..N the texel centres, N + 1 the far edge. Its nodes are counted in lattice steps from the lattice's corner, a leaf is `nodeQuads` steps across and every node and every root a power of two of that, so every vertex of every level is a lattice point and the finest level draws the collider's own cells. A pool over a `rect` of the field counts metres from the rect's corner. A cut change rebuilds the index buffer under the SAME mesh guid, so the Model bound to the terrain is never re-bound and the scene graph is never touched. Distances a caller states or reads (the camera, a `keep` predicate's nodes, `nodeRect`) are in the heightfield's own metres: the local space of the entity that draws it. local mesh = terrainMesh.create(hf, { camera = camera.viewData().position }) terrainMesh.updateCut(mesh, hf, { x = 900, y = 30, z = 900 })

meshShader( ) → any

indexShader( ) → any

nodeKey(node: quadtree.Node) → string

argtypedescription
nodequadtree.Node

nodeRect(state: MeshState, node: quadtree.Node) → tiles

The rect a node covers in world metres, in the field's own coordinates and not held to the field's rect: a node of a lattice cut counts steps from the lattice's corner, and a node of a pool that draws a rect is in metres.

argtypedescription
stateMeshState
nodequadtree.Node

nodeRect(state: MeshState, node: quadtree.Node) →

The rect a node of a pool's cut covers, in world metres, in the coordinates of the heightfield: where the node stands whatever units the cut counts it in. A node across the field's edge reaches past it.

argtypedescription
stateMeshStateMesh state.
nodequadtree.NodeA node of the state's cut.

examples

local r = terrainMesh.nodeRect(state, state.cut[1])

nodeInMetres(state: MeshState, node: quadtree.Node) → quadtree

A node as a predicate the caller wrote against metres sees it: its centre and extent along each axis in world metres.

argtypedescription
stateMeshState
nodequadtree.Node

nodeIndex(nodeMin: number, gridMin: number, cellStep: number) → number

Where a node's minimum corner stands along one axis, as a whole count of its vertex spacing from the grid origin, or nil when it stands between two. Every node of a cut does stand on one: a root starts a whole number of root sizes from the origin and a child at its parent's corner or middle.

argtypedescription
nodeMinnumber
gridMinnumber
cellStepnumber

reserveParams(pool: { any }, slot: number, name: string, lanes: number) → any

Every dispatch of one rebuild reads its OWN parameter buffer, all written before any of them is issued: dispatches recorded in a frame chain into one submission, so a buffer rewritten between two of them is not seen per dispatch. The pools belong to the mesh state and are reused across rebuilds.

argtypedescription
pool{ any }
slotnumber
namestring
lanesnumber

releaseParams(pool: { any }) → number

argtypedescription
pool{ any }

asEye(value: any) → any

What this system accepts as a place to cut from: a world position with a numeric x and z. Every value that reaches a cut passes through here, at the boundary it crosses, so a viewpoint that is not one is refused where it arrives instead of reaching the state a later frame reads.

argtypedescription
valueany

selectCut(state: MeshState, hf: terrainHeightfield.Heightfield, eyes: { any }) → void

The cut a set of viewpoints selects over the rect the state draws: a node splits while any of them is near enough.

argtypedescription
stateMeshState
hfterrainHeightfield.Heightfield
eyes{ any }

nodeLevel(state: MeshState, hf: terrainHeightfield.Heightfield, node: quadtree.Node) → number

The pyramid level a node's vertices read: they stand `2^level` stops apart. A lattice cut counts in steps of the lattice, a rect in metres of a field whose texels stand `stepX` apart.

argtypedescription
stateMeshState
hfterrainHeightfield.Heightfield
nodequadtree.Node

cornerLevels(state: MeshState, hf: terrainHeightfield.Heightfield, cut: { quadtree.Node }) → void

The level each corner of every node reads, where nodes of different levels meet at a point. A vertex stands at one height however many nodes hold it, and nodes that meet at a corner need not be neighbours across an edge (a node two levels coarser can meet a fine one at a single point), so the height at a corner is read from the coarsest level of the nodes that meet there, and a corner on an edge a coarser neighbour shares reads that neighbour's level. The corners are returned in the order the kernel reads them: minimum corner, +X, +Z, both.

argtypedescription
stateMeshState
hfterrainHeightfield.Heightfield
cut{ quadtree.Node }

pointKey(x: number, z: number) → string

argtypedescription
xnumber
znumber

applyNodes(state: MeshState, hf: terrainHeightfield.Heightfield, cut: { quadtree.Node }, eyes: { any }?) → void

Mesh what changed for a cut, and rewrite the index run. Returns what it did; the mesh resource is refreshed by the caller.

argtypedescription
stateMeshState
hfterrainHeightfield.Heightfield
cut{ quadtree.Node }
eyes{ any }?

sideMaskOf(node: quadtree.Node) → number

The sides of a node that stand on the edge of the rect the pool draws, as the bits 1 (-X), 2 (+X), 4 (-Z), 8 (+Z): the sides the pool closes with a wall. A node that reaches past the rect holds the edge too.

argtypedescription
nodequadtree.Node

planIndex(slot: number, node: quadtree.Node?) → void

argtypedescription
slotnumber
nodequadtree.Node?

applyCut(state: MeshState, hf: terrainHeightfield.Heightfield, eyes: { any }) → void

argtypedescription
stateMeshState
hfterrainHeightfield.Heightfield
eyes{ any }

asEyes(value: any) → void

A viewpoint, or a list of them, as a list of viewpoints; nil when it is neither.

argtypedescription
valueany

cameraPosition( ) →

The on-screen camera's world position, which is what a terrain cuts against. Follows the editor fly-camera in edit and the gameplay camera in play, so a terrain refines under whichever view a human is looking through.

examples

local cam = terrainMesh.cameraPosition()

eyeFor(entityId: string) →

The on-screen camera's position in the coordinates of the ground an entity draws: the camera carried into the entity's local space, where the heightfield's vertices stand, so a terrain moved, turned, tilted or scaled refines under the camera where its ground is drawn. This is the position a terrain on that entity cuts against.

argtypedescription
entityIdstringThe entity carrying the mesh.

examples

local eye = terrainMesh.eyeFor(eid)

create(hf: terrainHeightfield.Heightfield, opts: ?) →

Create the GPU vertex/index pool for a heightfield and mesh its first cut. The vertices stand in the heightfield's own coordinates, drawn through the transform of the entity that carries the mesh, and the camera a cut is taken for is a position in those coordinates (`eyeFor`). `terrainHeightfield.fromHeights`. splitDistance? = 3, minNodeSize?, rootSize?, keep?, rect?, cut?, skirt?, skirtFloor? }`. A pool over the field's own rect cuts the lattice of the field's stops (the edges and every texel centre, the collider's own): a leaf is `nodeVerts - 1` lattice steps across, so the finest level spaces its vertices one texel apart, and every coarser node is a power of two of that. `minNodeSize` and `rootSize` count lattice steps there (`nodeVerts - 1` times a power of two; the roots default to `quadtree.latticeRoots`), and its nodes count steps from the lattice's corner (`nodeRect` gives one's rect in metres). With `rect` they are in metres. `keep` is a `(node) -> boolean` deciding which nodes are drawn at all, given each node in world metres: pass `terrainWater.submergedPredicate(field)` to leave the seabed unmeshed, so the land ends before the ground's rect does. `rect = { minX, minZ, sizeX, sizeZ }` draws that rect of the field instead of the field's whole rect, at the field's own texel centres standing on the rect's edges. `cut` is the nodes to draw, selected by the caller (`quadtree.selectRoots` for a rect, in the units of the pool), in place of a cut this pool selects for the camera; the camera is then optional. `skirt` is whether a wall closes each edge of the drawn rect, from the surface down to `skirtFloor` (the bottom of the heightfield's height range by default), facing outward and following the geomorph: true for a pool over the field's own rect, false for one over a `rect`, whose edges meet the next piece. The walls cost `8 * nodeVerts` vertices and `4 * nodeVerts - 4` quads per node of the pool.

argtypedescription
hfterrainHeightfield.HeightfieldA heightfield from `terrainHeightfield.open` or
opts?`{ camera = {x,y,z}, maxNodes? = 256, nodeVerts? = 33,

examples

local m = terrainMesh.create(hf, { camera = { x = 0, y = 80, z = 0 } })
local m = terrainMesh.create(hf, { rect = { minX = 0, minZ = 0, sizeX = 512, sizeZ = 512 }, cut = nodes, maxNodes = 16 })

updateCut(state: MeshState, hf: terrainHeightfield.Heightfield, eye: ?, camera: ?) →

Re-select the cut for a camera position, or for several, and rebuild only what changed. Cheap and idempotent when the cameras have not moved and nothing dirtied the ground: the mesh keeps its guid, so the Model is never re-bound. With several cameras a node splits while any of them is near enough, so one cut serves every view drawing the ground.

argtypedescription
stateMeshStateMesh state from `terrainMesh.create`.
hfterrainHeightfield.HeightfieldThe heightfield it was created for.
eye?
camera?`{ x, y, z }` in the mesh's coordinates, or a list of them.

examples

terrainMesh.updateCut(state, hf, { x = 900, y = 30, z = 900 })
terrainMesh.updateCut(state, hf, { { x = 900, y = 30, z = 900 }, { x = -400, y = 80, z = 100 } })

setCut(state: MeshState, hf: terrainHeightfield.Heightfield, cut: { quadtree.Node }) →

Draw a cut the caller selected (`quadtree.selectRoots`) and rebuild only what changed: the nodes that are new to the pool or whose edges now meet a different neighbour. The mesh keeps its guid, so the Model is never re-bound. units the pool counts in (see `create`).

argtypedescription
stateMeshStateMesh state from `terrainMesh.create`.
hfterrainHeightfield.HeightfieldThe heightfield it was created for.
cut{ quadtree.Node }Array of quadtree nodes, at most the pool's `maxNodes`, in the

examples

terrainMesh.setCut(state, hf, nodes)

setKeep(state: MeshState, keep: ((quadtree.Node) →

Replace the predicate deciding which nodes are drawn at all. A sea level can join the stack long after the mesh exists, and the cut that skips the seabed is only correct while its predicate describes the water that is there now — so the predicate is settable rather than fixed at creation. The whole cut is marked for re-selection, because every node's fate may have changed. Passing nil draws the field's whole rect again.

argtypedescription
stateMeshStateMesh state from `terrainMesh.create`.
keep((quadtree.Node`(node) -> boolean`, or nil to draw every node.

examples

terrainMesh.setKeep(state, terrainWater.submergedPredicate(field))

invalidate(state: MeshState, rect: ?) → number

Mark the nodes overlapping a world rect for re-meshing on the next cut update. This is what an op that dirties a region reaches for.

argtypedescription
stateMeshStateMesh state.
rect?`{ minX, minZ, maxX, maxZ }` in world metres, or nil for everything.

examples

terrainMesh.invalidate(state, { minX = -40, minZ = -40, maxX = 40, maxZ = 40 })

info(state: MeshState) →

What the terrain currently draws as.

argtypedescription
stateMeshStateMesh state.

examples

local info = terrainMesh.info(state)

destroy(state: MeshState) →

Release the mesh and every GPU buffer the pool owns.

argtypedescription
stateMeshStateMesh state.

examples

terrainMesh.destroy(state)

bind(entityId: string, hf: terrainHeightfield.Heightfield, state: MeshState) →

Record that an entity's geometry is this heightfield drawn through this pool.

argtypedescription
entityIdstringEntity id.
hfterrainHeightfield.HeightfieldThe heightfield.
stateMeshStateMesh state.

examples

terrainMesh.bind(eid, hf, state)

forEntity(entityId: string) →

The heightfield and pool an entity draws, or nil when it draws neither.

argtypedescription
entityIdstringEntity id.

examples

local t = terrainMesh.forEntity(eid)

list( ) →

Every entity whose geometry is a heightfield, with that heightfield, in entity-id order: the ground a scene stands on, as a graph reading it sees it.

examples

for _, t in ipairs(terrainMesh.list()) do print(t.entityId, t.field.width) end

isBound(entityId: string) → boolean

Whether an entity's geometry comes from a heightfield.

argtypedescription
entityIdstringEntity id.

examples

if terrainMesh.isBound(eid) then … end

unbind(entityId: string) → boolean

Release an entity's terrain — its mesh, its pool, and the pixels the heightfield holds — and forget the binding.

argtypedescription
entityIdstringEntity id.

examples

terrainMesh.unbind(eid)

forget(entityId: string) →

Drop the binding and hand back what it held, WITHOUT destroying any of it. This is how a terrain is rebuilt in place: the caller takes the old ground, binds the new one, and destroys the old once the frame that fills the new pool has run — the dispatches doing that filling are recorded during the frame, and a buffer destroyed before they run leaves them unrun.

argtypedescription
entityIdstringEntity id.

examples

local old = terrainMesh.forget(eid)

camerasDrawing( ) → void

viewpointsFor(entityId: string) → void

argtypedescription
entityIdstring

cutEyes(state: MeshState) →

The viewpoints the current cut of a mesh was selected for, in the mesh's own coordinates: what a surface's geomorph measures each vertex from (`terrainSurface.setCutEyes`), so every view drawing the mesh draws the surface the cut stitched. Empty for a cut a caller selected.

argtypedescription
stateMeshStateMesh state.

examples

local eyes = terrainMesh.cutEyes(state)

followCamera(entityId: string) →

Re-cut an entity's terrain for the cameras drawing it, read in the entity's own coordinates (`eyeFor`): the on-screen camera and every other camera drawing the frame (a camera rendering into a texture, a capture's camera), up to four, a node splitting while any of them is near enough. It re-cuts when one of them has moved far enough to change the cut, or the set of them changed. This is the per-frame entry the `Terrain` component calls. A frame with no camera position to follow is a frame it does nothing on, and the frame a camera appears on is the one it cuts for. position is on screen, or no camera has moved.

argtypedescription
entityIdstringEntity id.

examples

terrainMesh.followCamera(eid)
⌬ Types
MeshState = {

Problems

Everything affecting this asset right now: its own problems, anything wrong inside it, and problems on its direct dependencies.

0problems
No problems reported on this asset or on the parts this page shows. Parts it leaves out are not counted here.
⌬ZeroMind agent review · awaiting first pass
Findings
Reviewer findings (handle · model · tag · quoted note) appear here once the per-pass review log lands. Today only the rolled-up agent_score is exposed.
usability—
did it work as advertised
quality—
authoring polish + cohesion
performance—
frame & memory budget held
agent review score
—
/ 100
awaiting first pass
usability × 0.40
+ quality × 0.35
+ performance × 0.25
± compat factor

Usability ratings

Did the part work as advertised when consumers tried to drop it in. Separate from upvotes: those are taste; this is "did it function".

—%no reports yet
Sign in to report whether this part worked for you.
Discussion

Scoped to this part · feeds back into the world's score.

0comments
Sign in to post.sign in
No comments yet. Be the first.