Chapter 11
Text, drawings, pictures, data
A model can read files that lie next to it: measurements from a table, a description as JSON, a font for a name tag, a drawing as SVG, a photo as PNG. Change the file, and the model is computed again, just as with a slider.
knotflow guesses nothing in the process. Which encoding a text file has, which separator a CSV file, which unit a drawing is measured in: you say so. If the file does not fit, there is an error with a hint instead of a model that is quietly wrong.
Where the files are
- The path is relative to the model and stays inside
the project:
"tiles.json"or"data/tiles.json", with forward slashes/, without..and without an absolute path. - The path must be written out:
read("tiles.json", …), notread(name, …). That way it is known which files a model needs before it runs. - Only the model itself reads files, no library. A library gets the data as an argument.
- On the command line (
kf render), in the language server and inkf mcpthe files simply lie next to the.kffile. - In the browser you open the folder under
Project → Open folder …. The browser reads exactly the
files the model names in
read("…")andread_bytes("…"). If another program changes one of them, it computes again within a second. The examples bring their files with them. - The file bar lists the files read under Data. Text files in UTF-8 can be edited there: for an example the change stays in the browser, for a folder it is written to the file. Other files (fonts, pictures, text in other encodings) are shown only with their size.
Reading text:
read and the encoding
read(path, encoding: …) gives the content of a text file
exactly as it is, line endings included. The encoding
says how the file's bytes become letters. For plain ASCII it does not
matter, for accented letters it does:
encoding: |
when |
|---|---|
"utf-8" |
the usual case today: editors, JSON, most programs |
"utf-8-bom" |
UTF-8 with a mark (BOM) at the start, as some Windows programs write it |
"windows-1252" |
CSV files from spreadsheets on Windows in Western Europe |
"latin-1" |
older files (ISO 8859-1) |
"utf-16le", "utf-16be" |
rare; some exports on Windows |
If a byte does not fit the encoding, that is an error, and the message usually suggests the right one: "read: byte 34 (line 4, column 2) is not UTF-8 – is the file in another encoding, "latin-1" perhaps?"
A simple list of numbers, one per line:
let values = [number(l) | l <- lines(read("heights.txt", encoding: "utf-8"), ending: "lf")]
export [cylinder((12 * i, 0, 0), (12 * i, 0, h), 5) | (i, h) <- enumerate(values)]
lines(text, ending:) cuts a text into lines. You say
what the line ending is: "lf" (Linux, macOS),
"crlf" (Windows), "cr" or "any".
number turns a text into a number;
number("3,5", decimal: ",") understands a decimal comma.
More helpers for text: split, trim,
join.
CSV: a list of records
A file rain.csv, saved the way a German spreadsheet on
Windows does it (semicolon, decimal comma, Windows line endings,
encoding Windows-1252):
Monat;Regen
Jan;48,5
Feb;41,2
Mär;45,0
Apr;50,3
The model for it, a bar chart:
param scale = 1 in 0.2..3 "height per mm of rain [mm]"
let rows = csv(read("rain.csv", encoding: "windows-1252"), separator: ";", decimal: ",",
header: true, ending: "crlf", columns: {Monat: "text", Regen: "number"})
fn bar(i, row) = box(8, 8, row.Regen * scale) |> move(x: 10 * i, z: row.Regen * scale / 2)
export [bar(i, row) | (i, row) <- enumerate(rows)]
csv(…)gives a list of records, one per row:{Monat: "Jan", Regen: 48.5}.columns:names the columns in the file's order, each as"number","text"or"bool". Withheader: truethe first line must have exactly these names; otherwise the message says what is there: "the header is "Monat", "Regen", the columns given are …".- A field is read with
row.Regen. If a column's name cannot be a name (with spaces or a hyphen), write it as a text:{"Rain [mm]": "number"}androw["Rain [mm]"].
Pitfall: if you open the file in an editor and save
it as UTF-8, change encoding: too. The error message tells
you at once, and the same for wrong line endings.
JSON: nested descriptions
JSON suits anything with more structure than a table.
shelf.json:
{
"depth": 30,
"boxes": [
{"name": "screws", "width": 40, "height": 25},
{"name": "nuts", "width": 30, "height": 20, "lid": true},
{"name": "springs", "width": 50, "height": null}
]
}
let data = json(read("shelf.json", encoding: "utf-8"), null: 15)
let depth = data.depth
let boxes = data.boxes
// where each box starts: the widths of those before it, 2 mm apart
fn start(i) = sum([b.width + 2 | b <- take(boxes, i)])
fn tray(b) = shell(extrude(rectangle(b.width, depth), b.height), 1.2, open: [(0, 0, 1)])
fn lid(b) = if get(b, "lid", false) then [box(b.width, depth, 1.2) |> move(z: b.height + 5)] else []
export [tray(b) |> move(x: start(i) + b.width / 2) | (i, b) <- enumerate(boxes)]
export flatten([lid(b) |> move(x: start(i) + b.width / 2) | (i, b) <- enumerate(boxes)]) color "ochre"
- JSON objects become records, arrays lists.
nullis an error unlessnull:says what it stands for. Here the springs box becomes 15 mm high. Withnull: falseyou can check for it yourself later.get(b, "lid", false)reads a field not every box has, with a value to use instead.has(b, "lid")only asks whether it is there;keys(r)gives all field names.- Fields with a hyphen:
data["tile-size"].
Tables with axes
Values that depend on two things (height per row and column, radius
per ring and angle) are looked up in a table.
heights.csv:
row,col,h
0,0,4
0,1,6
0,2,9
1,0,3
1,2,12
2,0,2
2,1,5
2,2,7
let rows = csv(read("heights.csv", encoding: "utf-8"), separator: ",", decimal: ".",
header: true, ending: "lf", columns: {row: "number", col: "number", h: "number"})
let t = table(rows, axes: ["row", "col"], value: "h", missing: 1)
let corner = t.cell({row: 0, col: 2})
let first = entries(t.slice({row: 0}))
fn block(r, c) = box(10, 10, h) |> move(x: 10 * c, y: -10 * r, z: h / 2)
where h = t.cell({row: r, col: c})
export [block(r, c) | r <- axis(t, "row"), c <- axis(t, "col")]
table(rows, axes:, value:)builds the table: the axes are columns of the rows,valuethe column with the value.celltakes a place on every axis and gives the value (corneris 9).slicefixes some axes and gives a smaller table along the others.axis(t, "col")gives the values on one axis (numbers sorted, texts in the order they first appear);entriesturns the table back into rows.- A combination that appears twice is an error. So is a missing one
(here row 1, column 1), unless
missing:says what stands there.
Fonts: names and lettering
Fonts are not texts but bytes: read_bytes reads them.
Any TrueType or OpenType font (.ttf, .otf)
works; the examples come with DejaVu Sans Bold
(examples/fonts/, with its licence).
let font = read_bytes("fonts/DejaVuSans-Bold.ttf")
let name = "Lina"
param size = 14 in 6..30 "font size [mm]"
param depth = 1 in 0.4..3 "depth of the engraving [mm]"
let reach = bounds([g.outline | g <- lettering(name, font: font, size: size)])
let w = reach.max.x - reach.min.x + 10
let h = reach.max.y - reach.min.y + 10
let mid = (reach.min + reach.max) / 2
let plate = rounded_rectangle(w, h, 3) |> translate(mid) |> extrude(4)
let cut = letters(name, font, size, depth + 1) |> move(z: 4 - depth)
export difference(plate, cut)
letters(text, font, size, height)gives the text as one solid standing on z = 0,heighthigh.sizeis the font size in mm (the font's em, a little more than the height of a capital letter).lettering(text, font:, size:)gives the outlines as curves: a list of{outline, holes}, the inside of an "o" being a hole. Use it to measure the text or to build shapes of your own.bounds(…)is the box around the outlines,{min, max}. That is how the plate fits the name.- The engraving is
depth + 1high and startsdepthbelow the top: it sticks out 1 mm above, so that the cut goes cleanly through the top face. \nin the text starts a new line. A character the font has no glyph for is an error.
Raised letters instead of an engraving:
letters(…) |> move(z: 4) as an export of
its own, with a colour of its own. That is what name_tag
does, for printers with two filaments.
Drawings: SVG
A drawing from a vector program becomes curves with
svg:
let shapes = svg(read("heart.svg", encoding: "utf-8"), unit: "document")
export raised(shapes, 3)
svg(text, unit:)gives the drawing's filled areas as a list of{outline, holes, id, fill}, with y up and the bottom left corner at the origin.unit:says how large the drawing becomes:"document"takes the width written in the file (such aswidth="60mm"),"mm"reads one unit of the drawing as 1 mm,"px"as 1/96 inch; a number gives millimetres per unit.raised(shapes, height)makes one solid of all the areas, with holes. To pick single parts, select byidorfill:[s | s <- shapes, s.id == "heart"].- Text, clones, masks and paths with only a stroke and no fill are errors. Convert them to paths in the drawing program first ("object to path", "stroke to path").
The cookie cutter cookie_cutter takes the outline with
svg(…)[0].outline and builds a thin wall along it with
offset (chapter 6).
Pictures: a PNG as a relief
param cell = 0.3 in 0.1..1 "width of a pixel on the plate [mm]"
param thin = 0.8 in 0.4..2 "thickness where the picture is white [mm]"
param thick = 3 in 1.5..6 "thickness where it is black [mm]"
let picture = image(read_bytes("knot.png"), channel: "luminance", cell: cell)
export relief(1 - picture, height: thick - thin, base: thin)
image(bytes, channel:, cell:)turns a PNG into a field: one number per pixel, 0 for black, 1 for white.cellis the width of a pixel in mm; a picture 240 pixels wide becomes 72 mm wide at 0.3 mm.channel:chooses what is read:"luminance"(brightness as the eye sees it),"gray","red","green","blue"or"alpha". Transparent pixels are an error unlesstransparent:gives their value.relief(field, height:, base:)is a closed solid with a flat bottom,base + height · valuehigh above each pixel.- You compute with a field as with a number, cell by cell:
1 - pictureinverts the picture;clamp,min,maxandblur(field, r)(soften) work too.
This is a lithophane: dark places thick, light ones
thin. Held against the light, the picture appears. Printing hints: white
filament, 100 % infill, preferably print the plate standing up;
cell not much smaller than the nozzle. Pictures up to 4
million pixels work; a few hundred pixels across are usually enough.
Heights from a picture: the Moon as a globe
A picture can hold heights too. moon_heights.png has two
pixels per degree of longitude and latitude (720 × 360), 16 bits; the
value says how high the Moon is there (measured by the laser altimeter
on NASA's Lunar Reconnaissance Orbiter).
sample(field, point) reads the field at any point, mixed
linearly between the pixels' centres:
param radius = 50 in 20..100 "radius of the globe [mm]"
param exaggeration = 8 in 1..30 "how many times higher than true to scale"
let heights = image(read_bytes("moon_heights.png"), channel: "gray", cell: 0.5)
fn km(v) = (v * 65535 - 20000) / 2000
fn place(lon, lat) = (radius + exaggeration * h * radius / 1737.4) * (cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat))
where h = km(sample(heights, (lon + 180, lat + 90)))
let rings = [interpolate([place(lon, lat) | lon <- range(-180, 180, step: 0.5)], closed: true, spacing: "even")
| lat <- range(-89.75, 90, step: 0.5)]
export loft(rings)
cellis otherwise millimetres per pixel; here the field is measured in degrees: withcell: 0.5a pixel is ½ degree wide, x runs from 0 to 360, y from 0 to 180 – the longitude + 180 and the latitude + 90. Which unit a field has only decides how you read it afterwards.kmturns the grey value (0 … 1, 16 bits) into kilometres above or below the mean radius;exaggerationmakes the mountains higher,radiusis the size of the globe in mm.- One ring per line of latitude, the loft (chapter 5) through all of them. At the poles, tiny flat caps remain.
- Near a pole a degree of longitude is very short, and the map's
pixels there are drawn out along the ring. Taken one by one, they would
stand round the pole as rays. So the example
moonaverages every height over aboutstepdegrees of the surface along the ring, that is overstep / cos(latitude)degrees of longitude. spacing: "even"lets the curve pass its points in equal steps. Then all rings share their knots, and the loft stays light. Without it every ring would have knots of its own, and the loft would have to carry all of them: minutes and tens of millions of triangles instead of a few seconds.- True to scale, the mountains would hardly be half a millimetre high at a radius of 50 mm.
The examples
- hex_tiles – game tiles from
hex_tiles.json: hexagons with forest, village, field at their edges and rivers as grooves. In the browser, change an edge from"forest"to"village"under Data, and little houses stand there. - mobile – a mobile from
mobile.json, nested as deep as you like; every rod hangs where it balances. Withprint = truethe parts lie flat for printing. - name_tag – a key ring tag: letters on a plate that fits the text, two colours.
- cookie_cutter – a cookie cutter from an SVG drawing.
- lithophane – a PNG as a lithophane.
- moon – the Moon as a globe from its heights (data: NASA's Scientific Visualization Studio, CGI Moon Kit).
- moon_halves – the same Moon to print: two halves
lying flat on the print bed, and a ring with a bayonet that holds them
together. Put the ring into the southern half and turn it to the stop,
then put the northern half on and turn it the same way. Closed, the
meridians meet.
gapis the play (0.25 mm); if it binds, a little more. Takes about a minute.
More on encodings, CSV and why knotflow guesses nothing: lesson 2.5.