knotflow Handbook Deutsch Lessons Modeller ↗ Source

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

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)]

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"

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")]

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)

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)

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)

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)

The examples

More on encodings, CSV and why knotflow guesses nothing: lesson 2.5.