Contents
Nilo reference
The whole language on one page. Nilo compiles a .n file to one plain JavaScript file with no runtime.
Every word with a meaning of its own is on this page: any other word in a piece is a name the author chose.
(cd compiler && go build -o nilo ./cmd/nilo) # the compiler, built once: compiler/nilo
./compiler/nilo piece.n -o piece.js # canvas target, size mode
./compiler/nilo piece.n --target svg -o piece.js # svg target
./compiler/nilo piece.n --opt speed -o piece.js # speed mode
./compiler/nilo piece.n --target svg --decimals 2 -o piece.js # marks to 2 decimals
./compiler/nilo piece.n --target svg --sizes -o piece.js # also the bytes of each library
./compiler/nilo piece.n --lib path/to/lib -o piece.js # libraries from another folder
./compiler/nilo sketch piece.n # sketching: a page that follows every saveThe output
| target | written | contract |
|---|---|---|
canvas (default) | function piece(hash, ctx) | hash is 0x and 64 hex digits; ctx is a 2D canvas context, drawn on in plate units (the host scales it to the screen). Setup runs inside piece. With a frame block, piece returns frame(t), t running from 0 up to (not including) 1 over one loop. |
svg | function piece(hash) | Returns the SVG text of the plate. No frame block. Coordinates are written in whole tenths of a unit, in a viewBox ten times the plate; with --decimals k the marks (polyline, polygon, curve), gradients and groups are written in plate units to k decimals, the viewBox the plate (the path commands then cannot be used). |
A piece with input lines takes one more argument, last: piece(hash, input) or piece(hash, ctx, input), an object
holding each input by its name (a vec as [x, y], a colour as [r, g, b], an array as an array of those).
The same hash always gives the same piece. --opt size (the default) writes the fewest bytes; --opt speed writes the
fastest frame. Both draw the same picture. The output is already minified; --readable writes it before minifying.
A piece
plate(1920, 2400) // the design size, in units (nilo sketch uses 1920 x 2400 when it is left out)
use noise v1, colour v1 // libraries, each with its version (see Libraries)
random layout, mark // named randoms
param count = layout.int(40 ..< 120)
let ink = #1b1b1f
kind spot { pos: vec, r: num } // the shape of one record (see Kinds)
let spots = spot[] // an array of them
fn grow(r: num) = r * 1.5
input seed: int // a value the host page hands in
effect wet(push: num) { ... } // what a layer's drawing goes through (svg target)
once { ... } // setup, run once per token; lines outside any block are setup too
frame(t: loop 8s) { ... } // drawn each frame; t is loop timeAny order; names must be made before they are used, except fns and kinds, which can be used from anywhere, and lets
of embedded data or number lists, which are set up first wherever they are written.
Words
Reserved (never a name of your own):
- statements and blocks:
plateuserandomparamkindfnonceframeloopletvarifelseforinwhilebreakcontinuereturnunittruefalseinputeffectlayerplace, andtimeinframe(t: time)(nilo sketch only) - the names of the libraries a piece uses (
noiseafteruse noise v1) - under nilo sketch:
randomis also the name of the named random a piece gets when it rolls fromrandomand declares none of that name (see Sketching) - inside an effect:
source, and the imagesfractal,turbulence,displace - types:
numintboolveccolorstrpaintrandomf32 - constants:
PITAUINF - built-in functions and commands: every name in the two tables below, and
by(insort(by: f)) - fields and methods:
.x.y.r.g.b.len.add.remove.reverse.sort.unit.float.int.chance
Names are letters, digits and _, not starting with a digit. A name may not hide another one (no two names the same
where both can be seen). A kind’s name is a name like any other: it may not be a built-in’s name or one of the words
above, and nothing else in the piece may take it.
Lexical
- Comments:
//to the end of the line. - Numbers:
12,1.5,1e-9, hex0xff. Write0.5, not.5. - Colours:
#rgbor#rrggbb. - Strings: double quotes, on one line, no escapes;
{value}puts a number or text in:"seed {s}". - Statements end at the end of a line;
;may also separate them. - A line that starts with an operator starts a new statement: break a long expression after an operator, not before.
(of a call,[of an index and?of a choice go on the line of what comes before them.
Types
| type | what | written |
|---|---|---|
num | a number (a double) | 1.5, x / 2 |
int | a whole number; with bit operators an unsigned 32-bit word | 3, 0xff, floor(x) |
bool | true or false | true, a < b |
vec | a point or offset x, y | vec(3, 4), p.x, p.y |
color | a colour, channels 0 to 255 | #c2452d, rgb(r, g, b), c.r c.g c.b |
str | text; also paints as a CSS colour | "rgb(10, 20, 30)", rgba(c, 0.5) |
paint | anything that fills or strokes: a colour, text that is a colour, or a gradient (see Paint) | #c2452d, rgba(c, 0.5), linear(a, b, [#a00, #00a]) |
num[] int[] f32[] vec[] color[] | arrays | [1, 2], vec[], num[4], f32[n] |
| colour list | colours written out in a list | [#a00, #0a0, #00a] |
a kind’s name, such as reed | a record of that kind (see Kinds) | reed(root: p, h: 900), reeds[i] |
reed[] | an array of records of the kind reed | reed[] |
| range | only in loops, slices and rolls | 0 ..< n (n left out), 0 ..= n (n taken in) |
| random | random numbers, a named random | random layout, random r = maker(seed) |
| loop time | the frame’s t, counted in turns | t, t * 2 + ph |
int arithmetic stays int except /, which gives num. An int goes wherever a num does.
Statements
| form | |
|---|---|
let x = e | a name for a value; it cannot change. let x: num = e checks the type. |
var x = e | a name whose value can change: x = e, x += e, x -= e, x *= e, x /= e |
if c { } else if c { } else { } | c is true or false |
for i in a ..< b { } | count; also a ..= b |
for x in xs { } | each element of an array or colour list |
for x in xs[a ..< b] { } | part of an array: the elements from a up to b |
for ch in "text" { } | each character’s code (an int) |
while c { } | |
break, continue | leave the loop, or go on to its next turn |
return e, return | in a fn |
random r = maker(seed) | a named random made by a random maker the piece writes (see Named randoms) |
r.field = e | change a field of a record (also += and the others; see Kinds) |
a[i] = e, a[i] += e | change an array element |
| a call | a drawing command, a fn, an array method, or a roll from a named random |
fn f(x: num) { } | a local fn: written inside a block, it sees the names round it (see Fns) |
layer e(args) { } | what the block draws, with the effect e applied (see Layers and effects) |
place(p, turn: a, scale: k, opacity: o, clip: outline) { } | what the block draws, gathered as one group: moved to p, turned, scaled, faded and clipped (see Place) |
Top-level only:
| form | |
|---|---|
plate(w, h) | the design size, numbers written out; a normal build needs it |
use noise v1, colour v1 | the libraries the piece calls, each with its version (see Libraries) |
random a, b | named randoms made from the hash, one 32-bit word (lane) each, in order (eight at most) |
param x = e | a setup value listed as a parameter of the piece (otherwise a let) |
kind name { f: type, ... } | the shape of one record; fields are num, int, bool, vec or color (see Kinds) |
fn f(x: num, ...) { } | a function; also fn f(x: num) = e, and fn f(x: num): num to state the result type |
input name: type, ... | values the host page hands in: num, int, bool, vec, color, num[], int[], vec[], color[] |
effect name(x: num, ...) { } | an effect for layers (see Layers and effects) |
once { } | setup |
frame(t: loop 8s) { } | drawn each frame, one loop every 8 seconds; at most one |
frame(t: time) { } | drawn each frame, t counting seconds with no loop (nilo sketch only; see Sketching) |
Parameter types: num, int, bool, vec, color, str, paint, random, num[], int[], f32[], vec[],
color[], a kind’s name (r: reed) and an array of a kind (xs: reed[]), and fn types such as fn(vec): bool. A
color[] parameter also takes a colour list written out ([#a00, #0a0]) or a let holding one. A fn gives one value
of any type but a named random, or nothing; it cannot call itself.
Fns
A call gives its values in order, then by name, in any order: sweep(r, path, width: 12, opacity: 0.9). A parameter
may have a default, a value written out, which a call that leaves it out takes: fn sweep(r: random, path: vec[], width: num, opacity: num = 0.5). The parameters after one with a default have defaults too. The values are worked
out in the order the call writes them, so rolls happen in that order.
A fn written inside a block is a local fn. It sees the names round it where it is written (lets, vars, parameters, named randoms, loop names) and reads their values as they are when it is called; it cannot set them.
fn sweep(path: vec[], ramp: color[], feather: num = 0.35) {
fn rampAt(f: num) = ramp[floor(clamp(f, 0, 1) * (ramp.len - 1))]
fn keep(d: num) = d < 1 - feather ? 1 : 0.2
...
}A parameter of a fn type takes a fn by its name, a fn at the top or a local fn; the fn it names is called where the parameter is called. Each call is compiled with the fn it hands in, so nothing is passed around when the piece runs, and a fn handed in is held to the rules where it is really called.
fn walk(p: vec, steps: int, keep: fn(vec): bool): vec[] { ... if !keep(q) { break } ... }
fn inside(q: vec) = len(q - centre) < radius
let path = walk(start, 40, keep: inside)Operators
Weakest first; operators on one row bind the same, left to right.
| operators | on | |
|---|---|---|
| 1 | c ? a : b and ranges a ..< b, a ..= b | |
| 2 | || | bool |
| 3 | && | bool |
| 4 | == != | numbers, or bools |
| 5 | < <= > >= | numbers |
| 6 | | | whole numbers |
| 7 | ^ | whole numbers |
| 8 | & | whole numbers |
| 9 | << >> | whole numbers (>> shifts in zeros) |
| 10 | + - | numbers; vec + vec, vec - vec |
| 11 | * / % | numbers; vec * num, num * vec, vec / num; % keeps the sign of the left side |
| 12 | -x !b ~n | |
| 13 | f(x) a[i] p.x |
Bit operators bind tighter than comparisons: a & 1 == 0 is (a & 1) == 0. Bit operators read and give unsigned
32-bit words. Dividing by zero gives INF.
Constants and functions
| name | gives | |
|---|---|---|
PI, TAU | num | half a turn and a full turn, in radians |
INF | num | infinity |
sin(a), cos(a) | num | a in radians; when a is loop time (or made from it), in turns: sin(t) goes once round per loop |
atan2(y, x) | num | the angle of (x, y), in radians |
polar(a, r) | vec | vec(r * cos(a), r * sin(a)), a in radians |
orbit(t, r) | vec | once round a circle of radius r per turn of loop time t |
sqrt(x) abs(x) exp(x) pow(a, b) | num | |
floor(x) ceil(x) round(x) | int | round takes halves up |
fract(x) | num | x - floor(x); of loop time, where it is in its turn (it jumps, see Rules) |
min(a, b, ...) max(a, b, ...) | num | two or more |
clamp(x, lo, hi) | num | |
smoothstep(e0, e1, x) | num | 0 below e0, 1 above e1, smooth between |
lerp(a, b, k) | num or vec | a + (b - a) * k |
finite(x) | bool | not infinite and a number |
fixed(x, k) | num | x as it reads written to k decimals (JavaScript’s toFixed), k written out |
vec(x, y) | vec | |
len(v) | num | the length of v |
dot(a, b) | num | a.x * b.x + a.y * b.y |
perp(v) | vec | vec(-v.y, v.x), a quarter turn |
rgb(r, g, b) | color | channels 0 to 255 |
rgba(c, a) | str | colour c at alpha a (0 to 1), to paint with; not taken apart |
linear(from, to, stops) | paint | a gradient running from point from to point to (see Paint) |
radial(c, r, stops) | paint | a gradient about centre c, out to radius r (see Paint) |
lane(k) | int | the k-th 32-bit word of the hash, k from 0 to 7, written out |
bytes("base64") | int array | embedded data, read by index (d[i], 0 to 255) and .len |
Drawing
Shapes gather into one path until fill or stroke paints it; then a new path starts. Where a point is wanted, two
numbers x, y may be written instead of a vec.
| command | |
|---|---|
circle(centre, r), circle(x, y, r) | a circle |
line(a, b), line(x1, y1, x2, y2) | a segment |
move(p), move(x, y) | start a new run of the path at p |
to(p), to(x, y) | carry the path on to p (a polyline is move then to for each point) |
quad(control, end) | a quadratic curve from where the path is (canvas only) |
bezier(c1, c2, end) | a cubic curve from where the path is (canvas only) |
rect(corner, size), rect(x, y, w, h) | a rectangle |
close() | close the run back to its move |
fill(colour) | paint the path’s inside |
stroke(colour, width), stroke(colour) | paint the path’s outline; width in units, 1 if left out |
background(colour) | paint the whole plate |
alpha(a) | the opacity of everything painted after it, 0 to 1 (canvas only) |
fill and stroke take a paint: a colour, a colour as text (rgba(...), a string) or a gradient (see Paint). On the
svg target, these path commands are drawn in setup only, not inside a fn.
Marks (svg target)
A mark is one whole shape, described in one statement with everything it is drawn with. It does not touch the path
above, and it can be drawn anywhere, inside a fn too. Every mark takes its points first (a vec[]), then what it is
painted with, by name. fill and stroke take a paint: a colour or a gradient (see Paint).
| mark | joins its points with | |
|---|---|---|
polyline(points, stroke: p, width: w, opacity: a, caps: "round") | straight lines, open | stroke is needed; width (default 1), opacity and caps ("round", "butt" or "square") may be left out |
polygon(points, fill: p, stroke: p, width: w, opacity: a) | straight lines, closed | fill, stroke or both; width (default 1) and opacity may be left out |
curve(points, smooth: s, closed: c, fill: p, stroke: p, width: w, opacity: a, caps: "round") | a smooth curve through them, or cubic pieces from segments: (see Curves) | fill, stroke or both; smooth (default 1), closed (default false), width (default 1), opacity and caps may be left out |
opacity fades the mark as one shape, its fill and stroke together. width and caps belong to a stroke, so a mark
that has them needs a stroke too.
let run = vec[]
for k in 0 ..< 20 { run.add(vec(k * 10, 50 + 5 * sin(k))) }
polyline(run, stroke: #1b1b1f, width: 1.5, opacity: 0.8, caps: "round")
polygon([vec(0, 0), vec(60, 0), vec(30, 50)], fill: #c2452d, stroke: #1b1b1f, width: 2)The canvas target does not draw marks yet; there, write move, to (or bezier) and fill or stroke.
Curves
curve(points, ...) draws a smooth curve through its points, in order. smooth says how round the corners are: 0
draws straight lines from point to point, 1 (the default) the usual smooth curve, a little more a looser one.
closed: true joins the last point back to the first and rounds that join too, so the outline has no ends. A curve is
open unless it says closed: true; a fill closes an open curve with a straight line, as it closes any open path.
curve(ring, closed: true, fill: #c2452d, stroke: #1b1b1f, width: 4) // a closed blob through the points
curve(path, smooth: 0.5, stroke: #1b1b1f, width: 4) // an open line, its corners tightenedTo place the handles yourself, give the segments by name instead: curve(segments: pts, ...). The list is the first
point, then three points for each piece of the curve: the piece’s two handles, then where it ends. One piece is 4
points, two pieces 7, and so on. A handle pulls the curve toward it without the curve reaching it. A list written out is
checked when compiling; a list built when the piece runs draws its whole pieces and leaves off any points over.
closed: true joins the end to the start, with a straight line if they are apart. smooth is for points, not segments.
// one piece from (100, 800) to (500, 800), bulging up through its handles
curve(segments: [vec(100, 800), vec(200, 500), vec(400, 500), vec(500, 800)], stroke: #1b1b1f, width: 6)The smoothing is the maths of the spline library, version 1. The compiler brings it in for a piece that draws a curve
through points, and it costs nothing in a piece that does not. That maths never changes, so a finished piece keeps its
curves. The library is still there for when the numbers are wanted: spline.through(points, smooth, closed) gives the
segments, and spline.sample(points, steps, smooth, closed) the same curve as plain points, for polygon, polyline
or a brush path. See the spline page.
Paint
A paint is whatever fills or strokes: a colour, a colour as text (rgba(c, a)), or a gradient. fill, stroke,
background and a mark’s fill: and stroke: take a paint. A colour is a paint, so it goes wherever a paint does. A
gradient is not a colour: it cannot be mixed or taken apart (colour.mix, .r), nor go in a color parameter or a
color field of a record. The type is written paint:
let ink: paint = #1b1b1f
fn blob(points: vec[], ink: paint) { curve(points, fill: ink) }A gradient is made with linear or radial. A point is a vec, or two numbers.
| gradient | |
|---|---|
linear(from, to, stops) | the colour runs from the point from to the point to, and holds the first and last colour before and after |
radial(centre, r, stops) | the colour runs from the centre out to radius r, and holds the last colour beyond it |
The stops are written one of two ways, and there are at least two colours:
- a list of colours, spread evenly from 0 to 1:
[#1d2b3a, #8c3b24, #f2dfc2]. An item is a colour orrgba(c, a). offset: colourpairs, to put each stop where you want it:0: #1d2b3a, 0.6: #8c3b24, 1: #f2dfc2. Offsets run from 0 to 1, low to high.
The colours are written out (a list, or a let holding one), so that the compiler can count them. An array whose length is known only when the piece runs is refused, and the message says to write the colours out.
let sky = linear(vec(0, 0), vec(0, 1500), [#1d2b3a, #8c3b24, #f2dfc2])
let sun = radial(vec(960, 1100), 300, 0: rgba(#ffffff, 0.9), 1: rgba(#ffffff, 0))
background(sky)
curve(sunPoints, fill: sun)A gradient is written where it is made, once, and its name stands for it wherever it paints (a loop makes a new one each
turn). It lives in a let, not a var. A fn takes one in a paint parameter, by its name (let g = linear(...), then
shape(points, g)); it does not give one back, and a record does not hold one. Its numbers are in plate units, in the
frame of what is drawn: inside a place block, vec(0, 0) is the placed point. The svg and canvas targets both draw
gradients; the marks are svg only.
Layers and effects (svg target)
layer e(args) { ... } draws its block with the effect e applied. An effect is described as images: source (what
the layer draws), noise, the source moved by noise, and sums of two images each times a number. It exists only while
compiling: the svg target writes it as a filter.
| image | |
|---|---|
source | what the layer draws |
fractal(freq, octaves, seed), turbulence(freq, octaves, seed) | noise; freq per unit, a vec (across and down) or one number |
displace(image, noise, scale) | image moved by the noise’s first two channels, up to scale units |
a * k + b * l | two images, each times a number, added |
effect wet(push: num, seedA: int, seedB: int) {
let a = displace(source, fractal(vec(0.02, 0.008), 2, seedA), push)
let b = displace(source, fractal(vec(0.008, 0.02), 2, seedB), push)
let both = a * 0.5 + b * 0.5
return source * 0.45 + both * 0.55
}
layer wet(12, 7645, 9063) { polygon(shape, fill: #46648c) }An effect’s lets name images; its numbers come from its parameters and numbers written out. The canvas target does not apply effects yet.
Colour per item: a colour list can be indexed by a number known only when the piece runs, chosen with ?:, kept in a
color field of a record, and painted:
let tips = [#b5482f, #2f6f8a, #d9a441]
kind reed { root: vec, tip: color }
let reeds = reed[]
reeds.add(reed(root: p, tip: tips[layout.int(0 ..< 3)]))
for r in reeds { circle(r.root, 9); fill(r.tip) }
fill(i == 0 ? #b5482f : #2f6f8a)Place
place(p, turn: a, scale: k, opacity: o, clip: outline) { ... } gathers what its block draws under one transform,
opacity and clip. It moves the block to p (a vec, or x, y), turns it a turns about that point (0.25 is a quarter
turn, clockwise on the plate), scales it k times, fades it to o as one picture and cuts it to the outline: a polygon,
its corners as a vec[], or a curve, clip: curve(points, smooth: s, closed: true) (or curve(segments: pts)). Everything but the block may be left out, the point too when something else is given (place(opacity: 0.5) { ... } fades a block where it stands). turn may be loop time. Blocks nest; inside, vec(0, 0) is the point p. The
transform moves everything the block draws, path commands and marks alike, on both targets and in both modes, and
nothing about it is kept once the block ends.
for i in 0 ..< 12 {
place(960, 1200, turn: i / 12, scale: 1 + i * 0.1) {
rect(300, -10, 200, 20)
fill(#1b1b1f)
}
}
// a faded wash, cut to a smooth outline: strokes inside show through each other no more than one picture does
place(opacity: 0.6, clip: curve(outline, closed: true)) {
for s in 0 ..< 9 { brush.sweep(marks, drags[s], 120, ramp) }
}opacity fades the finished group as one picture, so shapes that overlap inside it do not show through each other
(giving each shape its own opacity would). It is drawn on the svg target; the canvas target has no group to fade and
refuses it (alpha(a) fades one shape there).
clip is in the block’s own frame: it moves, turns and scales with the block. To cut to a shape on the plate and then
move what is inside it, nest: place(clip: window) { place(p, turn: a) { ... } }. A curve in a clip is the same curve
the curve mark draws, a shape that takes no paint; an outline is a region, closed whether it says closed or not
(closed there only says whether the smoothing goes round the join). Clips are drawn on both targets.
A shape is placed whole: what the block draws is painted (fill, stroke) inside it, and the path is painted before the block
starts (on the svg target; a fn that draws marks may hold a place block). The block runs to its end, so break, continue
and return stay outside it, and background, which paints the whole plate, stands outside it too.
Named randoms
A named random gives random numbers from the hash. random layout, mark at the top makes named randoms from lanes 0, 1, …. Each
roll is one of the lines below.
| roll | gives |
|---|---|
s.unit() | num from 0 up to 1 |
s.float(lo ..< hi) | num from lo up to hi (..= rolls the same) |
s.int(lo ..< hi) | int from lo up to hi - 1; lo ..= hi takes hi in |
s.chance(p) | true with probability p |
A piece can write a random maker and make named randoms with it (in setup, the frame or a fn):
random xorshift(seed: int) {
var a = seed ^ 0x9e3779b9
unit {
a = a ^ (a << 13)
a = a ^ (a >> 17)
a = a ^ (a << 5)
return a / pow(2, 32)
}
unit() // lines outside unit run once, when a named random is made; unit() rolls
}
random palette = xorshift(lane(0))Every roll happens in order, also a roll whose value nothing reads, so the rolls after it do not change.
Arrays
| on an array | |
|---|---|
a[i], a[i] = e | an element |
a.len | how many |
a.add(e) | add at the end |
a.remove(i) | take out element i |
a.reverse() | reverse in place |
a.sort(by: f) | sort by f(x), a fn of one element giving a number and doing nothing else |
for x in a | each element |
for x in a[lo ..< hi] | the elements from lo up to hi, whole numbers within the array (..= takes hi in) |
num[] (and the others) starts empty; num[4] holds four zeros; f32[n] holds n 32-bit floats and has a fixed
length. A colour list ([#a00, #0a0]) is a colour array: index it, loop over it, read .len, change it with the
methods above; let c: color[] = [...] says so. An array lives in a let (its elements can still change). Arrays made
at setup are fixed once the frame runs; arrays made in the frame or a fn can change. A loop over a whole array may not
add to it (see Rules).
To know where each element is, count through the indices: for i in 0 ..< a.len { let x = a[i] ... }.
Kinds
A kind is the shape of one record: its fields, each with its type. Records are kept in ordinary arrays.
kind reed { root: vec, h: num, tip: color }
let reeds = reed[]
reeds.add(reed(root: vec(x, 2100), h: 900, tip: tips[2]))
for r in reeds { circle(r.root, 9); fill(r.tip) }- Declaring.
kind name { field: type, ... }, at the top of the file, anywhere in it. The name starts with a lower case letter (reed,tipMark). A field isnum,int,bool,vecorcolor. An array or a record inside a record is not there yet. - Making a record.
reed(...)is called as a fn is: its fields in order, then by name in any order (reed(p, 900, tip: c)). Every field is given; there are no defaults. The values are worked out in the order written, so rolls happen in that order. - Reading and changing.
r.hreads a field.r.h = echanges it, and so do+=,-=,*=and/=. A vec field takes+=and-=of a vec, and*=and/=of a number; an int field is never divided. - Records are shared, not copied, as arrays are.
let b = ais a second name for the same record, so a change made through one name shows through the other, and a fn handed a record can change it. To copy one, make a new record from its fields:reed(a.root, a.h, a.tip). Records are not compared with==; compare the fields you mean. - Arrays of records.
reed[]starts empty and takes the array methods above (add,remove,reverse,sort(by: f),xs[i] = r).xs[i]is a record andxs[i].hits field. A record lives in alet, not avar; to choose one as you go, keep its index in avarand readxs[best]at the end. - Fns. A parameter can be a record (
r: reed) or an array of them (xs: reed[]), and a fn can give either:fn nearest(q: vec): lump { ... return lumps[best] }.sort(by: f)takes a fn of one record:fn height(b: bar) = b.h, thenbars.sort(by: height). - Setup and the frame. Records and arrays made at setup are fixed once the frame runs, fields too. Records made in the frame, or by a fn the frame calls, can change. A record the frame takes from setup stays setup’s wherever it goes: put in an array the frame made, or given back by a fn.
- What is kept. A record holds the fields something reads. A field nothing reads costs nothing (its value is still worked out where a record is made, for what that does: a roll).
kind bar { x: num, h: num }
let bars = bar[]
for i in 0 ..< 8 { bars.add(bar(x: i * 100, h: layout.float(100 ..< 900))) }
fn height(b: bar) = b.h
bars.sort(by: height)
for b in bars[1 ..< 4] { b.h = b.h + 50 } // part of the array
for i in 0 ..< bars.len { // with the index
let b = bars[i]
rect(b.x, 2400 - b.h, 80, b.h)
}
fill(#1b1b1f)list is gone: a record’s shape is declared with kind, and the records are kept in an array (list spots { ... }
becomes kind spot { ... } and let spots = spot[]). A piece that writes list is refused with exactly what to write.
Libraries
A library is Nilo written once and called from many pieces: a noise field, colour mixing, a brush. A piece names the libraries it uses at its top, each with its version, and calls their names with the library’s name and a dot in front.
use noise v1, colour v1, brush v1
let field = noise.table(layout)
let v = 0.5 + 0.5 * noise.at(field, p * 0.002)
brush.sweep(marks, path, 60, [colour.at(inks, v), colour.darken(ink, 0.3)])| library | what it holds | its page |
|---|---|---|
noise v1 | smooth noise as a number, from a table made from the piece’s own named random | the noise page |
colour v1 | mix, lighten, darken, shift hue, set lightness, read a ramp at 0 to 1 | the colour page |
brush v1 | the sweep: thin streaks laid close along a path (svg target) | the brush page |
spline v1 | the numbers of smooth curves through points: segments for curve(segments: ...), and the same curve as plain points (the curve mark smooths with its maths by itself) | the spline page |
Read a library’s page before using it. It lists every name, what each takes and gives, and an example.
- The version is part of the line:
use noise v1. A version never changes once a piece uses it; a change to a library is a new version (v2), and a piece moves only when its line is changed. A piece may use one version of each library. Under nilo sketch,use noisetakes the newest, with a warning. - Names stay apart. A library’s names are reached only through its name: the piece may have its own
atormix. The piece may not give anything of its own a library’s name. Names starting with_are a library’s own and cannot be called from a piece. - No hidden randomness. A library has no named randoms and does not read the hash. A fn that needs random numbers
takes one (
r: random) and rolls from it in order, so the piece decides where every number comes from. - Only what is called is shipped. The library code a piece reaches is compiled and minified with the piece as
one program, and costs what the same code written in the piece would. The rest writes nothing.
--sizesprints the bytes each library adds to the shipped file. - Errors name the file and line. An error inside a library’s fn that comes from how the piece calls it (a value of the wrong kind, a mark on the canvas target) is told at the piece’s call, with the library’s line.
- Where libraries are found:
lib/<name>/<version>/<name>.n, in thelibfolder beside the compiler, else in alibfolder up from the piece’s folder.--lib dirnames the folder instead.
Writing a library. A library is a .n file of fns, random makers, effects and lets, with use lines for
the libraries it calls (each with its version). It has no plate, random line, param, input, setup or drawing at
its top: drawing happens inside its fns, when a piece calls them. A library cannot declare a kind yet: kinds belong to
the piece, which hands a library fn the fields it needs as plain values or arrays. It calls its own names without a
prefix, and sees only its own names, the built-ins and the libraries it uses; a value from the piece comes in as a
parameter. A piece uses its effects as layer paper.wet(...) { ... }. A new version is a copy of the folder (v1
to v2), changed.
Rules checked when compiling
Each refusal says what to write instead. Under nilo sketch the rules of the frame, of loop time and of fract, and
the lines a finished piece writes out (plate, the random line, a loop length), are warnings instead (see Sketching).
A finished piece states its size with plate(w, h).
A frame draws the same picture every time. It may not roll from a named random made at setup, directly, through a fn
or by handing it to a fn; it may make named randoms of its own. It may not change a var, array or record made at setup
(see Kinds for where a record counts as made).
frame(t: loop 8s) { circle(vec(layout.unit() * 100, 50), 9) } // wrong
let x = layout.unit() // right: roll at setup...
frame(t: loop 8s) { circle(vec(x * 100, 50), 9) } // ...read it in the frameLoop time closes the loop. It may be multiplied by a whole number and shifted by a phase (t * 2 + ph, ph - t,
-t), nothing else. sin, cos and orbit of it take turns, so it needs no TAU.
sin(TAU * (t * 2 + ph)) // wrong sin(t * 2 + ph) // right
orbit(t * 1.5, 20) // wrong orbit(t * 2, 20) // right, or a longer loop: frame(t: loop 12s)
t / 2 // wrong frame(t: loop 16s) // right: a slower loopfract of loop time jumps from 1 back to 0 once a turn, and every value made from it jumps too, until its two ends
agree (as sin(PI * c) does for c = fract(t)). Anything painted from a jumping value must be painted under an
alpha that is zero at both ends. A jumping value may not be kept in a var or array, set the alpha, seed a named random,
or decide whether a var or array changes or whether a loop or fn leaves early.
let c = fract(t); circle(vec(c * 100, 50), 9); fill(ink) // wrong
let c = fract(t); alpha(sin(PI * c)); circle(vec(c * 100, 50), 9); fill(ink) // rightThrough a fn. A fn may be handed loop time (or a value made from it) in a num parameter; its body is then
checked with that parameter as loop time, under all the rules above. What a fn gives or draws jumps with any jumping
value handed to it; a fn that changes an array handed to it, or sets its own alpha and paints, may not be handed one.
fn sway(a: num) = sin(a * 1.5) // wrong when called sway(t): loop time times a fraction, inside the fn
fn sway(a: num) = sin(a + 0.25) // right: sway(t * 2 + ph) goes round twice per loopA roll on one side of ?:, or right of && or ||, is refused. It would happen whether that side is taken or
not, so the rolls after it would not be the ones written. Write it with if and else, or roll first into a let.
let x = flip ? r.float(0 ..< 1) : 0 // wrong
var x = 0; if flip { x = r.float(0 ..< 1) } // rightA place block holds whole shapes and runs to its end (see Place).
A gradient is a paint, not a colour, and is written where it is made: it goes in fill, stroke, background, a mark’s
fill: and stroke:, a let and a paint parameter (see Paint), and nowhere a colour is taken apart.
A local fn reads the names round it but does not set them; give the value back and set it where the fn is called. A fn handed in is called, not handed on or kept.
Names do not hide names. let x = 1 inside a block where x can already be seen is refused; pick another name.
A loop over a whole array may not add to it, directly, through a fn that names it, or through a fn it is handed
to; count instead: for i in 0 ..< dots.len. A loop over part of an array (dots[0 ..< 10]) runs over a copy.
Records are not compared with ==: compare the fields you mean.
A fn cannot call itself, directly or through another fn; write the repeat as a loop.
A finished piece names each library’s version (use noise v1), and uses a library’s names only through it
(see Libraries).
Types are checked: if and while take true or false, a record is made with every field given a value of its type
(an int field a whole number), let x: int = ... must be a whole number, a let cannot be set again (use var).
svg target: no frame block, no path commands inside a fn (marks and layers may be), no quad, bezier or alpha.
With --decimals, marks only.
canvas target: no marks and no layers yet, and no opacity on a place block.
Unused code writes nothing. A fn nothing calls, a let or param nothing reads, an array nothing reads but to add
to it, a kind nothing makes, a field nothing reads and a named random nothing rolls from produce no bytes. A let nothing reads whose value rolls from a named random that something
else rolls from keeps that roll (as a bare call), so the later rolls stay the same.
Sketching (nilo sketch)
nilo sketch piece.n starts a local server (port 8177, or the next free one; --port to choose), prints its
address, and serves a page that runs the piece. Every save recompiles it and the page follows, with no reload. A
sketch build is the size mode build, not searched and not minified. --target svg draws for the svg target; without
it a still piece that draws marks or layers is drawn for svg, anything else for canvas.
circle(960, 1200, 300)
fill(#1b1b1f)is a whole sketch: it shows a circle.
The page. The piece fills the window at the plate’s aspect, sharp at any pixel density; an svg piece is shown
rasterised. The hash is shown in a corner and kept in the address (?hash=), so a reload draws the same piece.
| key | |
|---|---|
r | a new random hash |
| left, right | back and on through the hashes seen this session |
| space | pause or play a frame |
, . | a paused frame back or on by a sixtieth of a second |
p | save the picture as a PNG |
s | save the SVG (svg target) |
w | capture the picture into wip/ beside the piece, as YYYY-MM-DD_NN_<name>__<hash, 7 digits>.png, NN counting up from 01 each day; the terminal prints the full hash with the path |
t | the param sliders |
h | the list of keys |
A compile error is shown over the picture with its file, line, the source line and the message, and the last good picture stays under it until the next good compile. An error while the piece runs is shown the same way, at the line that was running.
Loose mode. Under nilo sketch, and never in a normal build:
platemay be left out: the plate is 1920 x 2400.- a library’s version may be left out:
use noisetakes the newest. A save to a library file the piece uses is followed like a save to the piece, and an error in one is shown in that file. - the random line may be left out: a piece that rolls from
random(random.float(0 ..< 10),random.int(1 ..= 6),random.chance(0.3),random.unit()) and declares no namerandomgets a named random of that name, on the lane after the ones it declares. To finish the piece, declare it there:random random(orrandom layout, random), and the picture stays the same. frame(t: time) { }runs with free time:tcounts seconds from the start, with no loop to close. It is a plain number, sosin(t)takes radians like any number:sin(t * TAU / 4)goes round once every four seconds.frame(t: loop 8s)keeps its meaning.- the rules of the frame, of loop time and of
fract(Rules, above) are warnings, and the piece runs as written. Loop time used against its rule stays loop time (sin(t * 1.5)takes turns; the loop just does not close), andsin(TAU * t)is drawn as thesin(t)its warning asks for. - a roll from a setup named random inside the frame gives the same numbers every frame: the frame’s first roll from
that named random is the first number it gives after setup, its second the second, and so on, frame after frame.
So the picture holds still and a hash and a time reproduce it, as a finished piece does; motion comes from
t. - a frame that changes setup’s vars, arrays or records changes them for good: the next frame sees the change.
Each warning is listed in a footer under the picture with its line and the words a normal build refuses it with,
which say what to write instead. Lines outside any block are setup, drawn once, here as in a normal build.
nilo piece.n -o piece.js stays strict: the way from a sketch to a finished piece is to fix what the footer lists
until it is empty.
Sliders. Each param rolled from a range known when compiling (param count = layout.int(40 ..< 120),
param swing = mark.float(8 ..< 28)) gets a slider (t). Moving one sets that param for the hash on screen and the
piece is drawn again; the roll still happens, so every roll after it stays the same. Each slider has a reset, and
there is a reset for all; the source file is never changed, and the panel lists the values in force to copy. The
range and the hook a slider needs are in the sketch build only. An input has no range, so it gets no slider, and
the page hands a piece with inputs an empty set of them.
Three complete pieces
A canvas piece (compiles as written; bench/repro.mjs compiles the three pieces on this page):
// tide: dots that rise and fall in an 8 second loop
plate(1920, 2400)
random layout, mark
let paper = #f2eee4
let inks = [#1d2b3a, #c4512e, #3e7c6b]
param count = layout.int(200 ..< 400)
kind spot { pos: vec, r: num, ph: num, beats: int, ink: color }
let spots = spot[]
once {
for i in 0 ..< count {
spots.add(spot(pos: vec(layout.float(100 ..< 1820), layout.float(200 ..< 2200)),
r: mark.float(4 ..< 14), ph: mark.unit(), beats: mark.int(1 ..= 3),
ink: inks[mark.int(0 ..< 3)]))
}
}
// how far a dot has risen at loop time a (in turns)
fn rise(a: num, r: num) = sin(a) * r * 4
frame(t: loop 8s) {
background(paper)
for d in spots {
circle(d.pos + vec(0, rise(t * d.beats + d.ph, d.r)), d.r)
fill(d.ink)
}
}An svg piece (build with --target svg):
// rings: nested circles over a hatch, drawn once per token
plate(1920, 2400)
random layout
let paper = #f3efe6
let ink = #1b1b1f
background(paper)
for i in 0 ..< 40 {
let x = 100 + i * 43
line(x, 1900, x + 200, 2300)
}
stroke(ink, 1)
let centre = vec(layout.float(600 ..< 1320), layout.float(700 ..< 1500))
let rings = layout.int(6 ..< 14)
for k in 1 ..= rings {
circle(centre, k * 50)
}
stroke(ink, 3)An svg piece that uses libraries (build with --target svg):
// drift: brush sweeps along a noise flow, from one ramp
plate(1920, 2400)
use noise v1, colour v1, brush v1
random layout, marks
let inks = [#1d2b3a, #3e5c76, #9fb4c7, #ece6d8]
let field = noise.table(layout)
// a path along the flow from p, in steps of 12
fn follow(p: vec, steps: int): vec[] {
let path = vec[]
var q = p
for k in 0 ..< steps {
path.add(q)
q = q + polar(noise.octaves(field, q * 0.0008, count: 3) * TAU, 12)
}
return path
}
background(colour.lighten(inks[3], 0.5))
for i in 0 ..< 60 {
let path = follow(vec(layout.float(0 ..< 1920), layout.float(0 ..< 2400)), 40)
let v = layout.unit()
brush.sweep(marks, path, layout.float(40 ..< 100), [colour.at(inks, v - 0.2), colour.at(inks, v + 0.1)], body: 0.5)
}