diff --git a/docs/guide/README.md b/docs/guide/README.md new file mode 100644 index 0000000..233334d --- /dev/null +++ b/docs/guide/README.md @@ -0,0 +1,344 @@ +# formats-luau guide + +formats-luau reads, writes and converts file formats in pure Luau. One source tree runs on Roblox, on LuaJIT / LÖVE +and in the luau CLI. Each format maps onto the standard type of its category, so a PNG and a WebP both load as the +same `Image`, and every audio format opens as the same streaming `Decoder`. + +This page covers what every category shares: installing, inputs, detection, errors, options, saving and converting, +and the host notes. Each standard type has its own page: + +| Page | Type(s) | Formats | +|---|---|---| +| [Images](image.md) | `Image`, `Frame` (animation) | PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR | +| [Audio](audio.md) | `Audio`, `Decoder` | WAV, FLAC, MP3, Ogg Vorbis, Opus, AAC, M4A, AIFF, AU, CAF, VOC | +| [Music](music.md) | `Module`, `Midi` | MOD, S3M, XM, IT, MIDI, SoundFont 2 | +| [Video](video.md) | `VideoDecoder`, `Demuxer`, `Track`, `Packet` | MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Y4M, H.264 | +| [3D scenes](scene.md) | `Scene`, `Voxels` | glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX | +| [CAD](cad.md) | `Cad` (STEP) | STEP (B-rep through a plug-in) | +| [Fonts](font.md) | `Font` | TTF / OTF, WOFF, WOFF2, BMFont | +| [Archives](archive.md) | `Archive` | zip, tar, gzip, 7z, xz, zstd, Brotli, bzip2 | +| [Data](data.md) | plain values, `XmlNode`, `Date` | JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist | +| [Vector](vector.md) | `Vector` | SVG | +| [Layered images](layered.md) | `Layered` | PSD, Aseprite | +| [Tile maps](tilemap.md) | `TileMap` | Tiled TMX / TMJ | +| [Subtitles](subtitles.md) | `Subtitles`, `Cue` | SRT, WebVTT, ASS / SSA | +| [Playlists](playlist.md) | `Playlist` | M3U / M3U8 (HLS), PLS, XSPF | + +[Recipes](recipes.md) has short task-oriented snippets. [FORMATS.md](../FORMATS.md) lists every format with its +read and write capabilities, and [API.md](../API.md) is the API reference. + +```luau +local img = assert(F.load(pngBytes)) -- PNG -> Image +local small = assert(F.ops.image.resize(img, 32, 24, "lanczos")) +local webp = assert(F.save(small, nil, { format = "webp" })) -- Image -> WebP bytes (a buffer) +assert(F.detect(webp) == "webp") +``` + +Every snippet in this guide runs as a test under both runtimes (`bash tools/test.sh`). A snippet sees the library +as `F`, and its input files as variables such as `pngBytes` (a buffer) or `srtText` (a string). + +## Installing + +**Roblox (Rojo).** Build the Roblox tree, then let Rojo turn it into a model or sync it into Studio: + +```sh +python3 -I tools/build.py roblox # writes build/roblox/Formats (requires become instance paths) +rojo build -o Formats.rbxm # default.project.json mounts build/roblox/Formats; or: rojo serve +``` + +Put the `Formats` ModuleScript somewhere both client and server can see it, for example ReplicatedStorage: + + +```luau +local F = require(game:GetService("ReplicatedStorage").Formats) +``` + +Roblox has no file system: pass buffers or strings, for example from `HttpService:GetAsync` or a `buffer` you built. + +**LuaJIT and LÖVE.** Build the Lua 5.1 tree: + +```sh +python3 -I tools/build.py luajit # writes build/luajit/formats/ (plain Lua 5.1 + the LuaJIT FFI) +``` + +Then either copy `build/luajit/formats` into your game, or put the build on `package.path`: + + +```lua +package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path +local F = require("formats") +``` + +The library carries its own copy of the Luau standard library pieces it uses (`buffer`, `bit32`, `utf8`, ...). +Your own code gets them as globals with `require("formats._compat").install()`, which is useful when you read the +pixel buffers yourself. [examples/love](../../examples/love/main.lua) is a runnable LÖVE example. + +**luau CLI.** The repository's `.luaurc` defines the alias `@formats` for `src/Formats`, so a script run from the +repository root can require the sources directly. The CLI has no file system. + + +```luau +local F = require("@formats") +``` + +The runnable programs in [examples/](../../examples) work this way: `luau examples/image.luau`. + +## Inputs + +Every `load`, `open` and `detect` takes a source `src`: + +| `src` | Meaning | +|---|---| +| `buffer` | the file's bytes | +| `string` | the file's bytes; on hosts with a file system, a path when the string looks like one (under 4 KB, no NUL or newline) and the file exists | +| path | a file name (LuaJIT, LÖVE): read through `io.open`, or `love.filesystem` first under LÖVE | + +`opts.path = true` forces a path and `opts.data = true` forces bytes. A string is copied into a buffer once. + +```luau +local a = assert(F.load(pngBytes)) -- a buffer +local b = assert(F.load(buffer.tostring(pngBytes))) -- the same bytes as a string +assert(a.width == b.width and a.height == b.height) +``` + + +```luau +local img = assert(F.load("assets/photo.png")) -- a path (LuaJIT / LÖVE) +assert(img.width == 64) +local data = assert(F.host.readFile("assets/photo.png")) -- or read the bytes yourself +assert(buffer.len(data) > 0) +``` + +## Detection + +`F.load` finds the format by content first: each format scores the first bytes (its magic numbers). It falls back +to the extension of the path or of `opts.name`. `opts.format` (a format name or an extension) skips detection, and +`opts.category` (`"image"`, `"audio"`, ...) limits it, which is what the category facades `F.image`, `F.audio`, ... +do. + +```luau +assert(F.detect(pngBytes) == "png") +assert(F.detect(gifBytes) == "gif") +assert(F.detect("a,b\n1,2\n", { name = "table.csv" }) == "csv") -- text without magic: the name decides +local img = assert(F.image.load(jpegBytes)) -- only image formats are tried +local same = assert(F.load(jpegBytes, { format = "jpg" })) -- no detection at all +assert(img.width == same.width) +``` + +`F.formats(category?)` lists the formats and their capabilities without loading any format code. +`F.format(name)` returns the format module itself, for format-specific extras. + +```luau +local writable = {} +for _, info in F.formats("image") do + if info.caps.encode then + table.insert(writable, info.name) + end +end +assert(table.find(writable, "png") and table.find(writable, "webp")) +local png = assert(F.format("png")) +assert(png.name == "png" and png.category == "image") +``` + +## Errors + +Nothing in the library throws on bad data or bad arguments. A failing call returns `nil, err`: + +| Field | Meaning | +|---|---| +| `err.code` | one of the `F.Err` codes below | +| `err.message` | what went wrong, in words | +| `err.offset` | the byte offset in the input, when known | +| `err.format` | the format that failed, when known | + +`tostring(err)` prints all of it, for example `png: CORRUPT at 0x21: bad filter type 7`. + +| Code | Meaning | +|---|---| +| `TRUNCATED` | the data ends early | +| `CORRUPT` | the data is malformed | +| `CHECKSUM` | a CRC, Adler or hash does not match | +| `UNSUPPORTED` | valid data using a feature the library does not implement, or a format without an encoder | +| `UNKNOWN_FORMAT` | no format recognised the data, name or extension | +| `LIMIT` | a size limit was exceeded (`opts.maxPixels`, `opts.maxBytes`, ...) | +| `ARG` | a bad argument | +| `IO` | reading or writing a file failed, or the host has no file system | + +```luau +local img, err = F.load("definitely not an image") +assert(img == nil and err.code == F.Err.UNKNOWN_FORMAT) + +local cut = buffer.create(40) +buffer.copy(cut, 0, pngBytes, 0, 40) -- the first 40 bytes of a PNG +local bad, perr = F.load(cut) +assert(bad == nil and perr.format == "png") +print(tostring(perr)) -- "png: TRUNCATED ..." + +local ok, serr = F.save(F.Types.Image.new(4, 4), nil, { format = "ttf" }) +assert(ok == nil and serr.code == F.Err.UNKNOWN_FORMAT) -- no image format called ttf +``` + +`assert(F.load(src))` turns an error into a thrown error with the message, which is handy in scripts and tests. + +## Options + +Every call takes an optional `opts` table. The options every format understands: + +| Option | Meaning | +|---|---| +| `format` | the format to decode as or encode to (a name such as `"jpeg"`, or an extension such as `"jpg"`) | +| `category` | limit detection to one category | +| `name` | a file name hint for detection, and for formats that store names | +| `path` / `data` | force `src` to be a path / bytes | +| `maxPixels`, `maxBytes`, `maxFrames`, ... | size limits; going over returns `LIMIT` | + +Each format adds its own options, such as `quality` for JPEG, `lossless` for WebP, `level` for PNG and zip, or +`bitrate` for MP3. The type pages list them. + +```luau +local img = assert(F.load(pngBytes)) +local q90 = assert(F.save(img, nil, { format = "jpeg", quality = 90 })) +local q30 = assert(F.save(img, nil, { format = "jpeg", quality = 30 })) +assert(buffer.len(q30) < buffer.len(q90)) +local big, err = F.load(pngBytes, { maxPixels = 100 }) +assert(big == nil and err.code == F.Err.LIMIT) +``` + +## Saving + +`F.save(value, dest?, opts?)` encodes any standard value. The format comes from, in order: `opts.format`, the +extension of `dest`, then the format the value was loaded from (`value.meta.source.format`). + +| Call | Returns | +|---|---| +| `F.save(value, nil, opts)` | a `buffer` | +| `F.save(value, "out.png", opts)` | `true` after writing the file (hosts with a file system) | +| `F.saveString(value, opts)` | the encoded bytes as a `string` | + +```luau +local img = assert(F.load(gifBytes)) +local again = assert(F.save(img)) -- no format given: GIF again (the source format) +assert(F.detect(again) == "gif") +local qoi = assert(F.save(img, nil, { format = "qoi" })) +local s = assert(F.saveString(img, { format = "png" })) +assert(type(s) == "string" and string.sub(s, 2, 4) == "PNG") +local _, err = F.save(F.load(flacBytes), nil, { format = "aac" }) -- AAC is read-only +assert(err.code == F.Err.UNSUPPORTED) +print(tostring(err)) -- names a writable format to try instead +local _ = qoi +``` + + +```luau +local img = assert(F.load("assets/photo.png")) +assert(F.save(img, "out/photo.webp")) -- the extension picks WebP +assert(F.save(img, "out/photo.bin", { format = "bmp" })) -- opts.format wins over the extension +assert(F.detect("out/photo.bin") == "bmp") +``` + +Values you build yourself have no source format, so pass `opts.format` or a destination with an extension: + +```luau +local img = F.Types.Image.new(2, 2) -- 2 x 2 rgba8, all zero +local _, err = F.save(img) +assert(err.code == F.Err.ARG) -- "save: no format ..." +assert(F.save(img, nil, { format = "png" })) +``` + +## Converting + +`F.convert(src, format, opts?)` is a load followed by a save. `opts` go to both, and `opts.out = path` writes a +file instead of returning a buffer. + +```luau +local webp = assert(F.convert(pngBytes, "webp", { lossless = true })) +local mp3 = assert(F.convert(wavBytes, "mp3", { bitrate = 128 })) +assert(F.detect(webp) == "webp" and F.detect(mp3) == "mp3") +``` + + +```luau +assert(F.convert("assets/tone.wav", "flac", { out = "out/tone.flac" })) +local a = assert(F.load("out/tone.flac")) +assert(a.sampleRate == 44100 and a.channels == 2) +``` + +Some conversions cross categories: an animated GIF converts to a video (`F.convert(gifBytes, "avi")`), and a +single-stream archive such as `.tar.gz` loads as the archive inside. A music file renders to audio through +`F.save(song:render(), nil, { format = "wav" })` ([Music](music.md)). The type pages show these. + +## Hosts + +`F.host.name` is `"roblox"`, `"love"`, `"luajit"` or `"luau"`, detected when the library loads. + +| Host | Files | Bridges | +|---|---|---| +| Roblox | none: pass buffers or strings | `F.host.toEditableImage(img)` | +| LÖVE | `love.filesystem` (the game folder and the save directory), then `io` | `F.host.toImageData(img)`, `F.host.fromImageData(imageData)`, `F.host.toSoundData(audioOrDecoder)` | +| LuaJIT | `io.open` | | +| luau CLI | none | | + +```luau +assert(table.find({ "roblox", "love", "luajit", "luau" }, F.host.name)) +if not F.host.hasFiles then + local _, err = F.host.readFile("photo.png") + assert(err.code == F.Err.IO) +end +``` + +Every host has `F.host.readFile(path)`, `F.host.writeFile(path, buffer)` and `F.host.exists(path)`; without a file +system they fail with `IO`. Under LÖVE, relative paths are written to the save directory. + +**Roblox.** `toEditableImage` needs an `rgba8` image (convert others with `F.ops.image.convert(img, "rgba8")`) and +the EditableImage API enabled for the experience: + + +```luau +local img = assert(F.image.load(pngBytes)) +local editable = assert(F.host.toEditableImage(img)) +local label = Instance.new("ImageLabel") +label.Size = UDim2.fromOffset(img.width, img.height) +label.ImageContent = Content.fromObject(editable) +label.Parent = script.Parent -- a ScreenGui +``` + +**LÖVE.** `toImageData` copies an `rgba8` image into an `ImageData` (through the FFI), `fromImageData` copies back, +and `toSoundData` turns an `Audio` or a `Decoder` (read to its end) into 16-bit `SoundData`: + + +```lua +local F = require("formats") +local img = assert(F.load("sprite.png")) -- love.filesystem path +local texture = love.graphics.newImage(F.host.toImageData(img)) +local music = love.audio.newSource(F.host.toSoundData(F.audio.open("music.ogg")), "static") +music:play() +local shot = F.host.fromImageData(love.graphics.newCanvas(64, 64):newImageData()) +F.save(shot, "shot.png") -- to the save directory +``` + +**LuaJIT trace limits.** When the library loads on LuaJIT it raises the JIT's trace limits +(`jit.opt.start("maxtrace=8000", "maxmcode=65536")`). The big decoders (Opus CELT, VP8, H.264, MPEG-1) outgrow the +defaults and fall back to the interpreter, which is 2x or more slower. Set `FORMATS_NO_JIT_TUNE` before the first +`require` to leave the JIT settings alone: + + +```lua +FORMATS_NO_JIT_TUNE = true -- a global, read once when the library loads +local F = require("formats") +``` + +## Conventions + +- **Values.** Every top-level value has a `kind` (`"image"`, `"audio"`, `"scene"`, ...), so `F.save` knows its + category, and a `meta` table. `meta.source.format` records the format it was loaded from. +- **Constructors.** `F.Types` has constructors for values you build yourself: `F.Types.Image.new(w, h, format?)`, + `F.Types.Audio.new(rate, channels, frames)`, `F.Types.Scene.new()`, `F.Types.Vector.new(w, h)`, + `F.Types.Layered.new(w, h)`, `F.Types.Subtitles.new()`, `F.Types.Midi.new(division?)`, `F.Types.TileMap.new(...)`. +- **Buffers.** Buffers are tightly packed: image rows top to bottom with no padding, audio samples interleaved, + 3D accessors without stride. Indices into lists (nodes, meshes, materials, frames) are 1-based; byte offsets and + pixel coordinates are 0-based. +- **Times.** Times and durations are in seconds, except container packet timestamps (ticks of the track's + timescale) and MIDI events (ticks). +- **Editing.** `F.ops.image`, `F.ops.audio`, `F.ops.mesh`, `F.ops.layers` and `F.ops.vector` hold the editing + functions. They return new values unless they say they edit in place, and they return `nil, err` for bad + arguments. diff --git a/docs/guide/archive.md b/docs/guide/archive.md new file mode 100644 index 0000000..5524350 --- /dev/null +++ b/docs/guide/archive.md @@ -0,0 +1,212 @@ +# Archive + +Every archive format loads as one `Archive` value: a list of named entries whose bytes you `read` on demand. Zip, +tar and 7z hold many entries; gzip, xz, zstd, bzip2 and Brotli files are *single-stream* archives with one entry +(the decompressed data). A `.tar.gz` (`.tgz`, `.tar.xz`, `.tar.zst`, `.tar.bz2`, `.tar.br`) loads straight as the tar +inside. Zip, tar and gzip are writable; any Archive can be written as any of them. + +```luau +local zip = assert(F.archive.load(zipBytes)) +for _, e in zip:list() do + print(e.name, e.size, e.method, e.dir) -- "readme.txt" 116 "deflate" false +end +local readme = assert(zip:read("readme.txt")) -- a buffer +assert(string.find(buffer.tostring(readme), "archive example", 1, true)) + +zip:add("notes/todo.txt", "write the docs") -- a string or a buffer +local out = assert(F.save(zip)) -- a buffer, in the source format (zip) +assert(F.archive.load(out):read("notes/todo.txt")) +``` + +## The type + +`Archive`: + +| Field / method | Type | Meaning | +|---|---|---| +| `kind` | `"archive"` | | +| `format` | string | `"zip"`, `"tar"`, `"7z"`, `"gzip"`, `"xz"`, `"zst"`, `"bz2"`, `"br"` | +| `list(self)` | `{ ArchiveEntry }` | the entries in archive order (directories included) | +| `read(self, name)` | `buffer?, Err?` | a fresh copy of the entry's bytes, decompressed (lazily, on each call) | +| `add(self, name, data, opts?)` | | add or replace an entry; `data` is a buffer or a string | +| `write(self, opts?)` | `buffer?, Err?` | the archive in its own format (`F.save` does the same and can pick another format) | +| `meta` | table | `source.format`; `stream = true` for single-stream archives; `compression` (the outer format of an unwrapped `.tar.gz`); `comment` (zip, gzip) | + +`ArchiveEntry` (each `list()` call returns new tables; editing them changes nothing): + +| Field | Type | Meaning | +|---|---|---| +| `name` | string | the path inside the archive, `/` separated, no leading `/`; directories end in `/` in zip | +| `size` | number | uncompressed bytes (0 for directories) | +| `compressedSize` | number? | stored bytes (zip, gzip) | +| `method` | string? | `"store"`, `"deflate"`, `"lzma2"`, ... | +| `mtime` | number? | modification time, Unix seconds (UTC) | +| `dir` | boolean | a directory entry | +| `crc32`, `comment` | number?, string? | zip only | +| `mode`, `uid`, `gid`, `uname`, `gname`, `type`, `link` | | tar only (`mode` is the Unix permission bits, e.g. `420` = `0644`) | + +## Load + +```luau +local tar = assert(F.archive.load(tgzBytes)) -- a .tar.gz: the tar inside +assert(tar.format == "tar" and tar.meta.compression == "gzip") +for _, e in tar:list() do + assert(e.mtime == 1767225600) -- 2026-01-01T00:00:00Z, Unix seconds +end + +local seven = assert(F.archive.load(sevenzBytes)) -- 7z: LZMA / LZMA2 / Deflate / BZip2 / BCJ / delta +local csv = assert(seven:read("data/scores.csv")) +assert(buffer.tostring(csv):sub(1, 4) == "name") +``` + +Single-stream files hold one entry, named after the file without its compression extension when the loader knows +the name (a path, or `opts.name`), else after the name stored in the file (gzip `FNAME`), else `"data"`: + +```luau +local xz = assert(F.archive.load(xzBytes, { name = "notes.txt.xz" })) +assert(xz.meta.stream and #xz:list() == 1) +assert(xz:list()[1].name == "notes.txt") +local text = buffer.tostring(assert(xz:read("notes.txt"))) + +local zst = assert(F.archive.load(zstBytes)) -- no name given: the entry is "data" +assert(buffer.tostring(assert(zst:read("data"))) == text) +``` + +Pass `unwrap = false` to keep the outer single-stream archive of a `.tar.gz` (its one entry is the raw tar): + +```luau +local gz = assert(F.archive.load(tgzBytes, { unwrap = false })) +assert(gz.format == "gzip" and gz.meta.stream) +local inner = assert(gz:read(gz:list()[1].name)) +assert(F.detect(inner) == "tar") +``` + +Options for loading: + +| Option | Formats | Meaning | +|---|---|---| +| `unwrap` | gzip, xz, zst, bz2, br | `false`: do not open an archive inside a single-stream file (also off when `format` is given) | +| `name` | single-stream | the file name, used to name the entry (set for you when loading a path) | +| `verify` | zip | check each entry's CRC-32 on read (default `true`) | +| `maxEntries` | tar | refuse more entries (default 1e6) | +| `maxBytes` | bz2, br | refuse a bigger decompressed size | + +A path works on hosts with a file system: + + +```luau +local a = assert(F.load("assets/files.zip")) +assert(F.save(a, "out/files.tar")) -- the format from the extension +assert(F.archive.load("out/files.tar"):read("readme.txt")) +``` + +## Inspect + +`read` matches the exact name first; zip also finds entries case-insensitively and by base name. A missing entry is +`nil, Err` (code `ARG`), never an error: + +```luau +local zip = assert(F.archive.load(zipBytes)) +local data, err = zip:read("missing.txt") +assert(data == nil and err.code == F.Err.ARG) +assert(zip:read("README.TXT")) -- zip: case-insensitive lookup + +local files, bytes = 0, 0 +for _, e in zip:list() do + if not e.dir then + files += 1 + bytes += e.size + end +end +assert(files == 3) +``` + +## Edit + +`add` appends an entry or replaces the one with the same name. Its options depend on the format the archive came +from: + +| Option | zip | tar | +|---|---|---| +| `method` | `"deflate"` (default; stored when deflate does not shrink it) or `"store"` | | +| `level` | deflate level 0..9 (default 6) | | +| `mtime` | Unix seconds (default 1980-01-01, for reproducible output) | Unix seconds (default 0) | +| `mode` | | permission bits (default `0644`) | +| `dir` | name the entry `"dir/"` with `data = nil` | `{ dir = true }` | +| `comment`, `utf8`, `attributes` | per-entry comment, UTF-8 name flag, external attributes | | + +Zip archives also have `remove(name)` (true when the entry existed). Unchanged zip entries are copied as they are, +without recompressing. + +New archives come from the format modules: `F.format("zip").create()` and `F.format("tar").new()`. + +```luau +local zip = F.format("zip").create() +zip:add("assets/", nil) -- a directory +zip:add("assets/hello.txt", "hello", { level = 9, mtime = 1767225600 }) +zip:add("assets/raw.bin", buffer.create(1024), { method = "store" }) +local bytes = assert(F.save(zip, nil, { format = "zip", comment = "made by formats-luau" })) + +local back = assert(F.archive.load(bytes)) +assert(#back:list() == 3 and back.meta.comment == "made by formats-luau") +assert(back:list()[3].method == "store") +assert(back:remove("assets/raw.bin") and #back:list() == 2) + +local tar = F.format("tar").new() +tar:add("bin/", "", { dir = true }) +tar:add("bin/run.sh", "#!/bin/sh\necho hi\n", { mode = 493, mtime = 1767225600 }) -- 493 = 0755 +local tarData = assert(F.save(tar)) -- the tar's own format +assert(F.archive.load(tarData):list()[2].mode == 493) +``` + +## Save and convert + +`F.save(archive, dest?, opts?)` writes the archive's own format unless `opts.format` (or the destination's +extension) names another one; any Archive (a 7z, a tar, a zip) can be written as zip, tar or gzip. + +| Writing as | Options | What it holds | +|---|---|---| +| zip | `comment` (archive comment), `zip64` (force ZIP64 records) | every entry | +| tar | `format`: `"pax"` (default: ustar plus pax records when needed), `"gnu"`, `"ustar"` | every entry, with `mode` / `mtime` | +| gzip (`gz`, `tgz`) | `level` 0..9, `name` (FNAME), `mtime` | one entry: that file; several entries: a tar inside (a `.tar.gz`) | + +```luau +local seven = assert(F.archive.load(sevenzBytes)) +local zipData = assert(F.save(seven, nil, { format = "zip" })) -- 7z -> zip +local tgz = assert(F.save(seven, nil, { format = "tgz" })) -- 7z -> .tar.gz +local back = assert(F.archive.load(tgz)) +assert(back.format == "tar" and back.meta.compression == "gzip") +assert(F.detect(zipData) == "zip") + +local converted = assert(F.convert(tgzBytes, "zip")) -- load + save in one call +assert(F.archive.load(converted):read("src/main.luau")) + +local gzipped = assert(F.save("some text", nil, { format = "gzip", name = "note.txt" })) -- a buffer or a string +assert(F.archive.load(gzipped, { unwrap = false }):list()[1].name == "note.txt") +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| zip (`.zip`) | yes | yes | store / deflate entries, ZIP64, data descriptors, comments; no encryption | +| tar (`.tar`) | yes | yes | ustar, pax, GNU long names | +| 7z (`.7z`) | yes | - | copy / LZMA / LZMA2 / Deflate / BZip2 / BCJ / delta; no AES, PPMd, BCJ2 | +| gzip (`.gz`, `.tgz`) | yes | yes | single stream; concatenated members read as one | +| xz / lzma (`.xz`, `.txz`, `.lzma`) | yes | - | single stream | +| zstd (`.zst`, `.tzst`) | yes | - | single stream; no dictionaries | +| bzip2 (`.bz2`, `.tbz2`) | yes | - | single stream | +| Brotli (`.br`) | yes | - | single stream; no magic number, so pass a `.br` name or `format = "br"` | + +Full capability list: [FORMATS.md](../FORMATS.md). + +## Gotchas + +- `read` returns a new buffer every call and decompresses again; keep the buffer if you need it twice. +- `F.save(tar)` of an unwrapped `.tar.gz` writes a plain tar: the value *is* the tar. Pass `format = "tgz"` (or a + `.tar.gz` / `.tgz` destination) to compress it again. +- Writing gzip from an archive with exactly one entry writes that file, not a tar (`format = "tgz"` included); a + `.tar.gz` needs two or more entries. +- Brotli has no magic bytes: detection needs a `.br` name or `format = "br"`. +- Entry names are stored as given. Before extracting to disk, reject names containing `..` or starting with `/`. +- Directory entries: zip lists `"src/"` (trailing slash), 7z and tar list `"src"` with `dir = true`. diff --git a/docs/guide/audio.md b/docs/guide/audio.md new file mode 100644 index 0000000..454473c --- /dev/null +++ b/docs/guide/audio.md @@ -0,0 +1,254 @@ +# Audio + +Every audio format opens as the same streaming **Decoder** and loads as the same **Audio** value. A Decoder hands +out interleaved 32-bit float samples a block at a time, for playback and long files. An Audio holds the whole sound +in one buffer, for editing with `F.ops.audio`. Encoders take either one. A FLAC, an MP3 and an Ogg Vorbis file are +used the same way. + +```luau +local song = assert(F.audio.load(flacBytes)) -- Audio: the whole file decoded +print(song.sampleRate, song.channels, song.frames) -- 44100 2 44100 +print(song.tags.title, song.tags.artist) -- Docs Tone formats-luau +local quieter = F.ops.audio.gainDb(song, -6) +local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192 })) -- a buffer +assert(F.detect(mp3) == "mp3") +``` + +## The types + +### Audio + +`F.audio.load(src)` and `F.load(src)` return an Audio. `F.Types.Audio.new(sampleRate, channels, frames)` makes a +silent one. + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"audio"` | | +| `sampleRate` | number | frames per second (Hz) | +| `channels` | number | samples per frame | +| `frames` | number | the length in sample frames (`frames / sampleRate` = seconds) | +| `samples` | buffer | interleaved f32, `frames * channels * 4` bytes | +| `tags` | `{ [string]: string }` | `title`, `artist`, `album`, `date`, `genre`, `track`, `comment`, ...; keys are lower case | +| `meta` | table | `meta.source = { format = "flac", ... }` after a load | + +**Sample layout.** Samples are little-endian 32-bit floats, nominally in -1..1. The values are not clipped: the +encoders clip. Frame `i` (0-based), channel `c` (0-based) is at byte offset `(i * channels + c) * 4`: + +```luau +local a = F.Types.Audio.new(8000, 2, 8000) -- 1 s of stereo silence at 8 kHz +for i = 0, a.frames - 1 do + local v = math.sin(2 * math.pi * 440 * i / a.sampleRate) * 0.5 + buffer.writef32(a.samples, (i * 2 + 0) * 4, v) -- left + buffer.writef32(a.samples, (i * 2 + 1) * 4, -v) -- right +end +assert(buffer.len(a.samples) == a.frames * a.channels * 4) +local wav = assert(F.save(a, nil, { format = "wav" })) +``` + +**Channel order.** Channels come in WAVE order, whatever the source format uses: FL, FR, C, LFE, BL, BR, SL, SR. +Mono is one channel and stereo is FL, FR. Vorbis and Opus streams are reordered on decode. + +### Decoder + +`F.audio.open(src)` and `F.open(src)` return a Decoder. + +| Member | Meaning | +|---|---| +| `sampleRate`, `channels` | as in Audio | +| `frames` | total frames (an estimate for VBR streams without an index; 0 = unknown) | +| `duration` | seconds | +| `bitrate` | average bits per second | +| `tags` | as in Audio | +| `dec:read(n, out?)` | `buffer, count`: up to `n` frames as interleaved f32, and how many were read (0 at the end). The returned buffer is `out` when `out` holds at least `n * channels * 4` bytes; otherwise it is a new buffer. Only the first `count * channels * 4` bytes are valid. | +| `dec:seek(seconds)` | moves the read position | +| `dec:position()` | the read position in seconds | + +Some formats add their own fields. For example, `bitsPerSample` on WAV, FLAC and AIFF, and `pictures` (cover art) +on FLAC and M4A. + +```luau +local dec = assert(F.audio.open(flacBytes)) +assert(dec.sampleRate == 44100 and dec.channels == 2 and dec.duration == 1) +local block = buffer.create(1024 * dec.channels * 4) -- reused for every read +local total, peak = 0, 0 +while true do + local out, n = dec:read(1024, block) + if n == 0 then break end + for k = 0, n * dec.channels - 1 do + peak = math.max(peak, math.abs(buffer.readf32(out, k * 4))) + end + total += n +end +assert(total == dec.frames) +dec:seek(0.5) +assert(math.abs(dec:position() - 0.5) < 0.001) +``` + +## Loading + +| Call | Gives | +|---|---| +| `F.audio.load(src, opts?)` | an Audio: the whole file decoded | +| `F.audio.open(src, opts?)` | a Decoder | +| `F.load` / `F.open` | the same, when you don't know the category in advance | +| `F.ops.audio.toAudio(decoder)` | the rest of a Decoder as an Audio (`opts.maxFrames` limits it) | + +`src` is a buffer, a string of bytes, or a path on hosts with files. The format is detected from the content (see +the guide's [README](README.md#inputs)). Options: + +| Option | Formats | Meaning | +|---|---|---| +| `format` | all | decode as this format (`"mp3"`, `"wav"`, ...) and skip detection | +| `maxFrames` | wav, flac, mp3, aiff, au, voc, aac | `Err.LIMIT` past this many frames | +| `stereo` | opus | downmix surround streams to stereo | + +```luau +local tags = assert(F.audio.open(mp3Bytes)).tags -- opening reads the tags; nothing is decoded yet +assert(tags.title == "Docs Tone" and tags.album == "Guide" and tags.date == "2026") +local ogg = assert(F.audio.open(oggBytes)) +print(ogg.bitrate, ogg.duration) +local bad, err = F.audio.load("not audio at all") +assert(bad == nil and err.code == F.Err.UNKNOWN_FORMAT) +``` + +## Editing: `F.ops.audio` + +Every function returns a new Audio, or `nil, err` for bad arguments. Times are in seconds. Rates and channel counts +of other inputs are converted to the first input's. + +| Function | Does | +|---|---| +| `toAudio(audioOrDecoder, opts?)` | an Audio as it is, or a Decoder read to its end | +| `gain(a, factor)`, `gainDb(a, dB)` | scale every sample | +| `normalize(a, target?)` | scale so the peak is `target` (default 1) | +| `peak(a)`, `rms(a)` | `level, { per channel }` | +| `fade(a, inSeconds?, outSeconds?)` | linear fade-in / fade-out | +| `trim(a, start, stop?)` | the seconds `[start, stop)` | +| `concat({ a, b, ... })` | one after the other | +| `mix({ a, b, ... }, weights?)` | the sum, as long as the longest | +| `remix(a, channels, m?)` | any channel count. `m[out][in]` is an explicit matrix; the default comes from `matrix(from, to)` | +| `downmix(a, channels?)` | fewer channels (default 2), with ITU-R BS.775 coefficients | +| `upmix(a, channels)` | more channels: mono to FL / FR, stereo to FL / FR, the others silent | +| `matrix(from, to)` | the default remix matrix | +| `resample(a, rate, opts?)` | a new rate, band-limited; `opts.quality = "low" \| "medium" \| "high"` | + +```luau +local A = F.ops.audio +local a = assert(F.audio.load(wavBytes)) +local mono = assert(A.downmix(a, 1)) +local clip = assert(A.trim(A.resample(mono, 22050), 0.25, 0.75)) +assert(clip.channels == 1 and clip.sampleRate == 22050 and clip.frames == 11025) +local loop = assert(A.concat({ clip, A.fade(clip, 0.05, 0.05) })) +local level, perChannel = A.peak(loop) +local loud = assert(A.normalize(loop, 0.9)) +assert(math.abs(A.peak(loud) - 0.9) < 1e-4) +local both = assert(A.mix({ a, loud }, { 0.5, 0.5 })) -- loud is converted to a's 44.1 kHz stereo +assert(both.channels == 2 and both.sampleRate == 44100) +``` + +## Saving and converting + +`F.save(value, dest?, opts?)` takes an Audio or a Decoder. It picks the format from `opts.format`, else from the +destination's extension, else from the source format (`meta.source.format`). A Decoder has no source format, so pass +one. A Decoder is encoded as it is read, without decoding the whole file first. + +```luau +local a = assert(F.audio.load(wavBytes)) +local flac = assert(F.save(a, nil, { format = "flac", level = 8 })) -- buffer +local again = assert(F.save(F.audio.load(flac))) -- the source format: flac +local opus = assert(F.save(F.audio.open(mp3Bytes), nil, { format = "opus", bitrate = 64000 })) -- streamed +assert(F.audio.open(opus).sampleRate == 48000) +local wav24 = assert(F.convert(flacBytes, "wav", { sampleFormat = "s24" })) -- load + save +assert(F.audio.open(wav24).bitsPerSample == 24) +``` + + +```luau +assert(F.save(F.audio.open("assets/tone.flac"), "out/tone.ogg", { quality = 5 })) -- file in, file out +assert(F.detect("out/tone.ogg") == "vorbis") +``` + +Encoder options: + +| Format | Options | +|---|---| +| wav | `sampleFormat = "u8" \| "s16" \| "s24" \| "s32" \| "f32"` (default `"s16"`), `rf64`, `extensible`, `channelMask`, `tags` | +| flac | `level` 0..8 (default 5), `bits` 4..24 (default: the source depth, else 16), `blockSize`, `seekInterval`, `padding` | +| mp3 | `bitrate` **in kbps** (default 128), `layer` 3 or 2 (MP2), `mode = "stereo" \| "joint" \| "mono"`, `sampleRate`, `id3`, `resampleQuality` | +| vorbis | `quality` -1..10 (default 3) | +| opus | `bitrate` **in bits per second** (default 64000 per channel); CELT only; resampled to 48 kHz | +| aiff, au, voc | `sampleFormat` (see each format's `init.luau`) | +| m4a, caf | ALAC (lossless); m4a and caf also keep tags | + +Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the format has tags. + +## Formats + +| Read and write | Read only | +|---|---| +| wav (+ RF64), flac (+ Ogg FLAC), mp3 / mp2, vorbis (.ogg), opus, aiff / aifc, au, voc, caf, m4a (ALAC) | aac (ADTS), m4a / caf AAC | + +Each format's capabilities are listed in [FORMATS.md](../FORMATS.md). The audio tracks of video files open as +Decoders too: see `v.audio` in [video.md](video.md). Music files (MOD, MIDI, ...) render to a Decoder: see +[music.md](music.md). + +## Streaming in a game loop + +Decode a little per frame with a time budget. The game never stalls, and memory holds one block, not the whole song. + +```luau +local dec = assert(F.audio.open(oggBytes)) +local block = buffer.create(1024 * dec.channels * 4) +local queued = 0 +-- call once per game frame; returns true at the end of the stream +local function pump(budgetSeconds: number): boolean + local t0 = os.clock() + repeat + local out, n = dec:read(1024, block) + if n == 0 then return true end + queued += n -- hand out[0 .. n * channels * 4) to the audio device here + until os.clock() - t0 >= budgetSeconds + return false +end +while not pump(0.002) do end -- in a game: one pump(0.002) per frame +assert(queued == dec.frames) +``` + +On LÖVE, `F.host.toSoundData(audioOrDecoder)` makes a `SoundData` (16-bit) for `love.audio.newSource`. A queued +source can be fed block by block: + + +```lua +local F = require("formats") +local sd = F.host.toSoundData(F.audio.load("music.flac")) -- whole file +love.audio.newSource(sd):play() + +local dec = F.audio.open("music.ogg") -- streamed +local q = love.audio.newQueueableSource(dec.sampleRate, 16, dec.channels) +function love.update() + while q:getFreeBufferCount() > 0 do + local out, n = dec:read(4096) + if n == 0 then break end + local part = F.Types.Audio.new(dec.sampleRate, dec.channels, n) + buffer.copy(part.samples, 0, out, 0, n * dec.channels * 4) + q:queue(F.host.toSoundData(part)) + end + q:play() +end +``` + +Roblox has no API to play raw samples, so on Roblox the decoded samples are data only, for example for analysis or +visualisers. + +## Gotchas + +- **Bitrate units differ.** MP3 takes kbps (`bitrate = 192`); Opus takes bits per second (`bitrate = 96000`). +- `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono. +- `read(n, out)` returns a new buffer when `out` is too small. Always use the buffer it returns. +- Opus always decodes at 48 kHz. Resample with `F.ops.audio.resample` if you need another rate. +- `frames` of a VBR stream without an index is an estimate. Count the frames `read` returns if you need the exact + number. +- `F.save(decoder)` without `opts.format` or a destination fails with `Err.ARG`, because a Decoder has no source + format. +- `F.audio.load` does not take music files (MOD, MIDI). Use `F.music.open(src)` for their audio + ([music.md](music.md)). diff --git a/docs/guide/cad.md b/docs/guide/cad.md new file mode 100644 index 0000000..9e7aa6e --- /dev/null +++ b/docs/guide/cad.md @@ -0,0 +1,203 @@ +# CAD (STEP) + +STEP files (ISO 10303-21, "Part 21": AP203, AP214, AP242 and any other schema) load as a `Cad`: the file's header and +its *entity graph*, every `#id = TYPE(...)` instance with its arguments, exactly as written. Reading and writing the +graph is built in and lossless (parse, write, parse gives the same entities). + +Turning the graph into solid geometry needs a B-rep kernel, which formats-luau does not include: B-rep bodies and +tessellated meshes come from a plug-in you inject as `F.plugins.brep` (for example +brep-luau's modules). Without it, `F.cad.toBodies` / `fromBodies` / `tessellate` return +`UNSUPPORTED` and everything else on this page still works. + +```luau +local cad = assert(F.cad.load(stepText)) +print(cad.schema, cad.meta.count) -- AP214 6 +local step = assert(F.format("step")) -- the helpers below live on the format module +for _, id in step.byType(cad, "CARTESIAN_POINT") do + local e = cad.entities[id] + print(id, e.args[1], e.args[2][1], e.args[2][2], e.args[2][3]) -- 1 origin 0 0 0 / 5 tip 10 20 5.5 +end +``` + +## The type + +`Cad`: + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"cad"` | | +| `schema` | string | `"AP203"`, `"AP214"`, `"AP242"`, or the `FILE_SCHEMA` name as written | +| `header` | table | header entities by name: `FILE_DESCRIPTION`, `FILE_NAME`, `FILE_SCHEMA` (and any other), each a list of its arguments | +| `entities` | `{ [id]: StepEntity }` | the DATA instances by their `#id` (a sparse table: ids need not be contiguous) | +| `meta` | table | `source.format`, `count` (number of instances), `headerOrder` | + +`StepEntity`: + +| Field | Type | Meaning | +|---|---|---| +| `id` | number | the instance number (`#12` -> 12) | +| `type` | string | the entity type in upper case (`"CARTESIAN_POINT"`), or `"COMPLEX"` | +| `args` | `{ any }` | the parameters (below); empty for a complex instance | +| `parts` | `{ { type, args } }?` | complex instances `#6 = (A() B(*) C(...))`: one part per type, in file order | +| `section` | number? | the DATA section, in files with several (edition 3) | + +Parameters map to Luau values: + +| STEP | Luau | +|---|---| +| `12`, `1.5`, `0.` | a number (integral reals keep their real-ness when written back) | +| `'text'` | a string (Part 21 escapes `\X2\...` decoded to UTF-8) | +| `.T.`, `.MILLI.` | `{ enum = "T" }`, `{ enum = "MILLI" }` | +| `#4` | `{ ref = 4 }` | +| `(1., 2., 3.)` | a list | +| `LENGTH_MEASURE(2.5)` | `{ typed = "LENGTH_MEASURE", value = 2.5 }` | +| `"0FF"` | `{ binary = "0FF" }` | +| `$` / `*` | `step.NULL` / `step.DERIVED` (sentinels on the format module) | + +## Inspect + +`F.format("step")` has helpers for walking the graph: + +| Function | Returns | +|---|---| +| `get(cad, id | { ref = id })` | the entity (follows a reference) | +| `ids(cad)` | every instance id, ascending | +| `byType(cad, "TYPE")` | the ids of instances of a type (complex instances with such a part too), ascending | +| `part(entity, "TYPE")` | the args of that type: the entity's own, or one part of a complex instance | +| `add(cad, type, args)` | adds an instance after the highest id and returns its id | +| `real(list, index)` | marks `list[index]` as a real, so an integral value is written `3.` rather than `3` | +| `new(schema?)` | an empty Cad (`"AP214"` by default) | +| `NULL`, `DERIVED`, `SCHEMAS` | `$`, `*`, and the full `FILE_SCHEMA` names of AP203 / AP214 / AP242 | + +```luau +local cad = assert(F.cad.load(stepText)) +local step = assert(F.format("step")) +local placement = cad.entities[step.byType(cad, "AXIS2_PLACEMENT_3D")[1]] +local origin = assert(step.get(cad, placement.args[2])) -- args[2] is { ref = 1 } +assert(origin.type == "CARTESIAN_POINT" and origin.args[1] == "origin") +local axis = step.get(cad, placement.args[3]) +assert(axis.args[2][3] == 1) -- DIRECTION('z', (0., 0., 1.)) + +local unit = cad.entities[6] -- (LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI., .METRE.)) +assert(unit.type == "COMPLEX" and #unit.parts == 3) +local si = assert(step.part(unit, "SI_UNIT")) +assert(si[1].enum == "MILLI" and si[2].enum == "METRE") +assert(step.part(unit, "NAMED_UNIT")[1] == step.DERIVED) + +local name = cad.header.FILE_NAME -- name, time stamp, authors, organisations, ... +assert(name[1] == "part.step") +``` + +## Edit and save + +Edit `entities` / `header` directly, or add instances with `add`. `F.save` writes Part 21 text, one instance per line +in id order. + +| Encode option | Meaning | +|---|---| +| `schema` | `"AP203"`, `"AP214"`, `"AP242"` or a schema name: replaces `FILE_SCHEMA` | +| `name` | the `FILE_NAME` name (default: the header's, else `"model"`) | +| `timestamp` | the `FILE_NAME` time stamp when the header has none | +| `crlf` | CRLF line ends (default LF) | + +```luau +local cad = assert(F.cad.load(stepText)) +local step = assert(F.format("step")) +local coords = step.real(step.real(step.real({ 1, 2, 3 }, 1), 2), 3) -- written (1.,2.,3.) +local id = step.add(cad, "CARTESIAN_POINT", { "corner", coords }) +assert(id == 7) +local text = assert(F.saveString(cad, { schema = "AP242" })) +assert(string.find(text, "#7=CARTESIAN_POINT('corner',(1.,2.,3.));", 1, true)) +assert(string.find(text, "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF", 1, true)) +local back = assert(F.cad.load(text)) +assert(back.schema == "AP242" and back.meta.count == 7) +``` + +A new file from scratch: + +```luau +local step = assert(F.format("step")) +local cad = step.new("AP203") +local p = step.add(cad, "CARTESIAN_POINT", { "p", step.real(step.real(step.real({ 0, 0, 0 }, 1), 2), 3) }) +step.add(cad, "VERTEX_POINT", { "", { ref = p } }) +local text = assert(F.saveString(cad, { format = "step", name = "vertex.step" })) -- built here: no source format +assert(string.find(text, "CONFIG_CONTROL_DESIGN", 1, true) and string.find(text, "#2=VERTEX_POINT('',#1);", 1, true)) +``` + +## B-rep and meshes: the plug-in + +STEP stores solids as boundary representations (faces on surfaces, trimmed by edges on curves). Evaluating them takes +a geometry kernel, which you inject: + + +```luau +F.plugins.brep = { -- brep-luau's modules as they are + Step = require(path.to.brep.Step), + StepBrep = require(path.to.brep.StepBrep), + StepWrite = require(path.to.brep.StepWrite), + Tess = require(path.to.brep.Tess), +} +local cad = assert(F.cad.load(stepBytes)) +local scene = assert(F.cad.tessellate(cad, { chord = 0.05 })) -- a Scene: one node + mesh per solid +local glb = assert(F.save(scene, nil, { format = "glb" })) +local bodies = assert(F.cad.toBodies(cad)) -- the kernel's own body objects +local copy = assert(F.cad.fromBodies(bodies)) -- a Cad written by the kernel +``` + +| Function | Returns | +|---|---| +| `F.cad.toBodies(cad, opts?)` | `bodies, result`: the kernel's bodies, and its whole read result (stats, warnings) | +| `F.cad.fromBodies(bodies, opts?)` | a `Cad` (the kernel writes STEP text, parsed back) | +| `F.cad.tessellate(cad | bodies, opts?)` | a `Scene`: one node and mesh per body, one primitive per face colour, **z up, millimetres** (`meta.unit = 0.001`) | + +Options: `brep` (a plug-in for this call instead of `F.plugins.brep`), `chord` (the tessellation sag in millimetres, +default 0.05) or `tess` (the kernel's own tessellation options). + +Any kernel works if it has this shape (every function may throw; the library catches it and returns `nil, err`): + +| Function | Contract | +|---|---| +| `read(text, opts)` | STEP text -> `{ bodies = { body }, stats = ...? }`; a body may have `name` and `color` (`{ r, g, b }` 0..1) | +| `write(bodies, opts)` | bodies -> STEP text | +| `tessellate(body, opts)` | -> `{ positions = { {x, y, z} }, normals = { ... }?, indices = { 1-based, three per triangle }, faceOf = { [triangle] = face }? }` (a face may have `color`) | + +A minimal stand-in kernel shows the contract (and is handy in tests): every file is one triangle. + +```luau +local fake = { + read = function(text, opts) + return { bodies = { { name = "plate", color = { 1, 0, 0 } } }, stats = { bytes = #text } } + end, + tessellate = function(body, opts) + return { positions = { { 0, 0, 0 }, { 10, 0, 0 }, { 0, 10, 0 } }, indices = { 1, 2, 3 } } + end, +} +local cad = assert(F.cad.load(stepText)) +local none, err = F.cad.tessellate(cad) -- no plug-in installed +assert(none == nil and err.code == F.Err.UNSUPPORTED) + +local scene = assert(F.cad.tessellate(cad, { brep = fake })) +assert(scene.kind == "scene" and scene.meta.up == "z" and scene.meta.unit == 0.001) +assert(scene.meshes[1].name == "plate" and scene.meshes[1].primitives[1].indices.count == 3) +assert(scene.materials[1].extras.color[1] == 1) -- the body colour (baseColor is linear) +local _, werr = F.cad.fromBodies({}, { brep = fake }) -- this kernel cannot write +assert(werr.code == F.Err.UNSUPPORTED) +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| step (`.step .stp .p21`) | yes | yes | editions 1 to 3, complex instances, several DATA sections; B-rep and tessellation through the plug-in | + +STEP-XML (ISO 10303-28) and compressed `.stpZ` are not supported. See [FORMATS.md](../FORMATS.md). + +## Gotchas + +- **Ids are sparse.** `#entities` is meaningless; iterate `step.ids(cad)` (ordered) or `pairs(cad.entities)`. +- **References are tables.** `{ ref = 4 }` is not the entity; resolve it with `step.get(cad, ref)`. +- **Reals vs integers.** Luau has one number type. Values read as reals stay reals when written back; for new + values, mark integral reals with `step.real(list, index)`, or the file will contain `3` where the schema wants `3.`. +- **Complex instances** have `type = "COMPLEX"` and empty `args`; use `step.part(e, "TYPE")` or `e.parts`. +- **Tessellated scenes are z up in millimetres.** Convert for y-up engines with `F.ops.mesh.setUp(scene, "y")` and + `F.ops.mesh.setUnit(scene, 1)` (see [Scene](scene.md)). diff --git a/docs/guide/data.md b/docs/guide/data.md new file mode 100644 index 0000000..3b40019 --- /dev/null +++ b/docs/guide/data.md @@ -0,0 +1,356 @@ +# Data + +The data formats (JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist) decode to plain Luau values: tables, +strings, numbers, booleans. Three helpers fill the gaps Luau tables leave: `F.data.null` (a null that can sit in a +table), ordered objects (`F.Types.object`: key order, and `{}` that stays an object), and `F.Types.Date` (TOML, +YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. + +```luau +local v = assert(F.data.load('{"name": "ada", "tags": ["x", "y"], "boss": null}')) +assert(v.name == "ada" and v.tags[2] == "y") +assert(v.boss == F.data.null) -- JSON null is a sentinel, not nil + +v.level = 3 +local json = assert(F.saveString(v, { format = "json" })) +assert(json == '{"boss":null,"level":3,"name":"ada","tags":["x","y"]}') -- plain tables: keys sorted + +local yaml = assert(F.convert('{"a": [1, 2]}', "yaml", { format = "json" })) -- opts.format: the input's format +assert(buffer.tostring(yaml) == "a:\n - 1\n - 2\n") +``` + +## Values + +| Data | Luau value | +|---|---| +| object / map / table / dict | a table with string keys; maps of MessagePack / CBOR can have any key type | +| array / sequence / list | an array `{ ... }` (1-based) | +| string | string (UTF-8) | +| number | number (one type: integers and floats are both doubles; integers past 2^53 lose precision unless `bigInts = "string"`) | +| true / false | boolean | +| null (`null`, `~`, CBOR `null`, msgpack `nil`) | `F.data.null` (same as `F.null`; `tostring` gives `"null"`) | +| bytes (msgpack bin, CBOR byte string, plist ``, YAML `!!binary`) | `buffer` | +| date / time (TOML, YAML `!!timestamp`, plist ``, CBOR tags 0 / 1, msgpack timestamp) | `F.Types.Date` | + +Decoders give objects as `F.Types.object` tables when the key order is known: always for YAML, TOML, INI, CSV +(`header = true`), MessagePack, CBOR and plist; for JSON only empty objects, unless `ordered = true`. Encoders write +an object's keys in that order; plain tables are written with their keys sorted. + +## Ordered objects and empty tables + +```luau +local Types = F.Types +local o = Types.object() -- an empty object: writes as {} (a plain {} writes as []) +Types.set(o, "zeta", 1) -- assigns and records the key order +Types.set(o, "alpha", 2) +o.later = 3 -- plain assignment works too; keys not in the order come last, sorted +assert(table.concat(Types.keys(o), ",") == "zeta,alpha,later") +assert(Types.isObject(o) and not Types.isObject({})) +assert(F.saveString(o, { format = "json" }) == '{"zeta":1,"alpha":2,"later":3}') + +local keep = assert(F.data.load('{"b": 1, "a": 2}', { ordered = true })) +assert(F.saveString(keep, { format = "json" }) == '{"b":1,"a":2}') + +assert(F.saveString({}, { format = "json" }) == "[]") +assert(F.saveString(Types.object(), { format = "json" }) == "{}") +assert(F.saveString({}, { format = "json", emptyTable = "object" }) == "{}") +``` + +`Types.object(t, keys)` marks an existing table and gives its order; `Types.keys(t)` works on any table (plain +tables: sorted, numbers before strings). + +## Dates + +`F.Types.Date` values are tables with a metatable (`tostring` gives RFC 3339; `==` compares them). + +| Field | Meaning | +|---|---| +| `kind` | `"datetime"` (has an offset: an instant), `"datetime-local"`, `"date-local"`, `"time-local"` | +| `year`, `month`, `day` | the date (month 1..12, day 1..31) | +| `hour`, `minute`, `second` | the time of day | +| `nanosecond` | 0 .. 999999999 | +| `offset` | minutes east of UTC (`-480` = `-08:00`); nil for local kinds | + +```luau +local Date = F.Types.Date +local d = assert(Date.parse("1979-05-27T07:32:00-08:00")) +assert(d.kind == "datetime" and d.offset == -480 and d.hour == 7) +assert(Date.toUnix(d) == 296667120) -- seconds since 1970-01-01T00:00:00Z +assert(tostring(Date.fromUnix(0)) == "1970-01-01T00:00:00Z") +assert(Date.new({ year = 2026, month = 3, day = 4 }).kind == "date-local") +assert(Date.is(d) and Date.valid(d)) +assert(Date.parse("2026-02-30") == nil) -- out-of-range fields +``` + +## Load + +`F.data.load(src, opts?)` or `F.load(src, opts)`; `src` is a string, a buffer or (on hosts with files) a path. Text +formats sniff weakly (YAML, TOML and INI look alike; MessagePack and CBOR without its self-describe tag have no magic), +so pass `format` (a name or extension) unless the data comes from a named file: + +```luau +local cfg = assert(F.data.load('title = "x"\n[server]\nport = 8080\n', { format = "toml" })) +assert(cfg.server.port == 8080) + +local msg = assert(F.data.load(msgpackBytes, { format = "msgpack" })) +assert(msg.name == "ada" and msg.none == F.data.null) +assert(typeof(msg.raw) == "buffer" and buffer.len(msg.raw) == 3) -- bin -> buffer + +local bad, err = F.data.load("{bad", { format = "json" }) +assert(bad == nil and err.code == F.Err.CORRUPT) +print(tostring(err)) -- json: CORRUPT at 0x1: expected a key +``` + + +```luau +local scores = assert(F.load("assets/scores.csv", { header = true, numbers = true })) -- the extension decides +assert(scores[1].name == "ada" and scores[1].score == 1200) +``` + +## JSON + +| Option | Direction | Meaning | +|---|---|---| +| `ordered` | decode | every object as a `Types.object` with its key order | +| `bigInts` | decode | `"string"`: integers past 2^53 stay their exact text | +| `null` | decode | the value used for null (default `F.data.null`) | +| `lines` | both | JSON Lines: an array of values, one per line | +| `indent` | encode | pretty print: spaces per level, or the indent string | +| `sortKeys` | encode | plain tables' keys sorted (default `true`) | +| `emptyTable` | encode | `"array"` (default) or `"object"` for a plain `{}` | +| `ascii` | encode | escape non-ASCII as `\uXXXX` | +| `nan` | encode | `"error"` (default) or `"null"` for NaN / inf | + +```luau +local v = assert(F.data.load('{"a": [1, 2.5, null, true], "e": {}}')) +local pretty = assert(F.saveString(v, { format = "json", indent = 2 })) +assert(string.find(pretty, '\n "a": [\n 1,', 1, true)) + +local rows = assert(F.data.load('{"id": 1}\n{"id": 2}\n', { format = "json", lines = true })) +assert(#rows == 2 and rows[2].id == 2) +assert(F.saveString(rows, { format = "json", lines = true }) == '{"id":1}\n{"id":2}\n') +``` + +## XML + +XML decodes to a `"#document"` node; `doc.root` is the root element. + +| `XmlNode` field | Type | Meaning | +|---|---|---| +| `name` | string | the qualified element name (`"svg:rect"`), or `"#document"`, `"#comment"`, `"#cdata"`, `"#pi"`, `"#doctype"` | +| `attrs` | `Types.object` of strings | attributes, in document order | +| `children` | `{ XmlNode \| string }` | child nodes; text is plain strings | +| `parent` | XmlNode? | the parent (unless `parents = false`) | +| `text` | string? | the content of comment / CDATA / PI / doctype nodes | +| `target` | string? | a PI's target | +| `ns` | string? | the element's namespace URI (with `namespaces = true`) | +| `root`, `declaration`, `doctype` | | on the document: the root element, `{ version, encoding, standalone }`, `{ name, publicId, systemId, ... }` | + +Decode options: `comments`, `cdata`, `pi` (keep those nodes; by default comments and PIs are dropped and CDATA +merges into the text), `whitespace` (keep whitespace-only text), `namespaces`, `entities` (extra named entities), +`maxDepth`. Encode options: `indent`, `declaration` (default true for a document), `selfClose` (default true). + +```luau +local doc = assert(F.data.load([[ +Dune classic]], + { format = "xml", comments = true })) +local lib = doc.root +assert(lib.name == "library" and #lib.children == 3) + +local function text(node) -- all character data below a node + local out = {} + for _, c in node.children do + table.insert(out, if type(c) == "string" then c else text(c)) + end + return table.concat(out) +end +local book = lib.children[1] +assert(book.attrs.id == "b1" and text(book) == "Dune classic") +assert(table.concat(F.Types.keys(book.attrs), ",") == "id,lang") -- attribute order kept +assert(lib.children[2].name == "#comment" and lib.children[2].text == " shelf 2 ") + +-- edit: add an element, then write the document back +local new = { name = "book", attrs = F.Types.object({ id = "b3" }, { "id" }), children = { "Emma" } } +table.insert(lib.children, new) +local xml = assert(F.saveString(doc, { format = "xml" })) +assert(string.find(xml, 'Emma', 1, true)) +``` + +## YAML + +Maps decode to `Types.object`, `~` / `null` to `F.data.null`; anchors and aliases become shared tables (the same +Luau table twice). Decode options: `all` (every document of a multi-document stream, as an array), `tags` +(`"ignore"` resolves unknown tags as untagged), `null`, `maxAliasNodes` (the alias-bomb guard), `maxDepth`. Encode +options: `indent` (default 2), `all`, `explicitStart`, `sortKeys`. Shared tables are written as anchors. + +```luau +local y = assert(F.data.load("base: &b {color: red}\nitem: *b\nlist: [1, two, ~]\n", { format = "yaml" })) +assert(y.item == y.base and y.item.color == "red") +assert(y.list[3] == F.data.null) + +local docs = assert(F.data.load("---\nname: a\n---\nname: b\n", { format = "yaml", all = true })) +assert(#docs == 2 and docs[2].name == "b") +local out = assert(F.saveString(y, { format = "yaml" })) +assert(string.find(out, "base: &", 1, true) and string.find(out, "item: *", 1, true)) +``` + +YAML 1.2 core schema: `yes` / `no` / `on` / `off` are strings, not booleans. + +## TOML + +Tables decode to `Types.object` (file order kept), datetimes to `Types.Date` (all four kinds). Decode option: +`bigInts`. Encode options: `inline` (every sub-table inline), `indent` (indent keys of nested sections). + +```luau +local cfg = assert(F.data.load([=[ +title = "demo" +[server] +port = 8080 +started = 1979-05-27T07:32:00-08:00 +[[users]] +name = "ada" +[[users]] +name = "bob" +]=], { format = "toml" })) +assert(cfg.server.port == 8080 and #cfg.users == 2) +assert(F.Types.Date.is(cfg.server.started) and tostring(cfg.server.started) == "1979-05-27T07:32:00-08:00") + +cfg.server.port = 9090 +local text = assert(F.saveString(cfg, { format = "toml" })) +assert(string.find(text, "[server]\nport = 9090", 1, true)) +``` + +## CSV + +Rows decode to arrays of strings; with `header = true` the first row names the columns and every other row is a +`Types.object` keyed by them (column order kept). Fields are strings unless `numbers = true`. + +| Option | Direction | Meaning | +|---|---|---| +| `header` | both | decode: rows as records; encode (records): write the header row (default true) | +| `numbers` | decode | numeric fields become numbers | +| `delimiter` | both | one byte (default `","`; decode also `"auto"`: picks among `,` `;` tab `\|`) | +| `quote` | both | the quote byte (default `"`) | +| `maxRows` | decode | refuse more rows | +| `newline` | encode | row terminator (default `"\r\n"`) | +| `quoteAll` | encode | quote every field | +| `columns` | encode | record column order (default: first-seen) | + +```luau +local rows = assert(F.data.load(csvText, { format = "csv" })) +assert(rows[1][1] == "name" and rows[4][1] == "lee, jr") -- quoted field with a comma + +local recs = assert(F.data.load(csvText, { format = "csv", header = true, numbers = true })) +assert(#recs == 3 and recs[2].name == "bob" and recs[2].score == 950) + +table.insert(recs, F.Types.object({ name = "cy", score = 10, level = 1 }, { "name", "score", "level" })) +local out = assert(F.saveString(recs, { format = "csv", newline = "\n" })) +assert(string.sub(out, 1, 17) == "name,score,level\n") +assert(string.find(out, '"lee, jr",400,1\ncy,10,1\n', 1, true)) + +local tsv = assert(F.saveString({ { "a", "b" }, { "1", "2" } }, { format = "csv", delimiter = "\t" })) +assert(tsv == "a\tb\r\n1\t2\r\n") +``` + +## INI + +A `Types.object` of sections, each a `Types.object` of string values; keys before the first section sit at the top +level. Decode options: `types` (numbers and `true` / `false` / `yes` / `no` / `on` / `off` become numbers / booleans), +`inlineComments` (strip ` ;...` / ` #...`), `allowNoValue`, `strict` (duplicates are errors). Encode option: +`delimiter` (default `" = "`). + +```luau +local ini = assert(F.data.load("top = 1\n[server]\nhost = example.com\nport = 80\n", { format = "ini" })) +assert(ini.top == "1" and ini.server.port == "80") -- strings by default +local typed = assert(F.data.load("[s]\nport = 80\ndebug = yes\n", { format = "ini", types = true })) +assert(typed.s.port == 80 and typed.s.debug == true) +local text = assert(F.saveString(ini, { format = "ini" })) +assert(string.find(text, "[server]\nhost = example.com\n", 1, true)) +``` + +## MessagePack, CBOR + +Both decode maps to `Types.object` (any key type), bin / byte strings to buffers, timestamps (msgpack ext -1, CBOR +tags 0 / 1) to `Types.Date`. Decode options: `all` (a stream of concatenated values, as an array), `bigInts`, +`null`, `maxDepth`; msgpack `timestamps` / `ordered` (default true), CBOR `dates` (default true). Encode options: +`all`, `sortKeys`, `emptyTable` (`"array"` or `"map"`); msgpack `float32`, `stringsAsBin`; CBOR `compactFloats`, +`dates` (`"string"` or `"epoch"`), `selfDescribe` (prefix tag 55799, which also makes the bytes detectable). + +```luau +local c = assert(F.data.load(cborBytes, { format = "cbor" })) +assert(c.name == "ada" and c.ratio == 0.5 and c.tags[1] == "x") + +local packed = assert(F.save({ id = 7, blob = buffer.fromstring("\0\1") }, nil, { format = "msgpack" })) +local back = assert(F.data.load(packed, { format = "msgpack" })) +assert(back.id == 7 and buffer.len(back.blob) == 2) + +local tagged = assert(F.save({ when = F.Types.Date.fromUnix(0) }, nil, { format = "cbor", selfDescribe = true })) +assert(F.detect(tagged) == "cbor") +assert(F.data.load(tagged).when.year == 1970) +``` + +Extension and tag values without a mapping keep their type: `F.format("msgpack").ext(type, data)` / +`isExt(v)`; `F.format("cbor").tagged(tag, value)`, `isTagged`, `simple(n)`, `undefined`. + +## Plist + +XML and binary (`bplist00`) plists load; writing is XML. `dict` is a `Types.object`, `` a `Types.Date`, +`` a buffer, binary UIDs `F.format("plist").uid(n)` values. Decode option: `bigInts`; encode option: +`sortKeys` (plain tables). + +```luau +local p = assert(F.data.load(bplistBytes)) -- binary plists are detected +assert(p.CFBundleName == "Demo" and p.Version == 3 and p.Beta == false) +assert(p.Built.year == 2026 and typeof(p.Icon) == "buffer") +local xml = assert(F.saveString(p, { format = "plist" })) +assert(string.find(xml, "CFBundleName\n\tDemo", 1, true)) +``` + +## Save and convert + +Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too): +`F.save(value, nil, { format = "json" })` returns a buffer, `F.saveString` a string. `F.convert(src, format, opts)` +loads with `opts` (where `opts.format` names the input's format) and saves as `format` with the same options; a file +name hint (`name = "in.json"`) also names the input: + +```luau +local yaml = assert(F.convert('{"name": "ada", "tags": ["x"]}', "yaml", { name = "in.json" })) +local v = assert(F.data.load(yaml, { format = "yaml" })) +assert(v.name == "ada" and v.tags[1] == "x") + +local toml = assert(F.saveString(v, { format = "toml" })) +local mp = assert(F.save(v, nil, { format = "msgpack" })) +assert(F.data.load(mp, { format = "msgpack" }).tags[1] == "x") +``` + +What survives a conversion: everything maps across except types a target lacks. TOML has no null (`F.data.null` +is an error there), CSV needs rows, INI needs sections of scalars, JSON has no bytes or dates (encode them yourself: +`tostring(date)`), plist cannot hold null. + +## Formats + +| Format | Read | Write | Decodes to | +|---|---|---|---| +| json (`.json`, `.jsonl`, `.ndjson`, `.geojson`) | yes | yes | values; objects plain (or ordered) | +| xml (`.xml`, `.xsd`, `.rss`, `.atom`, `.xhtml`, ...) | yes | yes | `#document` XmlNode tree | +| yaml (`.yaml`, `.yml`) | yes | yes | values, ordered maps, shared aliases | +| toml (`.toml`) | yes | yes | ordered tables, Dates | +| csv (`.csv`, `.tsv`) | yes | yes | rows (arrays or records) | +| ini (`.ini`, `.cfg`, `.conf`, `.desktop`) | yes | yes | sections of strings | +| msgpack (`.msgpack`, `.mpk`) | yes | yes | values, buffers, Dates | +| cbor (`.cbor`) | yes | yes | values, buffers, Dates, tagged values | +| plist (`.plist`) | XML + binary | XML | values, buffers, Dates | + +Full capability list: [FORMATS.md](../FORMATS.md). + +## Gotchas + +- `nil` cannot sit in a table: check `v == F.data.null`, not `v == nil`, for JSON / YAML / CBOR nulls. Assigning + `nil` removes the key (it is not written). +- Luau has one number type: `1.0` reads back as `1`, and TOML / plist write integral floats as integers. Integers + past 2^53 need `bigInts = "string"` to survive. +- An empty plain table `{}` is written as an array; use `F.Types.object()` (or `emptyTable = "object"`) for `{}`. +- Text formats sniff weakly: give `format` (or a file name) for YAML, TOML, INI, CSV, MessagePack and CBOR without + its self-describe tag. +- XML whitespace-only text between elements is dropped by default (`whitespace = true` keeps it); text is never + trimmed otherwise. +- YAML aliases are shared tables: editing `y.item` also edits `y.base`. diff --git a/docs/guide/font.md b/docs/guide/font.md new file mode 100644 index 0000000..f6590d3 --- /dev/null +++ b/docs/guide/font.md @@ -0,0 +1,246 @@ +# Fonts + +Every font format loads as one `Font`: metrics, a character map, advances, kerning and glyph images. Outline fonts +(TrueType / OpenType `.ttf` / `.otf` / `.ttc`, WOFF, WOFF2) also give glyph outlines and rasterize at any size. +Bitmap fonts (AngelCode BMFont `.fnt`) crop their glyphs from page images. Fonts are read-only except BMFont, which is +also how an outline font is *baked* into a texture atlas for a game. + +```luau +local font = assert(F.font.load(ttfBytes)) +print(font.info.family, font.unitsPerEm) -- DejaVu Sans 2048 +local g = font:glyphIndex(string.byte("A")) -- code point -> glyph index (0 = .notdef, missing) +local img = assert(font:rasterize(g, 32)) -- an alpha8 Image, 32 px per em +print(img.width, img.height, img.meta.advance) -- 22 24 21.89 +assert(img.format == "alpha8") +``` + +## The type + +`Font`: + +| Field / method | Type | Meaning | +|---|---|---| +| `kind` | `"font"` | | +| `info` | table | `family`, `style`, `fullName`; outline fonts add the other `name` table strings (`postScriptName`, `version`, `copyright`, `license`, ...) | +| `unitsPerEm` | number | font units per em (TrueType: usually 1000 or 2048; BMFont: the size in pixels) | +| `ascent`, `descent`, `lineGap` | number | font units; `descent` is negative (below the baseline) | +| `numGlyphs` | number | glyph indices run `0 .. numGlyphs - 1` | +| `glyphIndex(self, cp)` | number | the glyph for a Unicode code point, `0` when the font has none | +| `advance(self, g)` | number | the horizontal advance (font units) | +| `kern(self, a, b)` | number | the kerning between glyphs `a` and `b` (font units, usually negative); `'kern'` table and GPOS pairs | +| `outline(self, g)` | `{ cmd }?` | the glyph's outline (outline fonts), `nil` for a bitmap font or a bad glyph | +| `rasterize(self, g, px)` | `Image?` | the glyph as an `alpha8` Image (below) | +| `pages` | `{ Image }?` | BMFont: the page images once loaded | +| `meta` | table | `source.format`; outline fonts: `outlines` (`"truetype"` / `"cff"`), `tables`, `os2`, `italicAngle`, `underlinePosition`, `fixedPitch`, `collection`; BMFont: `lineHeight`, `base`, `pageFiles`, `bmfont` (the parsed descriptor) | + +Outline fonts also have `font:bounds(g)` (`xMin, yMin, xMax, yMax` in font units, `nil` for an empty glyph), +`font:kernCodepoints(a, b)`, `font:leftSideBearing(g)` and `font:scale(px)` (pixels per font unit, `px / unitsPerEm`). + +**Units and directions.** Font units are the design grid: multiply by `px / unitsPerEm` to get pixels for a font +size of `px` pixels per em. In font units y points **up** from the baseline. Rasterized images are ordinary images, +rows top to bottom. + +### Outlines + +`outline(g)` returns a list of commands, each `{ op = name, x1, y1, ... }` with absolute coordinates in font units: + +| `op` | Numbers | Meaning | +|---|---|---| +| `"moveTo"` | `x, y` | start a contour | +| `"lineTo"` | `x, y` | straight line | +| `"quadTo"` | `cx, cy, x, y` | quadratic Bézier (TrueType outlines) | +| `"cubicTo"` | `c1x, c1y, c2x, c2y, x, y` | cubic Bézier (CFF / OpenType outlines) | +| `"close"` | | close the contour | + +TrueType fills by the nonzero rule, outer contours clockwise. + +```luau +local font = assert(F.font.load(ttfBytes)) +local cmds = assert(font:outline(font:glyphIndex(string.byte("A")))) +assert(cmds[1].op == "moveTo") +local x0, y0, x1, y1 = font:bounds(font:glyphIndex(string.byte("A"))) +assert(y0 == 0 and y1 > 0) -- y up: the A stands on the baseline +local counts = {} +for _, c in cmds do + counts[c.op] = (counts[c.op] or 0) + 1 +end +print(counts.moveTo, counts.lineTo, counts.close) -- 2 contours of straight lines +local _ = x0, x1 +``` + +### Rasterized glyphs + +`rasterize(g, px)` renders the glyph antialiased at `px` pixels per em (the CSS `font-size`, not the line height). +The result is an `alpha8` Image (one coverage byte per pixel, 0 to 255, rows top to bottom), cropped to the ink, with +the placement in `meta`: + +| `meta` field | Meaning (pixels) | +|---|---| +| `left` | from the pen position to the image's left edge | +| `top` | from the baseline **up** to the image's top row (as FreeType's `bitmap_top`) | +| `advance` | how far to move the pen afterwards (fractional) | +| `glyph` | the glyph index | + +Glyphs without ink (the space) give a 0 x 0 image that still has `meta.advance`. Outline fonts take an optional third +argument `{ scaleX, scaleY, shiftX, shiftY }` (pixels per font unit and a subpixel shift) for stretched or +subpixel-positioned glyphs. + +```luau +local font = assert(F.font.load(ttfBytes)) +local space = assert(font:rasterize(font:glyphIndex(32), 16)) +assert(space.width == 0 and space.meta.advance > 0) +assert(font:glyphIndex(0x4E00) == 0) -- no CJK in this font: .notdef +``` + +## Drawing a string + +Place each glyph at the pen position, move the pen by the advance plus the kerning, and draw the coverage onto an +image. `F.ops.image.blit` converts an `alpha8` glyph to white with that alpha and blends it "over" the canvas: + +```luau +local font = assert(F.font.load(ttfBytes)) +local px = 24 +local scale = px / font.unitsPerEm +local text = "AVA Hello" +local width = 0 +local prev = nil +for _, cp in utf8.codes(text) do -- measure: advances + kerning, in font units + local g = font:glyphIndex(cp) + width += font:advance(g) + (if prev then font:kern(prev, g) else 0) + prev = g +end +local baseline = math.ceil(font.ascent * scale) +local canvas = assert(F.ops.image.new(math.ceil(width * scale) + 2, math.ceil((font.ascent - font.descent) * scale))) +F.ops.image.fill(canvas, 20, 20, 40, 255) + +local pen = 1 +prev = nil +for _, cp in utf8.codes(text) do + local g = font:glyphIndex(cp) + if prev then + pen += font:kern(prev, g) * scale -- "AV" moves closer + end + local glyph = assert(font:rasterize(g, px)) + if glyph.width > 0 then + F.ops.image.blit(canvas, glyph, math.floor(pen + glyph.meta.left + 0.5), baseline - glyph.meta.top) + end + pen += glyph.meta.advance + prev = g +end +assert(font:kern(font:glyphIndex(65), font:glyphIndex(86)) < 0) +local png = assert(F.save(canvas, nil, { format = "png" })) +local _ = png +``` + +This is simple left-to-right layout: no shaping (ligatures, Arabic joining, combining marks) and no line breaking. + +## Load + +```luau +local ttf = assert(F.font.load(ttfBytes)) -- TrueType +local woff = assert(F.font.load(woffBytes)) -- WOFF 1 (zlib tables) +local woff2 = assert(F.font.load(woff2Bytes)) -- WOFF 2 (Brotli + glyf / loca / hmtx transforms) +assert(woff.info.family == ttf.info.family and woff2.numGlyphs == ttf.numGlyphs) +assert(woff.meta.source.format == "woff" and woff2.meta.source.format == "woff2") +``` + +| Option | Format | Meaning | +|---|---|---| +| `index` | ttf | which font of a collection (`.ttc` / `.otc`), 0-based (default 0); `F.format("ttf").count` gives the count | +| `pages` | bmfont | the page images, if you have them already (page 0 first) | +| `loadPage` | bmfont | `function(file, page) -> Image | buffer | string`: loads a page lazily, the first time a glyph needs it | + +## BMFont + +A BMFont is a descriptor (text, XML or binary `.fnt`) plus page images that hold the glyphs. The descriptor names the +page files (`meta.pageFiles`). Metrics are in **pixels**: `unitsPerEm` is the size the font was baked at, and +`advance`, `kern`, `ascent` and `descent` are pixels too. `outline` returns `nil`. `rasterize(g)` crops the glyph from its page +as `alpha8` (it ignores `px`; `meta.scale = px / unitsPerEm` tells you how much to scale). + +The pages load lazily: through `opts.loadPage`, through `opts.pages`, through `font:loadPages(loader)`, or, when the +font was loaded from a path, from the files next to the `.fnt`. Without any of these, `rasterize` returns `nil`. + +```luau +local bm = assert(F.font.load(fntText, { + loadPage = function(file, page) + assert(file == "mini_0.png" and page == 0) + return fntPageBytes -- an Image, or the encoded bytes + end, +})) +assert(bm.meta.source.format == "bmfont" and bm.meta.lineHeight == 9) +local a, b = bm:glyphIndex(65), bm:glyphIndex(66) +assert(bm:advance(a) == 7 and bm:kern(a, b) == -1) -- pixels +local glyph = assert(bm:rasterize(b)) -- loads page 0 now +assert(glyph.format == "alpha8" and glyph.width == 6 and glyph.height == 7) +assert(buffer.readu8(glyph.pixels, 0) == 255) -- the B's outline +``` + +```luau +local bm = assert(F.font.load(fntText)) -- no loader: the pages are not available yet +assert(bm:rasterize(bm:glyphIndex(65)) == nil) +assert(bm:loadPages(function(file) return F.image.load(fntPageBytes) end)) +assert(#bm.pages == 1 and bm:rasterize(bm:glyphIndex(65))) +``` + + +```luau +local bm = assert(F.font.load("assets/mini.fnt")) -- a path: mini_0.png is read from the same folder on demand +assert(bm:rasterize(bm:glyphIndex(65))) +``` + +### Baking a TTF into a BMFont + +`F.format("bmfont").bake(font, opts)` rasterizes the characters of any outline font and packs them into pages. It +returns a BMFont `Font` whose `pages` are `rgba8` Images (white, coverage in alpha) and whose `meta.pageFiles` are +the page file names. Kerning pairs between the baked characters are kept, rounded to pixels. + +| Option | Default | Meaning | +|---|---|---| +| `px` | 32 | pixels per em | +| `chars` | printable ASCII 32..126 | a string, or a list of code points | +| `pageSize` | smallest power of two that fits (up to 4096) | page width and height | +| `padding` | 1 | empty pixels around each glyph | +| `file` | `"font"` | page file name prefix: pages are `_.png` | + +Save the descriptor with `F.save` (`variant` = `"text"`, `"xml"` or `"binary"`) and each page as a PNG under its +file name: + +```luau +local ttf = assert(F.font.load(ttfBytes)) +local baked = assert(F.format("bmfont").bake(ttf, { px = 16, chars = "Hello, world!", file = "ui" })) +local fnt = assert(F.saveString(baked)) -- the text descriptor (bake gives variant "text") +assert(string.find(fnt, 'page id=0 file="ui_0.png"', 1, true)) +local files = { ["ui.fnt"] = fnt } +for i, page in baked.pages do + files[baked.meta.pageFiles[i]] = assert(F.save(page, nil, { format = "png" })) +end +local bin = assert(F.save(baked, nil, { variant = "binary" })) +local again = assert(F.font.load(bin, { pages = baked.pages })) +assert(again:advance(again:glyphIndex(string.byte("H"))) == baked:advance(baked:glyphIndex(string.byte("H")))) +``` + +`F.save(ttf, nil, { format = "bmfont", px = 16 })` bakes too, but returns only the descriptor: the page images are +not written anywhere. Use `bake` when you need the pages. + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| ttf (`.ttf .otf .ttc .otc`) | yes | - | TrueType and CFF outlines, collections, `kern` and GPOS pair kerning | +| woff | yes | - | | +| woff2 | yes | - | | +| bmfont (`.fnt`) | yes | yes | text, XML and binary descriptors; `bake` from any outline font | + +See [FORMATS.md](../FORMATS.md) for the capability matrix. + +## Gotchas + +- **No hinting, no shaping.** Glyphs are rendered from the outlines without hinting; there is no GSUB (ligatures, + contextual forms), no variable fonts (CFF2 / gvar return `UNSUPPORTED`) and no colour or bitmap glyphs. +- **`px` is the em size**, not the line height. The line height is `(ascent - descent + lineGap) * px / unitsPerEm`. +- **Units differ by kind.** Outline fonts measure in font units; BMFont in pixels at its baked size. Use + `font.unitsPerEm` for both: for a BMFont, `px / unitsPerEm` is the scale relative to the baked size. +- **Missing characters** map to glyph 0 (`.notdef`, usually an empty box); check `glyphIndex(cp) ~= 0`. +- **Fonts are read-only** except BMFont descriptors; `F.save(ttf)` returns `UNSUPPORTED` and suggests `bmfont`. +- **Per-glyph methods never throw**: a broken glyph gives `nil` from `outline` / `rasterize` (the reason is in + `font.meta.lastError`). diff --git a/docs/guide/image.md b/docs/guide/image.md new file mode 100644 index 0000000..4d85bc0 --- /dev/null +++ b/docs/guide/image.md @@ -0,0 +1,245 @@ +# Images + +Every image format (PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO / CUR, PNM / PAM / PFM, Radiance HDR) loads +as one `Image`: a width, a height, a pixel format and one tightly packed `buffer`. Animations (GIF, APNG, animated +WebP) and multi-image files (TIFF pages, ICO entries) add a list of `Frame`s. Editing goes through `F.ops.image`. + +```luau +local img = assert(F.image.load(pngBytes)) -- buffer, string, or a path on hosts with files +print(img.width, img.height, img.format) -- 64 48 rgba8 +local thumb = assert(F.ops.image.resize(img, 32, 24, "lanczos")) +local jpg = assert(F.save(thumb, nil, { format = "jpeg", quality = 85 })) +assert(F.detect(jpg) == "jpeg") +``` + +## The type + +`Image` + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"image"` | | +| `width`, `height` | number | pixels, both >= 1 for decoded images | +| `format` | string | the pixel format (below); decoders give `"rgba8"` unless `opts.native` asks otherwise | +| `pixels` | buffer | rows top to bottom, pixels left to right, no padding between rows | +| `frames` | `{ Frame }?` | animations / pages / icon entries; `nil` for a still image | +| `loops` | number | play count of an animation: `0` = forever, `1` = once, `n` = n plays | +| `meta` | table | `source` (`{ format, bitDepth?, colorType?, ... }`), and when the file has them: `icc` (buffer), `exif` (buffer, from the TIFF header on), `dpi` (`{ x, y }`), `palette` (`{ { r, g, b, a } }`), `text` (`{ [key]: string }`), `orientation` (JPEG EXIF, 1..8) | + +Pixel formats (`F.Types.BPP[format]` is the bytes per pixel): + +| `format` | Bytes / pixel | Layout of one pixel | Range | +|---|---|---|---| +| `rgba8` | 4 | R, G, B, A bytes | 0..255, straight (not premultiplied) alpha | +| `rgb8` | 3 | R, G, B | 0..255 | +| `gray8` | 1 | luma | 0..255 | +| `graya8` | 2 | luma, alpha | 0..255 | +| `alpha8` | 1 | alpha (glyph coverage) | 0..255 | +| `gray16` | 2 | luma, u16 little endian | 0..65535 | +| `rgba16` | 8 | R, G, B, A as u16 little endian | 0..65535 | +| `rgbaf32` | 16 | R, G, B, A as f32 little endian | linear, 0..1 nominal (HDR may exceed 1) | +| `yuv420p` | planar | Y plane `w * h`, then U and V planes `ceil(w/2) * ceil(h/2)` each | BT.601 full range unless `meta.yuv` says otherwise | + +For a packed format the pixel `(x, y)` (0-based, origin top left) starts at byte `(y * width + x) * bpp`: + +```luau +local img = assert(F.load(pngBytes)) +local x, y = 10, 5 +local o = (y * img.width + x) * 4 -- rgba8 +local r, g, b, a = buffer.readu8(img.pixels, o), buffer.readu8(img.pixels, o + 1), + buffer.readu8(img.pixels, o + 2), buffer.readu8(img.pixels, o + 3) +assert(buffer.len(img.pixels) == img.width * img.height * 4) +assert(select(1, F.ops.image.getPixel(img, x, y)) == r) -- the same pixel, through ops +local _ = g + b + a +``` + +`Frame` (one entry of `img.frames`) + +| Field | Type | Meaning | +|---|---|---| +| `image` | Image | the frame's own rectangle (not the full canvas) | +| `x`, `y` | number | where that rectangle sits on the `width x height` canvas | +| `delay` | number | seconds the frame stays on screen | +| `dispose` | `"none"` / `"background"` / `"previous"` | what happens to the frame's rectangle before the next frame: keep it, clear it to transparent, or restore what was there before | +| `blend` | `"source"` / `"over"` | replace the canvas pixels, or alpha-composite over them | + +For an animation, `img.pixels` is the first frame already composited onto the canvas, so code that ignores `frames` +still gets a sensible still image. `F.ops.image.coalesce(img)` composites every frame for you: + +```luau +local gif = assert(F.load(gifBytes)) +print(#gif.frames, gif.loops) -- 3 0 (forever) +local canvases = assert(F.ops.image.coalesce(gif)) -- { Image }: full width x height rgba8, one per frame +assert(#canvases == 3 and canvases[2].width == gif.width) +local delays = F.ops.image.durations(gif) -- { 0.1, 0.1, 0.1 } +assert(F.ops.image.frameCount(gif) == 3 and delays[1] == 0.1) +``` + +Make an image from scratch with `F.Types.Image.new(w, h, format?)` (zero-filled, so transparent black) or +`F.ops.image.new`: + +```luau +local img = F.Types.Image.new(16, 16) -- rgba8 +F.ops.image.fill(img, 255, 128, 0) -- opaque orange (alpha defaults to opaque) +F.ops.image.setPixel(img, 0, 0, 0, 0, 0, 0) -- one transparent pixel +local png = assert(F.save(img, nil, { format = "png" })) +assert(F.load(png).width == 16) +``` + +## Load + +```luau +local img, err = F.load(pngBytes) -- any category: detected from the content +local same = F.image.load(pngBytes) -- restricted to image formats +local jpg = F.image.load(jpegBytes, { scale = 2 }) -- JPEG: decode at half size (2, 4 or 8) +assert(jpg.width == 32) +local tooBig, lerr = F.load(pngBytes, { maxPixels = 100 }) +assert(tooBig == nil and lerr.code == F.Err.LIMIT) +local _ = img and same and err +``` + +| Option | Formats | Meaning | +|---|---|---| +| `format` | all | decode as this format (name or extension) instead of sniffing | +| `maxPixels` | all | refuse larger images with `Err.LIMIT` (default `2^26`) | +| `native` | JPEG, WebP, TIFF, PNM, QOI, TGA, HDR | keep the source layout: `gray8` / `gray16` / `rgb8` / `rgba16` / `rgbaf32` / `yuv420p` (lossy WebP) instead of `rgba8` | +| `scale`, `orient` | JPEG | reduced-size decode; apply the EXIF orientation (`meta.orientation` reports it either way) | +| `coalesce`, `frames` | WebP | every frame as a full canvas; `frames = false` decodes only the first | +| `page`, `maxPages` | TIFF | decode one page (1-based); cap on pages in `frames` | +| `maxFrames` | GIF | cap on frames | + +To read only the header, use the format module's `info` on a reader (no pixels are decoded): + +```luau +local info = assert(F.format("png").info(F.Bytes.reader(pngBytes))) +assert(info.width == 64 and info.height == 48 and info.bitDepth == 8) +``` + +## Edit with `F.ops.image` + +Every function returns a new Image (or `nil, err`) unless it says "in place". Inputs may be any pixel format; +geometric operations on `yuv420p` go through rgba8. + +```luau +local img = assert(F.load(pngBytes)) +local ops = F.ops.image +local small = assert(ops.resize(img, 32, 24)) -- filter: "bilinear" (default), "nearest", "lanczos" +local part = assert(ops.crop(img, 8, 8, 16, 16)) -- x, y, w, h (clipped to the image) +local mirrored = assert(ops.flip(img, "h")) -- "h" left-right, "v" top-bottom +local turned = assert(ops.rotate90(img, 1)) -- quarter turns counter-clockwise (-1 = clockwise) +local tilted = assert(ops.rotate(img, 30)) -- degrees counter-clockwise, canvas grows (opts.expand) +local grey = assert(ops.convert(img, "gray8")) -- any pixel format to any other +assert(turned.width == 48 and grey.format == "gray8" and tilted.width > 64) +local canvas = assert(ops.new(64, 64)) +ops.blit(canvas, part, 4, 4) -- in place, alpha "over" (opts.blend = "source" copies) +ops.blit(canvas, small, 30, 30, { opacity = 0.5 }) +local merged = assert(ops.composite(canvas, mirrored, -32, 40)) -- a copy of canvas with the image drawn on it +local pm = assert(ops.premultiply(img)) -- and ops.unpremultiply +local r, g, b, a = ops.getPixel(img, 63, 0) -- in the format's scale (0..255 / 0..65535 / float) +assert(a == 128 and select(4, ops.getPixel(pm, 63, 0)) == 128) +local copy = assert(ops.copy(img)) +ops.setPixel(copy, 0, 0, 255, 0, 0) -- in place; alpha defaults to opaque +local _ = merged and r and g and b +``` + +Conversions: 8 <-> 16 bit multiplies / divides by 257, float <-> integer clamps to 0..1 (no gamma), grey uses +`(19595 R + 38470 G + 7471 B + 32768) >> 16`. + +Animations: + +```luau +local ops = F.ops.image +local a = assert(ops.new(8, 8)) +local b = assert(ops.fill(assert(ops.new(8, 8)), 255, 0, 0)) +local anim = assert(ops.fromFrames({ a, b }, 0.5)) -- delays: one number or { seconds } +assert(#anim.frames == 2 and anim.frames[2].delay == 0.5) +anim.loops = 3 +local gif = assert(F.save(anim, nil, { format = "gif" })) +assert(F.load(gif).loops == 3) +``` + +## Save and convert + +`F.save(img, dest?, opts?)` picks the writer from `opts.format`, else from the extension of `dest`, else from +`img.meta.source.format` (the format it was loaded from). Without `dest` it returns the encoded `buffer`. + +```luau +local img = assert(F.load(pngBytes)) +local again = assert(F.save(img)) -- PNG again: the source format +local q = assert(F.save(img, nil, { format = "qoi" })) +local s = assert(F.saveString(img, { format = "bmp" })) -- a string instead of a buffer +local webp = assert(F.convert(pngBytes, "webp", { effort = 9 })) -- load + save in one call +assert(F.detect(again) == "png" and F.detect(q) == "qoi" and string.sub(s, 1, 2) == "BM" and F.detect(webp) == "webp") +``` + + +```luau +local img = assert(F.load("assets/photo.png")) -- a path (LuaJIT / LÖVE) +assert(F.save(img, "out/photo.jpg", { quality = 80 })) -- format from the extension; returns true +assert(F.convert("assets/anim.gif", "png", { out = "out/anim.png" })) -- an APNG +assert(F.load("out/anim.png").frames ~= nil) +``` + +Encoder options: + +| Format | Options | +|---|---| +| PNG | `level` (deflate 0..9, default 6), `colorType` (`"auto"`: smallest of RGBA / RGB / grey / grey + alpha), `apng` (write an APNG; automatic when `frames` is set) | +| JPEG | `quality` (1..100, default 90), `subsampling` (`"420"` / `"422"` / `"444"`), `progressive`, `optimize`, `restart`, `jfif`, `meta` (write EXIF / ICC / comment) | +| WebP | lossless only: `effort` (0..9, default 5), `exact` (keep RGB under transparent pixels), `loops`, `background` (`{ r, g, b, a }`) | +| GIF | `maxColors` (default 256), `method` (`"mediancut"` / `"octree"`), `dither`, `loops`, `globalPalette` | +| TIFF | `compression` (`"deflate"` default, `"lzw"`, `"packbits"`, `"none"`), `predictor`, `level`, `rowsPerStrip`; `frames` become pages | +| BMP | `header` (`"v4"` default, `"info"`) | +| TGA | `rle`, `origin` (`"bottom-left"` / `"top-left"`) | +| ICO | `cursor`, `png` (PNG entries); `frames` become entries (each up to 256 x 256) | +| PNM | the subtype from the extension or `format`: `pbm`, `pgm`, `ppm`, `pam`, `pfm` | + +## Formats + +Read and write unless noted; see [FORMATS.md](../FORMATS.md) for depths and details. + +| Format | Animation / pages | Alpha | Notes | +|---|---|---|---| +| PNG / APNG | APNG frames | yes | writes rgba8 only | +| JPEG | | no | lossy; reads baseline / progressive / arithmetic, 8 and 12 bit | +| WebP | frames | yes | reads lossy + lossless; writes lossless only | +| GIF | frames | 1-bit | writes through a palette quantizer (exact when <= 256 colours) | +| TIFF | pages | yes | 1..32-bit, float | +| BMP, TGA, QOI, ICO / CUR, PNM / PAM / PFM | ICO entries | yes | | +| HDR | | no | float (`native` gives rgbaf32) | + +An animated image also opens as a video (`F.video.open(gifBytes)`), and saves to a video format +(`F.convert(gifBytes, "avi")`): see [video.md](video.md). + +## Showing an image + + +```luau +local F = require(game.ReplicatedStorage.Formats) +local img = assert(F.image.load(pngBuffer)) -- e.g. from HttpService:GetAsync(...) +local editable = assert(F.host.toEditableImage(img)) -- needs rgba8: F.ops.image.convert first otherwise +local label = Instance.new("ImageLabel") +label.ImageContent = Content.fromObject(editable) +``` + + +```lua +local F = require("formats") +local img = assert(F.load("photo.png")) -- love.filesystem path +local image = love.graphics.newImage(F.host.toImageData(img)) +local back = F.host.fromImageData(love.image.newImageData("other.png")) -- ImageData -> rgba8 Image +``` + +## Gotchas + +- Encoders take `rgba8` (JPEG also `gray8` / `yuv420p`; TIFF, PNM and HDR more): convert first, e.g. + `F.save(F.ops.image.convert(img16, "rgba8"), nil, { format = "png" })`. PNG writing of 16-bit or palette images is + not supported; 16-bit PNGs decode to 8 bits. +- `frames[i].image` is only the frame's rectangle. Use `F.ops.image.coalesce` to get full canvases. +- GIF stores "repeat count" (plays - 1); `loops` is always the play count, so a loaded GIF that loops forever has + `loops = 0` and a GIF without a loop extension has `loops = 1`. +- A loaded GIF's `meta.background` is a palette index, while the WebP writer wants an `{ r, g, b, a }` colour: pass + `background` explicitly when converting GIF to WebP: `F.save(gif, nil, { format = "webp", background = { 0, 0, 0, 0 } })`. +- WebP writes lossless only (`lossless = false` returns `Err.UNSUPPORTED`). +- `alpha8` images (font glyphs) convert to white with that alpha. +- Pixel values are not colour managed: ICC profiles are kept in `meta.icc` but not applied. diff --git a/docs/guide/layered.md b/docs/guide/layered.md new file mode 100644 index 0000000..67c0eab --- /dev/null +++ b/docs/guide/layered.md @@ -0,0 +1,249 @@ +# Layered images (PSD, Aseprite) + +Photoshop documents and Aseprite sprites load as a `Layered`: a canvas size and a tree of layers, each with its own +rgba8 [Image](image.md), position, opacity, blend mode and visibility. `F.ops.layers.flatten` composites the tree +into one Image; `F.save` writes PSD or Aseprite, layers included. Aseprite animations also carry every frame's tree. + +```luau +local doc = assert(F.layered.load(psdBytes)) +print(doc.width, doc.height, #doc.layers) -- 48 32 3 +for i, layer in doc.layers do -- bottom to top + print(i, layer.name, layer.x, layer.y, layer.image.width, layer.image.height) +end +local flat = assert(F.ops.layers.flatten(doc)) -- an rgba8 Image, 48 x 32 +local png = assert(F.save(flat, nil, { format = "png" })) +assert(flat.width == 48 and F.detect(png) == "png") +``` + +## The type + +`Layered` + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"layered"` | | +| `width`, `height` | number | the canvas size in pixels | +| `layers` | `{ Layer }` | the layer tree, **bottom to top** (index 1 is drawn first); for an animation: frame 1's tree | +| `frames` | `{ { layers, delay } }?` | animations (Aseprite): every frame's tree and its delay in seconds; `frames[1].layers` is `layers` | +| `meta` | table | see below | + +`Layer` + +| Field | Type | Meaning | +|---|---|---| +| `name` | string | | +| `image` | `Image` | rgba8 pixels of the layer's own rectangle (straight alpha); a 0 x 0 Image for groups and empty layers | +| `x`, `y` | number | the image's top-left corner on the canvas, in pixels (may be negative or past the canvas) | +| `opacity` | number | 0..1 | +| `fillOpacity` | number? | 0..1, multiplied with `opacity` (PSD fill opacity, Aseprite cel opacity) | +| `blend` | string | a blend mode name (below) | +| `visible` | boolean | hidden layers are skipped by `flatten` unless `opts.hidden` | +| `children` | `{ Layer }?` | set on groups: the group's layers, bottom to top | +| `clip` | boolean? | a clipping layer: drawn only where the nearest non-clipping layer below it has alpha | +| `mask` | `LayerMask?` | a grey mask | + +`LayerMask` + +| Field | Type | Meaning | +|---|---|---| +| `image` | `Image` | `gray8` (or rgba8: its red channel); 255 shows the layer, 0 hides it | +| `x`, `y` | number | the mask's position on the canvas (not relative to the layer) | +| `default` | number | 0..255: the mask value outside its rectangle | +| `disabled` | boolean? | ignore the mask | + +**Blend modes**: `normal`, `dissolve`, `darken`, `multiply`, `colorBurn`, `linearBurn`, `darkerColor`, `lighten`, +`screen`, `colorDodge`, `linearDodge` (also `add`), `lighterColor`, `overlay`, `softLight`, `hardLight`, +`vividLight`, `linearLight`, `pinLight`, `hardMix`, `difference`, `exclusion`, `subtract`, `divide`, `hue`, +`saturation`, `color`, `luminosity`. Unknown names composite as `normal`. + +**Groups.** A group with `blend = "passThrough"` blends its children straight onto what is below (as Photoshop's +pass-through and Aseprite's plain groups). Any other blend first composites the children on their own transparent +canvas, then blends that result with the group's mode and opacity. + +**Format extras.** + +| Format | Extra fields | +|---|---| +| PSD | `meta.composite` (the merged image the file stores, an rgba8 Image), `meta.resources`, `meta.icc` | +| Aseprite | `meta.colorDepth` (32, 16, 8), `meta.palette` (`{ { r, g, b, a } }`), `meta.tags` (`{ name, from, to, direction, repeat, color }`, frames 1-based), `meta.transparentIndex`, `meta.pixelRatio`, `meta.grid`; per layer `flags`, `userData`, `zIndex`; on a frame's layer, `link` = the frame whose cel it reuses | + +```luau +local sprite = assert(F.layered.load(asepriteBytes)) +assert(#sprite.frames == 2 and sprite.frames[2].delay == 0.25) -- seconds +local hero2 = sprite.frames[2].layers[2] +assert(hero2.name == "Hero" and hero2.x == 12) -- the hero moved 8 px +assert(sprite.frames[2].layers[1].link == 1) -- the background cel is frame 1's +local walk = sprite.meta.tags[1] +assert(walk.name == "walk" and walk.from == 1 and walk.to == 2) +``` + +## Load + +`F.load` detects both formats by their magic numbers. Everything converts to rgba8: PSD bitmap, greyscale, indexed, +CMYK, Lab and 16 / 32-bit documents; Aseprite grayscale and indexed sprites. + +| Option | Format | Meaning | +|---|---|---| +| `layers` | PSD | `false` reads only the merged image (`meta.composite`), much faster; `layers` is then empty | +| `maxPixels` | both | refuse documents or layers larger than this (default 2^26) | +| `maxLayers` | PSD | default 10000 | +| `maxFrames` | Aseprite | default 65535 | + +```luau +local quick = assert(F.layered.load(psdBytes, { layers = false })) +assert(#quick.layers == 0 and quick.meta.composite.width == 48) +local preview = quick.meta.composite -- Photoshop's own flattening +assert(preview.format == "rgba8") +``` + +`F.image.load` does not read layered formats; load them with `F.layered.load` (or `F.load`) and flatten. + +## Flatten + +`F.ops.layers.flatten(layered, opts?)` returns a new rgba8 Image of `width x height`: + +| Option | Meaning | +|---|---| +| `frame` | the animation frame to flatten (1-based; default: `layered.layers`, which is frame 1) | +| `hidden` | `true` includes invisible layers | +| `background` | `{ r, g, b, a }` (0..255) painted under everything; default transparent | + +`F.ops.layers.flattenFrames(layered, opts?)` flattens every frame into one animated Image (`img.frames`, delays +from the frames), ready to save as GIF, APNG or WebP. A Layered without frames gives a still image. + +```luau +local sprite = assert(F.layered.load(asepriteBytes)) +local f2 = assert(F.ops.layers.flatten(sprite, { frame = 2 })) +local r, g, b, a = F.ops.image.getPixel(f2, 13, 9) -- inside the hero on frame 2 +assert(r == 220 and g == 50 and b == 50 and a == 255) + +local anim = assert(F.ops.layers.flattenFrames(sprite)) +assert(#anim.frames == 2 and anim.frames[2].delay == 0.25) +local gif = assert(F.save(anim, nil, { format = "gif" })) +assert(F.detect(gif) == "gif") + +local onWhite = assert(F.ops.layers.flatten(sprite, { background = { 255, 255, 255, 255 } })) +assert(onWhite.width == 32) +``` + +`F.ops.layers.leaves(layers)` walks the non-group layers of a tree, bottom to top, with their group depth: + +```luau +local doc = assert(F.load(psdBytes)) +local names = {} +for layer, depth in F.ops.layers.leaves(doc.layers) do + table.insert(names, layer.name .. "@" .. depth) +end +assert(table.concat(names, " ") == "Sky@0 Box@0 Glow@0") +``` + +## Build and edit + +`F.Types.Layered.new(w, h)` makes an empty document, `F.Types.Layered.layer(name, image, x?, y?)` a visible normal +layer at full opacity, and `F.Types.Layered.group(name, children)` a pass-through group. Layers are plain tables: +edit their fields directly. + +```luau +local L = F.Types.Layered +local doc = L.new(32, 32) + +local paper = assert(F.ops.image.new(32, 32)) +F.ops.image.fill(paper, 240, 240, 230) +local ink = assert(F.ops.image.new(16, 16)) +F.ops.image.fill(ink, 30, 60, 200) +local shade = assert(F.ops.image.new(32, 32)) +F.ops.image.fill(shade, 255, 0, 0, 128) + +local shadeLayer = L.layer("Shade", shade) +shadeLayer.clip = true -- only where Ink has alpha +shadeLayer.blend = "multiply" +local inkLayer = L.layer("Ink", ink, 8, 8) +inkLayer.opacity = 0.8 + +doc.layers = { L.layer("Paper", paper), L.group("Art", { inkLayer, shadeLayer }) } + +local mask = assert(F.ops.image.new(32, 16, "gray8")) +F.ops.image.fill(mask, 255, 255, 255) -- show the top half +doc.layers[2].blend = "normal" -- an isolated group (masks need one, see Gotchas) +doc.layers[2].mask = { image = mask, x = 0, y = 0, default = 0 } -- hide the rest + +local flat = assert(F.ops.layers.flatten(doc)) +local _, _, _, a = F.ops.image.getPixel(flat, 0, 0) +assert(a == 255) +local r1 = F.ops.image.getPixel(flat, 12, 12) -- ink under the mask's visible half +local r2 = F.ops.image.getPixel(flat, 12, 20) -- ink masked out: paper shows +assert(r1 < 200 and r2 == 240) +``` + +## Save and convert + +`F.save` writes PSD or Aseprite from any Layered (the source format by default, else `opts.format` or the +destination's extension). Flatten first to write an ordinary image format. + +| Format | Writes | Options | +|---|---|---| +| PSD | 8-bit RGB (PSB when a side is over 30000 px): every layer as RLE RGBA channels, groups, masks, clipping, opacity, fill opacity, hidden flags, Unicode names, and a merged composite | `composite` (an Image to store as the merged image; default: the layers flattened) | +| Aseprite | RGBA sprites (grayscale / indexed when `depth` asks and the pixels fit), frame 1's layer tree, every frame's cels (linked where a frame reuses an Image), palette, tags | `depth` (32, 16, 8), `level` (zlib level, default 6) | + +```luau +local L = F.Types.Layered +local doc = L.new(16, 16) +local a = assert(F.ops.image.new(16, 16)) +F.ops.image.fill(a, 0, 128, 255) +local b = assert(F.ops.image.new(4, 4)) +F.ops.image.fill(b, 255, 255, 0) +doc.layers = { L.layer("Back", a), L.layer("Dot", b, 6, 6) } + +local psd = assert(F.save(doc, nil, { format = "psd" })) +local back = assert(F.load(psd)) +assert(#back.layers == 2 and back.layers[2].name == "Dot" and back.layers[2].x == 6) + +local ase = assert(F.save(doc, nil, { format = "aseprite" })) +assert(F.detect(ase) == "aseprite") + +-- PSD -> Aseprite and back keeps the layers +local converted = assert(F.convert(psdBytes, "aseprite")) +assert(#assert(F.load(converted)).layers == 3) +``` + +An animation for Aseprite: give `frames` (each with its own tree and delay) and set `layers = frames[1].layers`. +Frames must have the same layer structure as frame 1. + +```luau +local L = F.Types.Layered +local doc = L.new(8, 8) +local dot = assert(F.ops.image.new(2, 2)) +F.ops.image.fill(dot, 255, 0, 0) +doc.frames = {} +for i = 1, 4 do + doc.frames[i] = { layers = { L.layer("Dot", dot, i, i) }, delay = 0.1 } +end +doc.layers = doc.frames[1].layers +local ase = assert(F.save(doc, nil, { format = "aseprite" })) +local back = assert(F.load(ase)) +assert(#back.frames == 4 and back.frames[3].layers[1].x == 3) +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| PSD / PSB | 1 / 8 / 16 / 32-bit, every colour mode, layers, groups, masks, clipping | 8-bit RGB | adjustment, type and smart-object layers keep only their pixels; no layer effects | +| Aseprite | RGBA, grayscale, indexed; frames, linked cels, tags, palette, user data | yes | tilemap layers are skipped (`meta.skipped`); slices not kept | + +See [FORMATS.md](../FORMATS.md) for the capability matrix. + +## Gotchas + +- `layers[1]` is the **bottom** layer. Insert at the end to put a layer on top. +- Layer and mask positions are canvas coordinates; layer images can extend past the canvas and are clipped when + flattened. +- `meta.composite` is whatever merged image the writing application stored (some store a blank one when + "maximize compatibility" is off). `flatten` always works from the layers. +- Flattening is our own compositing (W3C blend formulas); PSD effects (shadows, strokes) and adjustment layers are + not rendered, so the result can differ from Photoshop's `meta.composite`. +- Linked Aseprite cels share one Image table between frames: copy it (`F.ops.image.copy`) before editing a single + frame. +- `flatten` ignores the mask of a `passThrough` group (Photoshop applies it). Give a masked group a real blend mode + such as `"normal"` to isolate it. +- Pixels are straight (not premultiplied) alpha, like every Image. diff --git a/docs/guide/music.md b/docs/guide/music.md new file mode 100644 index 0000000..8055e38 --- /dev/null +++ b/docs/guide/music.md @@ -0,0 +1,266 @@ +# Music + +Music files hold notes and instruments, not a recording. Tracker modules (MOD, S3M, XM, IT) load as a **Module**: +the patterns, the order list, the samples and the instruments. Standard MIDI files load as a **Midi**: tracks of +timed events. Both render to the standard audio [Decoder](audio.md#decoder), so every music file can also be +played, analysed or saved as audio. MIDI renders through a SoundFont 2 bank, or through a small built-in set of +waveforms when you don't give one. + +```luau +local song = assert(F.music.load(modBytes)) -- Module +print(song.format, song.title, song.channels) -- mod basic 4 +local dec = song:render({ sampleRate = 22050 }) -- an audio Decoder (stereo f32) +local wav = assert(F.save(dec, nil, { format = "wav" })) -- streamed into a WAV +assert(F.detect(wav) == "wav") + +local tune = assert(F.music.load(midiBytes)) -- Midi +local bank = assert(F.music.load(sf2Bytes)) -- a SoundFont +local audio = assert(F.ops.audio.toAudio(tune:render({ soundfont = bank }))) +assert(audio.channels == 2 and audio.sampleRate == 44100) +``` + +## The types + +### Module (MOD, S3M, XM, IT) + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"music"` | | +| `format` | string | `"mod"`, `"s3m"`, `"xm"` or `"it"`: the effect family the engine plays | +| `title` | string | | +| `channels` | number | pattern channels | +| `speed`, `tempo` | number | initial ticks per row, and BPM (a tick lasts `2.5 / tempo` seconds) | +| `order` | `{ number }` | the play order: 0-based pattern numbers; 254 = skip (`+++`), 255 = end (`---`) | +| `restart` | number | the 0-based order index the song loops back to | +| `patterns` | `{ Pattern }` | pattern `n` (as numbered in `order`) is `patterns[n + 1]` | +| `samples` | `{ Sample }` | the sample data, as f32 | +| `instruments` | `{ Instrument }` | XM / IT instruments (empty for MOD and S3M, where the instrument column names a sample) | +| `instrumentMode` | boolean | notes go through instrument keymaps (XM, IT with instruments) | +| `globalVolume`, `mixVolume` | number | 0..128 | +| `channelPan`, `channelVolume`, `channelMute` | `{ number }`, `{ number }`, `{ boolean }` | per channel: pan 0..256 (128 = centre), volume 0..64 | +| `linear` | boolean | linear frequency slides (XM / IT) rather than Amiga periods | +| `meta` | table | `meta.source.format` | +| `module:render(opts?)` | Decoder | plays the song once (see [Rendering](#rendering)) | + +**Pattern layout.** A Pattern is `{ rows, data }`. `data` is a buffer of `rows * channels` cells of 5 bytes each, +row by row: note, instrument, volume column, effect, parameter. Row `r` (0-based), channel `c` (0-based) starts at +byte `(r * channels + c) * 5`. Notes are 0 (none), 1..120 (1 = C-0), 253 (note fade), 254 (note cut), 255 (key +off). The volume column and the effect bytes keep the file's own coding: MOD / XM effects 0..35, S3M / IT effects +1..26 (A = 1). + +```luau +local m = assert(F.music.load(modBytes)) +local p = m.patterns[m.order[1] + 1] -- the first pattern played +local notes = 0 +for row = 0, p.rows - 1 do + for ch = 0, m.channels - 1 do + local at = (row * m.channels + ch) * 5 + local note, instrument = buffer.readu8(p.data, at), buffer.readu8(p.data, at + 1) + if note > 0 and note <= 120 then + notes += 1 + local _ = instrument -- a sample number for MOD / S3M + end + end +end +assert(buffer.len(p.data) == p.rows * m.channels * 5 and notes > 0) +``` + +**Samples.** Each Sample has `name`, `data` (f32, interleaved when `channels` is 2), `length` (frames), +`channels`, `bits` (8 or 16, what writers store), `loopStart` / `loopEnd` (frames, end exclusive), `loopType` (0 none, +1 forward, 2 ping-pong), `volume` 0..64, and the tuning fields of its format (`finetune` and `relativeNote` for MOD +/ XM, `c5speed` for S3M / IT). + +```luau +local m = assert(F.music.load(modBytes)) +for i, s in m.samples do + if s.length > 0 then + assert(buffer.len(s.data) == s.length * s.channels * 4) + print(i, s.name, s.length, s.loopType) + end +end +``` + +### Midi + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"midi"` | | +| `format` | number | SMF type 0, 1 or 2 | +| `division` | number | ticks per quarter note (negative: SMPTE time) | +| `tracks` | `{ { events, name? } }` | | +| `meta` | table | `tempos`, `timeSignatures`, `keySignatures`, `length` (seconds), `source` | +| `midi:render(opts?)` | Decoder | set by the decoder; for a hand-built Midi use `F.format("midi").render(midi, opts)` | + +Each event is `{ tick, type, channel?, data?, meta? }`. `tick` is absolute (ticks since the start of the track, +not a delta). `channel` is 0..15. `data` holds the raw data bytes as numbers: + +| `type` | `data` | +|---|---| +| `noteOn`, `noteOff` | `{ note, velocity }` (a `noteOn` with velocity 0 is kept as written) | +| `aftertouch` | `{ note, pressure }` | +| `controller` | `{ controller, value }` | +| `program` | `{ program }` | +| `channelPressure` | `{ pressure }` | +| `pitchBend` | `{ lsb, msb }` (centre 0, 64) | +| `meta` | the meta event's bytes; `meta` is its type (0x03 track name, 0x51 tempo, 0x58 time signature, ...) | +| `sysex`, `escape` | the bytes after the length | + +```luau +local tune = assert(F.music.load(midiBytes)) +assert(tune.format == 1 and tune.division == 480 and #tune.tracks == 2) +assert(tune.tracks[2].name == "Melody") +assert(tune.meta.tempos[1].bpm == 120 and tune.meta.length == 2) +local notes = {} +for _, ev in tune.tracks[2].events do + if ev.type == "noteOn" and ev.data[2] > 0 then + table.insert(notes, ev.data[1]) -- MIDI note numbers: 60 = middle C + end +end +assert(#notes == 8 and notes[1] == 60) +local midi = assert(F.format("midi")) +assert(midi.tickToSeconds(tune, 480) == 0.5) -- one quarter note at 120 BPM +``` + +### SoundFont + +`F.music.load(sf2Bytes)` returns a SoundFont bank (`kind = "soundfont"`, read only): `info` (`name`, `engine`, +`comment`, ...), `presets` (each with `name`, `bank`, `preset`), `instruments`, `sampleHeaders` and `samples`. +Its only use is as `opts.soundfont` when rendering MIDI. + +```luau +local bank = assert(F.music.load(sf2Bytes)) +assert(bank.kind == "soundfont" and bank.info.name == "formats-luau test bank") +for _, p in bank.presets do + print(p.bank, p.preset, p.name) -- 0 0 Sine, ... +end +``` + +## Loading + +| Call | Gives | +|---|---| +| `F.music.load(src, opts?)` / `F.load` | a Module, a Midi or a SoundFont | +| `F.music.open(src, opts?)` / `F.open` | the rendered audio Decoder (decode and render options together) | + +`F.audio.open` and `F.audio.load` do not take music files; use `F.music.open`, or `F.open`, which detects any +category. + +| Option | Formats | Meaning | +|---|---|---| +| `maxBytes` | mod, xm, s3m, it | refuse more sample data (f32 bytes) | +| `strict` | midi | a truncated track is an error (default: keep the events read, `meta.truncated = true`) | +| `maxEvents` | midi | default 2^24 | + +```luau +local dec = assert(F.music.open(midiBytes, { soundfont = sf2Bytes, sampleRate = 22050 })) +assert(dec.sampleRate == 22050 and dec.channels == 2) +assert(math.abs(dec.duration - 3) < 0.01) -- 2 s of notes + the 1 s release tail +local d2 = assert(F.open(modBytes)) -- any category: a Decoder for a module +assert(d2.channels == 2) +``` + +## Rendering + +`render(opts?)` returns a Decoder (stereo f32). Read it block by block, convert it with `F.ops.audio.toAudio`, or +save it with `F.save(decoder, dest, { format = ... })`, which encodes as it reads. + +| Option | Applies to | Meaning | +|---|---|---| +| `sampleRate` | both | default 44100 | +| `soundfont` | MIDI | a SoundFont value, or SF2 bytes (buffer / string); default the built-in waveforms | +| `gain` | MIDI | linear output gain, default 0.5 | +| `tail` | MIDI | seconds rendered after the last event (release tails), default 1 | +| `maxVoices` | MIDI | default 256 | +| `interpolation` | modules | `"linear"` (default) or `"none"` | +| `stereoSeparation` | modules | 0..200 % (default 100; 200 makes MOD's Amiga panning hard left / right) | +| `loop` | modules | keep playing past the end (`frames` / `duration` still give one pass) | +| `maxDuration` | modules | seconds, default 3600 | + +```luau +local tune = assert(F.music.load(midiBytes)) +local plain = tune:render() -- built-in waveforms +local sf = tune:render({ soundfont = sf2Bytes, gain = 0.8, tail = 0.5 }) +assert(plain.frames == 3 * 44100 and sf.frames == 2.5 * 44100) -- 2 s of notes + the tail +local flac = assert(F.save(sf, nil, { format = "flac" })) +assert(F.detect(flac) == "flac") +``` + +A module's `frames` and `duration` come from one pass through the order list, with song loops detected: + +```luau +local song = assert(F.music.load(modBytes)) +local dec = song:render({ sampleRate = 22050, stereoSeparation = 200 }) +assert(dec.duration > 1 and dec.frames == math.floor(dec.duration * 22050 + 0.5)) +local first = assert(F.ops.audio.trim(F.ops.audio.toAudio(dec), 0, 1)) -- the first second as an Audio +assert(first.frames == 22050) +``` + +## Building and saving + +A Midi is plain data: build one with `F.Types.Midi.new(division?)` and save it as `.mid`. Events need absolute +ticks; the writer sorts nothing, so keep each track's events in tick order. A track's `name` is read from its +track-name meta event (0x03); the writer writes events only, so put the name in an event. + +```luau +local m = F.Types.Midi.new(480) -- 480 ticks per quarter note, SMF type 1 +local events = { + { tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- tempo: 500000 us per quarter + { tick = 0, type = "meta", meta = 0x03, data = { string.byte("Arpeggio", 1, -1) } }, -- the track name + { tick = 0, type = "program", channel = 0, data = { 0 } }, +} +for i, note in { 60, 64, 67, 72 } do + table.insert(events, { tick = (i - 1) * 240, type = "noteOn", channel = 0, data = { note, 100 } }) + table.insert(events, { tick = i * 240, type = "noteOff", channel = 0, data = { note, 0 } }) +end +table.insert(m.tracks, { events = events }) +local bytes = assert(F.save(m, nil, { format = "midi" })) +local back = assert(F.music.load(bytes)) +assert(back.tracks[1].name == "Arpeggio" and back.meta.length == 1) -- 4 eighth notes at 120 BPM +local dec = assert(F.format("midi").render(m, { soundfont = sf2Bytes })) -- render without saving first +assert(dec.frames > 0) +``` + +Modules save as MOD or XM. MOD writes the 31-sample format; XM modules convert to MOD when they fit (one sample per +instrument, effects 0..F, 64-row patterns). S3M and IT are read only. + +```luau +local song = assert(F.music.load(modBytes)) +local mod = assert(F.save(song)) -- the source format: MOD +local xm = assert(F.save(song, nil, { format = "xm", tracker = "my tool" })) +assert(F.detect(mod) == "mod" and F.detect(xm) == "xm") +local _, err = F.save(song, nil, { format = "it" }) +assert(err.code == F.Err.UNSUPPORTED) -- read only +``` + +| Format | Encoder options | +|---|---| +| midi | `runningStatus` (default true: the bytes python's mido writes) | +| xm | `tracker` (the tracker name field) | +| mod | none | + +## Formats + +| Format | Read | Write | Value | +|---|---|---|---| +| mod (MOD, 4..32 channels) | yes | yes | Module | +| xm | yes | yes | Module | +| s3m, it | yes | - | Module | +| midi (.mid, .kar, RMID) | yes | yes (SMF) | Midi | +| sf2 | yes | - | SoundFont | + +See [FORMATS.md](../FORMATS.md) for each format's capabilities. + +## Gotchas + +- **Saving music as audio needs a render.** `F.save(song, nil, { format = "wav" })` and `F.convert(modBytes, "wav")` + fail with `UNKNOWN_FORMAT` ("no format named wav for music"). Render first: + `F.save(song:render(), nil, { format = "wav" })`. +- `F.audio.open(midiBytes)` fails with `UNKNOWN_FORMAT`; use `F.music.open` or `F.open`. +- `track.name` is not written: add a meta 0x03 event to name a track. +- A Midi you build yourself has no `render` method; `F.format("midi").render(midi, opts)` renders it. +- MIDI event ticks are absolute, not the deltas stored in the file. Pitch bend `data` is `{ lsb, msb }`, not a + signed value: `(msb * 128 + lsb) - 8192`. +- Without a SoundFont, MIDI plays on simple built-in waveforms, which is fine for testing but not General MIDI. + SF3 banks (Ogg-compressed samples) are not supported. +- Pattern cells keep the file's own effect numbering, which differs between MOD / XM (0..35) and S3M / IT (1..26). +- A module's `duration` is one pass. `render({ loop = true })` keeps playing past it. diff --git a/docs/guide/playlist.md b/docs/guide/playlist.md new file mode 100644 index 0000000..6a67670 --- /dev/null +++ b/docs/guide/playlist.md @@ -0,0 +1,166 @@ +# Playlists + +M3U / M3U8 (including HLS), PLS and XSPF load as one `Playlist`: a list of entries with a location, an optional +title and duration, and whether a player can fetch it. Relative locations resolve against the playlist's own URL +when you pass it, and every entry is classified as playable (an `http(s)` URL) or not, with the reason. All three +formats are writable, so converting between them is a load and a save. + +```luau +local pl = assert(F.playlist.load(m3uText, { baseUrl = "https://example.com/lists/mix.m3u" })) +print(pl.format, pl.title, #pl.entries) -- m3u Docs Mix 3 +for _, e in pl.entries do + print(e.url, e.title, e.duration, e.playable) +end +-- https://example.com/music/first.mp3 Ada - First Song 215 true +-- http://radio.example/stream Live Radio nil true +-- https://example.com/lists/songs/local.flac nil nil true +local pls = assert(F.saveString(pl, { format = "pls" })) +``` + +## The type + +`Playlist`: + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"playlist"` | | +| `format` | string | `"m3u"`, `"hls"` (an M3U8 with HLS tags), `"pls"` or `"xspf"` | +| `entries` | `{ PlaylistEntry }` | in playlist order | +| `warnings` | `{ string }` | what was odd but readable (an unresolvable location, a `NumberOfEntries` mismatch, ...), with line numbers | +| `title` | string? | M3U `#PLAYLIST:`, XSPF `` (PLS has none) | +| `hls` | table? | HLS playlists only (below) | +| `meta` | table | `source.format`; XSPF: `creator`, `annotation`, `info`, `location`, `identifier`, `image`, `date` | + +`PlaylistEntry`: + +| Field | Type | Meaning | +|---|---|---| +| `url` | string | the location, resolved against `opts.baseUrl` (or XSPF `xml:base`) when relative | +| `title` | string? | `#EXTINF` title, PLS `TitleN`, XSPF `<title>` | +| `duration` | number? | seconds; `nil` when unknown (`-1` in M3U / PLS) | +| `playable` | boolean | an `http` / `https` URL a player can fetch | +| `reason` | string? | why not playable: `"local path"`, `"relative path without a base URL"`, `"scheme ftp"`, ... | +| `bandwidth`, `codecs`, `attributes` | | HLS master playlists: `BANDWIDTH`, `CODECS` and the whole attribute list (`RESOLUTION`, ...) | +| `byteRange` | `{ length, offset? }`? | HLS media playlists: `EXT-X-BYTERANGE` | +| `creator`, `album`, `annotation`, `info`, `image`, `trackNum`, `locations` | | XSPF tracks (`locations`: every `<location>`; `url` is the first) | + +## Load + +| Option | Meaning | +|---|---| +| `baseUrl` | the playlist's own URL (or a Windows path): relative entries resolve against it (RFC 3986) | +| `maxBytes` | refuse bigger files (default 64 MB) | + +Text decoding is forgiving: a UTF-8 BOM, CRLF or CR line ends, and Windows-1252 text (old M3U files) all work. + +```luau +local pl = assert(F.playlist.load(m3uText)) -- no base URL: the relative entry is not playable +local last = pl.entries[3] +assert(last.url == "songs/local.flac" and not last.playable) +assert(last.reason == "relative path without a base URL") +assert(#pl.warnings == 1) +print(pl.warnings[1]) -- line 7: relative path without a base URL: songs/local.flac + +local radio = assert(F.playlist.load(plsText)) +assert(radio.format == "pls" and radio.entries[1].title == "Radio One" and radio.entries[1].duration == nil) +assert(radio.entries[2].duration == 187) + +local spiff = assert(F.playlist.load(xspfText)) +local track = spiff.entries[1] +assert(spiff.format == "xspf" and track.creator == "Ada" and track.duration == 215) -- XSPF stores milliseconds +``` + +### HLS + +An M3U8 with HLS tags loads with `format = "hls"` and an `hls` table. A *master* playlist lists variant streams; a +*media* playlist lists segments. + +| `hls` field | Meaning | +|---|---| +| `master` | true for a master playlist (variants), false for a media playlist (segments) | +| `targetDuration`, `mediaSequence` | media: `EXT-X-TARGETDURATION`, `EXT-X-MEDIA-SEQUENCE` | +| `endList` | media: `EXT-X-ENDLIST` seen (false = live, the playlist grows) | +| `encrypted` | an `EXT-X-KEY` with a method other than NONE | +| `totalDuration` | media: the sum of the segment durations, seconds | +| `segmentFormat` | media: the segments' common extension (`"mp3"`, `"ts"`, `"aac"`, ...) or `"mixed"` | + +Segments that are MPEG-TS, AAC or fragmented MP4 are flagged unplayable (`reason` says so): the classification is +about what a simple player can stream as a file, not what the library can decode. + +```luau +local master = assert(F.playlist.load(hlsText, { baseUrl = "https://cdn.example/v/master.m3u8" })) +assert(master.format == "hls" and master.hls.master) +for _, v in master.entries do + print(v.bandwidth, v.attributes.RESOLUTION, v.url) +end +-- 800000 640x360 https://cdn.example/v/low/index.m3u8 +-- 2400000 1280x720 https://cdn.example/v/high/index.m3u8 +assert(master.entries[1].codecs == "avc1.4d401e,mp4a.40.2") + +local media = assert(F.playlist.load( + "#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXTINF:4,\nseg1.mp3\n#EXTINF:3.5,\nseg2.mp3\n#EXT-X-ENDLIST\n", + { format = "m3u8", baseUrl = "https://cdn.example/audio/list.m3u8" })) +assert(not media.hls.master and media.hls.endList and media.hls.segmentFormat == "mp3") +assert(media.hls.totalDuration == 7.5 and media.entries[2].url == "https://cdn.example/audio/seg2.mp3") +``` + +## Edit, save and convert + +Entries are plain tables: filter, reorder or add them, then save. The format comes from `opts.format`, the +destination's extension, or the format the playlist was loaded from (as everywhere, see the [guide](README.md#saving)). + +```luau +local pl = assert(F.playlist.load(m3uText, { baseUrl = "https://example.com/lists/mix.m3u" })) +local keep = {} +for _, e in pl.entries do + if e.duration then -- drop the live stream (unknown length) + table.insert(keep, e) + end +end +table.insert(keep, { url = "https://example.com/music/bonus.ogg", title = "Bonus", duration = 61, playable = true }) +pl.entries = keep + +local m3u = assert(F.saveString(pl)) -- M3U8 text, the source format +assert(string.find(m3u, "#EXTINF:61,Bonus\nhttps://example.com/music/bonus.ogg", 1, true)) +local pls = assert(F.saveString(pl, { format = "pls" })) +assert(string.find(pls, "NumberOfEntries=2", 1, true)) +local xspf = assert(F.saveString(pl, { format = "xspf" })) +assert(F.playlist.load(xspf).entries[2].duration == 61) +``` + +A playlist built from scratch needs `kind = "playlist"`, `entries` and a format to save as: + +```luau +local pl = { kind = "playlist", format = "m3u", title = "New", entries = { + { url = "https://example.com/a.mp3", title = "A", duration = 120, playable = true }, +}, warnings = {}, meta = {} } +local text = assert(F.saveString(pl, { format = "m3u" })) +assert(string.sub(text, 1, 7) == "#EXTM3U") +``` + +| Writer | Writes | +|---|---| +| m3u | `#EXTM3U`, `#PLAYLIST:` (opts.`title` overrides), `#EXTINF:<seconds>,<title>`, the locations | +| pls | `[playlist]`, `FileN` / `TitleN` / `LengthN` (`-1` for unknown), `NumberOfEntries`, `Version=2` | +| xspf | XSPF version 1: title, track location / title / creator / album / annotation / info / image / trackNum / duration | + +## Formats + +| Format | Extensions | Read | Write | +|---|---|---|---| +| m3u | `.m3u .m3u8` | yes, including HLS master and media playlists | yes (plain M3U8; HLS tags are not written) | +| pls | `.pls` | yes | yes | +| xspf | `.xspf` | yes | yes | + +See [FORMATS.md](../FORMATS.md). + +## Gotchas + +- **Pass `baseUrl`** for playlists fetched from the web: otherwise relative entries keep their text and are not + playable. +- **HLS round trips lose the HLS tags.** Saving an HLS playlist writes a plain M3U8 (locations, `#EXTINF`); variant + attributes, keys and byte ranges are not written. +- **M3U durations are written as whole seconds** (`#EXTINF:4,` for 3.5 s). +- **`F.detect` says `m3u`** for HLS text; `pl.format` tells you whether HLS tags were found. +- **Local paths** (`C:\Music\a.mp3`, `/home/me/a.mp3`, `file:` URLs) are kept as written and flagged unplayable; the + library never reads the files a playlist points to. diff --git a/docs/guide/recipes.md b/docs/guide/recipes.md new file mode 100644 index 0000000..aab1bee --- /dev/null +++ b/docs/guide/recipes.md @@ -0,0 +1,309 @@ +# Recipes + +Short task-oriented snippets. Each one runs as a test (see the [guide](README.md) for how the inputs such as +`pngBytes` are provided); the ones that read or write files run on hosts with a file system. + +- [Images](#images): thumbnail, format conversion, GIF to video and back, show an image in Roblox or LÖVE +- [Audio](#audio): transcode, tags, game-loop streaming, render a MIDI +- [3D](#3d): glTF to OBJ with textures, voxels to a mesh +- [Other files](#other-files): zip, CSV, SVG, fonts + +## Images + +### Make a thumbnail + +Fit the image into a 32 x 32 box, keeping its aspect ratio, and save it as a JPEG: + +```luau +local img = assert(F.image.load(pngBytes)) +local scale = math.min(32 / img.width, 32 / img.height, 1) +local w, h = math.max(1, math.floor(img.width * scale + 0.5)), math.max(1, math.floor(img.height * scale + 0.5)) +local thumb = assert(F.ops.image.resize(img, w, h, "lanczos")) +local jpg = assert(F.save(thumb, nil, { format = "jpeg", quality = 85 })) +assert(thumb.width == 32 and thumb.height == 24 and F.detect(jpg) == "jpeg") +``` + +JPEG has no alpha channel. To keep transparency, save as PNG or WebP instead. + +### Convert between image formats + +```luau +local webp = assert(F.convert(pngBytes, "webp", { lossless = true })) +local back = assert(F.load(webp)) +local orig = assert(F.load(pngBytes)) +assert(buffer.tostring(back.pixels) == buffer.tostring(orig.pixels)) -- lossless: the same pixels +``` + +### Animated GIF to video and back to frames + +An animated image converts to a video directly. AVI and MP4 store Motion-JPEG frames. + +```luau +local avi = assert(F.convert(gifBytes, "avi")) +local mp4 = assert(F.convert(gifBytes, "mp4", { quality = 90 })) +assert(F.detect(avi) == "avi" and F.detect(mp4) == "mp4") + +local v = assert(F.video.open(avi)) +local frames = {} +while true do + local f = v:nextFrame() + if not f then + break + end + table.insert(frames, v:toRGBA(f)) -- each frame as an rgba8 Image +end +assert(#frames >= 3 and frames[1].width == 32) +local gif = assert(F.save(assert(F.ops.image.fromFrames(frames, 1 / v.frameRate)), nil, { format = "gif" })) +assert(F.detect(gif) == "gif") +``` + +The GIF frames of `gifBytes` are full-canvas, so the frames you get back match the GIF's. GIF delays that are not a +whole number of video frames become repeated frames. + +### Every frame of an animation as a full image + +```luau +local gif = assert(F.image.load(gifBytes)) +local canvases = assert(F.ops.image.coalesce(gif)) -- frames composited onto full canvases +local delays = F.ops.image.durations(gif) -- seconds per frame +assert(#canvases == F.ops.image.frameCount(gif) and #delays == #canvases) +for i, frame in canvases do + local png = assert(F.save(frame, nil, { format = "png" })) + local _ = png, i -- e.g. F.save(frame, "frame" .. i .. ".png") +end +``` + +### Show an image in Roblox + +<!-- doc:display needs Roblox --> +```luau +local F = require(game:GetService("ReplicatedStorage").Formats) +local bytes = game:GetService("HttpService"):GetAsync("https://example.com/cat.webp") +local img = assert(F.image.load(bytes)) +if img.format ~= "rgba8" then + img = assert(F.ops.image.convert(img, "rgba8")) +end +local editable = assert(F.host.toEditableImage(img)) +local label = Instance.new("ImageLabel") +label.Size = UDim2.fromOffset(img.width, img.height) +label.ImageContent = Content.fromObject(editable) +label.Parent = game:GetService("Players").LocalPlayer.PlayerGui:WaitForChild("ScreenGui") +``` + +### Show an image in LÖVE + +<!-- doc:display needs LÖVE --> +```lua +local F = require("formats") +local image +function love.load() + local img = assert(F.load("cat.webp")) -- a love.filesystem path + image = love.graphics.newImage(F.host.toImageData(img)) +end +function love.draw() + love.graphics.draw(image, 0, 0) +end +``` + +## Audio + +### Transcode FLAC to MP3 + +`F.convert` streams audio: the encoder reads the decoder as it goes. + +```luau +local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192 })) -- MP3 bit rates are in kbit/s +local dec = assert(F.audio.open(mp3)) +assert(dec.sampleRate == 44100 and dec.channels == 2) +assert(math.abs(dec.duration - 1) < 0.1) +``` + +### Render a MIDI file with a SoundFont + +A MIDI file loads as a `Midi`; `render` turns it into an audio `Decoder`. Pass an SF2 SoundFont (bytes or a loaded +one); without it the built-in waveforms play. + +```luau +local song = assert(F.music.load(midiBytes)) +local dec = song:render({ soundfont = sf2Bytes, sampleRate = 44100 }) +assert(dec.channels == 2 and dec.duration > 0) +local wav = assert(F.save(assert(F.ops.audio.toAudio(dec)), nil, { format = "wav" })) +assert(F.detect(wav) == "wav") +``` + +`F.convert(midiBytes, "ogg")` does the same with the built-in waveforms. + +### Read the tags of any audio file + +Tag keys are lower case (`title`, `artist`, `album`, `date`, `genre`, `track`, `comment`, ...), whatever the +container calls them. + +```luau +for _, bytes in { flacBytes, mp3Bytes, oggBytes } do + local dec = assert(F.audio.open(bytes)) -- open reads the headers only + assert(dec.tags.title == "Docs Tone" and dec.tags.artist == "formats-luau") + print(string.format("%s - %s (%.1f s, %d Hz)", dec.tags.artist, dec.tags.title, dec.duration, dec.sampleRate)) +end +``` + +### Stream decode with a CPU budget per frame + +In a game loop, decode a little each frame instead of everything at once. Read in small blocks, stop when the time +budget for this frame is used up, and continue next frame. `os.clock()` works on every host, Roblox included. + +```luau +local dec = assert(F.audio.open(oggBytes)) +local block = buffer.create(1024 * dec.channels * 4) -- reused for every read +local decoded = 0 + +local function step(budget: number): boolean -- call once per frame; false when finished + local t0 = os.clock() + while os.clock() - t0 < budget do + local out, n = dec:read(1024, block) + if n == 0 then + return false + end + decoded += n -- hand out[0 .. n * channels * 4) to the mixer here + local _ = out + end + return true +end + +while step(0.002) do end -- in a game: RunService.Heartbeat / love.update +assert(decoded == dec.frames) +``` + +The same pattern works for video: call `v:nextFrame()` until the budget is used up or the next frame's `pts` is in +the future. + +## 3D + +### glTF to OBJ with textures + +A glTF's textures stay encoded (PNG / JPEG bytes in `texture.data`). The OBJ writer puts the `.mtl` and the texture +files into `opts.files`; with a destination path `F.save` writes them next to the `.obj`. + +```luau +local scene = assert(F.model.load(texturedGltfText)) -- a glTF with an embedded PNG texture +local files = {} +local obj = assert(F.save(scene, nil, { format = "obj", name = "box.obj", files = files })) +assert(files["box.mtl"]) -- the material library +local back = assert(F.model.load(obj, { format = "obj", files = files })) +assert(#back.materials >= 1 and back.textures[1] and back.textures[1].data) +``` + +<!-- doc:files --> +```luau +assert(F.convert("assets/BoxTextured.gltf", "obj", { out = "out/box.obj" })) -- .bin and .png read next to it +assert(F.host.exists("out/box.mtl")) +``` + +### MagicaVoxel .vox to a greedy mesh + +```luau +local scene = assert(F.model.load(voxBytes)) -- nodes reference voxel grids (scene.voxels) +assert(F.ops.mesh.meshVoxels(scene, { scale = 0.1 })) -- one greedy mesh per grid, colours per vertex +local prim = assert(F.ops.mesh.merge(scene)) -- everything in world space, one primitive +assert(prim.attributes.POSITION.count > 0 and prim.attributes.COLOR_0) +local glb = assert(F.save(scene, nil, { format = "glb" })) +assert(F.detect(glb) == "gltf") +``` + +Greedy meshing merges coplanar faces of the same colour into rectangles, so a 20 x 20 wall is two triangles instead +of 800. + +## Other files + +### Extract a zip and re-zip it + +```luau +local zip = assert(F.archive.load(zipBytes)) +local files = {} +for _, e in zip:list() do + if not e.dir then + files[e.name] = assert(zip:read(e.name)) -- a buffer per file + end +end +local new = assert(F.archive.load(assert(F.save(zip, nil, { format = "tar" })))) -- any archive -> tar +new:add("extra/hello.txt", "hi") +local rezipped = assert(F.save(new, nil, { format = "zip", level = 9 })) +local check = assert(F.archive.load(rezipped)) +for name, data in files do + assert(buffer.tostring(assert(check:read(name))) == buffer.tostring(data)) +end +``` + +<!-- doc:files --> +```luau +local zip = assert(F.archive.load("assets/files.zip")) +for _, e in zip:list() do + if not e.dir then + assert(F.host.writeFile("out/" .. string.gsub(e.name, "/", "_"), assert(zip:read(e.name)))) + end +end +``` + +### Read a CSV into rows + +```luau +local rows = assert(F.data.load(csvText, { format = "csv" })) -- { { "name", "score" }, { ... } } +local recs = assert(F.data.load(csvText, { format = "csv", header = true, numbers = true })) +assert(#rows == #recs + 1) +for _, r in recs do + print(r.name, r.score) -- records keyed by the header +end +``` + +### SVG to PNG + +```luau +local icon = assert(F.vector.load(svgText)) +local img = assert(F.ops.vector.rasterize(icon, 128, 128)) -- rgba8, antialiased +local png = assert(F.save(img, nil, { format = "png" })) +assert(img.width == 128 and F.detect(png) == "png") +``` + +### Bake a TTF to a BMFont + +`bake` renders the glyphs into packed page images. Save the descriptor and each page: + +```luau +local font = assert(F.font.load(ttfBytes)) +local bmfont = F.format("bmfont") +local baked = assert(bmfont.bake(font, { px = 24, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789" })) +local fnt = assert(F.saveString(baked, { format = "bmfont" })) -- the text descriptor +local pages = {} +for i, page in baked.pages do + pages[baked.meta.pageFiles[i]] = assert(F.save(page, nil, { format = "png" })) +end +local back = assert(F.font.load(fnt, { format = "bmfont", loadPage = function(file) return pages[file] end })) +assert(back:glyphIndex(string.byte("A")) ~= 0) +``` + +### Measure and draw a string with a TTF + +```luau +local font = assert(F.font.load(ttfBytes)) +local px = 20 +local scale = px / font.unitsPerEm +local canvas = assert(F.ops.image.new(200, 32)) +local baseline = math.ceil(font.ascent * scale) + 2 -- y of the baseline, pixels down +local x, prev = 2, nil +for _, cp in utf8.codes("Hello") do + local g = font:glyphIndex(cp) + if prev then + x += font:kern(prev, g) * scale + end + local glyph = font:rasterize(g, px) -- alpha8 coverage + if glyph and glyph.width > 0 then + -- meta.left / meta.top: the bitmap's offset from the pen; top counts up from the baseline + F.ops.image.blit(canvas, glyph, math.floor(x + glyph.meta.left), baseline - glyph.meta.top) + end + x += font:advance(g) * scale -- advance is in font units + prev = g +end +assert(x > 20) +local png = assert(F.save(canvas, nil, { format = "png" })) -- white text, transparent background +``` + +`alpha8` images blit as white with that alpha; tint the canvas afterwards, or blit onto a coloured background. diff --git a/docs/guide/scene.md b/docs/guide/scene.md new file mode 100644 index 0000000..525643e --- /dev/null +++ b/docs/guide/scene.md @@ -0,0 +1,412 @@ +# Scene (3D models) and Voxels + +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure +shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, +textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel +files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. + +```luau +local scene = assert(F.model.load(texturedGltfText)) +print(#scene.nodes, #scene.meshes, scene.meta.up) -- 2 1 y +local prim = scene.meshes[1].primitives[1] +local pos = prim.attributes.POSITION -- f32, 3 components, 24 vertices +assert(pos.type == "f32" and pos.components == 3 and pos.count == 24) +assert(prim.indices.count == 36 and prim.mode == "triangles") + +local merged = F.ops.mesh.merge(scene) -- one world-space triangle primitive +local lo, hi = F.ops.mesh.bounds(merged) +print(lo[1], hi[1]) -- -0.5 0.5 +local glb = assert(F.save(scene, nil, { format = "glb" })) +local obj = assert(F.convert(texturedGltfText, "obj")) +``` + +## The type + +**Indices are 1-based everywhere** (`node.mesh`, `node.children`, `prim.material`, `material.baseColorTexture.texture`, +`skin.joints`, `channel.node`, `scene.roots`). Only the *contents* of index accessors are 0-based vertex numbers, as +in glTF. + +### Scene + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"scene"` | | +| `nodes` | `{ Node }` | every node, in file order | +| `roots` | `{ number }` | the top-level node indices (the scene shown) | +| `meshes` | `{ Mesh }` | `{ name?, primitives = { Primitive }, weights? }` | +| `materials` | `{ Material }` | | +| `textures` | `{ Texture }` | | +| `cameras`, `lights`, `skins`, `animations` | arrays | see below | +| `voxels` | `{ Voxels }?` | voxel grids (VOX), shown by `node.voxels` | +| `meta.up` | `"y"` \| `"z"` | the source's up axis: `"y"` for glTF / OBJ, `"z"` for STL / VOX / CAD. Never rotated on load | +| `meta.unit` | `number?` | metres per scene unit when the file says (glTF: 1) | +| `meta.source` | table | `{ format = "gltf", binary = false, generator = ..., ... }` | + +### Node + +| Field | Type | Meaning | +|---|---|---| +| `name` | `string?` | | +| `children` | `{ number }` | child node indices | +| `mesh`, `camera`, `light`, `skin`, `voxels` | `number?` | indices into the scene arrays | +| `translation` | `{ x, y, z }?` | TRS form ... | +| `rotation` | `{ x, y, z, w }?` | ... unit quaternion | +| `scale` | `{ x, y, z }?` | | +| `matrix` | `{ number }?` (16) | ... or a **column-major** 4x4 matrix (`m[13], m[14], m[15]` = translation). Never both | +| `weights` | `{ number }?` | morph target weights | + +`F.Types.Scene.nodeMatrix(node)` gives the local matrix of either form (T * R * S), `F.Types.Scene.mul(a, b)` multiplies +two column-major matrices, and `F.Types.Scene.flatten(scene)` walks the tree from the roots and returns +`{ { primitive, matrix (world), node, mesh } }` for every primitive. + +```luau +local scene = assert(F.load(texturedGltfText)) +local root = scene.nodes[scene.roots[1]] +assert(#root.matrix == 16) -- this file uses a matrix (a -90 degree turn about x) +for _, placed in F.Types.Scene.flatten(scene) do + local m = placed.matrix -- world matrix, column-major + print(placed.node, placed.mesh, m[13], m[14], m[15]) +end +``` + +### Primitive and Accessor + +| Primitive field | Type | Meaning | +|---|---|---| +| `attributes` | `{ [name]: Accessor }` | `POSITION`, `NORMAL`, `TANGENT` (vec4, w = handedness), `TEXCOORD_n`, `COLOR_n`, `JOINTS_n`, `WEIGHTS_n`; custom ones start with `_` (PLY extra properties: `_quality`) | +| `indices` | `Accessor?` | 0-based vertex numbers (`u8` / `u16` / `u32`); nil = vertices in order | +| `mode` | string | `"triangles"`, `"lines"`, `"points"`, `"triangle_strip"`, `"triangle_fan"`, `"line_strip"`, `"line_loop"`, `"polygons"` | +| `faces` | `Accessor?` | `"polygons"` only: one `u32` vertex count per face; `indices` holds the faces one after another | +| `material` | `number?` | index into `scene.materials` | +| `targets` | `{ { [name]: Accessor } }?` | morph targets: `POSITION` / `NORMAL` / `TANGENT` deltas | + +| Accessor field | Type | Meaning | +|---|---|---| +| `data` | `buffer` | **tightly packed** little-endian elements: element `i`, component `c` sits at `(i * components + c) * size`. No stride, no padding; sparse accessors are already applied | +| `type` | string | `f32`, `f64`, `u8`, `u16`, `u32`, `i8`, `i16`, `i32`, or the normalized integers `unorm8`, `unorm16`, `snorm8`, `snorm16` (glTF `normalized: true`: `unorm8` 255 = 1.0, `snorm16` -32767 = -1.0) | +| `components` | number | 1 (scalar), 2, 3, 4 (vec4), or 4 / 9 / 16 with `matrix = true` (MAT2 / MAT3 / MAT4, column-major) | +| `count` | number | elements | + +Read any accessor without caring about its type with `F.Types.Scene.reader`, which converts normalized types to floats: + +```luau +local scene = assert(F.load(texturedGltfText)) +local prim = scene.meshes[1].primitives[1] +local get = assert(F.Types.Scene.reader(prim.attributes.POSITION)) +print(get(0, 0), get(0, 1), get(0, 2)) -- x, y, z of vertex 0 (0-based) +-- the same by hand: f32, 3 components, 4 bytes each +local x = buffer.readf32(prim.attributes.POSITION.data, (0 * 3 + 0) * 4) +assert(x == get(0, 0)) +local idx = prim.indices -- u16 here +local first = buffer.readu16(idx.data, 0) -- the first triangle's first vertex (0-based) +assert(first >= 0 and first < prim.attributes.POSITION.count) +``` + +Build accessors with `F.Types.Scene.accessor(data?, type, components, count)` (`data = nil` allocates zeros); the +byte size of one component is `F.Types.COMPONENT_SIZE[type]`. + +### Material, Texture, Sampler + +| Material field | Type | Meaning | +|---|---|---| +| `baseColor` | `{ r, g, b, a }` | **linear** 0..1 | +| `baseColorTexture`, `metallicRoughnessTexture`, `normalTexture`, `occlusionTexture`, `emissiveTexture` | `TextureRef?` | `{ texture (index), texCoord? (TEXCOORD_n, default 0), scale?, strength?, transform? (KHR_texture_transform: offset, scale, rotation) }` | +| `metallic`, `roughness` | number | 0..1 | +| `emissive` | `{ r, g, b }` | linear | +| `alphaMode`, `alphaCutoff` | `"opaque"` \| `"mask"` \| `"blend"`, number | | +| `doubleSided` | boolean | | +| `extensions` | table? | glTF `KHR_materials_*` by name, their fields as in glTF (texture infos as TextureRefs) | +| `extras` | table? | format extras. OBJ: `extras.obj.values` holds the MTL statements (`Kd`, `Ks`, `Ns`, ...), `extras.obj.maps` the texture maps; the PBR fields are derived from them | + +| Texture field | Type | Meaning | +|---|---|---| +| `data` | `buffer?` | the **encoded** image bytes (PNG, JPEG, WebP, KTX2, ...) | +| `mime` | `string?` | `"image/png"`, ... | +| `uri` | `string?` | the file name relative to the model, when the bytes were not embedded or not found | +| `image` | `Image?` | the decoded image, set by `F.model.loadTextures` (or you) | +| `sampler` | `Sampler?` | `{ wrapS, wrapT = "repeat" \| "clamp" \| "mirror", filter = "linear" \| "nearest", minFilter }` | + +**Model formats never decode images.** Textures stay encoded until you ask: + +```luau +local scene = assert(F.load(texturedGltfText)) +local tex = scene.textures[1] +assert(tex.mime == "image/png" and tex.image == nil) +local _, errs = F.model.loadTextures(scene) -- decodes every texture.data (or texture.uri via opts.resolve) +assert(next(errs) == nil) +local img = tex.image -- an rgba8 Image, 256 x 256 +assert(img.width == 256 and img.format == "rgba8") +local mat = scene.materials[1] +assert(scene.textures[mat.baseColorTexture.texture] == tex) +``` + +`loadTextures(scene, opts?)` returns `scene, errors` (`errors[i]` = the Err of texture `i`); textures whose image format +is missing keep `image = nil`. Saving a scene whose texture has only an `image` encodes it as PNG first. + +### Cameras, lights, skins, animations + +| Type | Fields | +|---|---| +| Camera | `type = "perspective"` (`yfov` radians, `aspect?`, `znear`, `zfar?`) or `"orthographic"` (`xmag`, `ymag`, `znear`, `zfar`) | +| Light | `type = "directional" \| "point" \| "spot"`, `color { r, g, b }`, `intensity`, `range?`, `innerCone?` / `outerCone?` (radians) | +| Skin | `joints { node index }`, `inverseBindMatrices` (Accessor, `f32`, 16 components, `matrix = true`), `skeleton?` | +| Animation | `name?`, `channels { { node, path = "translation" \| "rotation" \| "scale" \| "weights", input, output, interpolation = "LINEAR" \| "STEP" \| "CUBICSPLINE" } }` | + +A channel's `input` accessor holds the key times in **seconds** (`f32` scalars), `output` the values (vec3 for +translation / scale, vec4 quaternions for rotation; CUBICSPLINE stores in-tangent, value, out-tangent per key). +Skinned vertices carry `JOINTS_0` (indices into `skin.joints`, 0-based) and `WEIGHTS_0`. + +```luau +local scene = assert(F.load(riggedGlbBytes)) +local skin = scene.skins[1] +assert(skin.inverseBindMatrices.components == 16 and skin.inverseBindMatrices.count == #skin.joints) +local ch = scene.animations[1].channels[1] +local times = assert(F.Types.Scene.reader(ch.input)) +local lastKey = times(ch.input.count - 1, 0) -- seconds +print(scene.nodes[ch.node].name, ch.path, ch.interpolation, lastKey) +local prim = scene.meshes[1].primitives[1] +assert(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0) +``` + +## Loading + +```luau +local a = assert(F.load(boxGlbBytes)) -- detected by content: GLB +local b = assert(F.model.load(objText, { format = "obj" })) -- text formats: pass format (or a name) when sniffing is unsure +local c = F.load(objText, { name = "cube.obj" }) -- the name's extension is the fallback +assert(a.kind == "scene" and b.kind == "scene" and c.kind == "scene") +``` + +Model options (each format's own; unknown ones are ignored): + +| Option | Formats | Meaning | +|---|---|---| +| `resolve(uri) -> buffer \| string \| nil` | glTF, OBJ, DAE, ... | reads the other files a model names (`.bin`, `.mtl`, textures) | +| `files = { [name] = buffer \| string }` | glTF, OBJ, ... | the other files, by name, instead of `resolve` | +| `mtl` | OBJ | the material library text, when not found otherwise | +| `triangulate` | OBJ, PLY, OFF | `false` keeps n-gons as `mode = "polygons"` (default: fan-triangulated) | +| `flipV` | OBJ | `false` keeps OBJ's bottom-left UV origin (default flips to glTF's top-left) | +| `maxBytes`, `maxVertices`, `maxFaces` | various | size limits (`Err.LIMIT`) | + +### Files next to the model + +A `.gltf` may reference a `.bin` and image files; an `.obj` names its `.mtl`. Loading **from a path** on a host with a +file system (LuaJIT, LÖVE) reads them from the model's folder automatically (relative names only: no absolute paths, no +`..`, no URLs): + +<!-- doc:files --> +```luau +local scene = assert(F.load("assets/BoxTextured.gltf")) -- reads BoxTextured0.bin and CesiumLogoFlat.png too +assert(scene.textures[1].data ~= nil and scene.textures[1].uri == "CesiumLogoFlat.png") +local cube = assert(F.load("assets/cube.obj")) -- and cube.mtl +assert(cube.materials[1].name == "red") +``` + +From bytes (Roblox, the luau CLI, downloaded data) hand the files over yourself, as a table or a function: + +```luau +local files = { ["BoxTextured0.bin"] = boxBinBytes, ["CesiumLogoFlat.png"] = logoPngBytes } +local a = assert(F.load(boxGltfText, { files = files })) +local b = assert(F.load(boxGltfText, { resolve = function(uri) return files[uri] end })) +assert(a.textures[1].data and b.textures[1].data) + +local missing, err = F.load(boxGltfText) -- the .bin is required +assert(missing == nil and err.code == F.Err.IO) +local cube = assert(F.load(objText, { format = "obj", files = { ["cube.mtl"] = mtlText } })) +assert(cube.materials[1].baseColor[1] == 0.8) -- from Kd 0.8 0.1 0.1 +``` + +A missing **image** is not an error: the texture keeps its `uri` and no `data`. + +## Editing: `F.ops.mesh` + +Every function accepts any accessor type and writes `f32` attributes and `u32` indices. Bad arguments return +`nil, err`. + +| Function | Does | +|---|---| +| `merge(scene, opts?)` | bakes every primitive (node transforms applied) into one triangle primitive; `byMaterial = true` returns one per material. Lines and points are skipped; skins / morphs stay in rest pose | +| `bounds(primitive \| scene)` | `min { x, y, z }, max { x, y, z }` (a scene: world space) | +| `transform(prim, matrix)` | in place: positions, normals, tangents (and morph deltas); a mirroring matrix flips the winding | +| `triangulate(prim, opts?)` | a new triangle primitive from strips, fans and polygons (`method = "earclip"` default, or `"fan"`) | +| `computeNormals(prim, opts?)` | area-weighted `NORMAL`; `flat = true` splits corners for faceted shading | +| `computeTangents(prim, opts?)` | `TANGENT` (vec4, w = +-1) from `TEXCOORD_<opts.texCoord or 0>` | +| `weld(prim, opts?)` | merges identical vertices; `epsilon` merges near positions; `positionsOnly = true` merges by position alone | +| `unweld(prim)` | one vertex per index (no indices) | +| `f32(accessor)` | the accessor converted to `f32` | +| `scale(scene, factor)` | in place: geometry, translations, animations, cameras, lights; `meta.unit` is divided by factor | +| `setUnit(scene, metresPerUnit)` | rescales so one unit is that many metres (from `meta.unit`, default 1) | +| `setUp(scene, "y" \| "z")` | adds a root node that rotates the old roots to the new up axis (nothing baked) | +| `voxelsToPrimitive(voxels, opts?)`, `meshVoxels(scene, opts?)` | greedy meshing of voxel grids (below) | + +```luau +local M = F.ops.mesh +local scene = assert(F.load(texturedGltfText)) +local prim = assert(M.merge(scene)) -- 24 vertices, 36 indices, world space +local solid = assert(M.weld(prim, { positionsOnly = true })) +assert(solid.attributes.POSITION.count == 8) -- the cube's corners +local faceted = assert(M.computeNormals(M.unweld(prim), { flat = true })) +assert(faceted.attributes.NORMAL.count == 36) +-- scale by 2 and move 10 units along x (column-major: translation in elements 13..15) +M.transform(prim, { 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 10, 0, 0, 1 }) +local lo, hi = M.bounds(prim) +assert(lo[1] == 9 and hi[1] == 11) + +local quads = assert(F.load(objText, { format = "obj", triangulate = false })) +local poly = quads.meshes[1].primitives[1] +assert(poly.mode == "polygons" and poly.faces.count == 6) +assert(M.triangulate(poly).indices.count == 36) + +assert(M.setUnit(scene, 0.01)) -- centimetres: positions x 100 +assert(scene.meta.unit == 0.01) +assert(M.setUp(scene, "z") and scene.meta.up == "z") +``` + +Build a mesh from scratch with the constructors: + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local prim = { attributes = { POSITION = pos }, mode = "triangles", material = 1 } +local scene = S.fromPrimitive(prim, "triangle") -- one node, one mesh +scene.materials[1] = S.material("red") +scene.materials[1].baseColor = { 1, 0, 0, 1 } +F.ops.mesh.computeNormals(prim) +local stl = assert(F.save(scene, nil, { format = "stl" })) +assert(buffer.len(stl) == 84 + 50) -- binary STL: header + one facet +``` + +## Saving and converting + +`F.save(scene, dest?, opts?)` picks the writer from `opts.format`, else the destination's extension, else +`scene.meta.source.format`. `glb` and `gltf` are the same format: `format = "glb"` (or a `.glb` destination) writes +the binary container. + +| Writer | Other files | Options | +|---|---|---| +| glTF | `external = true` writes `<name>.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` | +| OBJ | `<name>.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` | +| STL | | `ascii = true` (default binary), `normals = "attribute"` | +| PLY, OFF, FBX, DAE, 3MF, USDA, VOX | see [FORMATS.md](../FORMATS.md) and the format's options | | + +Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the +`opts.files` table you pass, named after `opts.name`: + +```luau +local scene = assert(F.load(texturedGltfText)) +local files = {} +local gltf = assert(F.save(scene, nil, { format = "gltf", external = true, name = "box.gltf", files = files })) +assert(files["box.bin"] ~= nil) -- plus the texture, under its original name or box_1.png +local mtlFiles = {} +local obj = assert(F.save(scene, nil, { format = "obj", name = "box.obj", files = mtlFiles })) +assert(type(mtlFiles["box.mtl"]) == "string") +assert(string.find(buffer.tostring(obj), "mtllib box.mtl", 1, true)) +``` + +Saving to a path writes those files next to the destination: + +<!-- doc:files --> +```luau +local scene = assert(F.load("assets/BoxTextured.gltf")) +assert(F.save(scene, "out/box.glb")) -- one file, everything embedded +assert(F.save(scene, "out/box.gltf", { external = true })) -- box.gltf + box.bin + CesiumLogoFlat.png +assert(F.save(scene, "out/box.obj")) -- box.obj + box.mtl + the texture +assert(F.convert("assets/Box.glb", "stl", { out = "out/box.stl" })) +``` + +## Voxels + +MagicaVoxel `.vox` files load as a Scene with `meta.up = "z"`, units of one voxel, and grids in `scene.voxels`; each +node that shows a model has `node.voxels` (an index into `scene.voxels`) and no mesh until you mesh it. + +| Voxels field | Type | Meaning | +|---|---|---| +| `kind` | `"voxels"` | | +| `size` | `{ sx, sy, sz }` | cells per axis (z up) | +| `data` | `buffer` | one byte per cell, `0` = empty, `1..255` = palette index; cell `(x, y, z)` (0-based) at byte `x + sx * (y + sy * z)` | +| `palette` | `{ { r, g, b, a } }` | 255 entries, 0..255 **sRGB**, `palette[i]` for index `i`, shared by a file's models | +| `materials` | `{ [index]: { type, ... } }?` | MATL: `"diffuse"`, `"metal"`, `"glass"`, `"emit"`, ... with their properties | + +```luau +local V = F.Types.Voxels +local scene = assert(F.load(voxBytes)) +local grid = scene.voxels[1] +local sx, sy, sz = grid.size[1], grid.size[2], grid.size[3] +local filled = 0 +for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + if V.get(grid, x, y, z) ~= 0 then + filled += 1 + end + end + end +end +print(sx, sy, sz, filled) -- 20 21 20 398 +V.set(grid, 0, 0, 0, 1) -- paint a cell with palette entry 1 +local r, g, b, a = table.unpack(grid.palette[1]) +assert(a == 255) + +-- greedy meshing: merged faces, per-vertex colours from the palette +assert(F.ops.mesh.meshVoxels(scene)) -- every node with voxels now has a mesh +local prim = scene.meshes[scene.nodes[1].mesh].primitives[1] +assert(prim.attributes.COLOR_0.type == "f32") -- linear RGBA (glTF's COLOR_0 meaning) +local glb = assert(F.save(scene, nil, { format = "glb" })) +``` + +`voxelsToPrimitive(voxels, opts)` meshes one grid. Options (both functions): `pivot = "center"` (default, MagicaVoxel's +placement: cell `x` spans `x - floor(sx / 2)` ..) or `"corner"` (0 .. sx), `scale` (units per voxel, default 1), +`colors = "linear"` (default, `f32`) or `"srgb"` (`unorm8`, the palette bytes), `indexAttribute = true` (adds +`_PALETTE_INDEX`, `u8`). Call `meshVoxels` once per scene, after editing the grids: each call adds meshes. + +```luau +local V = F.Types.Voxels +local grid = V.new(4, 4, 2) -- empty; the default palette is a grey ramp +for x = 0, 3 do + for y = 0, 3 do + V.set(grid, x, y, 0, 200) -- a 4 x 4 floor + end +end +V.set(grid, 1, 1, 1, 10) +local prim = assert(F.ops.mesh.voxelsToPrimitive(grid, { pivot = "corner", colors = "srgb" })) +local lo, hi = F.ops.mesh.bounds(prim) +assert(hi[1] == 4 and hi[3] == 2) +local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves as a one-model .vox +assert(F.load(vox).voxels[1].size[1] == 4) +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`; no Draco / meshopt | +| OBJ + MTL | yes | yes | polygons, vertex colours, Phong + PBR MTL | +| STL | yes | yes | ASCII / binary, colour conventions; a triangle soup | +| PLY | yes | yes | ASCII / binary, point clouds, custom `_` attributes | +| OFF | yes | yes | | +| FBX | yes | yes | binary + ASCII 7.x, skins, animation | +| Collada (DAE / ZAE) | yes | yes | | +| 3MF | yes | yes | | +| USDA (+ USDZ read) | yes | yes | | +| VOX | yes | yes | voxel grids, scene graph, materials | +| STEP | via the CAD plug-in | | see [cad.md](cad.md) | + +Capabilities per format: [FORMATS.md](../FORMATS.md). + +## Gotchas + +- 1-based object indices, 0-based vertex indices and voxel coordinates. +- Matrices are column-major flat arrays of 16; quaternions are `{ x, y, z, w }`. +- Colours: `baseColor`, `emissive` and `f32` `COLOR_0` are linear; the voxel palette and `unorm8` colours from + `colors = "srgb"` are sRGB bytes. +- No format rotates the data to a common up axis: check `meta.up` (VOX, STL and CAD are z-up) and use + `F.ops.mesh.setUp` or your own matrix. +- OBJ UVs are flipped on load (`v = 1 - v`) to glTF's top-left origin, and flipped back on save. +- `F.ops.mesh.transform` and `computeNormals` / `computeTangents` change the primitive in place (and return it); + `merge`, `weld`, `unweld` and `triangulate` return new primitives. +- `merge` ignores skins and morph targets (the rest pose); bake animation yourself if you need a posed mesh. +- A text model (OBJ, ASCII STL / PLY) passed as a string is sniffed by content; pass `format` or `name` when the text + is ambiguous. diff --git a/docs/guide/subtitles.md b/docs/guide/subtitles.md new file mode 100644 index 0000000..d961bc2 --- /dev/null +++ b/docs/guide/subtitles.md @@ -0,0 +1,135 @@ +# Subtitles + +SRT, WebVTT and ASS / SSA files load as one **Subtitles** value: a list of timed cues, plus named styles where the +format has them. Cue text uses one small markup for all three (`<i>`, `<b>`, `<u>`, `<s>`, and line breaks as +`\n`), so converting between the formats keeps italics and line breaks. + +```luau +local subs = assert(F.subtitle.load(srtText)) +local cue = subs.cues[1] +print(cue.start, cue.stop, cue.text) -- 0.5 2 Hello, <i>world</i>. +local vtt = assert(F.saveString(subs, { format = "vtt" })) +assert(string.sub(vtt, 1, 6) == "WEBVTT") +``` + +## The type + +`F.Types.Subtitles.new()` makes an empty one. + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"subtitles"` | | +| `cues` | `{ Cue }` | in file order | +| `styles` | `{ [name]: { [field]: string } }` | ASS styles by name; empty for SRT and WebVTT | +| `meta` | table | `source`, and each format's extras (below) | + +| Cue field | Type | Meaning | +|---|---|---| +| `start`, `stop` | number | seconds | +| `text` | string | the shared markup: `<i>`, `<b>`, `<u>`, `<s>` (SRT also `<font ...>`, WebVTT `<c.class>` / `<v Name>` as written); lines separated by `"\n"` | +| `id` | string? | SRT index, WebVTT cue identifier | +| `style` | string? | ASS: the style name | +| `settings` | string? | WebVTT cue settings (`"align:start"`), SRT coordinates, as written | + +ASS cues also keep `layer`, `name`, `marginL`, `marginR`, `marginV`, `effect`, and `raw`: the original text with its +override blocks (`{\pos(...)}`, karaoke, ...), which the writer uses when `text` is unchanged. + +| Format | `meta` extras | +|---|---| +| ASS | `scriptInfo` (`Title`, `PlayResX`, ...), `scriptInfoOrder`, `styleFormat`, `styleOrder`, `eventFormat`, `comments`, `sections` (other sections, verbatim) | +| WebVTT | `header`, `notes`, `css` (STYLE blocks), `regions` | + +```luau +local s = assert(F.subtitle.load(assText)) +assert(#s.cues == 2 and s.cues[2].style == "Sign") +assert(s.cues[2].text == "A sign\nwith two lines") -- \N became a line break +assert(s.styles.Sign.Fontsize == "16" and s.styles.Default.PrimaryColour == "&H00FFFFFF") +assert(s.meta.scriptInfo.PlayResX == "640") +local v = assert(F.subtitle.load(vttText)) +assert(v.cues[1].id == "intro" and v.cues[1].settings == "align:start") +``` + +## Loading + +`F.subtitle.load(src, opts?)` or `F.load(src)`; text with a BOM, CRLF or CR line ends is fine. The one option is +`maxBytes` (default 64 MB). SRT has no magic number, but its timing lines are recognised. + +```luau +assert(F.detect(srtText) == "srt" and F.detect(vttText) == "vtt" and F.detect(assText) == "ass") +local s = assert(F.load(srtText)) +assert(s.kind == "subtitles" and s.cues[2].text == "Second line\nspans two rows.") +``` + +## Finding the cue at a time + +```luau +local s = assert(F.subtitle.load(srtText)) +local function cueAt(t: number): string? + for _, c in s.cues do + if t >= c.start and t < c.stop then + return c.text + end + end + return nil +end +assert(cueAt(1) == "Hello, <i>world</i>." and cueAt(2.2) == nil) +local plain = string.gsub(cueAt(1) :: string, "<[^>]+>", "") -- strip the markup for a plain label +assert(plain == "Hello, world.") +``` + +## Editing, saving, converting + +Cues are plain tables: shift, edit or add them, then save. The format comes from `opts.format`, the destination's +extension, or the source format. + +```luau +local s = assert(F.subtitle.load(srtText)) +for _, c in s.cues do + c.start += 1.5 -- delay everything by 1.5 s + c.stop += 1.5 +end +table.insert(s.cues, { start = 6, stop = 7.5, text = "<b>The end</b>" }) +local srt = assert(F.saveString(s)) -- SRT again; cues are renumbered from 1 +assert(string.find(srt, "00:00:02,000 --> 00:00:03,500", 1, true)) +local ass = assert(F.saveString(s, { format = "ass" })) -- markup becomes {\b1}...{\b0} +assert(string.find(ass, "{\\b1}The end{\\b0}", 1, true)) + +local fresh = F.Types.Subtitles.new() +table.insert(fresh.cues, { start = 1, stop = 2.5, text = "Hi" }) +assert(F.saveString(fresh, { format = "srt" }) == "1\n00:00:01,000 --> 00:00:02,500\nHi\n\n") +``` + +| Format | Writes | Options | +|---|---|---| +| srt | cues renumbered, times to the millisecond | `crlf` | +| vtt | header, STYLE / REGION blocks, cues (times to the millisecond) | | +| ass | an ASS v4.00+ script with the source's styles (a `Default` style when there are none); times to the centisecond | `crlf` | + +Converting ASS to SRT or WebVTT drops the styles and anything the markup cannot hold (positions, colours, karaoke); +converting to ASS gives every cue without a style the `Default` style. + +```luau +local srt = assert(F.convert(assText, "srt")) +local back = assert(F.subtitle.load(srt)) +assert(back.cues[1].text == "Hello, <i>world</i>." and back.cues[2].style == nil) +``` + +## Formats + +| Format | Read | Write | Styles | +|---|---|---|---| +| srt | yes | yes | no | +| vtt (WebVTT) | yes | yes | CSS kept in `meta.css` | +| ass / ssa | yes | yes (ASS v4.00+) | yes | + +See [FORMATS.md](../FORMATS.md). Text subtitle tracks inside Matroska files are read by `F.format("mkv").subtitles` +([video.md](video.md)). + +## Gotchas + +- Times are seconds as floating point numbers; writers round them (SRT / WebVTT to the millisecond, ASS to the + centisecond). +- Style fields are strings as written in the file (`Fontsize = "16"`, colours as `&HAABBGGRR`). Nothing is rendered. +- WebVTT cue text cannot hold blank lines or `-->`: the writer drops the blank lines and escapes the arrow. +- Tags in SRT text are not validated; unknown ones pass through as text. +- The cue list is not sorted for you. Sort by `start` after inserting cues out of order if the player needs it. diff --git a/docs/guide/tilemap.md b/docs/guide/tilemap.md new file mode 100644 index 0000000..bb86cd0 --- /dev/null +++ b/docs/guide/tilemap.md @@ -0,0 +1,214 @@ +# Tile maps (Tiled TMX / TMJ) + +[Tiled](https://www.mapeditor.org) maps load as a `TileMap`: the map grid, its tilesets, and a list of layers +(tile layers, object layers, image layers and groups) with Tiled's custom properties. The XML flavour (TMX) and the +JSON flavour (TMJ) decode to the same value, so converting between them is a load and a save. Standalone tileset +files (TSX / TSJ) load too. + +```luau +local map = assert(F.load(tmxText)) +print(map.width, map.height, map.tileWidth, map.tileHeight) -- 4 3 16 16 +local ground = map.layers[1] +local gid = ground.data[1 + 0 * map.width + 2] -- the tile at column 2, row 0 +assert(gid == 2) +local json = assert(F.saveString(map, { format = "tmj" })) +assert(F.detect(json, { name = "level.tmj" }) == "tiled") +``` + +## The type + +`TileMap` + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"tilemap"` | | +| `width`, `height` | number | the map size **in tiles** (for infinite maps: the bounds Tiled stored) | +| `tileWidth`, `tileHeight` | number | the grid cell size in pixels | +| `orientation` | string | `"orthogonal"`, `"isometric"`, `"staggered"`, `"hexagonal"` | +| `renderOrder` | string | `"right-down"`, `"right-up"`, `"left-down"`, `"left-up"` | +| `infinite` | boolean | tile layers use `chunks` instead of `data` | +| `tilesets` | `{ Tileset }` | sorted by `firstGid` | +| `layers` | `{ TileLayer }` | in Tiled's order: the first is drawn first (at the bottom) | +| `properties` | `{ [name]: value }` | custom properties (below) | +| `propertyTypes` | `{ [name]: type }?` | the Tiled type of each non-string property | +| `meta` | table | `source.format` (`"tmx"` or `"tmj"`), `tileset = true` for a TSX / TSJ file | + +Other Tiled map attributes keep their Tiled names in camel case: `version`, `tiledVersion`, `class`, +`nextLayerId`, `nextObjectId`, `backgroundColor`, `parallaxOriginX` / `Y`, `hexSideLength`, `staggerAxis`, +`staggerIndex`. + +`Tileset` + +| Field | Type | Meaning | +|---|---|---| +| `firstGid` | number | the gid of the tileset's tile 0 | +| `name`, `class` | string | | +| `tileWidth`, `tileHeight` | number | pixels | +| `columns`, `count` | number | tiles per row of the image, total tiles | +| `spacing`, `margin` | number | pixels between tiles / around the image | +| `imageSource` | string? | the tileset image's path **as written in the file** (relative to the map) | +| `imageWidth`, `imageHeight` | number? | | +| `image` | `Image?` | never set by the decoder: load the image yourself (below) | +| `source` | string? | an external tileset (`.tsx` / `.tsj`): only `firstGid` and `source` are known | +| `tiles` | `{ { id, class, properties, imageSource?, animation?, objectGroup? } }` | per-tile data; `id` is 0-based within the tileset; `animation = { { tileId, duration } }` with durations in **milliseconds** | +| `tileOffset`, `objectAlignment`, `transparentColor`, `properties` | | as in Tiled | + +`TileLayer` (every layer) + +| Field | Type | Meaning | +|---|---|---| +| `type` | string | `"tiles"`, `"objects"`, `"image"` or `"group"` | +| `id`, `name`, `class` | | | +| `visible`, `locked` | boolean | | +| `opacity` | number | 0..1 | +| `offsetX`, `offsetY`, `parallaxX`, `parallaxY`, `tintColor` | | as in Tiled (pixels, factors, `"#rrggbb"` / `"#aarrggbb"`) | +| `properties`, `propertyTypes` | | custom properties | + +By `type`: + +| Type | Fields | +|---|---| +| `"tiles"` | `width`, `height` (tiles); `data` = `width * height` gids, row by row from the top-left (`data[1 + x + y * width]`, `x` and `y` 0-based); or `chunks = { { x, y, width, height, data } }` on infinite maps (`x`, `y` in tiles, may be negative); `encoding` / `compression` as stored | +| `"objects"` | `objects`, `drawOrder` (`"topdown"` / `"index"`), `color` | +| `"image"` | `imageSource`, `imageWidth`, `imageHeight`, `repeatX`, `repeatY`, `transparentColor` | +| `"group"` | `layers` (the child layers) | + +An object: `id`, `name`, `class`, `x`, `y`, `width`, `height` (pixels), `rotation` (degrees clockwise), `visible`, +`shape` (`"rectangle"`, `"ellipse"`, `"point"`, `"polygon"`, `"polyline"`, `"text"`), `points` (`{ { x, y } }`, +relative to the object, for polygons and polylines), `text` (`{ text, fontFamily, pixelSize, color, ... }`), `gid` +(tile objects), `template`, `properties`. + +**Custom properties** are plain values: strings, numbers (`int`, `float`), booleans, colours as `"#aarrggbb"` +strings, files as path strings, objects as object ids, and `class` properties as `{ class, properties, +propertyTypes }`. `propertyTypes` remembers the Tiled type of each non-string property, so a save writes the same +types back. + +```luau +local map = assert(F.load(tmxText)) +assert(map.properties.music == "cave.ogg" and map.properties.gravity == 9.8) +assert(map.propertyTypes.gravity == "float") +local ts = map.tilesets[1] +assert(ts.firstGid == 1 and ts.columns == 4 and ts.imageSource == "tiles.png") +local things = map.layers[2] +assert(things.type == "objects") +local spawn = things.objects[1] +assert(spawn.shape == "point" and spawn.class == "Spawn" and spawn.x == 24 and spawn.y == 16) +``` + +## Gids and flip flags + +A gid (global tile id) of 0 is an empty cell. Otherwise the low 28 bits name a tile across all tilesets: the tile +belongs to the tileset with the largest `firstGid` not above it, and its index there is `gid - firstGid`. The top +bits are flags, kept as they are in `data`: + +| Bit | Value | Meaning | +|---|---|---| +| 31 | `0x80000000` | flipped horizontally | +| 30 | `0x40000000` | flipped vertically | +| 29 | `0x20000000` | flipped diagonally (with the other two: rotations) | +| 28 | `0x10000000` | rotated 120 degrees (hexagonal maps) | + +```luau +local map = assert(F.load(tmjText)) +local raw = map.layers[1].data[4] -- 2147483652 = 0x80000004 +local FLAGS = 0xF0000000 +local gid = bit32.band(raw, bit32.bnot(FLAGS)) +local flipH = bit32.btest(raw, 0x80000000) +assert(gid == 4 and flipH) + +-- the tileset and the tile's pixel rectangle in the tileset image +local function lookup(m, g) + local found = nil + for _, t in m.tilesets do + if t.firstGid <= g then + found = t + end + end + local index = g - found.firstGid + local col, row = index % found.columns, index // found.columns + return found, (found.margin or 0) + col * (found.tileWidth + (found.spacing or 0)), + (found.margin or 0) + row * (found.tileHeight + (found.spacing or 0)) +end +local ts, sx, sy = lookup(map, gid) +assert(ts.name == "t" and sx == 8 and sy == 8) -- tile 3 of a 2-column tileset +``` + +## Tileset images + +Tilesets keep their image as a path (`imageSource`), relative to the map file: a map format never decodes images. +Read the image yourself and attach it: + +<!-- doc:files --> +```luau +local mapPath = "assets/level.tmx" +local map = assert(F.load(mapPath)) +local dir = string.match(mapPath, "^(.*/)") or "" +for _, ts in map.tilesets do + if ts.imageSource and F.host.exists(dir .. ts.imageSource) then + ts.image = assert(F.image.load(dir .. ts.imageSource)) + end +end +assert(map.tilesets[1].image.width == 64) +``` + +On Roblox and in the luau CLI, fetch the bytes your own way and call `F.image.load(bytes)`. External tilesets +(`ts.source`) work the same way: `F.load(dir .. ts.source)` gives a TileMap with `meta.tileset = true` and the +tileset in `tilesets[1]`. + +## Load and save + +`F.load` detects TMX (`<map`) and TMJ (a JSON object with `"type": "map"` or Tiled's keys). JSON without those keys +is plain [data](data.md); pass `{ format = "tiled" }` or a `.tmj` name to force it. Option: `maxBytes` (default +256 MB). + +`F.save` writes the source's flavour unless `opts.format` says otherwise: + +| Option | Meaning | +|---|---| +| `format` | `"tmx"` / `"tsx"` (XML) or `"tmj"` / `"tsj"` / `"json"` (JSON) | +| `encoding` | tile data: `"csv"` (TMX default), `"base64"`, `"xml"` (TMX only); TMJ writes arrays unless `"base64"` | +| `compression` | for base64 data: `nil`, `"zlib"` or `"gzip"` | +| `level` | deflate level for compressed data (default 6) | +| `indent` | spaces per level (default 1 for TMX, 2 for TMJ; 0 = compact JSON) | + +```luau +local map = assert(F.load(tmxText)) +local tmj = assert(F.saveString(map, { format = "tmj", indent = 0 })) +local back = assert(F.load(tmj, { format = "tiled" })) +assert(back.layers[1].data[12] == 6 and back.properties.gravity == 9.8) + +local packed = assert(F.saveString(map, { encoding = "base64", compression = "zlib" })) +assert(string.find(packed, 'compression="zlib"', 1, true)) +``` + +Build a map from scratch with `F.Types.TileMap.new(width, height, tileWidth, tileHeight)`: + +```luau +local map = F.Types.TileMap.new(3, 2, 16, 16) +table.insert(map.tilesets, { name = "terrain", firstGid = 1, tileWidth = 16, tileHeight = 16, columns = 8, + count = 64, imageSource = "terrain.png", imageWidth = 128, imageHeight = 128 }) +table.insert(map.layers, { type = "tiles", name = "floor", width = 3, height = 2, visible = true, opacity = 1, + properties = {}, data = { 1, 1, 2, 0, 9, bit32.bor(9, 0x80000000) } }) +local tmx = assert(F.saveString(map, { format = "tmx" })) +local back = assert(F.load(tmx)) +assert(back.layers[1].data[6] == 0x80000009) +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| TMX / TSX | yes | yes | CSV, base64 (raw, zlib, gzip) and `<tile>` data; zstd data returns `UNSUPPORTED` | +| TMJ / TSJ | yes | yes | | + +Both are the `tiled` format in [FORMATS.md](../FORMATS.md). Wang sets and terrains are dropped. + +## Gotchas + +- `data` is 1-based in Luau but cells are 0-based: cell `(x, y)` is `data[1 + x + y * width]`. +- Always mask the flag bits before looking a gid up; a flipped tile's raw gid is over 2^31. +- Infinite maps have no `data` on their tile layers, only `chunks`. +- Object `y` is the bottom-left corner for tile objects (`gid` set) and the top-left for everything else (Tiled's + convention). +- Tile animation durations are milliseconds (Tiled's unit), unlike the seconds used elsewhere in the library. +- Colours are strings (`"#rrggbb"` or `"#aarrggbb"`), not tables. diff --git a/docs/guide/vector.md b/docs/guide/vector.md new file mode 100644 index 0000000..516cde5 --- /dev/null +++ b/docs/guide/vector.md @@ -0,0 +1,129 @@ +# Vector graphics (SVG) + +SVG files load as a `Vector`: a list of filled and stroked paths, already resolved from the document (shapes turned +into path commands, CSS and inherited styles applied, `use` expanded, gradients resolved). `F.ops.vector.rasterize` +renders any `Vector` to an rgba8 [Image](image.md) with antialiasing; `F.save` writes it back as SVG. + +```luau +local icon = assert(F.vector.load(svgText)) -- a string or buffer of SVG +print(icon.width, icon.height, #icon.paths) -- 64 64 3 +local img = assert(F.ops.vector.rasterize(icon, 128, 128)) +local png = assert(F.save(img, nil, { format = "png" })) +assert(img.width == 128 and F.detect(png) == "png") +``` + +## The type + +`Vector` + +| Field | Type | Meaning | +|---|---|---| +| `kind` | `"vector"` | | +| `width`, `height` | number | the document size in CSS pixels (`width` / `height` attributes, units converted; else the viewBox size) | +| `viewBox` | `{ x, y, w, h }` | the user-space rectangle that maps onto `width x height` | +| `paths` | `{ VectorPath }` | in paint order (first is drawn first, at the bottom) | +| `meta` | table | `groups` (group opacity / clips, by index), `clips` (clip paths), `preserveAspectRatio`, `unsupported` (`{ [element]: count }` of skipped elements such as `text`, `image`, `filter`), `source` | + +`VectorPath` + +| Field | Type | Meaning | +|---|---|---| +| `d` | `{ { op, ... } }` | absolute commands: `{ op = "M", x, y }`, `{ op = "L", x, y }`, `{ op = "Q", x1, y1, x, y }`, `{ op = "C", x1, y1, x2, y2, x, y }`, `{ op = "Z" }`; arcs and shapes arrive as these | +| `transform` | `{ a, b, c, d, e, f }?` | maps the path's coordinates to viewBox space: `x' = a x + c y + e`, `y' = b x + d y + f` | +| `fill`, `stroke` | `Paint?` | `nil` = none | +| `fillRule` | `"nonzero"` / `"evenodd"` | | +| `strokeWidth` | number | in the path's user units | +| `strokeLineJoin`, `strokeLineCap`, `strokeMiterLimit`, `strokeDashArray`, `strokeDashOffset` | | as the SVG properties (defaults `"miter"`, `"butt"`, 4, none, 0) | +| `opacity` | number | 0..1, applied to this path | +| `group`, `clip`, `id` | | index into `meta.groups` / `meta.clips`; the element id | + +`Paint`: `{ type = "color", color = { r, g, b, a } }` with 0..255 components (alpha already includes +`fill-opacity` / `stroke-opacity`), or a gradient `{ type = "linear" | "radial", stops = { { offset, r, g, b, a } }, +units = "objectBoundingBox" | "userSpaceOnUse", spread = "pad" | "reflect" | "repeat", transform?, opacity }` plus `x1, y1, x2, y2` (linear) or `cx, cy, r, fx, fy, fr` +(radial), in the units `units` names. + +```luau +local v = assert(F.load(svgText)) +local bg = v.paths[1] +assert(bg.fill.type == "linear" and #bg.fill.stops == 2) +local first = bg.fill.stops[1] -- { offset, r, g, b, a } +assert(first[1] == 0 and first[2] == 0x30 and first[5] == 255) +local sun = v.paths[2] +assert(sun.fill.type == "color" and sun.d[1].op == "M") +local hill = v.paths[3] +assert(hill.stroke ~= nil and hill.strokeWidth == 1) +``` + +## Load + +`F.load` detects SVG from the text (`<svg` near the start). Options: `maxBytes` (default 64 MB). + +```luau +local v, err = F.vector.load([[<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"> + <circle cx="4" cy="4" r="3" fill="red"/><text x="0" y="8">skipped</text></svg>]]) +assert(v and #v.paths == 1 and v.meta.unsupported.text == 1) +local _ = err +``` + +## Rasterize + +`F.ops.vector.rasterize(vector, w?, h?, opts?)` returns an rgba8 Image of `w x h` pixels (default: the vector's +size, rounded up). The viewBox maps onto it by `preserveAspectRatio` (default: centred, uniform scale), so a square +icon rendered into a wide image leaves transparent bars. + +| Option | Meaning | +|---|---| +| `background` | `{ r, g, b, a }` 0..255 under the drawing (default transparent) | +| `tolerance` | curve flattening in device pixels (default 0.1; larger is faster and coarser) | + +```luau +local v = assert(F.load(svgText)) +local wide = assert(F.ops.vector.rasterize(v, 256, 128)) +local _, _, _, a = F.ops.image.getPixel(wide, 0, 64) +assert(a == 0) -- the bar left of the centred square +local onWhite = assert(F.ops.vector.rasterize(v, 32, 32, { background = { 255, 255, 255, 255 } })) +assert(select(4, F.ops.image.getPixel(onWhite, 0, 0)) == 255) +``` + +## Build and edit + +```luau +local v = F.Types.Vector.new(100, 100) -- viewBox 0 0 100 100 +table.insert(v.paths, { + d = { { op = "M", 10, 10 }, { op = "L", 90, 10 }, { op = "L", 50, 90 }, { op = "Z" } }, + fill = { type = "color", color = { 0, 128, 255, 255 } }, + fillRule = "nonzero", strokeWidth = 1, opacity = 1, +}) +local svg = assert(F.saveString(v, { format = "svg" })) +assert(string.find(svg, "M 10 10 L 90 10", 1, true)) +local img = assert(F.ops.vector.rasterize(v, 50, 50)) +assert(select(3, F.ops.image.getPixel(img, 25, 10)) == 255) -- inside the triangle: blue +``` + +## Save + +`F.save(vector)` writes SVG (the only vector writer). Gradients become `<defs>` entries, transforms become +`transform` attributes. The output is a normalised SVG, not the original text. + +```luau +local v = assert(F.load(svgText)) +local out = assert(F.saveString(v)) +assert(F.load(out).paths[1].fill.type == "linear") +``` + +## Formats + +| Format | Read | Write | Notes | +|---|---|---|---| +| SVG | yes | yes | no text, images, patterns, masks, markers or filters (counted in `meta.unsupported`) | + +Tiled maps (`.tmx` / `.tmj`) are in the same category but load as a [TileMap](tilemap.md). See +[FORMATS.md](../FORMATS.md). + +## Gotchas + +- `F.convert(svgText, "png")` does not rasterize: it returns `Err.UNKNOWN_FORMAT` (PNG is not a vector format). + Rasterize first, then save the Image. +- `<text>` is not rendered: convert text to paths in your editor before exporting. +- Colours are 0..255 (not 0..1 as in model materials). +- Coordinates in `d` are in the path's own user space; apply `transform` to get viewBox coordinates. diff --git a/docs/guide/video.md b/docs/guide/video.md new file mode 100644 index 0000000..99e0395 --- /dev/null +++ b/docs/guide/video.md @@ -0,0 +1,305 @@ +# Video + +A video file opens as a **VideoDecoder**: frames come out one at a time, as Images, with their presentation time. +Underneath sits a **Demuxer**: the container's tracks and their compressed packets. Video tracks decode through a +codec registry (H.264, VP8, MPEG-1, Motion-JPEG, raw), and the first audio track opens as an audio +[Decoder](audio.md#decoder). Animated GIF, APNG and WebP open as videos too. [docs/video.md](../video.md) covers the +internals and how to add a codec. + +```luau +local v = assert(F.video.open(mp4Bytes)) -- H.264 + AAC +print(v.format, v.codec, v.width, v.height, v.frameRate, v.frames) -- mp4 h264 64 48 10 10 +local f = assert(v:nextFrame()) -- the first frame +local rgba = v:toRGBA(f) -- yuv420p -> rgba8 Image +local png = assert(F.save(rgba, nil, { format = "png" })) +local avi = assert(F.save(v, nil, { format = "avi" })) -- re-encoded as Motion-JPEG + PCM +assert(F.detect(png) == "png" and F.detect(avi) == "avi") +``` + +## The types + +Times: `VideoFrame.pts` / `duration`, `seek` and every `duration` field are **seconds**. Packet `pts` / `dts` / +`duration` are integer **ticks** of their track's `timescale` (exact, for remuxing): seconds = ticks / timescale. + +### VideoDecoder + +`F.video.open(src)`, `F.open(src)` and `F.load(src)` return one (`F.load` does not decode anything up front). + +| Member | Meaning | +|---|---| +| `kind` | `"video"` | +| `format` | the container: `"mp4"`, `"mkv"` / `"webm"`, `"avi"`, `"mpegts"`, `"y4m"`, `"gif"`, ... | +| `codec` | the video codec id: `"h264"`, `"vp8"`, `"mjpeg"`, `"mpeg1"`, `"rawvideo"`; `"frames"` for animated images and frame lists | +| `width`, `height` | pixels | +| `frameRate` | nominal frames per second | +| `frames` | the frame count when known (0 = unknown) | +| `duration` | seconds | +| `track` | the video Track being decoded | +| `audio` | the first audio track as an audio Decoder, or nil; `audioError` says why it is nil | +| `demuxer` | the Demuxer (nil for animated images and frame lists) | +| `meta` | container metadata (title, tags, ...) | +| `v:nextFrame()` | the next VideoFrame in display order; `nil, nil` at the end, `nil, err` on a decode error | +| `v:toRGBA(frameOrImage)` | an rgba8 Image (the frame's own image when it already is rgba8) | +| `v:seek(seconds)` | the next frame is the first at or after that time (decoded from the keyframe before it) | +| `v:reset()` | back to the start | + +### VideoFrame + +| Field | Meaning | +|---|---| +| `image` | an Image: `yuv420p` (what the codecs produce) or `rgba8` (`opts.rgba = true`, animated images) | +| `pts` | seconds from the start of the stream | +| `duration` | seconds | +| `keyframe` | true for frames that decode on their own | +| `index` | 1-based, counted in output order since the decoder was opened | + +A `yuv420p` image holds three planes in one buffer: Y (`width * height` bytes, rows top down), then U and then V, +each `ceil(width / 2) * ceil(height / 2)` bytes. `image.meta.yuv` gives the matrix (`"bt601"` / `"bt709"`) and the +range (`"limited"` / `"full"`); `toRGBA` and `F.ops.image.convert(img, "rgba8")` use it. + +```luau +local v = assert(F.video.open(webmBytes)) +local f = assert(v:nextFrame()) +local img = f.image +assert(img.format == "yuv420p" and f.pts == 0 and f.keyframe) +local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 +assert(buffer.len(img.pixels) == img.width * img.height + 2 * cw * ch) +local y = buffer.readu8(img.pixels, 10 * img.width + 20) -- luma at x = 20, y = 10 +local u = buffer.readu8(img.pixels, img.width * img.height + 5 * cw + 10) -- its chroma sample (U plane) +local _ = y + u +local r, g, b = F.ops.image.getPixel(v:toRGBA(f), 20, 10) +assert(r and g and b) +``` + +### Demuxer, Track, Packet + +`v.demuxer` (or `F.format("mp4").demux(F.Bytes.reader(bytes))` for the container alone) has: + +| Member | Meaning | +|---|---| +| `kind`, `format` | `"demuxer"`, the container name | +| `tracks` | `{ Track }` | +| `duration`, `startTime` | seconds; frame times count from `startTime` | +| `d:packets(trackId?)` | an iterator over the Packets of one track (or all), in file order, from the current position | +| `d:read(trackId?)` | the next Packet, or nil at the end | +| `d:seek(seconds)` | every track to its last keyframe at or before the time | +| `d:track(kind)` | the first Track of a kind (`"video"`, `"audio"`, ...) | + +| Track field | Meaning | +|---|---| +| `id` | the container's track number (Matroska track number, AVI stream index + 1, MPEG-TS PID, ...) | +| `kind` | `"video"`, `"audio"`, `"subtitle"` or `"data"` | +| `codec` | our codec id (`"h264"`, `"vp8"`, `"aac"`, `"vorbis"`, `"pcm_s16le"`, ...) | +| `codecTag` | the container's own id (`"avc1"`, `"V_VP8"`, `"MJPG"`, ...) | +| `timescale` | ticks per second for this track's packets | +| `width`, `height`, `frameRate` | video tracks | +| `sampleRate`, `channels`, `bitsPerSample` | audio tracks | +| `config` | codec configuration bytes (avcC, CodecPrivate, Vorbis headers, ...) | +| `duration`, `language`, `name`, `default` | when the container has them | + +A Packet is `{ track, pts, dts?, duration?, keyframe, data }`: `data` is a buffer of the compressed bytes. + +```luau +local v = assert(F.video.open(mp4Bytes)) +local d = v.demuxer +local vt, at = d:track("video"), d:track("audio") +assert(vt.codec == "h264" and at.codec == "aac" and at.sampleRate == 44100) +local count, bytes, keys = 0, 0, 0 +for p in d:packets(vt.id) do + count += 1 + bytes += buffer.len(p.data) + if p.keyframe then keys += 1 end + local seconds = p.pts / vt.timescale -- ticks -> seconds + local _ = seconds +end +assert(count == 10 and keys >= 2) +print(string.format("%d packets, %.1f kbit/s", count, bytes * 8 / d.duration / 1000)) +``` + +## Loading and playing + +| Option | Meaning | +|---|---| +| `rgba` | `nextFrame` returns rgba8 images (default: the codec's yuv420p) | +| `track` | the video track id to decode (default: the first video track) | +| `audio` | `false`: do not open the audio track | +| `maxPixels` | refuse bigger frames (`LIMIT`) | + +```luau +local v = assert(F.video.open(aviBytes, { rgba = true })) -- Motion-JPEG + PCM +local frames = 0 +while true do + local f, err = v:nextFrame() + assert(not err, tostring(err)) + if not f then break end + assert(f.image.format == "rgba8") + frames += 1 +end +assert(frames == v.frames) +v:seek(0.5) -- jump: decodes from the keyframe before 0.5 s +assert(v:nextFrame().pts == 0.5) +v:reset() +assert(v:nextFrame().pts == 0) +``` + +The audio track is an ordinary audio Decoder: read it, or turn it into an Audio. + +```luau +local v = assert(F.video.open(webmBytes)) +local a = assert(v.audio, tostring(v.audioError)) +assert(a.sampleRate == 44100 and a.channels == 1) +local sound = assert(F.ops.audio.toAudio(a)) +local ogg = assert(F.save(sound, nil, { format = "vorbis" })) -- the soundtrack on its own +assert(F.detect(ogg) == "vorbis") +``` + +Animated images open as videos (`codec = "frames"`, rgba8 frames, no demuxer). `F.video.fromImage(img)` does the same +for an Image you already have, and `F.video.fromFrames(images, delays?)` makes a video from a list of same-size +images (delays in seconds: one number for all, or one per frame; default 0.1). + +```luau +local g = assert(F.video.open(gifBytes)) +assert(g.codec == "frames" and g.frames == 3 and g.demuxer == nil) +local imgs = {} +for i = 1, 5 do + local im = assert(F.ops.image.new(32, 16)) + F.ops.image.fill(im, i * 50, 0, 0, 255) + imgs[i] = im +end +local v = assert(F.video.fromFrames(imgs, 1 / 5)) -- 5 frames at 5 fps +assert(v.frames == 5 and v.duration == 1) +``` + +## Saving and converting + +`F.save(video, dest?, opts?)` writes a container. Packets the destination can hold are copied as they are +(remuxing); otherwise frames are decoded and re-encoded as Motion-JPEG (the one video encoder), and audio as PCM. +Images and animated images save as videos too. + +| Destination | Video | Audio | +|---|---|---| +| webm | VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) | Opus / Vorbis copied | +| mkv | any codec copied, else MJPEG | copied, else PCM s16 | +| mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only | +| avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 | +| y4m | raw yuv420p | none | +| h264 | an H.264 track copied as an Annex B stream | none | + +MPEG-TS and MPEG-PS are read only. + +```luau +local mkv = assert(F.save(assert(F.video.open(mp4Bytes)), nil, { format = "mkv" })) -- remux: H.264 + AAC copied +local back = assert(F.video.open(mkv)) +assert(back.codec == "h264" and back.audio ~= nil) +local webm = assert(F.save(assert(F.video.open(webmBytes)), nil, { format = "webm" })) +assert(F.detect(webm) == "mkv") -- WebM is the mkv format +local avi = assert(F.convert(mp4Bytes, "avi", { quality = 80 })) -- decoded, re-encoded as MJPEG +assert(F.video.open(avi).codec == "mjpeg") +local y4m = assert(F.save(assert(F.video.fromFrames({ F.Types.Image.new(16, 16) }, 0.04)), nil, { format = "y4m" })) +assert(F.detect(y4m) == "y4m") +local gifAvi = assert(F.convert(gifBytes, "avi")) -- an animated image as a video +assert(F.detect(gifAvi) == "avi") +``` + +A VideoDecoder is consumed as it is saved: open the source again to save it twice. Uneven frame delays (a GIF's) +become a constant frame rate with repeated frames. + +## The codec registry + +`F.video.codecs` maps codec ids to entries `{ id, name, fourcc?, matroska?, new?, encode? }`. Containers use it to +name a track's codec from its FourCC or Matroska CodecID, so tracks of unknown codecs still remux. + +```luau +local C = F.video.codecs +assert(C.fromFourcc("MJPG") == "mjpeg" and C.fromMatroska("V_VP8") == "vp8") +assert(C.canDecode("h264") and not C.canDecode("vp9")) -- vp9 is known (remuxable) but has no decoder +assert(C.entry("h264").name == "H.264 / AVC") +``` + +`C.register(entry)` adds or replaces a codec at run time. `new(track, opts)` returns a decoder instance with +`decode(self, packet) -> err?`, `receive(self) -> image?, pts?, keyframe?`, `flush(self)` and `reset(self)`. +`C.simpleDecoder(decodeOne)` builds one for codecs with one picture per packet and no reordering: + +```luau +local C = F.video.codecs +assert(C.register({ + id = "solid", name = "Solid colour test codec", fourcc = { "SLID" }, + new = function(track) + return C.simpleDecoder(function(data: buffer) -- one packet -> one Image + local img = assert(F.ops.image.new(track.width, track.height)) + F.ops.image.fill(img, buffer.readu8(data, 0), 0, 0, 255) + return img + end) + end, +})) +assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid")) +``` + +## Playing in a game loop + +Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes +the video late instead of stalling the game. + +```luau +local v = assert(F.video.open(webmBytes)) +local clock, shown, pending = 0, 0, nil + +local function update(dt: number, budget: number) -- call once per game frame + clock += dt + local t0 = os.clock() + while os.clock() - t0 < budget do + pending = pending or v:nextFrame() + if not pending or pending.pts > clock then + return -- finished, or the next frame is not due yet + end + shown += 1 -- draw v:toRGBA(pending) (EditableImage / ImageData) + pending = nil + end +end + +for _ = 1, 120 do -- two seconds at 60 fps + update(1 / 60, 0.004) +end +assert(shown == 10) +``` + +On LÖVE, `F.host.toImageData(v:toRGBA(frame))` gives the ImageData for a texture (`Image:replacePixels` updates it +each frame); [examples/love/main.lua](../../examples/love/main.lua) plays a GIF this way. On Roblox, +`F.host.toEditableImage` makes an EditableImage; for later frames write the pixels into the same one: + +<!-- doc:display needs Roblox --> +```luau +local editable = assert(F.host.toEditableImage(v:toRGBA(first))) +-- each new frame: +editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) +``` + +## Formats + +| Format | Read | Write | Video codecs (decode) | +|---|---|---|---| +| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 | +| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | +| avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | +| mpegts, mpegps | yes | - | MPEG-1, H.264 | +| y4m | yes | yes | raw | +| h264 (Annex B) | yes | yes (copy) | H.264 | +| gif, png (APNG), webp | as video | as video via the image writers | frames | + +See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`. + +## Gotchas + +- Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with `tools/bench.luau` + and use the budget pattern above. +- The only video encoder is Motion-JPEG. H.264, VP8 and the others are copied (remuxed) or decoded, never + encoded; `F.save(v, nil, { format = "webm" })` needs a WebM-compatible source. +- Saving consumes the decoder, and so does iterating `v.demuxer:packets()`: they share the read position. +- `frame.index` keeps counting after `seek`; use `frame.pts` to know where you are. +- A video does not save to an image format: `F.save(v, nil, { format = "gif" })` and `F.convert(aviBytes, "gif")` + fail with `UNKNOWN_FORMAT`. Collect `v:toRGBA(frame)` images and save `F.ops.image.fromFrames(images, delay)`. +- Packet times are ticks, frame times are seconds. Divide by `track.timescale`. +- `nextFrame` returns yuv420p by default. Convert with `v:toRGBA(frame)` or open with `{ rgba = true }` before handing + pixels to `F.host.toEditableImage` / `toImageData`, which need rgba8. +- Calling a video format's `open` directly (through `F.format(name)`) leaves `v.audio = nil`; the audio hook is set + by `F.video.open` / `F.open` / `F.load`. diff --git a/examples/archive.luau b/examples/archive.luau new file mode 100644 index 0000000..ad7e7f9 --- /dev/null +++ b/examples/archive.luau @@ -0,0 +1,45 @@ +-- examples/archive.luau: builds a zip, lists and reads it, edits it, converts it to a .tar.gz and back, and gzips a +-- single file. Run from the repository root: luau examples/archive.luau (docs/guide/archive.md explains the API). +local F = require("@formats") + +-- a new zip: a directory, a text file, an incompressible file stored as is +local zip = F.format("zip").create() +zip:add("game/", nil) +zip:add("game/readme.txt", string.rep("formats-luau reads and writes archives. ", 20), { level = 9 }) +local noise = buffer.create(2048) +local seed = 7 +for i = 0, 2047 do + seed = (seed * 1103515245 + 12345) % 2147483648 + buffer.writeu8(noise, i, seed // 65536 % 256) +end +zip:add("game/noise.bin", noise, { method = "store" }) +local zipBytes = assert(F.save(zip, nil, { format = "zip", comment = "example" })) +print(string.format("zip: %d bytes", buffer.len(zipBytes))) + +-- list and read +local loaded = assert(F.archive.load(zipBytes)) +for _, e in loaded:list() do + print(string.format(" %-18s %6d -> %6s %s", e.name, e.size, tostring(e.compressedSize), e.method or (if e.dir then "dir" else ""))) +end +local readme = assert(loaded:read("game/readme.txt")) +assert(buffer.len(readme) == 800) + +-- edit: replace one entry, drop another, save (unchanged entries are copied without recompressing) +loaded:add("game/readme.txt", "short now") +assert(loaded:remove("game/noise.bin")) +local edited = assert(F.save(loaded)) +assert(#F.archive.load(edited):list() == 2) + +-- convert to .tar.gz: it loads back as the tar inside, with meta.compression = "gzip" +local tgz = assert(F.convert(edited, "tgz")) +local tar = assert(F.archive.load(tgz)) +assert(tar.format == "tar" and tar.meta.compression == "gzip") +print(string.format("tar.gz: %d bytes, %d entries, read back as %s inside %s", buffer.len(tgz), #tar:list(), tar.format, tar.meta.compression)) +assert(buffer.tostring(assert(tar:read("game/readme.txt"))) == "short now") + +-- one file through gzip +local gz = assert(F.save(readme, nil, { format = "gzip", name = "readme.txt" })) +local single = assert(F.archive.load(gz)) +assert(single.meta.stream and single:list()[1].name == "readme.txt") +print(string.format("gzip: %d -> %d bytes", buffer.len(readme), buffer.len(gz))) +print("archive example: ok") diff --git a/examples/audio.luau b/examples/audio.luau new file mode 100644 index 0000000..173b7bf --- /dev/null +++ b/examples/audio.luau @@ -0,0 +1,48 @@ +-- Audio example (formats-luau): build a sound, edit it with F.ops.audio, encode it to several formats, then stream it +-- back with a Decoder. Run from the repository root: luau examples/audio.luau (docs/guide/audio.md explains the API). +local F = require("@formats") +local A = F.ops.audio + +-- 1. one second of a stereo chord: interleaved f32 samples, frame i / channel c at byte (i * channels + c) * 4 +local rate = 22050 +local tone = F.Types.Audio.new(rate, 2, rate) +for i = 0, tone.frames - 1 do + local t = i / rate + buffer.writef32(tone.samples, (i * 2) * 4, 0.3 * math.sin(2 * math.pi * 261.63 * t)) -- left: C4 + buffer.writef32(tone.samples, (i * 2 + 1) * 4, 0.3 * math.sin(2 * math.pi * 329.63 * t)) -- right: E4 +end +tone.tags = { title = "Example chord", artist = "formats-luau" } + +-- 2. edit: fade, normalize, a mono copy at 16 kHz, then the two one after the other +local shaped = assert(A.normalize(assert(A.fade(tone, 0.05, 0.2)), 0.8)) +local mono = assert(A.resample(assert(A.downmix(shaped, 1)), 16000)) +local both = assert(A.concat({ shaped, mono })) -- mono is converted to stereo 22.05 kHz +print(string.format("edited: %d frames, %.2f s, peak %.2f", both.frames, both.frames / both.sampleRate, (A.peak(both)))) + +-- 3. encode: lossless and lossy +for _, fmt in { "wav", "flac", "mp3", "vorbis", "opus" } do + local opts = { format = fmt } + if fmt == "mp3" then opts.bitrate = 128 end -- kbit/s + if fmt == "opus" then opts.bitrate = 64000 end -- bit/s + local bytes = assert(F.save(both, nil, opts)) + local dec = assert(F.audio.open(bytes)) + print(string.format("%-6s %6d bytes %5d Hz %d ch %.2f s title=%s", fmt, buffer.len(bytes), dec.sampleRate, dec.channels, + dec.duration, tostring(dec.tags.title))) + assert(math.abs(dec.duration - 2) < 0.1) +end + +-- 4. stream a FLAC back in blocks, reusing one buffer, and measure its level +local dec = assert(F.audio.open(assert(F.save(both, nil, { format = "flac" })))) +local block = buffer.create(512 * dec.channels * 4) +local frames, sumSquares = 0, 0 +while true do + local out, n = dec:read(512, block) + if n == 0 then break end + for k = 0, n * dec.channels - 1 do + local s = buffer.readf32(out, k * 4) + sumSquares += s * s + end + frames += n +end +assert(frames == both.frames) +print(string.format("streamed %d frames, rms %.3f", frames, math.sqrt(sumSquares / (frames * dec.channels)))) diff --git a/examples/cad.luau b/examples/cad.luau new file mode 100644 index 0000000..26107ea --- /dev/null +++ b/examples/cad.luau @@ -0,0 +1,72 @@ +-- examples/cad.luau: reads a small STEP file, walks its entity graph (references, complex instances), adds an entity +-- and writes it back under another schema. Run from the repository root: luau examples/cad.luau +-- Solid geometry (B-rep bodies, meshes) needs a kernel plug-in, F.plugins.brep: see docs/guide/cad.md. +local F = require("@formats") + +local STEP = [[ +ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('example'),'2;1'); +FILE_NAME('bracket.step','2026-10-31T12:00:00',('me'),(''),'formats-luau','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#10=CARTESIAN_POINT('',(0.,0.,0.)); +#11=DIRECTION('',(0.,0.,1.)); +#12=DIRECTION('',(1.,0.,0.)); +#13=AXIS2_PLACEMENT_3D('',#10,#11,#12); +#14=PLANE('',#13); +#20=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +#21=PRODUCT('bracket','Bracket','',(#22)); +#22=PRODUCT_CONTEXT('',#23,'mechanical'); +#23=APPLICATION_CONTEXT('automotive design'); +ENDSEC; +END-ISO-10303-21; +]] + +local cad = assert(F.cad.load(STEP)) +local step = assert(F.format("step")) +print(string.format("schema %s, %d instances, file %s", cad.schema, cad.meta.count, cad.header.FILE_NAME[1])) + +-- count instances per type +local counts: { [string]: number } = {} +for _, id in step.ids(cad) do + local t = cad.entities[id].type + counts[t] = (counts[t] or 0) + 1 +end +local types: { string } = {} +for t in counts do + table.insert(types, t) +end +table.sort(types) +for _, t in types do + print(string.format(" %-22s %d", t, counts[t])) +end + +-- follow references: PLANE -> AXIS2_PLACEMENT_3D -> its location point +local plane = cad.entities[step.byType(cad, "PLANE")[1]] +local placement = assert(step.get(cad, plane.args[2])) +local location = assert(step.get(cad, placement.args[2])) +print("plane origin:", table.concat(location.args[2], ", ")) + +-- the length unit is a complex instance +local si = assert(step.part(cad.entities[20], "SI_UNIT")) +print("length unit:", si[1].enum, si[2].enum) -- MILLI METRE +assert(si[1].enum == "MILLI") + +-- the product name +local product = cad.entities[step.byType(cad, "PRODUCT")[1]] +print("product:", product.args[1], product.args[2]) + +-- add a point and write the file as AP242 +local p = step.add(cad, "CARTESIAN_POINT", { "tip", step.real(step.real(step.real({ 40, 0, 8 }, 1), 2), 3) }) +local text = assert(F.saveString(cad, { schema = "AP242" })) +assert(string.find(text, "#" .. p .. "=CARTESIAN_POINT('tip',(40.,0.,8.));", 1, true)) +local back = assert(F.cad.load(text)) +assert(back.schema == "AP242" and #step.ids(back) == 10) -- add() also updates meta.count +print(string.format("wrote %d bytes of AP242 with #%d added", #text, p)) + +-- without a kernel plug-in the B-rep calls say so +local _, err = F.cad.tessellate(cad) +print("tessellate without a plug-in:", err.code) +print("cad example: ok") diff --git a/examples/data.luau b/examples/data.luau new file mode 100644 index 0000000..1ede440 --- /dev/null +++ b/examples/data.luau @@ -0,0 +1,64 @@ +-- examples/data.luau: one record through JSON, YAML, TOML, MessagePack and CBOR, plus CSV rows, an INI file and an +-- XML document. Run from the repository root: luau examples/data.luau (docs/guide/data.md explains the values). +local F = require("@formats") +local Types = F.Types + +-- an ordered record with a null, an empty object and a date +local save = Types.object() +Types.set(save, "player", "ada") +Types.set(save, "level", 7) +Types.set(save, "items", { "sword", "lamp" }) +Types.set(save, "guild", F.data.null) +Types.set(save, "flags", Types.object()) -- stays {} (a plain {} would be written as []) +Types.set(save, "saved", Types.Date.parse("2026-10-31T12:00:00Z")) + +local json = assert(F.saveString(save, { format = "json", indent = 2 })) +print(json) +local back = assert(F.data.load(json, { format = "json", ordered = true })) +assert(back.guild == F.data.null and Types.isObject(back.flags) and back.items[2] == "lamp") +assert(table.concat(Types.keys(back), ",") == "player,level,items,guild,flags,saved") + +for _, fmt in { "yaml", "toml", "msgpack", "cbor" } do + local v = save + if fmt == "toml" then -- TOML has no null + v = Types.object() + for _, k in Types.keys(save) do + if save[k] ~= F.data.null then + Types.set(v, k, save[k]) + end + end + end + local bytes = assert(F.save(v, nil, { format = fmt })) + local again = assert(F.data.load(bytes, { format = fmt })) + assert(again.player == "ada" and again.level == 7) + if fmt ~= "yaml" then + assert(Types.Date.is(again.saved) and Types.Date.toUnix(again.saved) == Types.Date.toUnix(save.saved)) + end + print(string.format("%-8s %4d bytes", fmt, buffer.len(bytes))) +end + +-- CSV: records with a header row +local csv = "name,score\nada,1200\n\"lee, jr\",400\n" +local recs = assert(F.data.load(csv, { format = "csv", header = true, numbers = true })) +local total = 0 +for _, r in recs do + total += r.score +end +print(string.format("csv: %d records, total score %d", #recs, total)) +assert(total == 1600 and recs[2].name == "lee, jr") + +-- INI with typed values +local ini = assert(F.data.load("[window]\nwidth = 800\nfullscreen = no\n", { format = "ini", types = true })) +assert(ini.window.width == 800 and ini.window.fullscreen == false) + +-- XML: find elements by name +local doc = assert(F.data.load('<scores><s who="ada">1200</s><s who="bob">950</s></scores>', { format = "xml" })) +local who = {} +for _, c in doc.root.children do + if type(c) == "table" and c.name == "s" then + table.insert(who, c.attrs.who .. "=" .. c.children[1]) + end +end +print("xml: " .. table.concat(who, " ")) +assert(#who == 2) +print("data example: ok") diff --git a/examples/font.luau b/examples/font.luau new file mode 100644 index 0000000..c24ff33 --- /dev/null +++ b/examples/font.luau @@ -0,0 +1,64 @@ +-- examples/font.luau: loads a TrueType font, prints its metrics, renders a line of text into a PNG and bakes the font +-- into a BMFont (descriptor + page images). Run from the repository root: luau examples/font.luau +-- It needs a .ttf: from the repo it uses the docs test font (generate it first with python3 -I tools/fixtures.py docs), +-- elsewhere set TTF_BYTES below to the bytes of any font (the luau CLI cannot read files). docs/guide/font.md explains. +local F = require("@formats") + +local TTF_BYTES: buffer? = nil +if not TTF_BYTES then + local ok, IN = pcall(function() + return require("@tests/docs/snippets/_inputs") + end) + if ok then + TTF_BYTES = IN.ttfBytes + end +end +if not TTF_BYTES then + print("font example: no font. Run `python3 -I tools/fixtures.py docs` in the repository, or set TTF_BYTES.") + return +end + +local font = assert(F.font.load(TTF_BYTES)) +print(string.format("%s %s: %d glyphs, %d units per em, ascent %d, descent %d", font.info.family or "?", + font.info.style or "", font.numGlyphs, font.unitsPerEm, font.ascent, font.descent)) + +-- render "Hello, fonts!" at 32 px into a white-on-dark rgba8 image +local px, text = 32, "Hello, fonts!" +local scale = px / font.unitsPerEm +local width, prev = 0, nil +for _, cp in utf8.codes(text) do + local g = font:glyphIndex(cp) + width += font:advance(g) + (if prev then font:kern(prev, g) else 0) + prev = g +end +local canvas = assert(F.ops.image.new(math.ceil(width * scale) + 8, math.ceil((font.ascent - font.descent) * scale) + 8)) +F.ops.image.fill(canvas, 24, 28, 40, 255) +local baseline = 4 + math.ceil(font.ascent * scale) +local pen = 4 +prev = nil +for _, cp in utf8.codes(text) do + local g = font:glyphIndex(cp) + if prev then + pen += font:kern(prev, g) * scale + end + local glyph = assert(font:rasterize(g, px)) -- alpha8, placed by meta.left / meta.top + if glyph.width > 0 then + F.ops.image.blit(canvas, glyph, math.floor(pen + glyph.meta.left + 0.5), baseline - glyph.meta.top) + end + pen += glyph.meta.advance + prev = g +end +local png = assert(F.save(canvas, nil, { format = "png" })) +print(string.format("rendered %q: %d x %d, %d bytes of PNG", text, canvas.width, canvas.height, buffer.len(png))) + +-- bake printable ASCII at 20 px into a BMFont for a game's text renderer +local baked = assert(F.format("bmfont").bake(font, { px = 20, file = "ui" })) +local fnt = assert(F.saveString(baked)) +for i, page in baked.pages do + local bytes = assert(F.save(page, nil, { format = "png" })) + print(string.format("bmfont page %s: %d x %d, %d bytes", baked.meta.pageFiles[i], page.width, page.height, buffer.len(bytes))) +end +print(string.format("bmfont descriptor: %d bytes, %d characters", #fnt, #baked.meta.bmfont.chars)) +local again = assert(F.font.load(fnt, { pages = baked.pages })) +assert(again:rasterize(again:glyphIndex(string.byte("A")))) +print("font example: ok") diff --git a/examples/image.luau b/examples/image.luau new file mode 100644 index 0000000..9f88954 --- /dev/null +++ b/examples/image.luau @@ -0,0 +1,50 @@ +-- examples/image.luau: build an image, edit it with F.ops.image, save it in several formats, make an animated GIF and +-- read it back. Run from the repository root: luau examples/image.luau (the .luaurc alias @formats points at src/). +-- On LuaJIT / LÖVE, the same calls work with local F = require("formats") (docs/guide/image.md). +local F = require("@formats") +local I = F.ops.image + +-- a 64 x 48 rgba8 gradient: 4 bytes per pixel, rows top to bottom, pixel (x, y) at byte (y * width + x) * 4 +local img = F.Types.Image.new(64, 48) +for y = 0, 47 do + for x = 0, 63 do + local o = (y * 64 + x) * 4 + buffer.writeu8(img.pixels, o, x * 4) + buffer.writeu8(img.pixels, o + 1, y * 5) + buffer.writeu8(img.pixels, o + 2, 128) + buffer.writeu8(img.pixels, o + 3, 255) + end +end + +-- edit: a white square blitted on, then a thumbnail, a crop, a rotation and a grey copy +local square = assert(I.new(16, 16)) +I.fill(square, 255, 255, 255, 200) +assert(I.blit(img, square, 24, 16)) +local thumb = assert(I.resize(img, 32, 24, "lanczos")) +local corner = assert(I.crop(img, 0, 0, 16, 16)) +local turned = assert(I.rotate90(img, 1)) +local grey = assert(I.convert(img, "gray8")) +assert(thumb.width == 32 and corner.width == 16 and turned.width == 48 and grey.format == "gray8") +print(string.format("pixel (30, 20) after the blit: %d %d %d %d", I.getPixel(img, 30, 20))) + +-- save in several formats and load each back +for _, fmt in { "png", "jpeg", "webp", "qoi", "bmp", "tga", "gif" } do + local bytes = assert(F.save(img, nil, { format = fmt })) + local back = assert(F.load(bytes)) + assert(back.width == 64 and back.height == 48 and F.detect(bytes) == fmt) + print(string.format("%-5s %6d bytes", fmt, buffer.len(bytes))) +end + +-- an animation: four frames, 0.1 s each, looping forever +local frames = {} +for i = 1, 4 do + frames[i] = assert(I.rotate90(thumb, (i - 1) * 2)) -- every frame the same size: 0 or 2 quarter turns + local marker = assert(I.new(4, 4)) + I.fill(marker, 255, 0, 0) + I.blit(frames[i], marker, (i - 1) * 8, 0) -- a red marker that moves right +end +local anim = assert(I.fromFrames(frames, 0.1)) +local gif = assert(F.save(anim, nil, { format = "gif" })) +local back = assert(F.load(gif)) +assert(I.frameCount(back) == 4 and back.loops == 0) +print(string.format("animated gif: %d frames, %.1f s", I.frameCount(back), I.durations(back)[1] * 4)) diff --git a/examples/layered.luau b/examples/layered.luau new file mode 100644 index 0000000..9fb78c8 --- /dev/null +++ b/examples/layered.luau @@ -0,0 +1,55 @@ +-- examples/layered.luau: build a layered document (a group, a clipping layer, a blend mode), flatten it, save it as +-- PSD and Aseprite, and make a small Aseprite animation exported as a GIF. Run from the repository root: +-- luau examples/layered.luau (docs/guide/layered.md explains the type). +local F = require("@formats") +local I, L = F.ops.image, F.Types.Layered + +local function solid(w, h, r, g, b, a) + local img = assert(I.new(w, h)) + I.fill(img, r, g, b, a) + return img +end + +local doc = L.new(64, 64) +local shadow = L.layer("Shadow", solid(64, 64, 0, 0, 80, 255)) +shadow.clip = true -- only where Card has alpha +shadow.blend = "multiply" +local card = L.layer("Card", solid(40, 40, 250, 200, 60, 255), 12, 12) +doc.layers = { + L.layer("Paper", solid(64, 64, 245, 245, 240, 255)), -- bottom + L.group("Art", { card, shadow }), + L.layer("Glass", solid(64, 20, 255, 255, 255, 255), 0, 0), -- top +} +doc.layers[3].opacity = 0.25 + +local flat = assert(F.ops.layers.flatten(doc)) +print(string.format("flattened %dx%d, pixel (32, 40) = %d %d %d %d", flat.width, flat.height, I.getPixel(flat, 32, 40))) +for layer, depth in F.ops.layers.leaves(doc.layers) do + print(string.rep(" ", depth) .. layer.name .. " (" .. layer.blend .. ")") +end + +-- save and reload in both layered formats +for _, fmt in { "psd", "aseprite" } do + local bytes = assert(F.save(doc, nil, { format = fmt })) + local back = assert(F.load(bytes)) + assert(back.kind == "layered" and back.width == 64) + local again = assert(F.ops.layers.flatten(back)) + local r1 = I.getPixel(again, 32, 40) + local r2 = I.getPixel(flat, 32, 40) + assert(math.abs(r1 - r2) <= 2) + print(string.format("%-8s %6d bytes, %d top-level layers", fmt, buffer.len(bytes), #back.layers)) +end + +-- an animation: a dot moving across four frames +local anim = L.new(16, 16) +local dot = solid(4, 4, 255, 60, 60, 255) +anim.frames = {} +for i = 1, 4 do + anim.frames[i] = { layers = { L.layer("Back", solid(16, 16, 20, 20, 30, 255)), L.layer("Dot", dot, i * 3 - 2, 6) }, delay = 0.15 } +end +anim.layers = anim.frames[1].layers +local ase = assert(F.save(anim, nil, { format = "aseprite" })) +local gifImage = assert(F.ops.layers.flattenFrames(assert(F.load(ase)))) +local gif = assert(F.save(gifImage, nil, { format = "gif" })) +assert(I.frameCount(assert(F.load(gif))) == 4) +print("aseprite animation -> gif: 4 frames, " .. buffer.len(gif) .. " bytes") diff --git a/examples/love/main.lua b/examples/love/main.lua index 7b00776..a3cd6b0 100644 --- a/examples/love/main.lua +++ b/examples/love/main.lua @@ -3,8 +3,9 @@ -- FORMATS_SMOKE=1 xvfb-run love examples/love (headless: checks, a screenshot, then quits; exit code 1 on -- failure) -- It decodes repo fixtures (PNG suite, a MagicaVoxel model, a glTF box), round-trips an image through PNG / JPEG / --- WebP / GIF / QOI / BMP and a tone through FLAC / WAV / Vorbis / MP3, and shows them with love.graphics / love.audio --- through the host's toImageData / toSoundData. +-- WebP / GIF / QOI / BMP and a tone through FLAC / WAV / Vorbis / MP3, rasterizes an SVG, plays an animated GIF as a +-- video (decoded in love.update with a time budget per frame), and shows them with love.graphics / love.audio through +-- the host's toImageData / toSoundData. docs/guide/README.md explains the API. local root = (love.filesystem.getSource():gsub("/examples/love/?$", "")) package.path = root .. "/build/luajit/?.lua;" .. root .. "/build/luajit/?/init.lua;" .. package.path local F = require("formats") @@ -28,6 +29,8 @@ end local function errstr(e) return e and (type(e) == "table" and (tostring(e.code) .. ": " .. tostring(e.message)) or tostring(e)) or "" end local tiles, sound, voxelInfo = {}, nil, "" +local video, videoImage, videoClock, videoFrames = nil, nil, 0, 0 -- the animated GIF, played as a video +local BUDGET = 0.004 -- seconds of decoding per love.update local function tile(name, img) local data = F.host.toImageData(img) @@ -62,6 +65,31 @@ function love.load() end end + -- an SVG, rasterized to an rgba8 Image + local svg = [[<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24"> + <circle cx="12" cy="12" r="10" fill="#f4b400" stroke="#333" stroke-width="1"/> + <path d="M7 14 Q12 19 17 14" fill="none" stroke="#333" stroke-width="1.5" stroke-linecap="round"/> + <circle cx="9" cy="9.5" r="1.5" fill="#333"/><circle cx="15" cy="9.5" r="1.5" fill="#333"/></svg>]] + local vec, sve = F.load(svg, { format = "svg" }) + local icon, re = vec and F.ops.vector.rasterize(vec, 96, 96) + if check(icon ~= nil and icon.width == 96, "svg rasterize", errstr(sve or re)) then tile("svg", icon) end + + -- an animated GIF made from frames, reopened as a video and played in love.update + local frameList = {} + for i = 0, 7 do + local f = F.ops.image.new(48, 48) + F.ops.image.fill(f, 30, 30, 40, 255) + local block = F.ops.image.new(12, 12) + F.ops.image.fill(block, 255, 120 + i * 16, 40, 255) + F.ops.image.blit(f, block, i * 5, 18) + frameList[#frameList + 1] = f + end + local anim = F.ops.image.fromFrames(frameList, 0.08) + local gif, ge2 = anim and F.save(anim, nil, { format = "gif" }) + local ve2 + video, ve2 = gif and F.video.open(gif) + check(video ~= nil and video.frames == 8, "gif as video", errstr(ge2 or ve2)) + -- a voxel model: decode, mesh it, report local vox, ve = F.load(root .. "/tests/fixtures/vox/chr_knight.vox") if check(vox ~= nil and vox.kind == "scene", "vox fixture", errstr(ve)) then @@ -95,6 +123,25 @@ function love.load() end end +-- decode the next video frame when it is due, spending at most BUDGET seconds per update (the game-loop pattern: +-- a big frame never stalls the game for long, the video just runs late) +function love.update(dt) + if not video then return end + videoClock = videoClock + dt + local t0 = love.timer.getTime() + while love.timer.getTime() - t0 < BUDGET do + local f = video:nextFrame() + if not f then video:reset() break end -- loop + if f.pts + f.duration >= videoClock or f.index == video.frames then + local data = F.host.toImageData(video:toRGBA(f)) + if videoImage then videoImage:replacePixels(data) else videoImage = love.graphics.newImage(data) end + videoFrames = videoFrames + 1 + if f.index == video.frames then videoClock = 0 end + break + end + end +end + local frames = 0 function love.draw() love.graphics.clear(0.12, 0.12, 0.14) @@ -106,11 +153,16 @@ function love.draw() if x > 680 then x, y = 8, y + 124 end end love.graphics.print(voxelInfo, 8, 300) + if videoImage then + love.graphics.draw(videoImage, 228, 132, 0, 2) + love.graphics.print("gif as video", 228, 232) + end for i, line in ipairs(results) do love.graphics.print(line, 8, 320 + i * 14) end frames = frames + 1 if SMOKE and frames == 3 then + check(videoFrames > 0, "video frames shown", videoFrames) love.graphics.captureScreenshot(function(data) data:encode("png", "formats_smoke.png") print("screenshot: " .. love.filesystem.getSaveDirectory() .. "/formats_smoke.png") diff --git a/examples/music.luau b/examples/music.luau new file mode 100644 index 0000000..376d173 --- /dev/null +++ b/examples/music.luau @@ -0,0 +1,34 @@ +-- Music example (formats-luau): write a MIDI file from scratch, read it back, and render it to audio with the built-in +-- waveforms (pass a SoundFont as { soundfont = sf2Bytes } for real instruments). Run from the repository root: +-- luau examples/music.luau (docs/guide/music.md explains the API). +local F = require("@formats") + +-- 1. a Midi: 480 ticks per quarter note, absolute ticks, a tempo, a track name and a little melody +local midi = F.Types.Midi.new(480) +local events = { + { tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- 500000 us per beat = 120 BPM + { tick = 0, type = "meta", meta = 0x03, data = { string.byte("Melody", 1, -1) } }, -- the track name + { tick = 0, type = "program", channel = 0, data = { 0 } }, +} +local tick = 0 +for _, note in { 60, 62, 64, 65, 67, 67, 69, 67 } do + table.insert(events, { tick = tick, type = "noteOn", channel = 0, data = { note, 96 } }) + tick += 240 -- an eighth note + table.insert(events, { tick = tick, type = "noteOff", channel = 0, data = { note, 0 } }) +end +table.insert(midi.tracks, { events = events }) + +-- 2. save as .mid and read it back +local bytes = assert(F.save(midi, nil, { format = "midi" })) +local song = assert(F.music.load(bytes)) +print(string.format("midi: %d bytes, type %d, %d track(s), \"%s\", %.1f s at %d BPM", buffer.len(bytes), song.format, + #song.tracks, tostring(song.tracks[1].name), song.meta.length, song.meta.tempos[1].bpm)) +assert(song.meta.length == 2) + +-- 3. render: a Decoder (stereo f32), turned into an Audio, then saved as WAV +local dec = song:render({ sampleRate = 22050, tail = 0.5 }) +local audio = assert(F.ops.audio.toAudio(dec)) +local peak = F.ops.audio.peak(audio) +local wav = assert(F.save(audio, nil, { format = "wav" })) +print(string.format("rendered: %.2f s, peak %.2f, %d bytes of WAV", audio.frames / audio.sampleRate, peak, buffer.len(wav))) +assert(audio.frames == 2.5 * 22050 and peak > 0) diff --git a/examples/playlist.luau b/examples/playlist.luau new file mode 100644 index 0000000..58f93b1 --- /dev/null +++ b/examples/playlist.luau @@ -0,0 +1,47 @@ +-- examples/playlist.luau: reads an M3U with a base URL, inspects an HLS master playlist, and converts a playlist to +-- PLS and XSPF. Run from the repository root: luau examples/playlist.luau (docs/guide/playlist.md explains the type). +local F = require("@formats") + +local M3U = "#EXTM3U\n#PLAYLIST:Road Trip\n#EXTINF:215,Ada - First Song\nmusic/first.mp3\n" + .. "#EXTINF:187,Bob - Second Song\nhttps://cdn.example/second.ogg\n#EXTINF:-1,Live\nhttp://radio.example/live\n" + .. "C:\\Music\\local.flac\n" + +local pl = assert(F.playlist.load(M3U, { baseUrl = "https://example.com/lists/trip.m3u" })) +print(string.format("%s (%s): %d entries", pl.title, pl.format, #pl.entries)) +local total = 0 +for i, e in pl.entries do + print(string.format(" %d. %-32s %-18s %s", i, e.url, e.title or "", if e.playable then "ok" else "skip: " .. tostring(e.reason))) + total += e.duration or 0 +end +assert(pl.entries[1].url == "https://example.com/lists/music/first.mp3") +assert(not pl.entries[4].playable and pl.entries[4].reason == "local path") +print(string.format("known length: %d s", total)) + +-- keep only what a player can fetch, then convert +local keep = {} +for _, e in pl.entries do + if e.playable then + table.insert(keep, e) + end +end +pl.entries = keep +local pls = assert(F.saveString(pl, { format = "pls" })) +local xspf = assert(F.saveString(pl, { format = "xspf" })) +assert(F.playlist.load(pls).entries[2].duration == 187) +assert(F.playlist.load(xspf).entries[1].title == "Ada - First Song") +print(string.format("pls %d bytes, xspf %d bytes", #pls, #xspf)) + +-- an HLS master playlist: pick the variant that fits a bandwidth +local MASTER = "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360\nlow.m3u8\n" + .. "#EXT-X-STREAM-INF:BANDWIDTH=2400000,RESOLUTION=1280x720\nhigh.m3u8\n" +local hls = assert(F.playlist.load(MASTER, { baseUrl = "https://cdn.example/show/master.m3u8" })) +assert(hls.format == "hls" and hls.hls.master) +local best = nil +for _, v in hls.entries do + if v.bandwidth <= 1500000 and (not best or v.bandwidth > best.bandwidth) then + best = v + end +end +print("variant for 1.5 Mbit/s: " .. best.attributes.RESOLUTION .. " " .. best.url) +assert(best.url == "https://cdn.example/show/low.m3u8") +print("playlist example: ok") diff --git a/examples/scene.luau b/examples/scene.luau new file mode 100644 index 0000000..c7e36de --- /dev/null +++ b/examples/scene.luau @@ -0,0 +1,81 @@ +-- examples/scene.luau: builds a 3D scene from scratch (a cube with a material, plus a voxel grid), edits it with +-- F.ops.mesh and saves it as GLB, OBJ + MTL and STL. Run from the repository root: luau examples/scene.luau +-- (docs/guide/scene.md explains the Scene type). +local F = require("@formats") +local S = F.Types.Scene + +-- a unit cube: 8 corners, 12 triangles (indices are 0-based vertex numbers, as in glTF) +local corners = { + { -0.5, -0.5, -0.5 }, { 0.5, -0.5, -0.5 }, { 0.5, 0.5, -0.5 }, { -0.5, 0.5, -0.5 }, + { -0.5, -0.5, 0.5 }, { 0.5, -0.5, 0.5 }, { 0.5, 0.5, 0.5 }, { -0.5, 0.5, 0.5 }, +} +local tris = { + 0, 2, 1, 0, 3, 2, -- back (-z) + 4, 5, 6, 4, 6, 7, -- front (+z) + 0, 1, 5, 0, 5, 4, -- bottom + 3, 7, 6, 3, 6, 2, -- top + 0, 4, 7, 0, 7, 3, -- left + 1, 2, 6, 1, 6, 5, -- right +} +local pos = S.accessor(nil, "f32", 3, #corners) -- tightly packed: x, y, z per vertex +for i, c in corners do + for k = 1, 3 do + buffer.writef32(pos.data, ((i - 1) * 3 + k - 1) * 4, c[k]) + end +end +local idx = S.accessor(nil, "u32", 1, #tris) +for i, v in tris do + buffer.writeu32(idx.data, (i - 1) * 4, v) +end + +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, indices = idx, mode = "triangles", material = 1 }, "cube") +local red = S.material("red") +red.baseColor = { 0.8, 0.05, 0.05, 1 } -- linear RGBA +red.metallic, red.roughness = 0, 0.6 +scene.materials[1] = red +scene.nodes[1].translation = { 0, 0.5, 0 } -- sit on the ground (y up) +scene.meta.up = "y" + +-- flat normals: split the corners so each face has its own normal +local prim = scene.meshes[1].primitives[1] +prim = assert(F.ops.mesh.computeNormals(prim, { flat = true })) +scene.meshes[1].primitives[1] = prim +assert(prim.attributes.NORMAL.count == 36) + +local lo, hi = F.ops.mesh.bounds(scene) -- world space: the node's translation applies +print(string.format("cube bounds: (%g, %g, %g) .. (%g, %g, %g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3])) +assert(lo[2] == 0 and hi[2] == 1) + +-- save: GLB (one buffer), OBJ (+ the .mtl in opts.files), STL (geometry only) +local glb = assert(F.save(scene, nil, { format = "glb" })) +local files = {} +local obj = assert(F.save(scene, nil, { format = "obj", name = "cube.obj", files = files })) +local stl = assert(F.save(scene, nil, { format = "stl" })) +for name, data in files do + print("obj writes " .. name .. " too (" .. (if type(data) == "string" then #data else buffer.len(data)) .. " bytes)") +end +print(string.format("glb %d bytes, obj %d bytes, stl %d bytes", buffer.len(glb), buffer.len(obj), buffer.len(stl))) + +local back = assert(F.model.load(glb)) +assert(#back.meshes == 1 and back.materials[1].name == "red") + +-- voxels: a 4 x 4 x 4 grid with a staircase, greedy-meshed into triangles +local V = F.Types.Voxels +local grid = V.new(4, 4, 4) +grid.palette[1] = { 90, 160, 60, 255 } +local cells = 0 +for x = 0, 3 do + for y = 0, 3 do + for z = 0, x do + V.set(grid, x, y, z, 1) -- cell (x, y, z) = palette entry 1 (stored at x + 4 * (y + 4 * z)) + cells += 1 + end + end +end +local vprim = assert(F.ops.mesh.voxelsToPrimitive(grid)) +print(string.format("voxels: %d cells set, greedy mesh with %d triangles", cells, vprim.indices.count // 3)) +local vox = S.fromPrimitive(vprim, "stairs") +vox.materials[1] = S.material("voxels") +vprim.material = 1 +assert(F.save(vox, nil, { format = "glb" })) +print("scene example: ok") diff --git a/examples/tilemap.luau b/examples/tilemap.luau new file mode 100644 index 0000000..b1ef087 --- /dev/null +++ b/examples/tilemap.luau @@ -0,0 +1,57 @@ +-- examples/tilemap.luau: read a Tiled map (TMX), walk its tile layer with the flip flags, find an object, edit the map +-- and convert it to TMJ. Run from the repository root: luau examples/tilemap.luau (docs/guide/tilemap.md). +local F = require("@formats") + +local tmx = [[<?xml version="1.0" encoding="UTF-8"?> +<map version="1.10" orientation="orthogonal" renderorder="right-down" width="5" height="3" tilewidth="16" + tileheight="16" infinite="0" nextlayerid="3" nextobjectid="2"> + <tileset firstgid="1" name="terrain" tilewidth="16" tileheight="16" tilecount="16" columns="4"> + <image source="terrain.png" width="64" height="64"/> + </tileset> + <layer id="1" name="ground" width="5" height="3"> + <data encoding="csv"> +1,2,2,2,3, +5,0,0,0,7, +9,10,2147483658,10,11 +</data> + </layer> + <objectgroup id="2" name="things"> + <object id="1" name="door" type="Door" x="32" y="16" width="16" height="16"> + <properties><property name="locked" type="bool" value="true"/></properties> + </object> + </objectgroup> +</map>]] + +local map = assert(F.load(tmx)) +print(string.format("%dx%d tiles of %dx%d px, %d layers", map.width, map.height, map.tileWidth, map.tileHeight, #map.layers)) + +local FLIP_H, FLAGS = 0x80000000, 0xF0000000 +local ground = map.layers[1] +for y = 0, ground.height - 1 do + local row = {} + for x = 0, ground.width - 1 do + local raw = ground.data[1 + x + y * ground.width] + local gid = bit32.band(raw, bit32.bnot(FLAGS)) + row[#row + 1] = if gid == 0 then " ." elseif bit32.btest(raw, FLIP_H) then string.format("%2dh", gid) else string.format("%2d", gid) + end + print(table.concat(row, " ")) +end + +local door +for _, o in map.layers[2].objects do + if o.class == "Door" then + door = o + end +end +assert(door and door.properties.locked == true) +print(string.format("door at tile (%d, %d), locked", door.x // map.tileWidth, door.y // map.tileHeight)) + +-- edit: fill the hole in the middle row, then write TMJ and read it back +for x = 1, 3 do + ground.data[1 + x + 1 * ground.width] = 6 +end +local tmj = assert(F.saveString(map, { format = "tmj" })) +local back = assert(F.load(tmj, { format = "tiled" })) +assert(back.layers[1].data[8] == 6 and back.layers[1].data[13] == 0x8000000A) +assert(back.layers[2].objects[1].properties.locked == true) +print("as TMJ: " .. #tmj .. " characters; tileset image " .. back.tilesets[1].imageSource) diff --git a/examples/vector.luau b/examples/vector.luau new file mode 100644 index 0000000..2e75012 --- /dev/null +++ b/examples/vector.luau @@ -0,0 +1,41 @@ +-- examples/vector.luau: parse an SVG, inspect its paths, rasterize it at two sizes, build a Vector from scratch and +-- write it as SVG. Run from the repository root: luau examples/vector.luau (docs/guide/vector.md explains the type). +local F = require("@formats") + +local svg = [[<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24"> + <rect x="1" y="1" width="22" height="22" rx="4" fill="#2d6cdf"/> + <path d="M6 12 L10 16 L18 8" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" + stroke-linejoin="round"/> +</svg>]] + +local icon = assert(F.vector.load(svg)) +print(string.format("%dx%d, viewBox %s, %d paths", icon.width, icon.height, table.concat(icon.viewBox, " "), #icon.paths)) +for i, p in icon.paths do + print(i, p.fill and p.fill.type or "no fill", p.stroke and "stroke " .. p.strokeWidth or "no stroke", #p.d .. " commands") +end + +-- rasterize: the default size, and a larger one (the viewBox scales to fit) +local small = assert(F.ops.vector.rasterize(icon)) +local big = assert(F.ops.vector.rasterize(icon, 256, 256)) +assert(small.width == 48 and big.width == 256) +local r, _, b, a = F.ops.image.getPixel(big, 128, 20) +assert(a == 255 and b > r, "the blue background") +local png = assert(F.save(big, nil, { format = "png" })) +print("rasterized to a 256x256 PNG of " .. buffer.len(png) .. " bytes") + +-- a Vector from scratch: a red triangle, written as SVG and read back +local v = F.Types.Vector.new(32, 32) +table.insert(v.paths, { + d = { { op = "M", 4, 28 }, { op = "L", 16, 4 }, { op = "L", 28, 28 }, { op = "Z" } }, + fill = { type = "color", color = { 220, 40, 40, 255 } }, + fillRule = "nonzero", + strokeWidth = 0, + opacity = 1, +}) +local text = assert(F.saveString(v, { format = "svg" })) +local again = assert(F.vector.load(text)) +assert(#again.paths == 1) +local tri = assert(F.ops.vector.rasterize(again)) +local tr = F.ops.image.getPixel(tri, 16, 20) +assert(tr == 220) +print("triangle SVG: " .. #text .. " characters") diff --git a/examples/video.luau b/examples/video.luau new file mode 100644 index 0000000..abfe154 --- /dev/null +++ b/examples/video.luau @@ -0,0 +1,52 @@ +-- Video example (formats-luau): make frames with F.ops.image, write them as an AVI (Motion-JPEG), then open the +-- video, walk its packets and frames, seek, and turn it into an animated GIF. Run from the repository root: +-- luau examples/video.luau (docs/guide/video.md explains the API). +local F = require("@formats") +local I = F.ops.image + +-- 1. twelve 64 x 48 frames: a square moving across a dark background +local frames = {} +for i = 0, 11 do + local img = assert(I.new(64, 48)) + I.fill(img, 20, 24, 40, 255) + local square = assert(I.new(12, 12)) + I.fill(square, 255, 200, 40, 255) + I.blit(img, square, i * 4, 18) + frames[i + 1] = img +end +local clip = assert(F.video.fromFrames(frames, 1 / 12)) -- 12 fps +local avi = assert(F.save(clip, nil, { format = "avi", quality = 85 })) +print(string.format("avi: %d bytes", buffer.len(avi))) + +-- 2. open it: the decoder, its demuxer and the video track +local v = assert(F.video.open(avi)) +local track = v.track :: any +print(string.format("%s / %s %dx%d %.1f fps %d frames %.2f s", v.format, v.codec, v.width, v.height, v.frameRate, + v.frames, v.duration)) +local packets = 0 +for p in v.demuxer:packets(track.id) do + packets += 1 + assert(p.keyframe) -- every MJPEG frame is a keyframe +end +v:reset() + +-- 3. decode every frame (yuv420p), keep rgba8 copies, and check where the square ended up +local decoded = {} +while true do + local f = v:nextFrame() + if not f then break end + table.insert(decoded, v:toRGBA(f)) +end +local last = decoded[#decoded] +local r, g = I.getPixel(last, 44 + 6, 18 + 6) -- the centre of the last square +print(string.format("%d packets, last frame centre pixel r=%d g=%d", packets, r, g)) +assert(packets == 12 and r > 200 and g > 150) + +-- 4. seek, then turn the decoded frames into an animated GIF (a video does not save to an image format directly) +v:seek(0.5) +local f = assert(v:nextFrame()) +print(string.format("after seek(0.5): pts %.3f", f.pts)) +local gif = assert(F.save(assert(I.fromFrames(decoded, 1 / v.frameRate)), nil, { format = "gif" })) +local anim = assert(F.image.load(gif)) +print(string.format("gif: %d bytes, %d frames", buffer.len(gif), I.frameCount(anim))) +assert(I.frameCount(anim) == 12) diff --git a/tests/docs/.gitignore b/tests/docs/.gitignore new file mode 100644 index 0000000..233ed02 --- /dev/null +++ b/tests/docs/.gitignore @@ -0,0 +1,2 @@ +# generated by tools/docs_check.py (tools/fixtures/docs.py) +snippets/ diff --git a/tools/docs_check.py b/tools/docs_check.py new file mode 100644 index 0000000..181349f --- /dev/null +++ b/tools/docs_check.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +# Docs check (python3 -I tools/docs_check.py [page ...] [--list]): turns every code snippet of docs/guide/*.md and every +# example under examples/*.luau into tests, so a snippet that drifts from the API fails `bash tools/test.sh`. +# tools/fixtures/docs.py calls generate() (test.sh runs the fixture generators first), and running this script by +# hand regenerates the tests of the named pages (all by default). +# +# Snippets. Every ```luau block of a guide page runs, under both runtimes, unless a marker comment sits on the line +# right before its fence (an HTML comment, invisible when the page is rendered): +# <!-- doc:display <why> --> shown, not run: code that needs Roblox, LÖVE or a plug-in. ```lua blocks (LÖVE / plain +# LuaJIT code) must carry it too; other languages (sh, json, ...) are never run. +# <!-- doc:files --> runs only on hosts with a file system (LuaJIT): string literals starting with "assets/ +# or "out/ point into tests/gen/docs_files/, where the input generators put their files. +# <!-- doc:continue --> runs in the same scope as the snippet before it (its locals are visible). +# A snippet sees `F` (the library) and its input variables: every name it uses that ends in Bytes (a buffer) or Text +# (a string), e.g. pngBytes, srtText, looked up in the inputs the tools/fixtures/docs_*.py generators emit (each emits +# tests/gen/docs_<x>.luau = { files = { [file name] = bytes }, vars = { [variable] = file name } } through emit_inputs +# below). print is silenced. A snippet fails when it throws: write the expectations as assert(...). +# +# Examples. examples/*.luau are standalone programs (luau examples/image.luau from the repo root); each is copied into +# a test as it is. +# +# Output: tests/docs/snippets/<page>.luau and example_<name>.luau (gitignored, regenerated), plus _inputs.luau. +import os, re, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +GUIDE = os.path.join(ROOT, "docs", "guide") +EXAMPLES = os.path.join(ROOT, "examples") +OUT = os.path.join(ROOT, "tests", "docs", "snippets") +FIXTURES = os.path.join(ROOT, "tools", "fixtures") +FILES_DIR = "tests/gen/docs_files" # relative to the repo root (the tests run from there) + +MARKER = re.compile(r"^\s*<!--\s*doc:(\w+)\b(.*?)-->\s*$") +FENCE = re.compile(r"^```\s*([\w+-]*)\s*$") +VAR = re.compile(r"(?<![\w.:])([a-z]\w*(?:Bytes|Text))\b") +PATHLIT = re.compile(r"""(["'])(assets|out)/""") +LUA_LANGS = ("luau", "lua") + + +class DocError(Exception): + pass + + +def snippets(path): + """[(line, lang, code, marker)] for the fenced blocks of a markdown file""" + lines = open(path, encoding="utf-8").read().split("\n") + out, i = [], 0 + while i < len(lines): + m = FENCE.match(lines[i]) + if not m or not m.group(1): + if m: + raise DocError("%s:%d: a code fence without a language" % (os.path.relpath(path, ROOT), i + 1)) + i += 1 + continue + lang, start = m.group(1), i + 1 + prev = lines[i - 1] if i > 0 else "" + mk = MARKER.match(prev) + marker = mk.group(1) if mk else None + j = i + 1 + while j < len(lines) and not lines[j].startswith("```"): + j += 1 + if j >= len(lines): + raise DocError("%s:%d: unclosed code fence" % (os.path.relpath(path, ROOT), start)) + out.append((start, lang, "\n".join(lines[i + 1:j]), marker)) + i = j + 1 + return out + + +def input_modules(): + """the tests/gen modules the input generators emit: docs_<x> for every tools/fixtures/docs_<x>.py""" + return sorted(f[:-3] for f in os.listdir(FIXTURES) if f.startswith("docs_") and f.endswith(".py")) + + +def inputs_module(): + mods = input_modules() + req = "\n".join('\trequire("@tests/gen/%s"),' % m for m in mods) + return """-- tests/docs/snippets/_inputs: GENERATED by tools/docs_check.py - do not edit. The inputs the guide snippets read: +-- DocIN.pngBytes -> a fresh buffer of the file the variable names, DocIN.srtText -> a string (tools/fixtures/docs_*.py). +local mods = { +%s +} +local function find(var: string): string? + for _, m in mods do + local file = m.vars[var] + if file then + return m.files[file] + end + end + return nil +end +return setmetatable({}, { + __index = function(_, var: string): any + local data = find(var) + if data == nil then + error("docs: no input named " .. var .. " (add it to a tools/fixtures/docs_*.py generator)", 2) + end + if string.sub(var, -4) == "Text" then + return data + end + return buffer.fromstring(data) + end, +}) +""" % req + + +def indent(code, n=2): + pad = "\t" * n + return "\n".join(pad + l if l.strip() else "" for l in code.split("\n")) + + +def page_test(path): + """(test source, run count, display count) for one guide page""" + rel = os.path.relpath(path, ROOT) + name = os.path.basename(path)[:-3] + chunks = [] # { line, files, code, vars } + shown = 0 + for line, lang, code, marker in snippets(path): + if lang not in LUA_LANGS: + continue + if marker not in (None, "display", "files", "continue"): + raise DocError("%s:%d: unknown marker doc:%s" % (rel, line, marker)) + if marker == "display": + shown += 1 + continue + if lang != "luau": + raise DocError("%s:%d: a ```lua block must be marked <!-- doc:display ... --> (only luau blocks run)" % (rel, line)) + files = marker == "files" + if files: + code = PATHLIT.sub(lambda m: m.group(1) + FILES_DIR + "/" + m.group(2) + "/", code) + if marker == "continue": + if not chunks: + raise DocError("%s:%d: doc:continue on the first snippet" % (rel, line)) + prev = chunks[-1] + prev["code"] += "\n-- docs line %d\n" % line + code + prev["vars"] |= set(VAR.findall(code)) + prev["files"] = prev["files"] or files + continue + chunks.append({"line": line, "files": files, "code": code, "vars": set(VAR.findall(code))}) + out = ["-- tests/docs/snippets/%s: GENERATED by tools/docs_check.py from %s - do not edit (edit the page)" % (name, rel), + 'local F = require("@formats")', + 'local DocT = require("@tests/T")', + 'local DocIN = require("@tests/docs/snippets/_inputs")', + 'local t = DocT.suite("docs/%s")' % name, + "local print = function(...: any) end", + "local snippets: { { line: number, files: boolean, run: () -> () } } = {}"] + for c in chunks: + decl = "".join("\t\tlocal %s = DocIN.%s\n" % (v, v) for v in sorted(c["vars"])) + out.append("snippets[#snippets + 1] = { line = %d, files = %s, run = function()\n%s%s\n\tend }" + % (c["line"], "true" if c["files"] else "false", decl, indent(c["code"]))) + out.append("""local ran, skipped = 0, 0 +for _, s in snippets do + if s.files and not F.host.hasFiles then + skipped += 1 + else + local ok, err = xpcall(s.run, debug.traceback) + t:check(ok, "%s:" .. s.line .. ": " .. tostring(err)) + ran += 1 + end +end +t:note("%%d snippets ran, %%d need a file system (skipped on %%s)", ran, skipped, F.host.name) +local _ = print +t:done() +""" % rel) + return "\n".join(out), len(chunks), shown + + +def example_test(path): + name = os.path.basename(path)[:-5] + src = open(path, encoding="utf-8").read() + head = "-- tests/docs/snippets/example_%s: GENERATED by tools/docs_check.py from examples/%s.luau - do not edit\n" % (name, name) + return head + src + + +def pages(filters=()): + if not os.path.isdir(GUIDE): + return [] + out = sorted(os.path.join(GUIDE, f) for f in os.listdir(GUIDE) if f.endswith(".md")) + return [p for p in out if not filters or any(f in os.path.basename(p) for f in filters)] + + +def examples(): + if not os.path.isdir(EXAMPLES): + return [] + return sorted(os.path.join(EXAMPLES, f) for f in os.listdir(EXAMPLES) if f.endswith(".luau")) + + +def write(path, text): + os.makedirs(os.path.dirname(path), exist_ok=True) + if os.path.exists(path) and open(path, encoding="utf-8").read() == text: + return + with open(path, "w", encoding="utf-8") as f: + f.write(text) + + +def generate(filters=()): + """writes the tests; returns (output paths, runnable snippets, display-only snippets, examples)""" + os.makedirs(OUT, exist_ok=True) + os.makedirs(os.path.join(ROOT, FILES_DIR, "assets"), exist_ok=True) + os.makedirs(os.path.join(ROOT, FILES_DIR, "out"), exist_ok=True) + want, nrun, nshow = {}, 0, 0 + want[os.path.join(OUT, "_inputs.luau")] = inputs_module() + for p in pages(filters): + src, r, s = page_test(p) + want[os.path.join(OUT, os.path.basename(p)[:-3] + ".luau")] = src + nrun, nshow = nrun + r, nshow + s + exs = examples() if not filters else [e for e in examples() if any(f in e for f in filters)] + for e in exs: + want[os.path.join(OUT, "example_" + os.path.basename(e))] = example_test(e) + if not filters: + for f in os.listdir(OUT): + p = os.path.join(OUT, f) + if f.endswith(".luau") and p not in want: + os.remove(p) + for p, text in want.items(): + write(p, text) + return list(want), nrun, nshow, len(exs) + + +def emit_inputs(ctx, files, vars): + """for tools/fixtures/docs_<x>.py: emits tests/gen/docs_<x>.luau ({ files, vars }) and writes the files into + tests/gen/docs_files/assets/ (the doc:files snippets read them there on hosts with a file system). + files: { file name: bytes }; vars: { variable name (ends in Bytes / Text): file name }""" + for v, f in vars.items(): + if not VAR.fullmatch(v): + raise DocError("docs input variable %s must end in Bytes or Text" % v) + if f not in files: + raise DocError("docs input %s names a missing file %s" % (v, f)) + adir = os.path.join(ctx.root, FILES_DIR, "assets") + os.makedirs(adir, exist_ok=True) + os.makedirs(os.path.join(ctx.root, FILES_DIR, "out"), exist_ok=True) + for f, data in files.items(): + p = os.path.join(adir, f) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as fh: + fh.write(data if isinstance(data, bytes) else data.encode()) + ctx.emit(ctx.name, {"files": files, "vars": vars}) + + +def main(): + args = [a for a in sys.argv[1:] if not a.startswith("--")] + if "--list" in sys.argv: + for p in pages(args): + for line, lang, code, marker in snippets(p): + if lang in LUA_LANGS: + print("%s:%d %s %s" % (os.path.relpath(p, ROOT), line, lang, marker or "run")) + return + try: + paths, nrun, nshow, nex = generate(args) + except DocError as e: + print("docs_check: " + str(e)) + sys.exit(1) + print("docs_check: %d snippets to run, %d display-only, %d examples -> %s" % (nrun, nshow, nex, os.path.relpath(OUT, ROOT))) + + +if __name__ == "__main__": + main() diff --git a/tools/fixtures/docs.py b/tools/fixtures/docs.py new file mode 100644 index 0000000..8ac9a8d --- /dev/null +++ b/tools/fixtures/docs.py @@ -0,0 +1,15 @@ +# Docs snippets (tools/fixtures.py): every ```luau block of docs/guide/*.md and every examples/*.luau becomes a test +# under tests/docs/snippets/ (tools/docs_check.py explains the markers). Generated here so `bash tools/test.sh` +# always tests the pages as they are; the inputs the snippets read come from tools/fixtures/docs_*.py. +import importlib.util, os + +INPUTS = ["docs/guide", "examples", "tools/docs_check.py"] + + +def generate(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + dc = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dc) + paths, nrun, nshow, nex = dc.generate() + print("fixtures: docs: %d snippets to run, %d display-only, %d examples" % (nrun, nshow, nex)) + ctx.outputs.extend(paths) diff --git a/tools/fixtures/docs_2d.py b/tools/fixtures/docs_2d.py new file mode 100644 index 0000000..590d87f --- /dev/null +++ b/tools/fixtures/docs_2d.py @@ -0,0 +1,106 @@ +# Docs inputs for the 2D pages (tools/fixtures.py; see tools/docs_check.py): a layered PSD written by ImageMagick (three +# layers: Sky, Box, a half-transparent Glow; the merged image flattened by ImageMagick), a two-frame Aseprite sprite +# (built with the chunk writer of tools/fixtures/aseprite.py), an SVG icon and a Tiled map as TMX and TMJ (hand-written +# from the Tiled format docs) with its tileset image tiles.png (ImageMagick). +# tests/gen/docs_2d.luau { files, vars = { psdBytes, asepriteBytes, svgText, tmxText, tmjText, tilesPngBytes } } +import importlib.util, os, struct, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/aseprite.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs2d_" + name, os.path.join(ctx.root, "tools", *name.split("/"))) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +SVG = """<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 32 32"> + <defs> + <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"> + <stop offset="0" stop-color="#3070c0"/> + <stop offset="1" stop-color="#a0d0ff"/> + </linearGradient> + </defs> + <rect width="32" height="32" rx="4" fill="url(#sky)"/> + <circle cx="22" cy="10" r="5" fill="#ffd040"/> + <path d="M2 30 L12 16 L20 26 L24 21 L30 30 Z" fill="#306030" stroke="#103010" stroke-width="1"/> +</svg> +""" + +# a 4 x 3 map of 16 x 16 tiles: one tileset (tiles.png, 4 columns), a tile layer, an object layer with a spawn point +TMX = """<?xml version="1.0" encoding="UTF-8"?> +<map version="1.10" tiledversion="1.11.0" orientation="orthogonal" renderorder="right-down" width="4" height="3" tilewidth="16" tileheight="16" infinite="0" nextlayerid="3" nextobjectid="2"> + <properties> + <property name="music" value="cave.ogg"/> + <property name="gravity" type="float" value="9.8"/> + </properties> + <tileset firstgid="1" name="tiles" tilewidth="16" tileheight="16" tilecount="8" columns="4"> + <image source="tiles.png" width="64" height="32"/> + </tileset> + <layer id="1" name="ground" width="4" height="3"> + <data encoding="csv"> +1,2,2,3, +5,0,0,7, +6,6,6,6 +</data> + </layer> + <objectgroup id="2" name="things"> + <object id="1" name="spawn" type="Spawn" x="24" y="16"> + <point/> + </object> + </objectgroup> +</map> +""" + +TMJ = """{ "type": "map", "version": "1.10", "orientation": "orthogonal", "renderorder": "right-down", + "width": 2, "height": 2, "tilewidth": 8, "tileheight": 8, "infinite": false, "nextlayerid": 2, "nextobjectid": 1, + "tilesets": [ { "firstgid": 1, "name": "t", "tilewidth": 8, "tileheight": 8, "tilecount": 4, "columns": 2, + "image": "t.png", "imagewidth": 16, "imageheight": 16 } ], + "layers": [ { "id": 1, "name": "main", "type": "tilelayer", "width": 2, "height": 2, "x": 0, "y": 0, + "opacity": 1, "visible": true, "data": [ 1, 2, 3, 2147483652 ] } ] } +""" + + +def aseprite(ctx): + A = load(ctx, "fixtures/aseprite.py") + W, H = 32, 24 + sky = bytes((40, 90, 160, 255)) * (W * H) + hero = bytes((220, 50, 50, 255)) * 64 + f1 = [ + A.layer_chunk("Background", flags=1 | 2 | 8), + A.layer_chunk("Hero"), + A.tags_chunk([("walk", 0, 1, 0, 0)]), + A.cel_chunk(0, 0, 0, W, H, sky), + A.cel_chunk(1, 4, 8, 8, 8, hero), + ] + f2 = [ + A.cel_chunk(0, 0, 0, W, H, b"", link=0), + A.cel_chunk(1, 12, 8, 8, 8, hero), + ] + return A.sprite(W, H, 32, [(100, f1), (250, f2)]) + + +def generate(ctx): + dc = load(ctx, "docs_check.py") + files = {"icon.svg": SVG, "level.tmx": TMX, "level.tmj": TMJ, "sprite.aseprite": aseprite(ctx)} + with tempfile.TemporaryDirectory() as d: + out = os.path.join(d, "art.psd") + ctx.nix("imagemagick", ["magick", + "(", "-size", "48x32", "xc:#3070c0", "-set", "label", "Sky", ")", + "(", "-size", "16x16", "xc:#e04040", "-set", "page", "+8+8", "-set", "label", "Box", ")", + "(", "-size", "20x10", "xc:rgba(255,255,0,0.5)", "-set", "page", "+24+18", "-set", "label", "Glow", ")", + "(", "-clone", "0--1", "-background", "none", "-flatten", ")", "-insert", "0", + "-depth", "8", "-type", "TrueColorAlpha", out]) + files["art.psd"] = open(out, "rb").read() + tiles = os.path.join(d, "tiles.png") + ctx.nix("imagemagick", ["magick", "-size", "64x32", "pattern:checkerboard", "-depth", "8", tiles]) + files["tiles.png"] = open(tiles, "rb").read() + dc.emit_inputs(ctx, files, { + "psdBytes": "art.psd", + "asepriteBytes": "sprite.aseprite", + "svgText": "icon.svg", + "tmxText": "level.tmx", + "tmjText": "level.tmj", + "tilesPngBytes": "tiles.png", + }) diff --git a/tools/fixtures/docs_3d.py b/tools/fixtures/docs_3d.py new file mode 100644 index 0000000..d302144 --- /dev/null +++ b/tools/fixtures/docs_3d.py @@ -0,0 +1,167 @@ +# Docs inputs for the 3D, CAD and font guide pages (tools/fixtures.py, tools/docs_check.py): Khronos glTF samples +# from tests/fixtures/gltf (BoxTextured embedded and with external .bin + PNG, Box.glb, RiggedSimple.glb), a +# hand-written OBJ + MTL cube, MagicaVoxel's chr_knight.vox, a small hand-written STEP file, an ASCII subset of +# DejaVu Sans (nixpkgs dejavu_fonts) made by fontTools as TTF, WOFF and WOFF2, and a two-glyph BMFont (text +# descriptor + PNG page) written here. +# tests/gen/docs_3d.luau { files = { [name] = bytes }, vars = { texturedGltfText = ..., ... } } +import importlib.util, json, os, struct, subprocess, zlib + +INPUTS = ["tools/docs_check.py", "tests/fixtures/gltf", "tests/fixtures/vox"] + +OBJ = """# a unit cube, one material +mtllib cube.mtl +o cube +v 0 0 0 +v 1 0 0 +v 1 1 0 +v 0 1 0 +v 0 0 1 +v 1 0 1 +v 1 1 1 +v 0 1 1 +vt 0 0 +vt 1 0 +vt 1 1 +vt 0 1 +usemtl red +f 1/1 4/4 3/3 2/2 +f 5/1 6/2 7/3 8/4 +f 1/1 2/2 6/3 5/4 +f 2/1 3/2 7/3 6/4 +f 3/1 4/2 8/3 7/4 +f 4/1 1/2 5/3 8/4 +""" + +MTL = """newmtl red +Ka 0 0 0 +Kd 0.8 0.1 0.1 +Ks 0.5 0.5 0.5 +Ns 32 +""" + +STEP = """ISO-10303-21; +HEADER; +FILE_DESCRIPTION(('a point and a direction'),'2;1'); +FILE_NAME('part.step','2026-10-31T12:00:00',('docs'),(''),'formats-luau docs','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1=CARTESIAN_POINT('origin',(0.,0.,0.)); +#2=DIRECTION('z',(0.,0.,1.)); +#3=DIRECTION('x',(1.,0.,0.)); +#4=AXIS2_PLACEMENT_3D('',#1,#2,#3); +#5=CARTESIAN_POINT('tip',(10.,20.,5.5)); +#6=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +ENDSEC; +END-ISO-10303-21; +""" + +def docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def png(w, h, rgba): + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff) + raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")) + + +def fonts(ctx): + """ASCII subset of DejaVu Sans as ttf / woff / woff2 bytes""" + out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#dejavu_fonts"], + capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1] + path = os.path.join(out, "share", "fonts", "truetype", "DejaVuSans.ttf") + code = r""" +import io, sys, json, base64 +from fontTools import subset +from fontTools.ttLib import TTFont +res = {} +for flavor in (None, "woff", "woff2"): + f = TTFont(sys.argv[1] if len(sys.argv) > 1 else %r) + opts = subset.Options() + opts.layout_features = ["kern"] + opts.name_IDs = ["*"] + opts.hinting = False + opts.flavor = flavor + s = subset.Subsetter(opts) + s.populate(unicodes=range(32, 127)) + s.subset(f) + b = io.BytesIO() + f.flavor = flavor + f.save(b) + res[flavor or "ttf"] = base64.b64encode(b.getvalue()).decode() +print(json.dumps(res)) +""" % path + import base64 + res = json.loads(ctx.python(["fonttools", "brotli"], code)) + return {k: base64.b64decode(v) for k, v in res.items()} + + +def bmfont(): + """a 16 x 8 page with 'A' (a filled 6 x 7 block) and 'B' (an outline), and its text descriptor""" + w, h = 16, 8 + px = bytearray(w * h * 4) + for y in range(7): + for x in range(6): + o = (y * w + x) * 4 + px[o:o + 4] = b"\xff\xff\xff\xff" + bx = 8 + x + if x in (0, 5) or y in (0, 6): + o = (y * w + bx) * 4 + px[o:o + 4] = b"\xff\xff\xff\xff" + fnt = ('info face="Mini" size=8 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=0 aa=1 ' + 'padding=0,0,0,0 spacing=1,1\n' + 'common lineHeight=9 base=7 scaleW=16 scaleH=8 pages=1 packed=0\n' + 'page id=0 file="mini_0.png"\n' + 'chars count=2\n' + 'char id=65 x=0 y=0 width=6 height=7 xoffset=0 yoffset=0 xadvance=7 page=0 chnl=15\n' + 'char id=66 x=8 y=0 width=6 height=7 xoffset=0 yoffset=0 xadvance=7 page=0 chnl=15\n' + 'kernings count=1\n' + 'kerning first=65 second=66 amount=-1\n') + return fnt, png(w, h, bytes(px)) + + +def generate(ctx): + dc = docs_check(ctx) + g = "tests/fixtures/gltf/" + files = { + "box_textured_embedded.gltf": ctx.read(g + "BoxTextured/glTF-Embedded/BoxTextured.gltf"), + "BoxTextured.gltf": ctx.read(g + "BoxTextured/glTF/BoxTextured.gltf"), + "BoxTextured0.bin": ctx.read(g + "BoxTextured/glTF/BoxTextured0.bin"), + "CesiumLogoFlat.png": ctx.read(g + "BoxTextured/glTF/CesiumLogoFlat.png"), + "Box.glb": ctx.read(g + "Box/glTF-Binary/Box.glb"), + "RiggedSimple.glb": ctx.read(g + "RiggedSimple/glTF-Binary/RiggedSimple.glb"), + "cube.obj": OBJ.encode(), + "cube.mtl": MTL.encode(), + "chr_knight.vox": ctx.read("tests/fixtures/vox/chr_knight.vox"), + "part.step": STEP.encode(), + } + f = fonts(ctx) + files["DejaVuSans-ascii.ttf"] = f["ttf"] + files["DejaVuSans-ascii.woff"] = f["woff"] + files["DejaVuSans-ascii.woff2"] = f["woff2"] + fnt, page = bmfont() + files["mini.fnt"] = fnt.encode() + files["mini_0.png"] = page + dc.emit_inputs(ctx, files, { + "texturedGltfText": "box_textured_embedded.gltf", # glTF with its texture embedded (data: URIs) + "boxGltfText": "BoxTextured.gltf", # glTF referencing BoxTextured0.bin and CesiumLogoFlat.png + "boxBinBytes": "BoxTextured0.bin", + "logoPngBytes": "CesiumLogoFlat.png", + "boxGlbBytes": "Box.glb", + "riggedGlbBytes": "RiggedSimple.glb", # skin + animation + "objText": "cube.obj", + "mtlText": "cube.mtl", + "voxBytes": "chr_knight.vox", + "stepText": "part.step", + "ttfBytes": "DejaVuSans-ascii.ttf", + "woffBytes": "DejaVuSans-ascii.woff", + "woff2Bytes": "DejaVuSans-ascii.woff2", + "fntText": "mini.fnt", + "fntPageBytes": "mini_0.png", + }) diff --git a/tools/fixtures/docs_av.py b/tools/fixtures/docs_av.py new file mode 100644 index 0000000..8019408 --- /dev/null +++ b/tools/fixtures/docs_av.py @@ -0,0 +1,116 @@ +# Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them): +# tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG + +# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of +# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT / +# ASS subtitles. +# tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } } +import importlib.util, os, struct, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/sf2.py", "tools/fixtures/mod.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_av_" + name, os.path.join(ctx.root, "tools", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def vlq(n): + out = [n & 0x7F] + n >>= 7 + while n: + out.append(0x80 | (n & 0x7F)) + n >>= 7 + return bytes(reversed(out)) + + +def track(events): + body = b"".join(vlq(dt) + data for dt, data in events) + b"\x00\xff\x2f\x00" + return b"MTrk" + struct.pack(">I", len(body)) + body + + +def midi(): + """SMF 1, 480 ticks per quarter: track 1 = name + tempo 120 bpm, track 2 = an eight-note melody on channel 0""" + t1 = track([(0, b"\xff\x03\x05Tempo"), (0, b"\xff\x51\x03" + (500000).to_bytes(3, "big")), + (0, b"\xff\x58\x04\x04\x02\x18\x08")]) + ev = [(0, b"\xff\x03\x06Melody"), (0, b"\xc0\x00")] + for i, note in enumerate([60, 62, 64, 65, 67, 65, 64, 62]): + ev.append((0, bytes((0x90, note, 100)))) + ev.append((240, bytes((0x80, note, 0)))) + t2 = track(ev) + return b"MThd" + struct.pack(">IHHH", 6, 1, 2, 480) + t1 + t2 + + +SRT = """1 +00:00:00,500 --> 00:00:02,000 +Hello, <i>world</i>. + +2 +00:00:02,500 --> 00:00:04,250 +Second line +spans two rows. +""" + +VTT = """WEBVTT + +intro +00:00.500 --> 00:02.000 align:start +Hello, <b>world</b>. + +00:02.500 --> 00:04.250 +Second cue. +""" + +ASS = """[Script Info] +Title: Docs +ScriptType: v4.00+ +PlayResX: 640 +PlayResY: 360 + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1 +Style: Sign,Arial,16,&H0000FFFF,&H000000FF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,1,0,8,10,10,10,1 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +Dialogue: 0,0:00:00.50,0:00:02.00,Default,,0,0,0,,Hello, {\\i1}world{\\i0}. +Dialogue: 0,0:00:02.50,0:00:04.25,Sign,,0,0,0,,A sign\\Nwith two lines +""" + + +def generate(ctx): + dc = load(ctx, "docs_check") + files = {} + with tempfile.TemporaryDirectory() as d: + src = ["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1"] + for name, codec in ( + ("clip.mp4", ["-c:v", "libx264", "-profile:v", "baseline", "-pix_fmt", "yuv420p", "-g", "5", + "-c:a", "aac", "-b:a", "64k"]), + ("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]), + ("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]), + ): + out = os.path.join(d, name) + ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out]) + files[name] = open(out, "rb").read() + files["tune.mid"] = midi() + sf2 = load(ctx, "fixtures/sf2") + files["bank.sf2"] = sf2.build_sf2(False)[0] + mod = load(ctx, "fixtures/mod") + files["song.mod"] = mod.song_basic() + files["subs.srt"] = SRT + files["subs.vtt"] = VTT + files["subs.ass"] = ASS + dc.emit_inputs(ctx, files, { + "mp4Bytes": "clip.mp4", + "aviBytes": "clip.avi", + "webmBytes": "clip.webm", + "midiBytes": "tune.mid", + "sf2Bytes": "bank.sf2", + "modBytes": "song.mod", + "srtText": "subs.srt", + "vttText": "subs.vtt", + "assText": "subs.ass", + }) diff --git a/tools/fixtures/docs_data.py b/tools/fixtures/docs_data.py new file mode 100644 index 0000000..218e596 --- /dev/null +++ b/tools/fixtures/docs_data.py @@ -0,0 +1,94 @@ +# Docs inputs for the archive / data / playlist pages (tools/fixtures.py; tools/docs_check.py explains the inputs): +# a zip and a .tar.gz by Python's zipfile / tarfile, a 7z (p7zip), .xz (xz) and .zst (zstd) by the reference tools, +# MessagePack / CBOR by the msgpack / cbor2 Python packages, a binary plist by plistlib, a CSV and playlists as text. +# tests/gen/docs_data.luau { files = { [name] = bytes }, vars = { zipBytes = "files.zip", ... } } +import importlib.util, io, os, plistlib, tarfile, tempfile, zipfile, datetime + +INPUTS = ["tools/docs_check.py"] + +MTIME = 1767225600 # 2026-01-01T00:00:00Z +README = b"formats-luau archive example\n" * 4 +SCORES = "name,score,level\nada,1200,3\nbob,950,2\n\"lee, jr\",400,1\n" +CODE = r""" +import sys, json, msgpack, cbor2, datetime +v = {"name": "ada", "score": 1200, "tags": ["x", "y"], "ratio": 0.5, "none": None, "raw": b"\x00\x01\x02"} +sys.stdout.buffer.write(json.dumps({"msgpack": msgpack.packb(v).hex(), "cbor": cbor2.dumps(v).hex()}).encode()) +""" + + +def docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + import json + dc = docs_check(ctx) + files = {} + tree = {"readme.txt": README, "src/main.luau": b"print('hello')\n", "data/scores.csv": SCORES.encode()} + b = io.BytesIO() + with zipfile.ZipFile(b, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr(zipfile.ZipInfo("src/", (2026, 1, 1, 0, 0, 0)), b"") + for name, data in tree.items(): + info = zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_DEFLATED + z.writestr(info, data) + files["files.zip"] = b.getvalue() + b = io.BytesIO() + with tarfile.open(fileobj=b, mode="w:gz", format=tarfile.PAX_FORMAT) as t: + for name, data in tree.items(): + info = tarfile.TarInfo(name) + info.size, info.mtime, info.mode = len(data), MTIME, 0o644 + t.addfile(info, io.BytesIO(data)) + files["files.tar.gz"] = b.getvalue() + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "notes.txt") + with open(src, "wb") as f: + f.write(README) + ctx.nix("xz", ["xz", "-k", "-9", src]) + ctx.nix("zstd", ["zstd", "-q", "-19", src, "-o", src + ".zst"]) + files["notes.txt.xz"] = open(src + ".xz", "rb").read() + files["notes.txt.zst"] = open(src + ".zst", "rb").read() + seven = os.path.join(d, "files.7z") + for name, data in tree.items(): + p = os.path.join(d, "t", name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + ctx.nix("p7zip", ["sh", "-c", "cd '%s' && 7z a -bd -mx=5 '%s' readme.txt src data > /dev/null" % (os.path.join(d, "t"), seven)]) + files["files.7z"] = open(seven, "rb").read() + packed = json.loads(ctx.python(["msgpack", "cbor2"], CODE)) + files["player.msgpack"] = bytes.fromhex(packed["msgpack"]) + files["player.cbor"] = bytes.fromhex(packed["cbor"]) + files["info.plist"] = plistlib.dumps({"CFBundleName": "Demo", "Version": 3, "Beta": False, + "Built": datetime.datetime(2026, 1, 1, 12, 0, 0), + "Icon": b"\x89PNG"}, fmt=plistlib.FMT_BINARY, sort_keys=False) + files["scores.csv"] = SCORES + files["mix.m3u"] = ("#EXTM3U\n#PLAYLIST:Docs Mix\n#EXTINF:215,Ada - First Song\nhttps://example.com/music/first.mp3\n" + "#EXTINF:-1,Live Radio\nhttp://radio.example/stream\nsongs/local.flac\n") + files["master.m3u8"] = ("#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=800000,CODECS=\"avc1.4d401e,mp4a.40.2\",RESOLUTION=640x360\n" + "low/index.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=2400000,RESOLUTION=1280x720\nhigh/index.m3u8\n") + files["radio.pls"] = ("[playlist]\nFile1=http://radio.example/stream\nTitle1=Radio One\nLength1=-1\n" + "File2=https://example.com/music/second.mp3\nTitle2=Second Song\nLength2=187\n" + "NumberOfEntries=2\nVersion=2\n") + files["mix.xspf"] = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<playlist version=\"1\" xmlns=\"http://xspf.org/ns/0/\">\n" + " <title>Docs Mix\n \n \n https://example.com/music/first.mp3\n" + " First Song\n Ada\n 215000\n" + " \n \n\n") + dc.emit_inputs(ctx, files, { + "zipBytes": "files.zip", + "tgzBytes": "files.tar.gz", + "sevenzBytes": "files.7z", + "xzBytes": "notes.txt.xz", + "zstBytes": "notes.txt.zst", + "msgpackBytes": "player.msgpack", + "cborBytes": "player.cbor", + "bplistBytes": "info.plist", + "csvText": "scores.csv", + "m3uText": "mix.m3u", + "hlsText": "master.m3u8", + "plsText": "radio.pls", + "xspfText": "mix.xspf", + }) diff --git a/tools/fixtures/docs_inputs.py b/tools/fixtures/docs_inputs.py new file mode 100644 index 0000000..4ab1ff3 --- /dev/null +++ b/tools/fixtures/docs_inputs.py @@ -0,0 +1,90 @@ +# Docs inputs (tools/fixtures.py): the shared files the guide snippets read (tools/docs_check.py), made by reference +# tools: a PNG written here (zlib), GIF / JPEG / WebP by ImageMagick, a stereo tone as WAV (Python's wave), FLAC, MP3 +# and Ogg Vorbis by ffmpeg with tags. +# tests/gen/docs_inputs.luau { files = { [name] = bytes }, vars = { pngBytes = "photo.png", ... } } +# tests/gen/docs_files/assets/ the same files, for the snippets that load by path +import importlib.util, io, math, os, struct, tempfile, wave, zlib + +INPUTS = ["tools/docs_check.py"] + + +def docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def png(w, h, rgba): + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff) + raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")) + + +def photo(w, h): + """a gradient with a soft-edged disc: red across, green down, a translucent right edge""" + out = bytearray() + for y in range(h): + for x in range(w): + d = math.hypot(x - w / 2, y - h / 2) / (h / 2) + out += bytes((x * 255 // (w - 1), y * 255 // (h - 1), 255 if d < 0.6 else 64, 255 if x < w - 8 else 128)) + return bytes(out) + + +def tone(rate, seconds, channels=2): + n = int(rate * seconds) + b = io.BytesIO() + with wave.open(b, "wb") as wv: + wv.setnchannels(channels) + wv.setsampwidth(2) + wv.setframerate(rate) + frames = bytearray() + for i in range(n): + env = min(1.0, i / 441, (n - i) / 441) + for c in range(channels): + f = 440 if c == 0 else 660 + frames += struct.pack("