Skip to content

Latest commit

 

History

History
833 lines (637 loc) · 46.1 KB

steps.mdx

File metadata and controls

833 lines (637 loc) · 46.1 KB
title Steps and forces
description A graph is two tables of rows, and a run folds passes over a value.

A graph is two tables of rows. The points table holds x, y and the columns you declare. The edges table holds rows that name two points. A point or an edge that you hold is the name of its row, in this state and in each later state. A lattice is one table of faces with fixed rows, and the stencil relates each face to the faces beside it.

A table takes three writes. You add a row, you remove a row, or you set a column. Every verb on this page is a few of these writes. A selection is the query that names the rows. A run folds passes over a value.

t.steps()

/_sig/Toolkit.steps.mdx

t.steps(n, start, ...passes, { every? }) runs the passes n times. A pass is a function (value) => value. The value can be a material, a lattice, a mesh or an object that holds several. The passes of one step run in order. Each pass reads what the pass before it returned. A pass has one argument. To count the steps, a pass writes a counter column.

With { every }, a material, a lattice or a mesh keeps its start, every every-th state and the last state on history. An object keeps no history. t.steps is on the toolkit because passes draw with t.pick, t.rnd and t.chance. Below, each step moves the ring out a little, and the sketch draws every second state from history.

import { sketch, circle, strokes } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const ring = t.sample(circle(50, 50, 30), { count: 60 });
  const grow = (g) => g.move((p) => [(p.x - 50) * 0.06, (p.y - 50) * 0.06 * (1 + 0.5 * Math.sin(p.index))]);
  const grown = t.steps(8, ring, grow, { every: 2 });
  return grown.history.map((h) => strokes(h));
});

The two tables

g.points and g.edges are selections of the whole tables. Each write on them returns a new material. The material you had does not change.

Write Points Edges
add a row g.points.add(xy, cols?), g.points.add([xy, …], cols?) g.edges.add([a, b], cols?), g.edges.add([[a, b], …], cols?), g.edges.add(e)
remove a row g.points.remove(sel): also the edges that name the points g.edges.remove(sel): the points stay
set a column g.points.set('h', value, where?, opts?), g.points.set({ h, k }, where?, opts?) g.edges.set('w', value, where?, opts?)

Faces are a third domain with one write, g.faces.set(…). A face comes from the edges, so you cannot add or remove a face. The faces page shows it.

set()

/_sig/points.set.mdx /_sig/edges.set.mdx

A value is a number, or a function of the row. The object form of set is one instant: every function reads the table as it was before the write. A chain of set calls is a sequence. A write to a column that is not declared declares it, with 0 on every other row. x and y are columns too.

where is a selection, one member, or a test of the row. It names the rows that the write changes. A set on a filtered selection writes only its own members.

The last argument can be an object of options. transfer tells what a column does at a new row. A point column is 'interpolate' (the default) or 'nearest'. 'interpolate' blends the two values, and 'nearest' copies the nearer one. An edge column is 'copy' (the default) or 'distribute'. 'copy' gives the value of a split edge to both halves, and 'distribute' shares it by length. A later write of a value keeps the policy of the column. Below, the points on the right get older in each step, and the rings grow with the age.

import { sketch, circle, strokes } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const ring = t.sample(circle(50, 50, 34), { count: 30 }).points.set('age', 0);
  const age = (g) => g.points.set('age', (p) => p.age + 1, (p) => p.x > 50);
  const aged = t.steps(5, ring, age);
  return [strokes(aged), aged.points.map((p) => circle(p, 0.5 + p.age * 0.5, { pen: 'stabilo-88-blue' }))];
});

add()

/_sig/points.add.mdx /_sig/edges.add.mdx

points.add adds one point or a list of points. A new point must give every declared column. edges.add adds one edge [a, b], an edge value, or a list of them. An end of an edge row is a point value or a vertex. A position is not an end, and the write stops with an error that tells you to use point(…). To add a point and an edge to it, make the point with point(xy, cols). Add the point, and then add the edge.

:::note Pairs in a write. m.edges.add(pairs) adds one edge for each pair. A pair that is an edge already adds nothing. A pair that comes two times adds one edge. Each pair names rows of the state as it was before the write. :::

Below, each tip of a tree grows one shoot in its heading. At every fifth depth, a tip grows two shoots. The pass adds the new tips as point values, and then it adds the stems that join them to their parents.

import { sketch, strokes, material, add, mul, fromAngle, point } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const seed = material([[50, 92]], { heading: -Math.PI / 2, depth: 0, tip: 1 });
  const grow = (g) => {
    const tips = g.points.filter((p) => p.tip === 1 && p.y > 10 && p.y < 96 && p.x > 10 && p.x < 90);
    const stems = tips.map((p) => {
      const turns = p.depth % 5 === 0 ? [p.heading - 0.5, p.heading + 0.5] : [p.heading + t.noise(p.x / 20, p.y / 20) * 0.4];
      return turns.map((h) => [p, point(add(p, mul(fromAngle(h), 3.2)), { heading: h, depth: p.depth + 1, tip: 1 })]);
    }).flat();
    return g.points.set('tip', 0, tips).points.add(stems.map(([, shoot]) => shoot)).edges.add(stems);
  };
  return strokes(t.steps(26, seed, grow));
});

remove()

/_sig/points.remove.mdx /_sig/edges.remove.mdx

points.remove deletes points and the edges that touch them. The neighbours of a removed point do not join. edges.remove deletes edges and keeps their points. Below, the ring loses its points in the upper left. A new hub joins four points of the ring: the top, the bottom, the left and the right. Each spoke is an edge value.

import { sketch, circle, strokes, point, edge } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const ring = t.sample(circle(50, 50, 34), { count: 36 });
  const hub = point([50, 50]);
  const spokes = ring.points.filter((p) => Math.abs(p.x - 50) < 1 || Math.abs(p.y - 50) < 1).map((p) => edge(p, hub));
  return strokes(ring.points.remove(ring.points.filter((p) => p.x < 40 && p.y < 40)).points.add(hub).edges.add(spokes));
});

Here a cloud of points joins each pair that is closer than 16. Each pair comes two times, one time from each end, and the write adds one edge. Then the web loses the edges on the left half of the sheet. The points stay.

import { sketch, circle, strokes } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const cloud = t.scatter({ spacing: 12 });
  const pairs = [...cloud.points].flatMap((a) => cloud.points.near(a, { radius: 16 }).map((b) => [a, b]));
  const joined = cloud.edges.add(pairs);
  const trimmed = joined.edges.remove(joined.edges.filter((e) => e.a.x < 50 && e.b.x < 50));
  return [strokes(trimmed), cloud.points.map((p) => circle(p, 0.8))];
});

What a write skips

A write skips data that cannot land. It does not throw, and it does not warn. It throws for a wrong program, for example a missing column on a new point or a reserved name.

The write skips When
everything it gets nothing: an empty selection, or undefined from an empty pick
a row a value or an end names no row in this state
an edge row the two ends name one point
a row the geometry has the value already, the pair is an edge already, or it comes two times in one write
one row a position or a value is not a finite number

A value is a name

/_sig/point.mdx /_sig/edge.mdx

point(xy, cols?) and edge(a, b, cols?) make a point and an edge that have a name from the start. A value that you hold, or a view from a state, names its row in each later state and in each write. A write skips a value that the geometry has already, and a reference to a value that the geometry does not have.

import { sketch, circle, strokes, add, polar, point } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 3 }, (t) => {
  const start = t.sample(circle([50, 50], 10), { count: 12 });
  const web = (g) => {
    const from = t.pick(g.points);
    if (!from) return g;
    const fresh = point(add(from, polar(5, t.rnd(2 * Math.PI))));
    return g.points.add(fresh).edges.add([fresh, g.points.near(fresh, { radius: 10 }).at(0)]);
  };
  return strokes(t.steps(500, start, web));
});

Queries

A selection answers filter, near, without, at, slice and map. at(-1) is the last member. without takes a selection or one member. t.pick(sel) gives one member, or undefined when the selection is empty. t.pick(sel, 5) gives five members as a selection, in the order of the selection. A share below one is a chance for each member: t.pick(sel, 0.1) keeps each member with a chance of 0.1. So a small selection can give some members or none. A choice for each member is a pick, then two verbs. The picked members go one way, and without gives the rest.

Recipes

A recipe is a few writes with one name. You can write the recipe, or you can write its writes.

Recipe The writes
g.extrude(p, offset, cols?) add a point at p plus offset, then add the edge from p to it
g.split(edges, at?) for each edge: add a point along it, remove the edge, add two edges
g.replace(edges, motif, opts?) for each edge: remove the edge, add the inner points of the motif, add the edges of the motif
g.replace(faces, motif) for each face: add the points of the motif, split the walls where its outline lands, add the edges inside the motif
g.move(...by, where?) set x and y in one instant

New rows go at the end of their table. A split and a replace are different. The first new edge takes the row of the edge that it replaces, and the other new edges go at the end. So each other edge keeps its row. The order of g.edges is then not the order that the writes give.

extrude()

/_sig/Material.extrude.mdx

extrude takes an offset, not a position. polar(r, angle) is an offset of length r at an angle in radians. In a curved sketch, an offset is a step along the geodesic. extrude of undefined gives back the material. To name the new point in a later write, write the two writes with a point value. Below, each step extrudes the last point. The heading turns a little at random, and the new point keeps its heading in a column. The chain wanders.

import { sketch, strokes, material, polar } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 1 }, (t) => {
  const walk = (g) => {
    const tip = g.points.at(-1);
    const heading = tip.heading + t.rnd(-0.9, 0.9);
    return g.extrude(tip, polar(1, heading), { heading });
  };
  return strokes(t.steps(300, material([[50, 50]], { heading: 0 }), walk));
});

split()

/_sig/Material.split.mdx

split puts the new point at at of the way from a to b, 0.5 when you give no at. at can be a function of the edge. An at outside 0 to 1 cuts nothing. A point column goes to the new point by its transfer policy. The new point and the two new edges answer the old edge as their source. In t.steps, a row that a step makes answers source for one step. The next pass can read it, and the state after that forgets it. The value that t.steps returns answers for its last step. The two edges share its columns by the edge policy. The edge from a takes the row of the old edge, and the edge to b goes at the end. Below, each step splits the edges that are longer than 12.

import { sketch, circle, strokes } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const ring = t.sample(circle(50, 50, 34), { count: 8 });
  const finer = t.steps(3, ring, (g) => g.split(g.edges.filter((e) => e.length > 12)));
  return [strokes(finer), finer.points.map((p) => circle(p, 1, { pen: 'stabilo-88-blue' }))];
});

replace()

/_sig/Material.replace.mdx

Swap every selected edge for a motif. The edge goes, and the motif's chain takes its place between the same two points. replace reads the motif in its own frame. That frame runs along the line from its first point to its last, and across it. One motif rides an edge of any length at any angle. Point columns cross by their transfer policy. Edge columns go to the pieces as a split's children get them. A motif point that lands on a point already there is that point, so two motifs that meet share a vertex.

An L-system is exactly this substitution, over and over. A Koch curve is one motif and four steps.

import { sketch, strokes, material, circle } from 'occlude';

export default sketch({ aspect: [1, 1], margin: 6 }, (t) => {
  const b = t.bounds();
  const h = Math.sqrt(3) / 6;
  const motif = material([[0, 0], [1 / 3, 0], [0.5, h], [2 / 3, 0], [1, 0]], { edges: [[0, 1], [1, 2], [2, 3], [3, 4]] });
  const seed = t.sample(circle(b.w / 2, b.h * 0.56, b.w * 0.42), { count: 3 });
  const flake = t.steps(4, seed, (g) => g.replace(g.edges, motif, { flip: true }));
  return strokes(flake.curves);
});

:::note A motif is ONE open chain, read from its edges and not from its row order. Nothing but the build order decides a material's rows. A motif with the right points in the wrong order would draw something else. flip mirrors it across the edge. flip is true, false or a test of the edge. The seed's winding decides the outward side. :::

Replace a face

g.replace(faces, motif) swaps each selected face for the faces of a motif. It is the same word as the edge form. It reads faces when you give it a face selection, one face or a list of faces. The face form has no options. There is no kind option: g.faces.filter((f) => f.kind === 'thin') selects the faces.

A motif is a material with faces. Its outline is the edge of all its faces together, and it must be one loop with no hole. To make a motif, give material its faces: material(points, { faces: [[0, 1, 2], …] }). Each face is a loop of point indices, and its first index is its first corner. The loop can go in either direction. Each side of a loop becomes an edge.

replace reads the motif in the frame of each face.

  • A face whose source is a placement, such as a cell of t.tiling, takes the motif through that placement. So draw the motif as the model face. On the flat sheet, the model face has its centre at [0, 0], one corner on +x and walls of the tiling's side. In a curved sketch, it is about the centre of the space.
  • Every other face takes the motif through a similarity. The similarity puts [0, 0] on the first corner of the face and [1, 0] on its second corner. So the unit face starts at [0, 0], its first wall goes along +x with a length of 1, and it goes counter-clockwise. A curved space has no unit length. There, a face without a placement stops the call with an error.

A corner is a point where the boundary of a face turns. In a curved sketch, replace reads the turn in the space. At a sample of a curved wall, the wall goes straight on. At a point that an earlier replace put on a wall, it also goes straight on. These points are not corners. The outline of the motif must have the same number of corners as the face. If not, the call stops with an error, for example "the motif's outline has 4 corners and this face has 3". The corners of the outline go on the corners of the face, the first on the first. A point on a side of the outline goes on the matching wall. Each other point of the motif goes where the frame puts it.

A wall stays the wall of the faces on its two sides. The points of the motif split it. A point that lands on a point that is there already is that point. So two neighbours that one call replaces share the new points on their wall. A neighbour that you keep keeps its face and its columns, and its loop goes through the new points. A piece of a wall keeps the columns of the wall. An edge column of an outline edge of the motif goes on each piece under that edge. An edge inside the motif is a new edge with the columns of the motif edge. In a curved sketch, that edge is a geodesic with samples.

The replaced face stays in g.faces as the parent of its new faces. It has no loop of its own, and its area is the area of its children. The new faces come after all the other faces. They are the faces of the motif in their order, for each replaced face in turn. The source of a new face is its parent, and depth counts the replaces. A face column goes from the parent to the children by its transfer policy. A face column of the motif, such as kind, goes to the new faces, and it replaces the value of the parent. replace changes only a leaf, so it skips a face that holds other faces. It also skips a face with a hole. It skips a tiling cell that the drawable edge cuts or that a gap makes smaller.

A rhomb of a Penrose tiling does not divide into rhombs, but each half of a rhomb divides into halves. These are Robinson's triangles. A thin half and a thick half each have a left hand and a right hand, so there are four motifs. The loop of each half starts at its apex, so the next pass reads the apex as the first corner. A pass replaces the leaves of each kind and hand with its motif. The pass takes its selection of leaves at the start, so the new faces wait for the next pass. The edge column base marks the side between the two halves of a rhomb. The drawing hatches the thin halves and draws each edge that is not a base one time.

import { sketch, strokes, polygon, fill, material, clip, rect, pen, mm } from 'occlude';

export default sketch({ aspect: [1, 1], pens: {
  wall: pen({ width: mm(0.25), color: '#23252B' }),
  thin: pen({ width: mm(0.2), color: '#2457D6' }),
} }, (t) => {
  const b = t.bounds();
  const phi = (1 + Math.sqrt(5)) / 2;
  const mix = (p, q, s) => [p[0] + (q[0] - p[0]) * s, p[1] + (q[1] - p[1]) * s];
  const turns = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
  // A half-rhomb: the apex a, the legs to b and c, the base from b to c.
  // Its loop starts at the apex, so the next pass reads the apex first.
  const half = (kind, a, b, c) => (turns(a, b, c) > 0 ? { kind, hand: 'left', loop: [a, b, c] } : { kind, hand: 'right', loop: [a, c, b] });
  // Halves as a material: shared points, a face each, `base` on each base.
  const build = (halves) => {
    const pts = [];
    const index = (p) => {
      const at = pts.findIndex((q) => Math.hypot(q[0] - p[0], q[1] - p[1]) < 1e-9);
      return at >= 0 ? at : pts.push(p) - 1;
    };
    const loops = halves.map((h) => h.loop.map(index));
    const bases = new Set(loops.map((l) => [l[1], l[2]].sort().join()));
    return material(pts, { faces: loops })
      .faces.set({ kind: (f) => halves[f.index].kind, hand: (f) => halves[f.index].hand })
      .edges.set('base', (e) => (bases.has([e.a.index, e.b.index].sort().join()) ? 1 : 0));
  };
  // Robinson's cut of each half, in the unit frame: apex at [0, 0], the
  // next corner on the left at [1, 0].
  const cut = (kind, hand) => {
    const turn = kind === 'thin' ? Math.PI / 5 : (3 * Math.PI) / 5;
    const far = [Math.cos(turn), Math.sin(turn)];
    const [A, B, C] = hand === 'left' ? [[0, 0], [1, 0], far] : [[0, 0], far, [1, 0]];
    if (kind === 'thin') {
      const P = mix(A, B, 1 / phi);
      return build([half('thin', C, P, B), half('thick', P, C, A)]);
    }
    const Q = mix(B, A, 1 / phi);
    const R = mix(B, C, 1 / phi);
    return build([half('thick', R, C, A), half('thick', Q, R, B), half('thin', R, Q, A)]);
  };
  const motifs = ['thin', 'thick'].flatMap((kind) => ['left', 'right'].map((hand) => ({ kind, hand, motif: cut(kind, hand) })));
  // The start: a sun of ten thin halves, every second one turned over.
  const c = [b.w / 2, b.h / 2];
  const at = (k) => mix(c, [c[0] + Math.cos((k * Math.PI) / 10), c[1] + Math.sin((k * Math.PI) / 10)], b.w * 0.76);
  const sun = build(Array.from({ length: 10 }, (_, i) => (i % 2 ? half('thin', c, at(2 * i - 1), at(2 * i + 1)) : half('thin', c, at(2 * i + 1), at(2 * i - 1)))));
  // One pass: each kind and hand of the leaves it starts with, for its cut.
  const inflate = (g) => {
    const leaves = g.faces.filter((f) => f.leaf);
    return motifs.reduce((h, { kind, hand, motif }) => h.replace(leaves.filter((f) => f.kind === kind && f.hand === hand), motif), g);
  };
  const tiles = t.steps(5, sun, inflate);
  return clip(rect(0, 0, b.w, b.h), [
    // The thin rhombs hatched: the fills go down first.
    tiles.faces.filter((f) => f.leaf && f.kind === 'thin').map((f) => polygon(f, { fill: fill('hatch', { angle: 60, spacing: mm(0.7) }), fillPen: 'thin', stroke: false })),
    // Every rhomb wall once: the edges that are not a base.
    strokes(tiles.edges.filter((e) => !e.base), { pen: 'wall' }),
  ]);
});

Below, the first step cuts one triangle in four. The next two steps cut each corner triangle again, and a middle triangle stays a leaf at its depth. The middle triangles of each depth have their own pen, so you can see how the faces hold each other.

import { sketch, strokes, polygon, fill, material, pen, mm } from 'occlude';

export default sketch({ aspect: [1, 1], pens: {
  wall: pen({ width: mm(0.25), color: '#23252B' }),
  one: pen({ width: mm(0.2), color: '#2457D6' }),
  two: pen({ width: mm(0.2), color: '#B4552B' }),
  three: pen({ width: mm(0.2), color: '#2E8B57' }),
} }, (t) => {
  const b = t.bounds();
  const h = Math.sqrt(3) / 2;
  // The unit triangle cut in four: three corners and the middle.
  const motif = material([[0, 0], [1, 0], [0.5, h], [0.5, 0], [0.75, h / 2], [0.25, h / 2]], {
    faces: [[0, 3, 5], [3, 1, 4], [5, 4, 2], [3, 4, 5]],
  }).faces.set('kind', (f) => (f.index === 3 ? 'middle' : 'corner'));
  const w = b.w * 0.94;
  const x = (b.w - w) / 2;
  const y = (b.h + w * h) / 2;
  const start = material([[x, y], [x + w, y], [x + w / 2, y - w * h]], { faces: [[0, 1, 2]] });
  // Each step cuts every corner triangle again. A middle stays as it is.
  const deep = t.steps(3, start, (g) => g.replace(g.faces.filter((f) => f.leaf && f.kind !== 'middle'), motif));
  const pens = ['one', 'two', 'three'];
  return [
    // The middle of each depth in its own pen. The fills go down first.
    deep.faces.filter((f) => f.kind === 'middle').map((f) => polygon(f, {
      fill: fill('hatch', { angle: 20 + 50 * f.depth, spacing: mm(1.5 - 0.35 * f.depth) }),
      fillPen: pens[f.depth - 1],
      stroke: false,
    })),
    // Every wall once.
    strokes(deep, { pen: 'wall' }),
  ];
});

move()

/_sig/Material.move.mdx

move adds the sum of its displacements to each point. A displacement is a vector, a function of the point, or a force. Every displacement reads the graph as it was before the move. A last argument that is a selection, a point value or a vertex names the points that move. A move is a step in the space of the material. So in a curved sketch, the point walks the sum of its moves along a geodesic.

import { sketch, circle, strokes } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const ring = t.sample(circle(50, 50, 32), { count: 48 });
  const wavy = ring.move((p) => [0, Math.sin(p.x / 4) * 8]);
  return [strokes(ring, { pen: 'pigma-005-black' }), strokes(wavy, { pen: 'stabilo-88-blue' })];
});

Forces

/_sig/force.tension.mdx /_sig/force.separation.mdx /_sig/force.drift.mdx /_sig/force.boundary.mdx /_sig/force.vortex.mdx /_sig/force.field.mdx /_sig/force.relax.mdx

A force gives a vector at a point. Nothing moves until a pass gives the force to move. tension pulls toward connected neighbours that are further than rest. separation pushes away from every source within radius, and a negative amount turns it round, so it pulls toward the sources. drift reads a direction from a noise function. It turns slowly from one step of the run to the next. The noise of the toolkit knows its run, so drift reads the step that t.steps makes. This is true whatever holds the values of the run. boundary pushes inward near the edge of an area and everywhere outside it. vortex turns around a centre. field reads a vector field. relax moves a vertex toward the mean of its neighbours. A vertex with fewer than two neighbours does not move, so the end of a chain stays where it is. boundary reads the area's contours(). separation reads the sources' points.

Forces as values

force.tension({ rest, amount? }), force.separation({ radius, excludeConnected?, amount? }) and force.relax({ amount }) are forces with no state. g.move prepares each from g one time and adds them. A force with no state gives a calm step, and you do not tune it. tension and separation move a point by half the mean of the pulls on it. Two points that are too near go apart to radius in one step, and a stretched edge goes back to rest. A point in a crowd moves no more than half the radius. The number of points that push it does not change this. amount scales the step, and it is a number or a function of the point. relax moves a point amount of the way to the mean of its neighbours. force.drift, force.boundary, force.vortex and force.field are functions of the point already, so move reads them as they are.

The forms that take a state first, as in force.tension(g, { rest }), prepare the force from that state. They give the sum of the pulls as a function of the point, and you scale it yourself. The forms that take sources take amount too. Here is one force alone. Five lumps on a ring push the ring out. The black ring is the start. The blue ring is the same ring after ten steps under separation.

import { sketch, circle, strokes, force, mul } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const ring = t.sample(circle(50, 50, 20), { count: 40 }).points.set('lump', (p) => (Math.sin(p.u * 10 * Math.PI) > 0.5 ? 1 : 0));
  const spread = t.steps(10, ring, (g) => {
    const apart = force.separation(g.points.filter((p) => p.lump === 1), { radius: 14 });
    return g.move((p) => mul(apart(p), 0.35));
  });
  return [strokes(ring, { pen: 'pigma-005-black' }), strokes(spread, { pen: 'stabilo-88-blue' })];
});

separation also takes a radius for each vertex: { radius: (p) => p.r } gives every point its own. The radius of a pair is then the sum of the two. That sum is the distance two discs need to stay clear of each other. The push peaks at that sum and fades to zero there. One grid still serves. It takes its cell from the widest radius among the sources, and each query reaches as far as its own point asks. Here the discs come from a noise field, and the run ends with none of them over another.

import { sketch, circle, rect, force, mul } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 4 }, (t) => {
  const b = t.bounds();
  const page = t.material(rect(8, 8, b.w - 16, b.h - 16));
  const seeds = t.scatter({ spacing: 7.5 }).points.set('r', (p) => 1.5 + 6.5 * t.noise(p.x / 40, p.y / 40) ** 2);
  const packed = t.steps(220, seeds, (g) => {
    const push = force.sum(
      force.separation(g, { radius: (p) => p.r }),
      force.boundary(page, { radius: 9 }),
    );
    return g.move((p) => mul(push(p), 0.25));
  });
  return packed.points.map((p) => circle(p, p.r, { pen: p.r > 4.5 ? 'stabilo-88-blue' : 'pigma-005-black' }));
});

Eight words, and a pass usually sums a few of them. Here a ring grows: tension holds the chain together, separation keeps it off itself, relax smooths it, and drift wanders it. A second pass ages every edge by one step. It splits an edge that has stretched too far, and it first sets the age of that edge to 0. A split copies an edge column to both children. Each piece of wall keeps the age of the step that last divided it. The drawing then finds the youngest growth.

import { sketch, strokes, circle, force, mul } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 6 }, (t) => {
  const wander = force.drift(t.noise, { amount: 0.24, frequency: 0.05 });
  const settle = (g) => {
    const push = force.sum(
      force.tension(g, { rest: 1.6 }),
      force.separation(g, { radius: 4, excludeConnected: true }),
      force.relax(g, { amount: 0.4 }),
      wander,
    );
    return g.move((p) => mul(push(p), 0.15));
  };
  const divide = (g) => {
    const stretched = g.edges.filter((e) => e.length > 1.8 && t.chance(0.3));
    return g.edges.set('age', (e) => e.age + 1).edges.set('age', 0, stretched).split(stretched);
  };
  const grown = t.steps(150, t.sample(circle(50, 50, 8), { count: 24 }).edges.set('age', 0), settle, divide);
  return [
    strokes(grown.edges.filter((e) => e.age >= 15), { pen: 'pigma-005-black' }),
    strokes(grown.edges.filter((e) => e.age < 15), { pen: 'stabilo-88-blue' }),
  ];
});

The other three forces pull toward something. A separation with a negative amount pulls toward its sources. An amount of -1 / radius pulls with a strength of 1 when touching, and fades to zero at the radius. vortex turns around a centre. field reads a vector field. This field is the curl of a noise. A curl runs along the contours of the noise, and not across them. force.sum adds all three forces. { every: 1 } keeps every state, so the sketch draws each dot's full path from history. A seed point that you hold names its row in each state of the history. The drawing stops at the edge of the drawable.

import { sketch, stroke, circle, clip, rect, material, force, curl, mul } from 'occlude';

export default sketch({ aspect: [2, 1], seed: 3 }, (t) => {
  const b = t.bounds();
  const posts = [[0.28 * b.w, 0.7 * b.h], [0.74 * b.w, 0.3 * b.h]];
  const push = force.sum(
    force.separation(posts, { radius: 0.3 * b.w, amount: -1 / (0.3 * b.w) }),
    force.vortex([0.5 * b.w, 0.5 * b.h], { strength: 1, falloff: 0.2 * b.w }),
    force.field(curl((x, y) => t.noise(x / 50, y / 50) * 8)),
  );
  const seeds = material(t.grid({ cols: 34, rows: 17 }).faces.map((f) => f.centroid));
  const flown = t.steps(80, seeds, (g) => g.move((p) => mul(push(p), 0.3)), { every: 1 });
  const trail = (p) => flown.history.map((h) => { const q = h.points.rows(p).at(0); return [q.x, q.y]; });
  return clip(rect(0, 0, b.w, b.h), [
    seeds.points.map((p) => stroke(trail(p))),
    posts.map((p) => circle(p, 3, { pen: 'stabilo-88-blue' })),
  ]);
});

t.force

The toolkit carries the same forces as t.force. t.force.boundary also takes a shape, because the toolkit can change a shape into an area. The pure force.boundary(rect(…)) refuses a shape, and its message names t.force.boundary. t.force.separation takes points, so it refuses a shape: make the points with t.material(shape) or t.sample(shape, { count }). In a sketch with a space, the t.force words measure in that space. Below, dots start over all of the page, and t.force.boundary pushes them into a square frame.

import { sketch, circle, rect, mul } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 3 }, (t) => {
  const frame = rect(25, 25, 50, 50);
  const held = t.steps(40, t.scatter({ spacing: 7 }), (g) => {
    const push = t.force.sum(t.force.boundary(frame, { radius: 4 }), t.force.separation(g, { radius: 4 }));
    return g.move((p) => mul(push(p), 0.3));
  });
  return [rect(25, 25, 50, 50, { pen: 'stabilo-88-blue' }), held.points.map((p) => circle(p, 0.8))];
});

force.sum()

/_sig/force.sum.mdx

Adds forces. The same pass with separation alone, with boundary alone, and with their sum, in three pens.

import { sketch, circle, strokes, force, mul } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const box = [[10, 10], [90, 10], [90, 90], [10, 90]];
  const run = (make, pen) => strokes(t.steps(14, t.sample(circle(50, 50, 34), { count: 40 }), (g) => g.move((p) => mul(make(g)(p), 0.5))), { pen });
  return [
    run((g) => force.separation(g, { radius: 9, excludeConnected: true }), 'pigma-005-black'),
    run((g) => force.boundary(box, { radius: 30 }), 'stabilo-88-blue'),
    run((g) => force.sum(force.separation(g, { radius: 9, excludeConnected: true }), force.boundary(box, { radius: 30 })), 'stabilo-88-green'),
    strokes(t.material(circle(50, 50, 34)), { pen: 'pigma-005-black' }),
  ];
});

Your own interaction

A force of your own is a function, not a word of the library. Sum what you want over the points within a radius. g.points.near(p, { radius }) gives those points, from an index built once for the state, and a vertex is never its own neighbour. sumBy adds the vectors up. To skip the points at the other end of p's edges, take them out: .without(p.adjacent).

import { sketch, circle, force, sub, unit, mul, sumBy, distance } from 'occlude';

export default sketch({ aspect: [1, 1] }, (t) => {
  const cloud = t.scatter({ spacing: 9 });
  const keep = force.boundary([[6, 6], [94, 6], [94, 94], [6, 94]], { radius: 12, strength: 3 });
  const spread = t.steps(12, cloud, (g) => {
    const repel = (p) => sumBy(g.points.near(p, { radius: 14 }), (q) => mul(unit(sub(p, q)), 14 - distance(p, q)));
    return g.move((p) => mul(force.sum(repel, keep)(p), 0.05));
  });
  return [cloud.points.map((p) => circle(p, 0.6)), spread.points.map((p) => circle(p, 1.4, { pen: 'stabilo-88-blue' }))];
});

The lattice as one table

/_sig/l.faces.set.mdx

l.faces is a selection of the faces, in row-major order, and l.faces.set(...) is the write of the lattice. A face of a lattice answers these words of every face: index, area, perimeter, centroid (its centre), bounds, contours() and adjacent. Its adjacent holds up to four faces: the faces beside it that are in the lattice. A lattice does not nest, so each face is a root and a leaf. Its parent and source are undefined and its children is empty. Its depth is 0 and its leaf is true. A lattice has no edge table and no point table, so edges, boundaryEdges, points, corners, normal and extract() refuse by name. A face also answers i, j, every column by name and c.laplacian(column). l.face(p) is the face under a position or a point. The where of a lattice write can also be points, and then it names the faces under them. A face off the lattice reads 0, and no write gets to it. A lattice cannot add or remove a face, so l.faces.add and l.faces.remove refuse by name. l.field(column) gives a column back as a field.

Every function of one set reads the faces as they were before the write. So a pass over the whole grid is one instant. A diffusion is one set: l.faces.set('a', (c) => c.a + rate * c.laplacian('a')). A decay is one more: l.faces.set('a', (c) => c.a * (1 - rate)). A rate above 0.25 runs away. Inside a lattice callback, f is valid only during the call. To keep it, hold f.index or l.faces.at(i).

1. Ring growth, and the slipped copy

A ring grows sprouts from its rim and joins two points in each step. The copy on the right sometimes joins to the first point, so it gathers toward one place.

import { sketch, circle, strokes, polar, distance } from 'occlude';

export default sketch({ aspect: [2, 1], seed: 11 }, (t) => {
  const { pick, rnd, chance } = t;
  const center = [50, 50];
  const ring = t.sample(circle(center, 12), { count: 60 });
  const first = ring.points.at(0);
  const rim = (g) => g.points.filter((p) => distance(p, center) > 10);

  const sprout = (g) => g.extrude(pick(rim(g)), polar(2, rnd(2 * Math.PI)));
  const join = (g) => g.edges.add([pick(g.points), pick(g.points)]);
  const joinToFirst = (g) => g.edges.add([pick(g.points), chance(0.05) ? first : pick(g.points)]);

  const grown = t.steps(400, ring, sprout, join);
  const slipped = t.steps(400, ring, sprout, joinToFirst);
  return [strokes(grown), strokes(slipped.translate([100, 0]), { pen: 'stabilo-88-blue' })];
});

2. Growth under forces, and a flaw that heals

Forces settle a ring, and each long edge splits. On the right, a few long edges break in place of a split.

import { sketch, circle, strokes, force } from 'occlude';

export default sketch({ aspect: [2, 1], seed: 6 }, (t) => {
  const { pick } = t;
  const seed = t.sample(circle([50, 50], 8), { count: 24 });

  const settle = (g) => g.move(
    force.tension({ rest: 1.6 }),
    force.separation({ radius: 4, excludeConnected: true }),
    force.relax({ amount: 0.4 }),
    force.drift(t.noise, { amount: 0.24, frequency: 0.05 }),
  );
  const stretched = (g) => g.edges.filter((e) => e.length > 1.8);
  const cut = (g) => g.split(stretched(g));
  const cutOrBreak = (g) => {
    const s = stretched(g), broken = pick(s, 1 / 50);
    return g.edges.remove(broken).split(s.without(broken));
  };

  const clean = t.steps(95, seed, settle, cut);
  const flawed = t.steps(95, seed, settle, cutOrBreak);
  return [strokes(clean), strokes(flawed.translate([100, 0]), { pen: 'stabilo-88-blue' })];
});

3. Order to chaos on one sheet

A mesh of triangles pushes itself apart and loses points. The push and the loss grow from left to right.

import { sketch, strokes, connect, force } from 'occlude';

export default sketch({ aspect: [3, 2], seed: 5 }, (t) => {
  const { chance } = t;
  const b = t.bounds();
  const chaos = (p) => ((p.x - b.x) / b.w) ** 2;
  const grid = connect.triangulate(t.grid({ cols: 45, rows: 30 }).faces.map((f) => f.centroid));

  const settle = (g) => g.move(force.separation({ radius: 5, amount: (p) => 0.3 * chaos(p) }));
  const erode = (g) => g.points.remove(g.points.filter((p) => chance(0.02 * chaos(p))));

  return strokes(t.steps(40, grid, settle, erode));
});

4. Rain, and faster rain

Drops of ink fall on random cells, spread and fade. The right half spreads faster.

import { sketch, strokes, rect } from 'occlude';

export default sketch({ aspect: [2, 1], seed: 5 }, (t) => {
  const { pick } = t;
  const b = t.bounds();
  const sky = t.lattice({ spacing: 1, area: rect(b.x, b.y, b.w / 2, b.h) }).faces.set('ink', 0);

  const rain = (rate) => (l) => l
    .faces.set('ink', (c) => c.ink + 40, pick(l.faces))
    .faces.set('ink', (c) => c.ink + rate * c.laplacian('ink'))
    .faces.set('ink', (c) => c.ink * 0.99);

  const slow = t.steps(90, sky, rain(0.1));
  const fast = t.steps(90, sky, rain(0.22));
  const levels = [0.02, 0.04, 0.08, 0.16, 0.32, 0.64];
  return [
    strokes(t.isolines(slow.field('ink'), levels)),
    strokes(t.isolines(fast.field('ink'), levels).translate([b.w / 2, 0]), { pen: 'stabilo-88-blue' }),
  ];
});

5. A wave on a pond

Three stones fall into a pond. Each step pushes the speed by the Laplacian of the height, and then the height by the speed.

import { sketch, strokes } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 2 }, (t) => {
  const pond = t.lattice({ spacing: 1 }).faces.set({ h: 0, v: 0 }).faces.set('h', 5, t.throw({ count: 3 }));

  const push = (l) => l.faces.set('v', (c) => c.v + 0.2 * c.laplacian('h'));
  const flow = (l) => l.faces.set('h', (c) => c.h + c.v);

  return strokes(t.isolines(t.steps(120, pond, push, flow).field('h'), { count: 8 }));
});

6. Lines, walkers, and a web

Five lines cross. Walkers leave from the crossings and from every point. The black web joins each point to the neighbours that nothing stands between.

import { sketch, strokes, connect, polar } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 7 }, (t) => {
  const { pick, rnd, chance } = t;
  const lines = connect.pairs(t.throw({ count: 5 }), t.throw({ count: 5 })).planarize().resample({ spacing: 2 });
  const crossings = lines.points.filter((p) => p.edges.length === 4);

  const wander = (g) => g.extrude(chance(0.3) ? pick(crossings) : pick(g.points), polar(1.5, rnd(2 * Math.PI)));

  const walked = t.steps(3000, lines, wander);
  return [strokes(walked, { pen: 'stabilo-88-blue' }), strokes(connect.unimpeded(walked.points, { room: 2 }))];
});

7. A verb of your own: each new point joins two points near it

A pass is a function, so a verb of your own is a pass. Each new point joins two points near it.

import { sketch, circle, strokes, add, polar, point } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 3 }, (t) => {
  const { pick, rnd } = t;
  const start = t.sample(circle([50, 50], 10), { count: 12 });

  const web = (g) => {
    const from = pick(g.points);
    if (!from) return g;
    const q = point(add(from, polar(5, rnd(2 * Math.PI))));
    return g.points.add(q).edges.add(g.points.near(q, { radius: 10 }).slice(0, 2).map((p) => [q, p]));
  };

  return strokes(t.steps(500, start, web));
});

8. A tree that branches from its tips

Each step grows one tip on in its heading. Sometimes a branch leaves the point behind a tip.

import { sketch, strokes, material, polar, angleTo } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 4 }, (t) => {
  const { pick, rnd, chance } = t;
  const trunk = material([[50, 95], [50, 85]], { edges: [[0, 1]] });
  const tips = (g) => g.points.filter((p) => p.edges.length === 1 && p.y < 90);
  const heading = (v) => angleTo(v.adjacent.at(0), v);

  const grow = (g) => { const v = pick(tips(g)); return g.extrude(v, polar(2, heading(v) + rnd(-0.4, 0.4))); };
  const fork = (g) => { const v = pick(tips(g)); return chance(0.15) ? g.extrude(v.adjacent.at(0), polar(2, heading(v) + (chance(0.5) ? 0.7 : -0.7))) : g; };

  return strokes(t.steps(600, trunk, grow, fork));
});

9. Age on a column, and pruning by it

Every point gets older in each step, and old tips fall off. The edges with a young end are blue.

import { sketch, strokes, circle, polar } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 9 }, (t) => {
  const { pick, rnd } = t;
  const ring = t.sample(circle([50, 50], 12), { count: 20 }).points.set('age', 0);

  const age = (g) => g.points.set('age', (p) => p.age + 1);
  const sprout = (g) => g.extrude(pick(g.points), polar(5, rnd(2 * Math.PI)), { age: 0 });
  const prune = (g) => g.points.remove(g.points.filter((p) => p.age > 40 && p.edges.length === 1));

  const alive = t.steps(300, ring, age, sprout, prune);
  const young = alive.edges.filter((e) => e.a.age < 20 || e.b.age < 20);
  return [strokes(alive.edges.without(young)), strokes(young, { pen: 'stabilo-88-blue' })];
});

10. Space colonisation: growth pulled by attractors

Each step, one point grows toward the food near it. The blue dots are the food that no branch got to.

import { sketch, strokes, dots, circle, material, add, sub, unit, mul } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 12 }, (t) => {
  const { pick } = t;
  const food = t.throw(circle([50, 45], 35), { count: 400 });
  const root = material([[50, 92]]);

  const reach = (g) => {
    const v = pick(g.points);
    const pull = food.points.near(v, { radius: 12 }).map((f) => unit(sub(f, v))).reduce(add, [0, 0]);
    return g.extrude(v, mul(unit(pull), 2));
  };

  const grown = t.steps(1500, root, reach);
  return [strokes(grown), dots(food.points.filter((f) => grown.points.near(f, { radius: 2 }).length === 0), { pen: 'stabilo-88-blue' })];
});

11. Gray-Scott on the lattice, as the equations

The two columns a and b react and diffuse. One set with an object is one instant, so b reads the old a.

import { sketch, strokes } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 1 }, (t) => {
  const dish = t.lattice({ spacing: 0.5 })
    .faces.set({ a: 1, b: 0 })
    .faces.set('b', 1, (c) => Math.abs(c.centroid[0] - 50) < 4 && Math.abs(c.centroid[1] - 50) < 4);

  const react = (l) => l.faces.set({
    a: (c) => c.a + 0.2 * c.laplacian('a') - c.a * c.b * c.b + 0.055 * (1 - c.a),
    b: (c) => c.b + 0.1 * c.laplacian('b') + c.a * c.b * c.b - 0.117 * c.b,
  });

  return strokes(t.isolines(t.steps(4000, dish, react).field('b'), [0.15, 0.25]));
});

12. Graph and lattice together

The value of the run is an object that holds a graph and a lattice. The graph grows only where the ink is thin, and each new point puts ink down.

import { sketch, strokes, circle, add, polar, point } from 'occlude';

export default sketch({ aspect: [1, 1], seed: 8 }, (t) => {
  const { pick, rnd } = t;
  const start = { web: t.sample(circle([50, 50], 5), { count: 12 }), ink: t.lattice({ spacing: 1 }).faces.set('v', 0) };

  const grow = ({ web, ink }) => {
    const from = pick(web.points.filter((p) => ink.face(p).v < 0.3));
    const fresh = point(add(from, polar(2, rnd(2 * Math.PI))));
    return {
      web: web.points.add(fresh).edges.add([from, fresh]),
      ink: ink.faces.set('v', (c) => c.v + 1, ink.face(fresh)).faces.set('v', (c) => c.v + 0.1 * c.laplacian('v')),
    };
  };

  const { web } = t.steps(800, start, grow);
  return strokes(web);
});

13. Three flaws of one growth on one sheet

One growth and three flaws. The second sometimes splits a tenth of all edges. The third joins a few long edges to random points. The fourth sometimes kicks a point away.

import { sketch, strokes, circle, polar, force } from 'occlude';

export default sketch({ aspect: [3, 1], seed: 6 }, (t) => {
  const { pick, rnd, chance } = t;
  const seed = t.sample(circle([0, 0], 6), { count: 20 });
  const settle = (g) => g.move(force.tension({ rest: 1.5 }), force.separation({ radius: 3.5 }), force.relax({ amount: 0.3 }));
  const stretched = (g) => g.edges.filter((e) => e.length > 1.7);

  const cut = (g) => g.split(stretched(g));
  const cutTenth = (g) => g.split(chance(1 / 40) ? pick(g.edges, 0.1) : stretched(g));
  const cutOrJoin = (g) => {
    const s = stretched(g), j = pick(s, 1 / 40);
    return g.split(s.without(j)).edges.add(j.map((e) => [e.a, pick(g.points)]));
  };
  const cutAndWander = (g) => g.split(stretched(g)).move((p) => (chance(0.01) ? polar(1, rnd(2 * Math.PI)) : [0, 0]));

  const runs = [cut, cutTenth, cutOrJoin, cutAndWander].map((flaw) => t.steps(160, seed, settle, flaw));
  return runs.map((r, i) => strokes(r.translate([37.5 + i * 75, 50])));
});