# core.adjacency (procNode)
Answer a neighbour relation over a geometry as a table of offsets and items: the points around a point, the primitives that use a point, the primitives across an edge, the edges and points of a primitive, and the rest of eight relations.
Relations (`<owner>_<listed>`): `point_points`, `point_faces`, `point_edges`, `face_points`, `face_edges`, `face_faces`, `edge_points`, `edge_faces`. Built from `core.owner`, `core.edges`, the `expand` kernel (a side or an end per edge; the two faces of each edge that has two are laid out over the live total of those pairs, which one read-back states), `sort` of the owner keys, `scatter` for each owner's count, `scan` for the offsets and `gather`. Outputs: `offsets` (where each owner's list starts in `items`), `counts` (the length of each list) and `items`. The relation's owners are numbered as its first word says: points, primitives or edges.
## Inputs
- `geometry` (Geometry). The geometry whose neighbours are listed.
- `relation` (one of point_points, point_faces, point_edges, face_points, face_edges, face_faces, edge_points, edge_faces). Default `"point_points"`. Which relation: the owner's kind, then the listed kind. "point_faces" lists, for each point, the primitives that use it.
## Outputs
- `offsets`: where each owner's list starts in `items`.
- `counts`: the length of each owner's list.
- `items`: the listed elements, owner after owner.
# core.arclength (procNode)
The length along every curve: each point's distance from the start of its curve as `s`, and each curve's total as `length`.
Built from `core.owner`, `attribute.promote` (positions to vertices), `gather` of each vertex's next position, `math.length`, a segmented `scan` for the distance so far and a segmented `reduce` for the total. A closed curve counts its closing segment in `length`; an open curve has none. Written as `s` on the point class and `length` on the primitive class.
## Inputs
- `curve` (Curves). The curves measured.
## Outputs
- `curve`: the curves with `s` (distance along the curve) on the point class and `length` (the curve total) on the primitive class.
# core.boundary (procNode)
The open edges of a geometry and the rings (or chains) they form, each ordered along its walk.
Built from `core.edges`, `compact` of the open edges, the `loops` kernel (the edge that follows each one), `jump` rounds (the smallest edge in reach, then the distance to the end of each list; the rounds are `ceil(log2(edges))`), `loops_cut` and `loops_place`, and `scan` of the ring lengths (`segments = 0`).
## Inputs
- `geometry` (Geometry). The geometry whose boundary is walked.
## Outputs
- `edges`: Record `a`, `b`, `from`, `to`, `source`, `count` of the open edges.
- `rings`: Record `ring`, `position`, `order`, `starts`, `count` of the rings.
# core.column (procNode)
Make a column from a list of numbers, one element each: the values a graph computed one by one gathered into a run the device can read, such as the births of each source before a scan.
Built from `op.transfer.upload`.
## Inputs
- `values` (List<Number>). The numbers, in order.
- `type` (one of Int, Float). Default `"Int"`. Whether the elements are whole numbers or floats.
## Outputs
- `column`: the Column of the numbers.
# core.concat (procNode)
Join several geometries into one: points, vertices and primitives end to end, links renumbered, every column any geometry holds.
Built from the `concat` kernel, one run per column any geometry holds in each class (the `concat` module lists them, the structure columns and stored numbers such as `id`, `N` and `uv` included). `core.join` answers where each part starts. The `concat` module in this node's folder decides every column of a class in one call: the type it takes (the type the first part with elements holds it as; a part that holds it at another width is refused by name, one that holds it as another type of the same width is cast by value), the part that decides it, its description words, and whether the parts bind as they stand. A column every part holds as that type, with elements, in a run of its own, costs two dispatches whatever the number of parts: the typed destination and the join. Any other column first casts each part by value to the joined type, and the elements of a part that holds no such column stand at zero for it. The link columns shift by what comes before: `vertex.pt` by the points of earlier parts, `primitive.vstart` by their vertices. A column of a type the device cannot hold (text, a record) is laid end to end by the `concat` module in this node's folder, as a column of values; a part that holds no such column leaves its elements without a value.
## Ids
The point `id` of each part moves past the ids of the parts before it, so every id of the result is unique. A part spans the larger of its next id and its point count. A part without an `id` column is numbered in order after them.
A column carries no statement of what its values mean, so the join keeps a list of the point columns that hold the `id` of another point, in the `concat` module of this node: `parent`. Where some part holds ids, each part's `parent` values move by the amount its ids move, a negative value (no parent) stays, and a part without a `parent` column parents nothing (-1). Where no part holds ids, `parent` values refer to nothing the join renumbers and join as they are. A hierarchy built in two parts, each numbered from 0, keeps its parenting through the join.
## Inputs
- `geometries` (List<Geometry>). The geometries joined, in order.
## Outputs
- `geometry`: the joined geometry.
# core.corners (procNode)
For every vertex, the vertex after it and the vertex before it in its primitive (a cycle), and the primitive it belongs to.
Built from `core.owner` and the `gather` kernel. A primitive's run of `vcount` vertices starting at `vstart` is read as a cycle: the vertex after the last is the first. Outputs `owner`, `next` and `previous`, vertex indices.
## Inputs
- `geometry` (Geometry). The geometry whose vertices are read.
## Outputs
- `owner`: the primitive of each vertex.
- `next`: the vertex after it in its primitive.
- `previous`: the vertex before it.
# core.edges (procNode)
The edge table of a geometry: every distinct side of its primitives as a point pair (a < b), the primitives along each side, whether the side is open (one primitive) or manifold (at most two), and the edge each vertex slot's side belongs to.
Built from the `edges` kernel (the sides of every primitive), two stable `sort` passes (by the higher point, then the lower), `gather`, the `edges_runs` kernel (run heads, then the table), `compact` of the heads, an inclusive `scan` of the heads (the edge of each sorted place) and `scatter` through the slot order to give `sideEdge`, the edge id of every vertex slot.
## Inputs
- `geometry` (Geometry). The geometry whose sides are listed.
- `faces` (Bool). Default `true`. True for a geometry of faces, whose primitives wrap from their last vertex to their first; false for curves, which wrap only where their `closed` attribute says.
## Outputs
- `edges`: Record `a`, `b`, `faceStart`, `faceCount`, `faces`, `open`, `manifold`, `reversed`, `sideEdge` (the edge each vertex slot's side belongs to, -1 for a slot with no side) and `count`.
# core.entity.read (procNode)
Read live entities as columns, one element per entity, with the number read as `count`.
Built from `io.engine` with `readEntities`, then `op.transfer.upload` of the columns it answers. The result is one Record: a column for each field read, and `count`; `core.points` makes points of it. The query names the entities by `ids` (a list of entity ids), `name` (a Name or glob), `component`, or `colliders` (with `sensors`); `fields` is `{ pose = true, space = "world" }` for `P`, `orient` and `scale`, or a list of `position`, `rotation`, `scale`, `id`, `shapeType`, `params` and `Component.field` names.
## Inputs
- `query` (Record). Which entities: `ids` (entity ids), `name` (a Name or a glob), `component`, or `colliders = true` with `sensors`.
- `fields` (Record, optional). What to read: `{ pose = true, space = "world" | "local" }`, or a list of `position`, `rotation`, `scale`, `id`, `shapeType`, `params`, or `Component.field`.
- `space` (one of world, local). Default `"world"`. The space the pose fields of a list are read in.
## Outputs
- `read`: Record of one column per field read, and `count`.
# core.interpolate (procNode)
Carry a geometry's attributes to sample points: point and vertex values blended by the barycentric weights, primitive values taken from the sample's primitive, values that cannot blend taken from the nearest corner.
Built from `gather` at the sample's corners and `math` operators for the blend, over the names `geometry.names[class]` lists for each class. A column of floats blends by `bary`; a column of integers takes the corner with the largest weight.
## Inputs
- `geometry` (Geometry). The geometry sampled.
- `samples` (Points). The samples: points with `prim`, `ia`, `ib`, `ic` (corner vertices) and `bary` (their weights), as `core.sample.surface` and `core.sample_curve` make them.
## Outputs
- `points`: the samples with the geometry's attributes.
# core.islands (procNode)
Label every primitive with the connected island it belongs to: primitives that share a point are in the same island. Answers the island of each primitive and the number of islands.
Built from `core.edges`, `jump` in label mode folded until no label changes (`g:fold` with `stop = "changed"`), `gather`, `scatter` and `compact`. Every point takes the smallest point number of the points joined to it by an edge; a primitive's island is the label of its first point, renumbered 0 to count - 1 in order of first appearance by label. Outputs `islands` (one number per primitive) and `count`.
## Inputs
- `geometry` (Geometry). The geometry whose primitives are labelled.
## Outputs
- `islands`: the island number of each primitive.
- `count`: how many islands.
# core.join (procNode)
The numbers a join of several geometries needs: where each part starts in every class, the description words the `concat` kernel reads for one attribute, and each class's counts and starts as lists. `core.concat` and `core.realize` call it.
Built from `op.transfer.readback` of each part's counts and the Luau node over `join.module`, which sits in this node's folder.
## Inputs
- `what` (one of layout, words, sources). Default `"layout"`. Which numbers are answered.
- `geometries` (List<Geometry>, optional). For "layout": the geometries joined, in order.
- `layout` (Record, optional). For "words" and "sources": what "layout" answered.
- `class` (one of point, vertex, primitive). Default `"point"`. For "words": the class of the attribute.
- `name` (String). Default `""`. For "words": the attribute's name.
## Outputs
- `value`: for "layout" the Record `starts`, `counts`, `parts` and a total per class; for "words" the List of description words; for "sources" the Record of per-class `counts` and `starts` lists.
# core.make (procNode)
Make geometry on the device from a count for each owner and a shape. Every owner makes its own piece and the pieces sit end to end with their links already offset.
The `make` kernel's `sizes` pass, a prefix sum of the sizes, and the `make` kernel's `fill` pass; the columns are set into an empty geometry. The totals the fill pass is sized by come from the counts when every owner makes `count` (a row of points needs one multiplication, the other shapes one call of the `make` module); a count the graph states is a number already and the cook does not wait on the device for it, and a count left on the device is read back. When `counts` gives each owner its own, the totals are read back from the prefix sum.
## Inputs
- `shape` (one of points, strip, fan, grid, ring). Default `"points"`. What each owner makes: a row of points, a zigzag of triangles, triangles round a centre, a lattice of quads, or one closed primitive round a circle.
- `counts` (Column<Int>). One count for each owner: the points along its main axis. Left out, every owner makes `count`.
- `count` (Number). Default `0`. The points along the main axis of each owner when `counts` is left out.
- `owners` (Number). Default `1`. How many owners make a piece when `counts` is left out.
- `across` (Number). Default `2`. For the grid: how many points it holds along its second axis.
## Outputs
- `geometry`: the geometry with `P` on its points (the unit square or the unit circle), `pt` on its vertices and `vstart` and `vcount` on its primitives; a ring also carries `closed`.
# core.names (procNode)
The names of every column a class of a geometry holds, sorted.
A class holds its structure columns (`P` and `id` on points, `pt` on vertices, `vstart` and `vcount` on primitives, `closed` on curves) and the attributes written on it. `attribute.carry` and `core.concat` move and join a class by walking this list, one column at a time.
## Inputs
- `geometry` (Geometry). The geometry whose columns are listed.
- `class` ("point", "vertex" or "primitive"). The class whose columns are listed.
- `links` (Bool). Default `true`. Whether the columns that tie the classes together (`pt`, `vstart`, `vcount`, `closed`, `curve`) are listed; `false` lists the other columns of the class.
## Outputs
- `names`: the sorted list of column names.
# core.neighbours (procNode)
What stands near each point: how many points lie within a radius (optionally inside a cone), the nearest one, their centroid, the mean of an attribute over them, or the push away from them.
Built from `core.pairs` (the points within the radius of each point), the `hash_nearest` kernel over `core.spatial`, `gather`, `math` operators for the cone and the push, and `scatter` folds back to the points. `mode` "measure" writes `neighbors` (count), `nearest` (distance to the nearest), `centroid`, and `neighbor_<name>` for `mean`; "nearest" writes `nearest_index` (the source point nearest each point, -1 where none lies within `radius` when it is above 0) and `nearest`; "repel" writes `push`, the average direction away from the neighbours within `radius`, each weighted by how close it stands. `direction`, `cone` and `mean` are plain values chosen when the graph is built. Without `sources` a point's neighbours are the other points of `points`.
## Inputs
- `points` (Geometry). The points that look around.
- `sources` (Geometry, optional). The points looked at. Left empty, each point looks at the others of `points`.
- `radius` (Number). Default `1.0`. How far a point looks. 0 looks without limit in "nearest" mode.
- `mode` (one of measure, nearest, repel). Default `"measure"`. What is answered: counts and centroids, the nearest source, or the push away.
- `direction` (String). Default `""`. A Vec3 point attribute each point looks along; given, only neighbours inside the cone count.
- `cone` (Number). Default `360.0`. The full angle in degrees of the cone around `direction`; 360 counts every side.
- `mean` (String). Default `""`. A numeric point attribute whose neighbours' average each point takes as `neighbor_<name>`.
## Outputs
- `points`: the points with the answers as attributes.
# core.normals.corner (procNode)
A normal for every vertex that smooths across the primitives around its point where they meet at less than a crease angle, and keeps an edge hard where they meet at more.
Built from `core.normals.face`, `core.adjacency` (the primitives around each point), `core.owner`, the `expand` kernel (one slot per primitive around the vertex's point), `gather`, `math.dot`, `math.where` and `scatter` with an add fold, then `math.normalize`. A vertex takes the sum of the normals of the primitives around its point whose normal is within `angle` degrees of its own primitive's, each weighted by area or equally. Written as `N` on the vertex class.
## Inputs
- `geometry` (Geometry). The geometry whose vertices get normals.
- `angle` (Number). Default `60`. The crease angle: primitives around a point whose normals differ from a vertex's own by no more than this are smoothed into it.
- `weighting` (one of area, uniform). Default `"area"`. How each primitive counts in the average: by its size or equally.
- `name` (String). Default `"N"`. The attribute the normals are written under on the vertex class.
## Outputs
- `geometry`: the geometry with a normal on every vertex.
# core.normals.face (procNode)
Give every primitive its normal: the direction its vertices wind around, written as `N` on the primitive class. `scaled` is the same direction scaled by twice the primitive's area.
Built from `core.corners`, `attribute.promote` (point to vertex), `gather` of the next corner, `math.cross` and a segmented `reduce` over each primitive's run (`segments = primitive.count`).
## Inputs
- `geometry` (Geometry). The geometry whose primitives get normals.
- `name` (String). Default `"N"`. The attribute the normals are written under on the primitive class.
## Outputs
- `geometry`: the geometry with a normal on every primitive.
- `scaled`: the same direction scaled by twice the primitive's area, a Vec3 column per primitive.
# core.normals.point (procNode)
The normal of the surface at every point: the normals of the primitives that use the point, summed with each weighted by its area, by the angle it spans at the point, or equally, and normalized, written as `N` on the point class.
Built from `core.normals.face`, `attribute.promote` (primitive to point, sum) for "area" and "uniform"; for "angle" the corner angle `math.acos` of the dot product of the two unit edges at each vertex, the face normal gathered to the vertex by its owner, scaled by that angle and scattered to the point.
## Inputs
- `geometry` (Geometry). The geometry whose points get normals.
- `weighting` (one of area, angle, uniform). Default `"area"`. How the primitives around a point count: "area" weights each by its size, "angle" by the angle it spans at the point, "uniform" counts each equally.
- `name` (String). Default `"N"`. The attribute the normals are written under on the point class.
## Outputs
- `geometry`: the geometry with a normal on every point.
# core.owner (procNode)
The primitive each vertex belongs to, and the vertex's place within that primitive.
Built from the `expand` kernel over the primitives' runs: primitive `i` owns the `vcount` vertices that start at `vstart`. Outputs `owner` (the primitive id of each vertex) and `local_index` (the vertex's position in its primitive's run). The building block under every promotion between vertices and primitives.
## Inputs
- `geometry` (Geometry). The geometry whose vertices are owned.
## Outputs
- `owner`: the primitive of each vertex.
- `local_index`: the vertex's place in its primitive's run.
# core.pairs (procNode)
Every pair of points within a radius: for each query point, the source points that stand within the radius of it, as a list of owners and items.
Built from `core.spatial` over the sources, the `hash_count` and `hash_gather` kernels, `scan` of the counts and `expand` of each query's list into one row per pair. Outputs: `owner` (the query point of each pair), `items` (the source point of each pair), `counts` and `offsets` (each query's list in `items`) and `total`. A point is not its own neighbour when the queries are the sources.
## Inputs
- `points` (Geometry). The query points.
- `sources` (Geometry, optional). The points looked at. Left empty, the query points look at each other.
- `radius` (Number). Default `1.0`. How far a query point reaches.
## Outputs
- `owner`: the query point of each pair.
- `items`: the source point of each pair.
- `counts`: the length of each query's list.
- `offsets`: where each query's list starts in `items`.
- `total`: the number of pairs.
- `spatial`: the `core.spatial` record the sources were indexed by.
# core.points (procNode)
Points made from columns: a count of points, each attribute given as a column, a field or a constant.
Built from the `make` kernel (`SHAPE = "points"`) for the elements and a point-class write for every entry of `columns`. The call is `g.core.points({ columns = { P = positions, mass = 1.0 }, count = 64 })`; `count` is how many points there are.
## Inputs
- `columns` (Record, optional). The attributes, by name: each a column of the point count, a field evaluated over the points, or a constant. `P` places the points; the other names are carried as point attributes.
- `count` (Number). Default `0`. How many points.
## Outputs
- `points`: the points.
# core.raster.add_layer (procNode)
Add a named layer to a raster, every cell zero; a layer already there is left as it is.
Built from `g.has` over the raster's layers and a point-class column write.
## Inputs
- `raster` (Raster). The raster extended.
- `name` (String). Default `""`. The layer's name.
## Outputs
- `raster`: the raster with the layer.
# core.raster.blend (procNode)
Blend a value into one layer of a raster, cell by cell, by a weight, over every cell the tiles hold (the cells of the field, the cells of a border tile past it and the ring around the tiles): replace, add, take the greater or lesser, or multiply.
Built from `g.field.substitute` (the cell position into `value` and `weight`, each held cell at its own position) and the `grid` kernel in write mode over the raster's tile layout (`MODE = write`, `BLEND = mode`), the patch window starting `apron` cells before the field's first cell and spanning `heldX` by `heldZ`. Every tile that holds a cell, as core or as apron, receives it, so the aprons agree. The weight scales how much of the value is blended in: 0 leaves the cell alone and 1 applies the mode in full.
## Inputs
- `raster` (Raster). The raster written.
- `layer` (String). Default `"height"`. The layer written.
- `value` (Value). Default `0.0`. What is blended in, per cell: a number, a column over the held cells (`core.raster.read` with `held`) or a field of the cell's position.
- `weight` (Value). Default `1.0`. How much of the value applies per cell, 0 to 1.
- `mode` (one of replace, add, max, min, multiply). Default `"replace"`. How the value meets the cell: replaces it, is added to it, or the greater, the lesser or the product of the two is kept.
## Outputs
- `raster`: the raster with the layer written.
# core.raster.cells (procNode)
Name the cells of a raster as a flat run, x fastest then z: the position of each cell's centre, and the place in a layer's tiled storage that holds it, optionally at an offset of whole cells.
Built from `g.element.id` and `math` operators over the raster's layout members. Every node that reads or writes a layer cell by cell calls it.
## Inputs
- `raster` (Raster). The raster whose cells are named.
- `dx` (Number). Default `0`. Cells along x the stored place is offset by; the read is held to the edge of the field.
- `dz` (Number). Default `0`. Cells along z the stored place is offset by.
- `held` (Bool). Default `false`. Name every cell the tiles hold rather than the cells of the field: `heldX` cells across and `heldZ` down, the run starting `apron` cells before the field's first cell. An offset is then held to the edge of what the tiles hold.
## Outputs
- `count`: the cells of the field, `cellsX` times `cellsZ`; with `held`, `heldX` times `heldZ`.
- `position`: a Vec3 field: the world position of each cell's centre (a cell past the field has the position it has in the field's grid).
- `index`: an Int field: the place in a layer's stored column that holds each cell, offset by `dx`, `dz` and held to the field (or to what the tiles hold, with `held`). A cell past the field is addressed in the border tile beside it.
# core.raster.column (procNode)
A layer of a raster as its stored column: the cells of every tile, apron included, tile after tile, each tile `stride` by `stride` cells with x fastest. What a kernel that works tile by tile binds.
## Inputs
- `raster` (Raster). The raster read.
- `layer` (String). Default `"height"`. The layer read.
## Outputs
- `column`: the layer's stored column.
# core.raster.new (procNode)
Open a rect of ground as a Raster: a grid of cells, cut into tiles of 256 cells a side that each store a ring of 8 neighbour cells (stride 272), with named layers of one number per cell, all zero. The tiles store more than the rect: the cells of a border tile past the rect and the ring around the tiles are stored like the rest, and a write reaches them.
The Raster is a Record. Layout members: `cellsX`, `cellsZ`, `resolution`, `min`, `size`, `origin` (Vec3, the `y` lane 0), the same as numbers `minX`, `minZ`, `sizeX`, `sizeZ`, `originX`, `originZ`, `core` (256), `apron` (8), `stride` (272), `tilesX`, `tilesZ`, `tiles` (also `tileCount`), `heldX` and `heldZ` (the cells the tiles hold across and down: the tiles' cores, `tilesX * core` by `tilesZ * core`, and the ring of `apron` cells around them), `layerNames` (the list of layer names) and `layers`, a Geometry whose point class holds the stored cells of every tile, one column per layer. The `grid` kernel and `core.raster.cells` read that layout.
## Inputs
- `origin` (Vec2). Default `{ x = 0, z = 0 }`. The world centre of the rect, in metres.
- `size` (Vec2). The extent of the rect along x and z, in metres, as `{ x, z }`.
- `resolution` (Float). Metres per cell.
- `layers` (List<String>, optional). The layers the raster opens with.
## Outputs
- `raster`: the Raster.
# core.raster.read (procNode)
Read a layer of a raster as a column over the field's cells, x fastest then z, each cell optionally taken from a neighbour a whole number of cells away; a read past the edge answers the edge cell.
Built from `core.raster.cells` and the `gather` kernel.
## Inputs
- `raster` (Raster). The raster read.
- `layer` (String). Default `"height"`. The layer read.
- `dx` (Number). Default `0`. Cells along x the read is offset by.
- `dz` (Number). Default `0`. Cells along z the read is offset by.
- `held` (Bool). Default `false`. Read every cell the tiles hold, the cells past the field included, rather than the cells of the field.
## Outputs
- `value`: a Float column over the field's cells, or over the held cells.
- `count`: the cells read.
# core.raster.reduce (procNode)
Fold a layer of a raster to one number: the sum, mean, least or greatest of its cells.
Built from `core.raster.read` and `core.reduce`.
## Inputs
- `raster` (Raster). The raster folded.
- `layer` (String). Default `"height"`. The layer folded.
- `op` (one of sum, mean, min, max). Default `"sum"`. How the cells fold.
## Outputs
- `value`: the folded number.
# core.raster.remove_layer (procNode)
Remove a named layer from a raster.
Built from a point-class column removal on the raster's layers.
## Inputs
- `raster` (Raster). The raster shortened.
- `name` (String). Default `""`. The layer removed.
## Outputs
- `raster`: the raster without the layer.
# core.raster.resolve (procNode)
Fold a layer of fixed-point changes into the layer they change: every cell of `delta` holds a whole number of 1/`fixed` units, added to `layer`; `delta` is then zero.
Built from the `gather` kernel reading `delta`'s words as 32-bit integers, `math.to_float`, and a `core.raster.blend` pass that adds them, so every tile that holds a cell takes the result; `delta` is then written zero in every place it is stored. Every cell the tiles hold, the cells past the field included, takes its own change.
## Inputs
- `raster` (Raster). The raster resolved.
- `layer` (String). Default `"height"`. The layer the changes are added to.
- `delta` (String). Default `""`. The layer holding the changes as 32-bit integers.
- `fixed` (Number). Default `65536`. How many integer units make one unit of the layer.
## Outputs
- `raster`: the raster with the changes added and `delta` zero.
# core.raster.sample (procNode)
Sample a layer at world positions with a bilinear blend of the four cells around each, reading the cells the raster holds past the field for a position beside it, and holding the last cell past everything the tiles hold.
Built from `core.raster.read` (held), `g.field.gather` and `math.lerp`, as a field over whatever elements the positions come from.
## Inputs
- `raster` (Raster). The raster sampled.
- `layer` (String). Default `"height"`. The layer sampled.
- `at` (Value). The positions sampled: a Vec3 field or column, read by x and z.
## Outputs
- `value`: a Float field of the blended layer value at each position.
- `count`: the cells of the field.
# core.raster.stencil (procNode)
Measure the shape of a layer around every cell: its slope in degrees or its curvature (the laplacian over x and z).
Built from the `grid` kernel in stencil mode over every stored cell, then `gather` through `core.raster.cells` to a column over the field's cells.
## Inputs
- `raster` (Raster). The raster measured.
- `layer` (String). Default `"height"`. The layer measured.
- `kind` (one of slope, curvature). Default `"slope"`. What is measured: the slope in degrees, or the curvature.
- `held` (Bool). Default `false`. Answer a column over every cell the tiles hold rather than over the cells of the field.
A cell's neighbours are the cells its tile stores around it, so a cell at the edge of the field is measured against the cells the raster holds beyond it.
## Outputs
- `value`: a Float column over the field's cells, or over the held cells.
- `count`: the cells measured.
# core.realize (procNode)
Copy source geometries onto points: every point stands a copy of its source (one source for all, or the one its `variant` names), the copy placed by the point's position, orientation and scale.
Built from `core.concat` (the sources as one catalog), `core.join` (each source's counts and starts), `scan` of the per-point element counts, the `expand` kernel (one row per copied element), `gather` of the catalog's columns, `math` operators for the placement, and `gather` to renumber `vertex.pt` and `primitive.vstart` into the copies. Every attribute of an instance point, `orient`, `scale` and `variant` included, stands on each point of its copy.
## Inputs
- `points` (Points). The instance points.
- `sources` (List<Geometry>). The geometries copied, in the order `variant` counts them.
- `variant` (String). Default `""`. The point attribute that picks a source by number, 0 for the first; empty gives every point the first source.
- `orient` (String). Default `"orient"`. The point attribute holding each point's rotation as a quaternion; empty places without rotation.
- `scale` (String). Default `"scale"`. The point attribute holding each point's scale; empty places at full size.
## Outputs
- `geometry`: the copies as one geometry.
# core.reduce (procNode)
Fold a column to one value, or to one value per segment: sum, mean, least, greatest, count or the place of the least or greatest.
One `reduce` kernel run. `fold` names the fold. `starts` holds where each segment starts; the kernel then gets `segments = starts.count`, and without `starts` it folds the whole column with `segments = 0`.
## Inputs
- `values` (Column). The column folded.
- `fold` (one of add, mean, min, max, count, argmin, argmax). Default `"add"`. How the elements fold: added up, averaged, the least, the greatest, how many, or the index of the least or the greatest.
- `starts` (Column<Int>, optional). Where each segment starts in the column; the fold is then one value per segment.
## Outputs
- `value`: the first folded element.
- `values`: one element per segment (a single element without `starts`).
- `picked`: for argmin and argmax, the chosen element's index.
# core.resample.curve (procNode)
Redistribute the points of every curve evenly by arc length: a fixed number per curve, or as many as fit a spacing.
Built from `core.arclength`, `core.points` (one row per new point, from the `expand` kernel over the per-curve counts), `core.sample_curve`, `core.interpolate`, and an exclusive `scan` for the new curves' starts. The result is curves again: `vertex.pt` runs through the new points in order and `primitive.vstart`, `vcount` and `closed` describe each curve; a curve's own attributes carry over.
## Inputs
- `curve` (Curves). The curves resampled.
- `count` (Number). Default `16`. Points per curve when `spacing` is 0.
- `spacing` (Number). Default `0.0`. The distance between points; each curve takes as many as fit. 0 uses `count`.
## Outputs
- `curve`: the resampled curves.
# core.sample.surface (procNode)
Choose points on a surface, area-weighted and deterministic: the face and the barycentric place of each, as samples.
Built from `core.owner`, `core.normals.face`, the `expand` kernel (each primitive fanned into triangles), `gather`, `math` operators for the triangle areas, an inclusive `scan` of the areas, `field.random` draws, the `search` kernel (the triangle each draw falls in) and `core.points`. The result is Points with `P`, `prim` (the primitive), `ia`, `ib`, `ic` (the three vertices of the triangle), `bary` (the weights of those vertices) and `N` (the primitive's normal). `core.interpolate` carries a geometry's attributes to such samples.
## Inputs
- `geometry` (Geometry). The surface sampled.
- `count` (Number). Default `256`. How many samples.
- `seed` (Number). Default `1`. Which of the possible layouts this is.
- `graphId` (String). Default `""`. The graph the draws are keyed to, so two graphs with one seed draw different places.
- `nodeId` (String). Default `""`. The node the draws are keyed to.
## Outputs
- `samples`: points with `P`, `N`, `bary`, `prim`, `ia`, `ib`, `ic`.
# core.sample_curve (procNode)
Find the places along curves that arc-length positions name: for each row, the segment of its curve and the weights of the segment's two ends.
Built from `core.arclength`, `core.owner`, an exclusive `scan` of the curves' lengths (each curve's start in one ascending run of distances), the `search` kernel over that run, `gather` and `math` operators. The result is the rows with `prim` (the curve), `ia`, `ib`, `ic` (the segment's start vertex, its end vertex, the end again), `bary` (weights 1 - w, w, 0), `P` (the position there), `tangent` and `t`. `core.interpolate` carries the curve's attributes to them.
## Inputs
- `curve` (Curves). The curves sampled.
- `owner` (Value). Default `0`. For each row, the curve it samples: a primitive number.
- `t` (Value). Default `0.0`. For each row, how far along its curve: 0 at the start, 1 at the end.
- `rows` (Points). The points that become the samples: one per row.
## Outputs
- `samples`: the rows standing on the curves, with `P`, `tangent`, `t`, `prim`, `ia`, `ib`, `ic`, `bary`.
# core.scatter (procNode)
Fold a column into the places an index names: every element sends its value to the element its index names, and each receiver folds what reached it.
Three `scatter` kernel runs (`init`, `fold`, `finish`) over columns of the result's type. The same answer every run for the folds that do not depend on arrival order.
## Inputs
- `values` (Column). The column sent.
- `index` (Column<Int>). For each element, the place it is sent to; an index outside the result sends nowhere.
- `size` (Number). Default `0`. How many places there are.
- `fold` (one of add, mean, min, max, set). Default `"add"`. How values that meet fold: added up, averaged, the least, the greatest, or the one from the greatest source index.
- `fill` (Value). What a place nothing reached holds; zero when left out. With a `fill` the answer is a Field over the places.
## Outputs
- `value`: the folded column, `size` elements of the type of `values`.
# core.scratch (procNode)
A run of one whole number, zero, for a binding a kernel mode does not read.
A dispatch binds each buffer at one slot only, so every binding a mode leaves unread (the `starts` of an unsegmented scan or reduce, the `la` and `lb` of a jump that does not label pairs) takes a run of its own. Each call answers a new run.
## Inputs
None.
## Outputs
- `run`: a column of one Int, 0.
# core.select (procNode)
Keep the elements of a geometry a mask picks and drop the rest, renumbering the links between points, vertices and primitives.
Built from `math.ne` over the mask, `compact` (the kept elements and the inverse map), `core.owner`, `gather`, a segmented `reduce` (`segments = primitive.count`), `scatter`, `attribute.carry` for every class and `scan` for the new run starts. Keeping points drops every primitive that loses a vertex; keeping primitives keeps their vertices and, by default, the points those vertices read; `points` set to "all" keeps every point.
## Inputs
- `geometry` (Geometry). The geometry to filter.
- `class` (one of point, primitive). Default `"point"`. Which elements the mask is over.
- `points` (one of used, all). Default `"used"`. For class "primitive": which points stay, the points the kept primitives use or every point.
- `mask` (Value). Default `1`. A column or field over the class's elements: an element is kept where the value is not 0.
## Outputs
- `geometry`: the kept elements with the links renumbered.
# core.spatial (procNode)
A spatial index over a set of points: the bucket order and spans every neighbour query reads.
Built from the `hash` kernel (the bucket of each point's cell), `sort` of those buckets and the `hash_starts` kernel (where each bucket's points lie in the sorted order). The point count is read back once; the bucket count is the least power of two at least the count and at least 16, worked out with `math.log` and `math.ceil`. Outputs `order`, `range`, `buckets` and `invCell`, which `hash_count`, `hash_gather` and `hash_nearest` read.
## Inputs
- `points` (Geometry). The points indexed, by their `P`.
- `cell` (Number). Default `1.0`. The side of a grid cell: queries reach about this far in one step, so a radius near it answers fastest.
## Outputs
- `order`: the points ordered by bucket.
- `range`: each bucket's span in `order`.
- `buckets`: the bucket count.
- `invCell`: one over the cell side.
# core.stitch (procNode)
Join consecutive rings of points with quads, and optionally close the ends with caps: the surface of a tube, a sweep or a loft.
Built from `attribute.carry` (the geometry's vertices and primitives followed by the new ones, which read index -1 and so carry zeros, sized by `size`), `math` operators for the quad and cap layout, and `gather` of the ring points. `rings` holds every ring end to end, `size` points each; a quad runs ring `r` point `j`, point `j + 1`, then the same two points of ring `r + 1`. With `closed`, the last point of a ring joins the first. A cap is one primitive running round a whole end ring: the first ring wound the other way, the last ring in its own order. The ring count is read back from `rings.count`.
## Inputs
- `geometry` (Geometry). The geometry holding the ring points; the quads and caps are added to it.
- `rings` (Column<Int>). The point numbers of every ring, one ring after another, `size` points each.
- `size` (Number). Default `3`. How many points each ring holds.
- `closed` (Bool). Default `true`. Whether each ring is a loop: the last point joins the first, so a ring of k points makes k quads to the next ring instead of k - 1.
- `caps` (one of none, start, end, both). Default `"none"`. Which ends are closed by a primitive running round the end ring.
## Outputs
- `geometry`: the geometry with the quads and caps added.
# core.weld (procNode)
Merge the points of a geometry that stand within a distance of each other, joining the primitives that used them.
Built from `core.pairs` (the points within the distance), `jump` in label mode folded until no label changes (every point takes the smallest point number of the points joined to it), `compact`, `scatter` with a mean fold for the merged positions (with `place` "first" the carried position stands), `attribute.carry` for every other attribute (a merged point takes the values of the lowest-numbered point of its group) and `gather` to renumber `vertex.pt`. With `match` set to \"position+normal\" two points merge only when their `N` normals differ by no more than `angle` degrees. Every pair within the distance ends in one group, so a chain of points each within the distance of the next merges whole.
## Inputs
- `geometry` (Geometry). The geometry welded.
- `distance` (Number). Default `0.0001`. Points closer than this merge.
- `match` (one of position, position+normal). Default `"position"`. What has to agree: position alone, or position and the `N` point normal.
- `angle` (Number). Default `1.0`. For "position+normal": how far apart two normals may be and still merge.
- `place` (one of mean, first). Default `"mean"`. Where a merged point stands: at the mean of its group, or at the position of the lowest-numbered point of the group (the point `attribute.carry` takes the other attributes from).
## Outputs
- `geometry`: the welded geometry.
- `map`: for each point of the input, the number of the welded point it merged into, as a column as long as the input's points.
A graph's call `g.core.weld({ ... })` gives a table of both outputs by name, so a graph that welds a geometry and works on the result reads `g.core.weld({ ... }).geometry`; `map` carries a value of every input point onto the welded points, for example as the `index` of a `core.scatter`.
# Nodebox (asset type)
A nodebox is a namespace folder that groups related `.procNode/` children, the way a toolbox groups
`.tool/` children. A node's name is its folder name inside its box: `points.nodebox/disc.procNode` is
called `points.disc`, and nothing inside the node states that name. Moving or renaming a node is a VFS
move that keeps its guid.
## Where it lives
- Source: `<anywhere>/<family>.nodebox/`, usually inside a `.package`, an effect or a world's content.
- Identity: the folders above it and `<family>` (`fx.points` for `fx/points.nodebox`; the `.nodebox`
suffix strips). A graph calls its nodes by `<family>.<node>` alone.
- Folder shape (open child set):
- `README.md`: what the family is for. Required.
- `.metadata`: description and tags. Required. It also states where the box's nodes work: `context` (one of
`proc.registry.contexts()`: `geometry`, `field`, `value`, `sim`, `raster`, `material`, `prefab`) and, when every
node of the box reads the scene or assets beside its inputs or writes them beside its outputs, `pulls` /
`pushes` (`scene` or `asset`). A node that works elsewhere states its own in its `.metadata`.
`procgen` `describeNode` and the `context`, `pulls` and `pushes` filters of `searchNodes` read them.
- `<node>.procNode/`: any number of nodes.
## How a graph reaches a node
`g.<family>.<node>(args)` resolves the node by its asset identity: the box and the folder name together
(`g.points.disc`), a path (`g["/zero/source/fx/ring.procNode"]`), `~` (the nearest enclosing package,
effect or world root: `g["~/ring"]`) or a short name the asset system resolves (`g.disc`). A name that
matches two nodes is an error naming both; a name that matches none is an error naming the closest nodes.
Each call is recorded in the graph's reference table by the node's guid.
## How to create one
```luau
asset.create("nodebox", "points", { folder = "fx" })
local box = asset.resolve("points.nodebox")
asset.create("procNode", "disc", { into = box })
```
## Discovery
- `asset.list("nodebox")`: every box.
- `asset.inspect("points")`: the nodes in it and what each does.
- `asset.list("procNode")`: every node, in or out of a box.
## In the Inspector
Nodes: how many nodes the box holds, each node's full name and what it does, and a link to each.
# procNode: one reusable step of procedural generation
A `.procNode` is a node authored as content: a folder whose `init.luau` is the node. It
returns `proc.define(function(g) ... end)`, the same function-of-`g` form a `.procGraph` is
written in, so a node is a small graph that other graphs call. Its `g:describe` text says
what it makes and when to use it, its `g:input` declarations are what a call passes, and
what it returns (or declares with `g:output`) is what the call gives back.
```
MyNode.procNode/
init.luau -- the node
README.md -- what it produces, its inputs, its outputs
.metadata -- description and tags
```
## What a node states
- **`g:describe(text)`**: what the node produces and when to use it. It is the text search,
the node catalogue and the Inspector show.
- **`g:input(name, default, opts)`**: one input of the node. The default types it (`Float`,
`String`, `Bool`, `Vec3`, `Color`, `List<T>`, `Record`); `opts` adds `type` (for a default
that does not state one, or none), `description`, `options`, `min`, `max` and `optional`. A
call names inputs in a table, or passes them in declaration order.
- **Outputs**: the returned table names them (`return { geometry = geometry }`), and
`g:output(name, value)` declares one as the node builds. A node with one output answers
that value to its caller; a node with several answers a record by output name; a node with
none answers nothing.
- **Written as literals.** What a node takes and gives is read from its source without running
it, the way search and description read it here and the way ZeroMind reads it, so each
declaration states its values as written: `g:describe` and each `g:input` once, at the top
level of the function, with a literal name, default and options (a file constant holding a
literal, or `asset.resolve("<identity>", "<type>")`, reads as one); outputs named by the table
the function returns, or by `g:output`, the same names on every branch of a condition and never
inside a loop. `asset.interface(node)` answers what the source declares, with each part it
cannot read as a problem, and a push refuses a node with such a problem
(`interface.unreadable`).
- **The body** is the node's work: calls to other nodes, arithmetic over sockets, `for`, folds,
steps and state, as the builder README (`proc.module/builder.module/README.md`) describes.
A node that uses another node is recorded in the graph that calls it, so a node can be built
from nodes.
## How a graph calls a node
A node inside a `<family>.nodebox` is called by its box and folder name:
`points.nodebox/disc.procNode` is `g.points.disc({ ... })`, and nothing inside the node states
that name. A node is also reached by:
- its path (`g["/zero/source/fx/ring.procNode"]`),
- `~`, the nearest enclosing package, effect or world root (`g["~/ring"]`),
- its guid,
- a short name only one node answers to (`g.disc`).
A name that matches two nodes and a name that matches none are errors that name the
candidates. Each call is recorded in the calling graph by the node's guid, so the node travels
with every graph that uses it, and a rename or a move keeps the reference. A `.procGraph` is
called the same way and answers what it returns.
## Nodeboxes
A nodebox is the family a node lives in: a namespace folder grouping related nodes (`points`,
`mesh`, `field`, `terrain`). `nodebox.assetType` describes it. A node placed in a box takes the
box's name as its prefix; a node outside any box is reached by path, `~` or guid.
`asset.create("nodebox", family)` makes a box and `asset.create("procNode", name, { into = box })`
makes a node in it.
## Finding nodes
`asset.list("procNode")` lists every node. The `procgen` toolbox's `searchNodes` finds them by
meaning across every published node, and with no query lists the ones this engine holds grouped
by family; its `describeNode` answers one node's inputs, their types and defaults, and its
outputs. Both read what each node's source declares and run no node. The type's `indexing`
recipe embeds a node's README and its source, so a search by meaning finds a node by what its
description and README say it is for: write them in the words someone looking for the node
would use.
## Registration
Every node the asset index lists is known to the procgen registry by what its source declares,
read when it is asked for and read again when the source changes; nothing runs a node to list
it. Its code loads the first time a build runs it. After that, the lifecycle hooks keep it
current: `onChange` loads it again and hot-reloads on an edit, `onDelete` removes it. Editing
`init.luau` cooks again every graph that reaches the node, and only the nodes downstream of the
change do work. `init.luau` is compiled from its current source on each load, so a module it
pulls in uses an absolute require
(`require("@builtin::systems.procgen.proc")`).
What a node is built from is more than its own file. A module its `init.luau` requires while it
builds, at any depth of requires, is part of it: when that module changes, `onDependencyChange`
loads the node again from the module as it now stands. A file its `init.luau` reads with
`vfs.read` while it builds is part of it too, and so is a file a module it calls reads with
`proc.read` (a module's own `vfs.read` is its own and makes no dependency). Writing such a file
loads the node again (`proc.sourceChanged`). Either way the node's definition moves, so every
graph and Generator reaching it cooks again, from one version of everything it was built from.
`proc.builder.readsOf("<node>.procNode/init.luau")` lists the files its last build read. A graph that references a node which is not
registered errors at load, naming the missing guid. A graph that reaches itself, directly or
through other nodes, errors at cook.
## Content requirements
`README.md` carries real text: what the node produces, its inputs and its outputs. `.metadata`
carries a `description` (what the node computes and the value type it answers) and `tags` (the
family, so search finds it). It may state where the node works: `context`, `pulls` and `pushes`
(the values `proc.registry.contexts()`, `"scene"` and `"asset"` name). A node in a nodebox that
states none takes its box's; `procgen` `describeNode` and `searchNodes` answer them.
A node written with `proc.graph` and `g:node` (the `procNodes/` of the procgen package) is called only
by a `proc.graph` graph, through `g:node`. A graph built with `proc.define` does not call it: `g.op.<name>`
of it is refused where it is written, naming the node written in the call form that answers to the same name.
## In the Inspector
Operation: the node's id and what it does, its cost and caching when it declares them, and its
inputs and outputs, from the procgen registry's schema for it. A node that did not register says
so.
# assetType (asset type)
An asset type says what a kind of asset is: the files an asset of the kind is
made of, the code that gives it behaviour, the interface a person uses to work
with it, and how it is found, pictured and checked. A `<typename>.assetType/`
folder declares a type called `<typename>`, and every `<name>.<typename>/`
folder is an asset of it. `assetType` is itself a type, so a type is an asset
like any other: it is created, versioned, installed and contributed the same way.
## Making a type
`asset.create("assetType", "<typename>")` scaffolds a type. The type registers
the moment its folder is written, anywhere under `/zero/source/`, and from then
on `<name>.<typename>/` folders are its assets. An asset of a type that is not
registered yet is not an asset, so make the type first.
A type folder is a root: `~.x` in any file inside it names the type's own `x`,
wherever the type is installed. Keep the type's whole implementation inside its
folder and reach it that way.
What a type folder must hold is set by this type's own `type.yaml`, the same way
every type's `type.yaml` sets what its assets hold. `asset.validate` on a type
reports anything missing, and the scaffold produces a folder that passes.
## What sets your type's schema (`type.yaml`)
`type.yaml` is the structural contract every asset of the type is checked
against. The keys below are the ones the engine reads; a key not listed here is
ignored.
| Key | What it controls |
|---|---|
| `suffix` | The folder suffix of the type's assets. Defaults to `.<typename>`. |
| `primary` | The file or files that are the asset's content: what the asset resolves to when it is used. |
| `entry_files`, `primary_aliases` | Further files that load as the asset or share its identity. |
| `is_container` | Whether the suffix stays in the identities of what the asset holds. |
| `is_opaque_walker` | Whether a walk of the tree stops at the asset and registers only its primary. |
| `plural_dir`, `classify_exts` | Loose files in a folder of this name, or with these extensions, are assets of the type. |
| `is_text_default` | Whether the asset's files are text unless stated otherwise. |
| `broadcasts_subassets` | Whether assets nested inside an asset of the type are found by their own short name. |
| `root` | `true` makes every asset of the type a root, so `~.x` inside one names that asset's own `x`. |
| `contract_ref: { field, category }` | A key of the primary file that names another asset the asset is built on. |
| `files: { required, optional }` | The files an asset holds (below). |
| `allow_unlisted` | `false` reports every file the type does not declare. |
| `aliases_from: [{ file, key }]` | Further names an asset answers to, read from its own files. |
| `settings:` | Typed per-asset settings (below). |
| `inspector:` | The interface people use for the type and its assets (below). |
| `preview:` | How an asset is pictured (below). |
| `references:` | Names of other assets the type's files carry (below). |
| `indexing:` | What search reads for each asset (below). |
| `describe:` | How a missing description is generated (below). |
### The files an asset holds
Each entry under `files.required` or `files.optional` is
`{ path, kind: file | folder, one_of_group?, content? }`. `*` in a path matches
within one segment. Entries that share a `one_of_group` are satisfied by any one
of them. `content` lists checks on the file's bytes:
| Check | Passes when |
|---|---|
| `non_empty` | the file has content |
| `json_field { key, type?, non_empty?, accept? }` | the JSON holds the key (a dotted path) with that shape |
| `yaml_field { key, type?, non_empty?, accept? }` | the same for YAML |
| `described { keys?, headings?, message? }` | the file says what the asset is (see "Ask your assets to say what they are") |
Each check takes a `message`, which is what the author is told when it fails.
### Settings
`settings: { values, schema: { type | instance, export? } }` gives every asset
typed settings. `values` names the file an asset's values live in; `schema.type`
declares one schema for the whole type, and `schema.instance` names a file each
asset declares its own in. `asset.create` writes the resolved values, and a write
to the values file reaches `onChange` with what changed.
## The human side (`inspector.luau`)
A type is used by people through its Inspector, and without one the type is
usable only from code. The Inspector is the type's interface for a person: for a
procedural graph it is the graph editor, for a kit it is the tracking view of
what the kit holds and what is still missing. Writing it is part of writing the
type.
`inspector: { type, instance? }` in `type.yaml` names the files. `type` is the
interface for the type itself and for its assets; `instance` names a file an
asset may ship to add its own. Each returns:
```luau
return {
sections = { { id = "graph", title = "Graph", build = function(ctx) ... end } },
replace = { contents = { ... } }, -- replace a default section by id
order = { "graph", "contents" }, -- section order
}
```
`build(ctx)` receives the asset and builds the section. A section's `title`, and
the text its rows carry, is a string or an `i18n.text` value read from a catalog
(`i18n.text("inspectors.mesh.title")`), which follows the editor's language. `asset.create("assetType",
...)` scaffolds a working `inspector.luau` to start from. `asset.validate` on a
type that names no inspector, or names one that does not load, reports it.
## Say what your type is for (`about.yaml`)
Every type carries an `about.yaml` that says what the type is for, in three
plain-language texts:
```yaml
intent: "Sets the typeface of the text in your game: UI, labels, signs and 3D lettering."
function: "A font, from a TTF, OTF or WOFF file, made available to all of Zero's text, including 3D text."
usage: "You choose it by name for your UI or your text, and the text appears in that typeface."
```
- **`intent`** is what the type is for in someone's game, in the words a game maker uses. Up to 800 bytes.
- **`function`** is how it works today: what an asset of it is made of and what the engine does with it. Up to 1500 bytes.
- **`usage`** is what a person or an agent does with one. Up to 1200 bytes.
Write about the type as a whole, not one asset of it, and say what it does now.
Agents read these texts to learn when to reach for the type and how; people
searching find the type by them. The scaffold starts each text with
`[[describe]]` and a note on what to write; a text that still starts that way
counts as not written. `services describe` can write them.
They show up in `asset.inspect` as `detail.about`, in
`assetTypeRef:getAbout()`, at the end of the type's `types/<typename>` guide,
and at the top of the type's Inspector.
## Ask your assets to say what they are
A type can require each asset to carry a description: a file, written by the
author or generated, saying what the asset is and what it is for. Declare it with
a `described` check:
```yaml
files:
required:
- path: "README.md"
kind: "file"
content:
- { check: "described", message: "Say what this widget is for and where it goes." }
```
A file that is missing, empty or still has a line starting with `[[describe]]`
fails the check, and so does a YAML file whose named `keys` are missing or over
their `max_bytes`, or a Markdown file missing a named heading. `asset.validate`
names the asset, and a push that carries it is refused with `message`.
`services describe` finds such assets and writes their descriptions.
`describe:` steers what is generated:
```yaml
describe:
guidance: "Say what the widget shows, what input it reacts to, and where it fits in a UI."
examples:
- "<identity of an asset of this type whose description reads well>"
```
An example is an asset of your type whose description is a true, written one,
never a placeholder and never the asset being described; with none, leave
`examples` empty. A type whose assets the model cannot perceive (a sound, a
motion) says so in `guidance`, and the description is drawn only from what the
asset's own files state.
Start the file unwritten in your `template/`: a heading and one line starting
with `[[describe]]`, never example content, which every new asset would carry
verbatim. A type whose assets say what they are through their own content (a
mesh, a texture) declares no check.
## The type's code (`behavior.luau`)
`behavior.luau` returns one table. These are the keys the engine reads from it;
anything else on the table is the type's own.
### What the type's assets can do
| Key | Shape | What the engine does with it |
|---|---|---|
| `ref` | `{ [name] = function(self, ...) }` | Every function becomes a method on every asset of the type: `ref:name(...)`. |
| `modules` | `{ [name] = require(".x") }` | Code the type's assets reach with `asset.containing(__FILE__).modules.<name>`. |
| `events` | an events schema | Events an asset fires. Readers subscribe through `ref.events.<name>:connect(...)`; the type fires them. |
| `refShapes` | `{ [method] = function(self) -> (typeExpr, source?) }` | The result type of a `ref` method for one particular asset (below). |
| `namePattern` | a Lua pattern | The names `asset.create` accepts for the type's assets. Default `^[A-Za-z][A-Za-z0-9_]*$`. |
| `derive` | `{ output, module, compute, fingerprint, matches?, required?, timeout? }` | A file computed from the asset when it is committed; a `required` one holds the commit until it lands. |
Some `ref` names mean the same for every type, and the engine calls them:
- **`instantiate(self, target?, opts?) -> (root, idMap)`**: puts the asset in a scene. Defining it is what makes the type scene-instantiable. Its return is a contract (below).
- **`inspect(self) -> detail`**: what `asset.inspect` reports for the asset beyond the common record (below).
- **`preview(self, opts)`**: renders the asset's picture; it wins over the type's `preview:` recipe.
- **`previewMaterial(self) -> { material }`**: the material a `surface` preview paints.
- **`saveDefinition(self)`**: writes the asset's in-memory edits back to its files in edit mode.
Some names are answered for every asset before the type is asked, so a `ref`
entry of the same name is never reached: `getSource`, `getBytes`, `getText`,
`exists`, `deps`, `canInstantiate`, `canPreview`, `preview` (which calls yours
when you define one), `meta`, `runtime`, `events`, `typeRef`, `modules`, and the
residency flags `has_backing_asset`, `has_runtime_changes`, `cpu_resident`,
`gpu_resident`.
### When the engine calls the type
| Hook | Signature | When it runs |
|---|---|---|
| `onCreate` | `(name, opts) -> { [path] = contents }` | On `asset.create`. Returns the files of the new asset, laid over the type's `template/`. Annotate `opts`: its type is the schema `asset.create` checks the caller's arguments against. A `""` key writes a single loose file. |
| `onReplace` | `(dest, files) -> files` | On an `asset.create` over an asset already at `dest`, after `onCreate`, so what the author added can be carried into the replacement. |
| `onRegister` | `(self)` | Once per asset, when it first registers: when the world loads, on a live `asset.create`, and when an asset arrives later (installed, pulled, synced). This is what makes an asset take effect the moment it is written. |
| `onChange` | `(ref, change)` | On every write to a file inside an asset of the type. `change` is `{ path, asset, type, kind, origin }`, plus `settings` and `settingsChanged` for a write to the settings values file; `kind` is `edited` or `seeded`, `origin` is `local` or `remote`. Filter on `change.path`. Writes to one asset arrive in order, each after the hook for the one before has finished, and the hook may wait on what it reads. A write the hook makes inside its own asset arrives later like any other, so keep the hook convergent. |
| `onDependencyChange` | `(ref, change)` | When a module the asset's code requires is re-run, or a name the asset carries starts resolving. `change.kind` is `dependency`. |
| `onDelete` | `(ref)` | When an asset of the type leaves the world: deleted, or the world it is in is swapped away. |
| `validate` | `(ref) -> { { code, message, severity?, path? } }` | On `asset.validate`, after the `type.yaml` checks, for the type's own rules. `severity` defaults to `error`. Runs on every push, so a type's rules hold at publish. A hook that fails reports `validate.hook_failed`. |
### Settings hooks
| Hook | When it runs |
|---|---|
| `settingsDefaults(name, opts, asked) -> table` | Once per `asset.create`, for values the schema's defaults do not give. |
| `settingsCorrections(values, name, opts) -> (corrections?, reasons?)` | On every settings write. A correction to a field the writer named refuses the write, giving the reason. |
| `settingsDerivedDefaults(values, explicit, changed)` | On a settings write, for fields derived from others. |
| `normalizeSettings(values, stored?)` | On every read and write, to map an earlier spelling of a field to the current one. |
| `settingsHealed(values, stored)` | On a read, to repair stored values. |
| `settingsSchemaProblem(schema, ref) -> string?` | When an asset's own schema is read; a returned string refuses the schema. |
`creationInputs` (`{ [opt] = true | selectorOpt }`) names `asset.create` options
that are inputs to the type rather than settings.
### Reloading
An edit to `behavior.luau` reaches existing assets with no restart.
## How an asset is pictured (`preview:`)
| `kind` | The picture is | The type provides |
|---|---|---|
| `instantiate` | the asset placed in the preview studio through its `instantiate` | `ref.instantiate` |
| `image` | a file the asset holds, fitted to the frame | `source: { files }`, the candidate files in order |
| `surface` | the asset painted on a mesh | `mesh`, and `ref.previewMaterial` |
| `custom` | whatever `ref.preview` returns | `ref.preview` |
```yaml
preview:
kind: surface
mesh: sphere
```
`angle: [yaw, pitch]` turns the camera. The studio owns the light, the backdrop
and the framing, so an asset pictures the same in every world. A type with no
`preview:` that defines `instantiate` still answers `ref:preview()`.
A picture is rendered when something asks to view it (the editor showing the
asset, `ref:preview()`), when previews are generated on request
(`assets.generatePreviews`), and when the asset is staged. An edit alone
renders nothing. The picture records what it was made
from, so a stale one is told from a current one.
## The names your type's assets hold (`references:`)
Where your type's own format or API carries the name of another asset, declare
it here:
```yaml
references:
keys: # a top-level key of the type's files that holds a name, or a table of them
- { key: "shader", type: "shader" }
args: # an argument of a call, counting from 1
- { call: "g:node", position: 2, type: "procNode" }
fields: # a field of the options table a call takes
- { call: "fx.beam", field: "material", type: "material" }
```
`type` is the category the name resolves in. `asset.declareReferenceKey`,
`asset.declareReferenceArg` and `asset.declareReferenceField` declare the same
from a script.
## What search reads (`indexing:`)
`indexing:` is how assets are found. Search reaches an asset only through what
its type's `indexing:` names, and adds nothing of its own. That includes you: an
asset indexed badly is one you cannot find later, when you are making something
else and need it. A type whose assets are never looked for says `indexing: none`.
```yaml
indexing:
data: # text, read from the asset's files
- role: identity
extractor: verbatim
source: { file: "README.md" }
- role: interface
extractor: symbols
source: { files: ["init.luau"] }
- role: implementation
extractor: verbatim
source: { files: ["init.luau"] }
content: # the picture
- role: identity
modality: image
source: { file: "preview.png" }
facets: # what a query filters and re-ranks by
file: ".metadata"
rigged: { type: bool, from: { components: { contains: SkinnedModel } } }
roughness: { type: number, filter: range, from: { file: "mat.yaml", field: "floats.roughness" } }
```
**Roles.** Each `data` and `content` entry has a `role`, and a query matches in
two slots:
- **`identity`**: what an asset is. For anything you look at, the picture; for anything else, the text that says what it is.
- **`capability`**: what it does and how it is made. `interface` (the signatures or shape a caller uses) and `implementation` (the body) both count as capability, and a type with code usually declares both.
Ask what a person would recognise an asset of the type by, and what it does, and
point each role at the file that says it. For text, that is the asset's
description: the file your template starts with a `[[describe]]` block, which the
author writes or `services describe` fills in (see "Ask your assets to say what
they are").
**`data`.** `extractor: verbatim` embeds a file's text as it is; `symbols` embeds
the declared signatures of code. `source` is `{ file }` or `{ files: [...] }`.
Never index a file name (`source: { field: name }`): one
or two words carry nothing to match.
**`content`.** `modality: image` embeds the picture itself, so a text query
matches what the asset looks like. A type whose assets are looked at makes the
picture its identity.
**`facets`.** What a query narrows and re-ranks the matches by. `file` is embedded
whole, so keys nobody declared in it are still found. Each further key is
computed for every asset and states a value for every one, including `false`: a
file can imply "not rigged" but never say it, and a query separates rigged from
unrigged only because the unrigged ones say `rigged: false`. A key is
`{ type: bool | number | enum, filter?: range, from }`, where `from` is
`{ file, field }` (a field of one of the asset's files, dotted for nesting),
`{ metadata: key }`, or `{ components: { contains | any_outside } }` (what the
asset's entities carry).
## What blocks a push
A push checks every asset it carries against its type. These refuse it:
- a required file that is missing, a `content` check that fails, a `described` file not written yet;
- an error from the type's `validate`.
Unlisted files and warnings do not. A `described` file blocks only a push that
changes the asset. When a push is refused, the message names each asset and what
it lacks. `world.publishBlockers()` and `zm status` read the same list without
pushing.
## Typing a result from the asset (`refShapes`)
A `ref` method whose result depends on the asset (one entry per child folder, per
row of a config, per control a map declares) can only be annotated as
`{ [string]: Thing }`, which accepts any key. `refShapes` states the result for
each asset instead: a function returning a Luau type expression for that asset,
and the module whose types the expression uses. Read the asset; never run it.
```lua
-- inputMap.assetType/behavior.luau
M.refShapes = {
activate = function(self): (string, string)
local names = {}
for _, control in ipairs(M.ref.controls(self)) do
table.insert(names, control.name .. ": Handle")
end
if #names == 0 then return "", "" end
return "{ " .. table.concat(names, ", ") .. " }", "@builtin::modules.zinput.scheme"
end,
}
```
With it, `map.jump:onPressed(fn)` is checked and `map.noexisting` is reported.
A per-asset type applies where the call site names which asset: a component
field whose default names it, or an annotation `AssetRef<"inputMap", "<identity>">`.
`asset.resolve(name, category)` carries only the category, and a name computed
at runtime carries nothing, so calls on those keep the declared return. The type
belongs to the call's result: index it there, or bind what you need from it
there, and the names stay checked.
`require("@builtin::assetTypes.assetType.shared.refShapes").published()` shows
what was published: `categories` (each type's method surface) and `returns`
(per-asset results by identity, then method). An identity missing from
`returns` was never published. Results are recomputed when an asset is written;
at most 64 assets of one type are read.
## Putting an asset in a scene (`ref.instantiate`)
A caller writes one piece of code against every instantiable type, so what
`instantiate` returns is fixed:
```lua
local Instantiable = require("@builtin::assetTypes.assetType.shared.instantiable")
M.ref = {
instantiate = function(self, target, opts)
local root = Instantiable.root(self, target, opts)
-- compose the asset under `root`, now
return Instantiable.result(self, root, idMap)
end,
}
```
**In.** `target` is the entity the asset lands under, or onto for a hierarchy
type; with none, the type spawns a new root. `position`, `rotation` (three
numbers in degrees, or a quaternion), `scale`, `name` and `temporary` mean the
same for every type: `Instantiable.root` applies them to a root you make,
`Instantiable.place` to one you adopt. Document any options of your own in the
hook's `--!arg` docs.
**Out.** `(root, idMap)`. `root` is the composed root, live when you return:
build synchronously, never defer to a component's `awake`. `idMap` maps each
original id to the spawned one, so a component that composes the asset again on
every load can pass it back in and keep references into the composition. Every
call goes through `Instantiable.result`, which refuses a root that is not live
and turns a missing `idMap` into `{}`.
## Inspecting an asset (`ref.inspect`)
`asset.inspect(ref)` builds a record every asset shares (`identity`, `name`,
`guid`, `source`, `typeName`, `typeDefinitionPath`, `scope`, `origin`,
`description`, `tags`), then calls `ref.inspect(self)` for the type's own
`detail`:
```lua
M.ref = {
inspect = function(self)
-- read the asset's own files, never runtime state: inspect works on an asset
-- that has not been compiled, uploaded or registered
return { --[[ what makes this asset what it is ]] }
end,
}
```
Without it, the record is the shared part alone, and an agent inspecting the
asset learns nothing of what it is. A hook that raises leaves `detail` empty and
sets `record.warning`.
## Discovery
- `asset.list("assetType")`: every registered type.
- `asset.inspect("<typename>")`: the type, its README and its `about.yaml` texts.
- `asset.resolve("<typename>", "assetType")`: the type itself.
·computeshader · born here
❒asset # gather
Builds a column from another column and a run of indices: element `i` of the
result is element `index[i]` of `src`. An index below 0 or past the end of
`src` gives zeros. The element type is the `T` specialization (`f32`, `i32`,
and two to four lanes of either); a three-lane column is read and written
tightly packed, twelve bytes an element.
Dispatch over `n`, the number of indices. Exact: each result element has one
writer. It declares `fusion:` (the value of element `i` is `element(i)`, a thread
runs where `skip(i)` is false), so a chain of fused kernels evaluates it inside
one dispatch.
Most nodes that reorder, select or copy elements read their columns through it:
`core.select`, `core.concat`, `core.make`, `core.weld`, `attribute.gather`,
`attribute.promote`, `elements.sort` and the geometry nodes among them.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` slots are live: a slot at or past it holds zeros. It binds 4
storage buffers (3 in the plain variant), and `dst` holds `n` elements.
# field.index
The element number, counted from 0. Unwired it is an Int field over whatever reads it (`fieldc.leaves.elementId`: the number of the element being written). With a `domain` it is an Int column of 0 to n - 1, one per element of the domain.
# math.where (procNode)
Choose between two values by a condition: `a` where `cond` is not 0, `b` where it is.
The `where` operation of the authoring surface, called through the Luau node on `proc.fieldc.operators`. Operands are numbers, vectors, Columns or Fields. When every operand is a plain number or vector the answer is the plain result, folded where the node cooks; otherwise the answer is a Field: a template over its operands that whatever reads it evaluates in one dispatch together with the chain around it. Nothing dispatches for this node alone.
·computeshader · born here
❒asset # sort
A stable radix sort of a column's keys into a permutation: place `s` of `perm`
holds the index of the element that sorts `s`-th, so a gather by `perm` puts
any column in key order.
| Specialize | Options | Meaning |
|------------|---------|---------|
| `KEY` | `f32`, `i32` | the scalar a key holds |
Elements with equal keys keep their run order, in both directions
(`params.descending` 1 sorts from the greatest key down), and `-0` and `+0` are
one key. The sort works 4 bits of the key at a time from the least significant
up, and a pass whose digit is the same in every key is skipped, so a run of keys
inside a narrow range takes fewer passes. `work` is the sort's second
permutation; its contents after a dispatch are not an answer.
The dispatch size `n` is the number of keys. One workgroup of 128 works the whole
run; the other workgroups of a larger dispatch return.
Exact: the sort is a function of the keys and their order, so the same keys give
the same permutation on every dispatch.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` keys are live: they are sorted, and a slot at or past the live
count holds its own index in `perm`. A live count of 0 sorts nothing and `perm` is
the identity. It binds 4 storage buffers (3 in the plain variant).
Nodes that order or group elements run it, among them `attribute.order`, `elements.sort`, `core.edges`,
`core.adjacency`, `core.spatial`, `geometry.bvh`, `geometry.boolean`, `geometry.decimate` and `geometry.shared`.
·computeshader · born here
❒asset # expand
Turns a count per element into runs. Element `j` takes `counts[j]` slots, in
element order; slot `s` of the result holds `owner[s]`, the element it belongs
to, and `local_index[s]`, its place within that element's run. `offsets` is the
exclusive prefix sum of `counts` (what the `scan` kernel makes of it), so every
slot finds its element by a binary search and has one writer.
`owner` is an appended output: its live count is the sum of the counts, up to
the capacity the dispatch was given. Slots at and past the live count hold -1.
An element with a count of zero has no slot; a column of all zeros gives a live
count of zero.
Dispatch over `n`, the capacity of the result. Exact.
`core.owner` runs it to give every vertex its primitive and its place in the primitive's run. `core.realize`,
`core.pairs`, `core.adjacency`, `core.resample.curve`, `core.sample.surface`, `core.normals.corner` and the geometry
nodes that make new primitives (`geometry.extrude`, `geometry.sweep`, `geometry.triangulate`, `geometry.bevel` and
others) expand their counts with it.
Over a live count (`COUNT=device`, see the abi README) the elements are the first
`domain_count` of `counts` and `offsets`, so they can be held in runs larger than
their live count, and the counter of `owner` states the sum of their counts as it is,
above the capacity too: the first `n` slots are written and the sum minus `n` is how
many did not fit. A node that states `n` as a bound checks the count against it. The
plain variant clamps the count to `n`. It binds 6 storage buffers (5 in the plain
variant).
Over live elements (`ELEMENTS=device`) the elements are the first `element_count` of `counts` and `offsets`, whatever
`n` covers: a result sized by one class (the vertices) expanded from the elements of another (the primitives). It binds
one storage buffer more.
·computeshader · born here
❒asset # scan
The prefix fold of a run of elements, whole or per segment: running sums,
running least and greatest, running products. (The running product of 4x4
matrices is `scan_mat4`.)
| Specialize | Options | Meaning |
|------------|---------|---------|
| `T` | `f32`, `i32`, `vec2` to `vec4` of either | the element; a vector scans lane by lane |
| `OP` | `add`, `min`, `max`, `mul` | the operator |
`params.exclusive` picks the fold of the elements before each one or the fold up
to and including it. The first element of a group has nothing before it: an
exclusive scan holds 0 there for `add`, 1 for `mul`, and the element itself for
`min` and `max`. `total` holds the fold of each group, 0 for an empty group. A
segmented scan (`params.segments` above 0, the number of segments) restarts at
each start in `starts`; an unsegmented one binds any one-word run there.
One workgroup scans one group at a time, a tile of 128 elements at a time, with
the fold of everything before a tile carried into the next. The dispatch size
`n` is the number of elements; any workgroup count from 1 up scans every group.
Exact: the order of combination is fixed, so the same run gives the same bits on
every dispatch, and an integer scan is the exact integer answer.
Over a live count (`COUNT=device`, see the abi README) `n` is the capacity and the
first `domain_count` elements are the run. Every slot of `dst` at or past it holds the
total of the last group (the whole run, or the last segment; 0 for an empty one), which
is the scan of the run padded with the operator's identity. An `i32` scan's `total` is a count another kernel takes as its
domain (`{ count = total, capacity = ... }`). It binds 5 storage buffers (4 in the plain
variant).
Over live segments (`SEGMENTS=device`) `params.segments` is the most segments there can be, which sizes `total`, and the
first `segment_count` of them are live: a segment past them is not scanned, and a run of no live segments scans nothing.
It binds one storage buffer more than the variant it extends.
Nodes that need offsets, running totals or arc lengths run it, among them `core.make`, `core.select`, `core.edges`,
`core.arclength`, `core.realize`, `core.sample_curve`, `core.sample.surface`, `attribute.accumulate` and
`sim.particles`.
# proc
Code-authored, graph-backed procedural generation for the Zero engine.
A graph is one function of `g`: `proc.define(function(g) ... end)`. Nodes are called by
family and name (`g.<family>.<name>({ ... })`), inputs are declared with `g:input(name, default, opts)`,
the returned table is the graph's outputs, and `io.output` is how the graph stands in the world.
`builder.module/README.md` holds every rule of that form.
This module owns the whole procedural model: the graph builder + data model,
the operation registry, the type system, the lazy cached evaluator, deterministic scoped hashing, and the node-family op
implementations. Authored `.procGraph` graphs are persisted via
`procGraph.assetType`; the `procgen.preview` / `procgen.spawn` operations live in
`procgen.toolbox` and are invoked as tools: `tools.use("procgen", "preview", args)`
from a script or an agent's `tool_exec` script, or `zero procgen preview` in the
shell. Generated
meshes/materials/textures/bundles are persisted through their own `.assetType`.
An op family can also come from outside this package: a `.procPack` asset
registers its ops in the same registry, called as `g.op.<id>(...)` exactly like the ones
shipped here (`proc.registerPack(name, ops)` is what it registers through, and
what a test or a tool calls to hold a family for the life of one VM).
`terrain.*` is one such pack, shipped in `terrainSystem.package/procPacks/`
and covering a whole landscape; `guides { path =
"systems/terrainSystem/documentation/terrain" }` is its guide.
To find out what the registry holds, use the `procgen` toolbox: `searchNodes`
searches it and `describeNode` describes one node or op. `proc.search_ops(query)` and
`proc.schema(id)` are the same answers in-process, for a graph builder looking
something up while it runs.