comments: Types down to layouts, units and spec notes

This commit is contained in:
4DBug committed 2026-11-01 01:57:14 -05:00
1 parent f3daec0744
commit 07c874574c
1 file changed
+5 -79
+5 -79
View File
@@ -1,20 +1,13 @@
--!strict
-- Types: the standard value types every format of a category decodes to and encodes from, plus small constructors.
-- A PNG and a WebP both load as an Image; a WAV and an MP3 both open as an audio Decoder. Every top-level value has a
-- `kind` field ("image", "audio", "scene", ...) so F.save knows the category without a format name.
--
-- local T = require("@rosetta/Types")
-- local img = T.Image.new(64, 32) -- rgba8, zero-filled
-- local snd = T.Audio.new(44100, 2, 44100) -- 1 s of silent stereo f32
--
-- Shared enums are plain strings. Buffers are tightly packed, rows top to bottom, interleaved channels.
-- Types: the standard value types each category decodes to and encodes from, plus small constructors. Every
-- top-level value has a `kind` ("image", "audio", "scene", ...). Shared enums are plain strings; buffers are tightly
-- packed, rows top to bottom, channels interleaved.
local Err = require("@rosetta/core/Err")
local Types = {}
export type Err = Err.Err
-- ------------------------------------------------------------------------------------------------ Image
-- pixel formats: bytes per pixel. rgba8 is the default every decoder produces unless opts.native asks to keep the
-- source layout. yuv420p: Y plane (w*h) then U and V planes (ceil(w/2) * ceil(h/2) each).
export type PixelFormat = "rgba8" | "rgba16" | "rgbaf32" | "rgb8" | "gray8" | "gray16" | "graya8" | "alpha8" | "yuv420p"
@@ -65,7 +58,6 @@ export type Image = {
}
local Image = {}
-- new(width, height, format?) -> a zero-filled Image (format defaults to rgba8)
function Image.new(width: number, height: number, format: PixelFormat?): Image
local f: PixelFormat = format or "rgba8"
local size
@@ -86,16 +78,13 @@ function Image.new(width: number, height: number, format: PixelFormat?): Image
meta = {},
}
end
-- bpp(format) -> bytes per pixel (nil for planar formats)
function Image.bpp(format: string): number?
return BPP[format]
end
Types.Image = Image
-- ------------------------------------------------------------------------------------------------ Audio
export type Tags = { [string]: string } -- title, artist, album, date, genre, track, comment, ...
-- the streaming decoder every audio format's open() returns (the shape the absorbed wav/mp3/flac/ogg/opus share)
export type Decoder = {
sampleRate: number,
channels: number,
@@ -109,7 +98,6 @@ export type Decoder = {
position: (self: any) -> number, -- seconds
}
-- a fully decoded sound (F.load / F.audio.load)
export type Audio = {
kind: "audio",
sampleRate: number,
@@ -134,7 +122,6 @@ function Audio.new(sampleRate: number, channels: number, frames: number): Audio
end
Types.Audio = Audio
-- ------------------------------------------------------------------------------------------------ Music (trackers, MIDI)
export type Module = {
kind: "music",
title: string,
@@ -163,12 +150,6 @@ function Midi.new(division: number?): Midi
end
Types.Midi = Midi
-- ------------------------------------------------------------------------------------------------ Video
-- A video file opens (F.video.open / a video format's open) as a VideoDecoder; F.load returns the same object (kind =
-- "video", decoded lazily). Underneath sits a Demuxer: the container's tracks and their packets. Video tracks decode
-- through the codec registry (codecs/video/Video: by codec id or FourCC, so other codecs can plug in), audio tracks through
-- the audio formats (the api hook opts.openAudio, since a format never requires another format).
--
-- Times: Packet pts / dts / duration are integer ticks of the track's timescale (exact, for remuxing); VideoFrame pts
-- / duration and every `duration` / `seek` argument are seconds.
export type Track = {
@@ -211,11 +192,9 @@ export type Demuxer = {
duration: number, -- seconds (0 = unknown)
startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it)
meta: { [string]: any }, -- title, tags, ...
-- packets(trackId?) -> iterator of Packets in file order (one track, or all), from the current position
packets: (self: any, track: number?) -> () -> Packet?,
-- read(trackId?) -> the next Packet (one track, or any) | nil at the end
read: (self: any, track: number?) -> Packet?,
-- seek(seconds): every track to its last keyframe at or before the time
-- seek: every track to its last keyframe at or before the time
seek: (self: any, seconds: number) -> (),
track: (self: any, kind: string) -> Track?, -- the first (default) track of a kind
}
@@ -253,23 +232,10 @@ export type VideoCodecDecoder = {
reset: (self: any) -> (), -- after a seek: drop references / held pictures
}
-- ------------------------------------------------------------------------------------------------ Scene (3D, glTF-shaped)
-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no
-- padding, sparse accessors already applied). unorm / snorm types are glTF's normalized integers (value / 255,
-- max(value / 127, -1), ...). Positions are in scene units (meta.unit = metres per unit when known), meta.up is the
-- source's up axis ("y" for glTF / OBJ, "z" for STL / VOX / most CAD) - no format rotates the data on load.
--
-- Textures keep the encoded image (texture.data + texture.mime, PNG / JPEG / ... bytes) or an external reference
-- (texture.uri): a model format never decodes images (a format does not require another format). Decode them at the
-- api layer, lazily: `F.model.loadTextures(scene)` sets texture.image = F.image.load(texture.data) for each texture
-- whose image format is available (or do it yourself when needed). Writers embed texture.data when set, else write
-- texture.uri; a texture with only a decoded image must be encoded first (texture.data = F.save(texture.image, nil,
-- { format = "png" }), texture.mime = "image/png"), which `F.model.save` does for you.
--
-- Other files (OBJ's .mtl, glTF's .bin / images): decoders ask `opts.resolve(uri) -> buffer | string | nil`, or look
-- up `opts.files[uri]` (a table of buffers / strings); the api sets opts.resolve to read files next to a path it
-- loaded. Encoders that write more than one file return the main file and put the others into `opts.files` (when the
-- caller passes a table there; the api does, and writes them next to the destination), named after `opts.name`.
export type Accessor = {
data: buffer, -- tightly packed, little endian
type: "f32" | "f64" | "u8" | "u16" | "u32" | "i8" | "i16" | "i32" | "unorm8" | "unorm16" | "snorm8" | "snorm16",
@@ -377,7 +343,6 @@ export type VoxelBlocks = {
entities: { any }?, -- entity records (NBT compounds)
}
local Voxels = {}
-- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own)
function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?): Voxels
local pal = palette
if not pal then
@@ -389,7 +354,6 @@ function Voxels.new(sx: number, sy: number, sz: number, palette: { { number } }?
end
return { kind = "voxels", size = { sx, sy, sz }, data = buffer.create(sx * sy * sz), palette = pal :: { { number } }, materials = nil }
end
-- get / set(v, x, y, z [, index]): 0-based cell coordinates, no bounds check
function Voxels.get(v: Voxels, x: number, y: number, z: number): number
return buffer.readu8(v.data, x + v.size[1] * (y + v.size[2] * z))
end
@@ -430,7 +394,6 @@ function Scene.new(): Scene
meta = {},
}
end
-- the byte size of one component of an accessor type
local COMPONENT_SIZE: { [string]: number } = {
f32 = 4,
f64 = 8,
@@ -446,7 +409,6 @@ local COMPONENT_SIZE: { [string]: number } = {
snorm16 = 2,
}
Types.COMPONENT_SIZE = table.freeze(COMPONENT_SIZE) :: { [string]: number }
-- accessor(data, type, components, count) -> Accessor (data = nil allocates a zero-filled buffer)
function Scene.accessor(data: buffer?, type: any, components: number, count: number): Accessor
local d = data or buffer.create(count * components * (COMPONENT_SIZE[type] or 4))
return { data = d, type = type, components = components, count = count }
@@ -463,7 +425,6 @@ function Scene.material(name: string?): Material
doubleSided = false,
}
end
-- one-node scene around a single primitive (mesh-only formats: STL, OBJ, PLY, OFF)
function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
local s = Scene.new()
s.meshes[1] = { name = name, primitives = { prim } }
@@ -473,8 +434,6 @@ function Scene.fromPrimitive(prim: Primitive, name: string?): Scene
end
Types.Scene = Scene
-- reader(acc) -> get(i, c): element i (0-based), component c (0-based) as a number; normalized types are converted
-- to floats (unorm8 255 -> 1, snorm16 -32767 -> -1, glTF rules). Nil for an unknown type.
function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)?
local d, n, t = acc.data, acc.components, acc.type
local size = COMPONENT_SIZE[t]
@@ -537,7 +496,6 @@ function Scene.reader(acc: Accessor): ((i: number, c: number) -> number)?
return nil
end
-- the identity and products of column-major 4x4 matrices (flat arrays of 16)
local IDENTITY = table.freeze({ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 })
Scene.IDENTITY = IDENTITY
function Scene.mul(a: { number }, b: { number }): { number }
@@ -553,7 +511,6 @@ function Scene.mul(a: { number }, b: { number }): { number }
end
return m
end
-- nodeMatrix(node) -> the node's local matrix (node.matrix, or T * R * S)
function Scene.nodeMatrix(node: Node): { number }
if node.matrix and #node.matrix == 16 then
return node.matrix
@@ -583,8 +540,6 @@ function Scene.nodeMatrix(node: Node): { number }
}
end
export type Placed = { primitive: Primitive, matrix: { number }, node: number, mesh: number }
-- flatten(scene) -> { { primitive, matrix (world), node, mesh } } for every mesh primitive reachable from the roots
-- (depth first, in order; cycles and repeated visits are cut). Scenes without roots use every node without a parent.
function Scene.flatten(scene: Scene): { Placed }
local out: { Placed } = {}
local nodes = scene.nodes or {}
@@ -628,7 +583,6 @@ function Scene.flatten(scene: Scene): { Placed }
return out
end
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Rosetta.plugins.brep)
-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order;
-- section = the DATA section index when a file has more than one (edition 3)
@@ -641,7 +595,6 @@ export type Cad = {
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Font
export type Font = {
kind: "font",
info: { family: string?, style: string?, fullName: string?, [string]: any },
@@ -678,7 +631,6 @@ export type BitmapStrike = {
map: { [number]: number }?, -- extra code point -> glyph index (0-based) mappings (several code points on one glyph)
}
-- ------------------------------------------------------------------------------------------------ Archive
export type ArchiveEntry = { name: string, size: number, compressedSize: number?, method: string?, mtime: number?, dir: boolean }
export type Archive = {
kind: "archive",
@@ -690,7 +642,6 @@ export type Archive = {
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ Data
-- data formats decode to plain Luau values; JSON null / YAML ~ / CBOR null is this sentinel (nil cannot sit in a
-- table). XML decodes to XmlNode trees. Byte strings (msgpack bin, CBOR bytes, plist data) are buffers.
local nullMeta = { __tostring = function()
@@ -701,12 +652,8 @@ Types.null = table.freeze(setmetatable({}, nullMeta))
-- Objects (maps) whose key order matters, and empty objects (which would otherwise read back as empty arrays), carry
-- an "object" metatable with their key order. Decoders mark empty objects always and every object when asked
-- (opts.ordered); encoders write an object's keys in that order (keys added later, or plain tables: sorted).
-- local o = Types.object() o.b = 1; o.a = 2 -- or Types.object({ a = 2, b = 1 }, { "b", "a" })
-- Types.set(o, "c", 3) -- assigns and appends "c" to the order
-- for _, k in Types.keys(o) do ... end
local OBJECT = { __object = true }
local objectMeta: { [any]: { any } } = setmetatable({}, { __mode = "k" }) :: any -- object -> its key order
-- object(t?, keys?) -> t marked as an object, keys = its key order (default: none recorded; Types.set appends)
function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
local o: { [any]: any } = t or {}
if getmetatable(o) == nil then
@@ -715,11 +662,9 @@ function Types.object(t: { [any]: any }?, keys: { any }?): { [any]: any }
objectMeta[o] = keys or {}
return o
end
-- isObject(v) -> true for tables made by Types.object
function Types.isObject(v: any): boolean
return type(v) == "table" and objectMeta[v] ~= nil
end
-- set(o, k, v): o[k] = v, appending k to o's key order when new (o must be an object; a plain table just assigns)
function Types.set(o: { [any]: any }, k: any, v: any)
local order = objectMeta[o]
if order and o[k] == nil and v ~= nil then
@@ -727,7 +672,6 @@ function Types.set(o: { [any]: any }, k: any, v: any)
end
o[k] = v
end
-- keyLess(a, b): a total order for table keys (by type name, then value; numbers before strings)
local function keyLess(a: any, b: any): boolean
local ta, tb = type(a), type(b)
if ta ~= tb then
@@ -740,8 +684,6 @@ local function keyLess(a: any, b: any): boolean
end
Types.keyLess = keyLess
-- isArray(t, emptyIsMap?) -> t is a plain array 1 .. #t (no other keys, not an ordered object); an empty table is an
-- array unless emptyIsMap
function Types.isArray(t: { [any]: any }, emptyIsMap: boolean?): boolean
if Types.isObject(t) then
return false
@@ -759,8 +701,6 @@ function Types.isArray(t: { [any]: any }, emptyIsMap: boolean?): boolean
end
return c == n
end
-- keys(t) -> the keys in order: an object's recorded order (keys since removed are skipped), then any other keys
-- sorted (numbers before strings)
function Types.keys(t: { [any]: any }): { any }
local order = objectMeta[t]
local out, seen = {}, {}
@@ -859,7 +799,6 @@ end
DateLib.civilFromDays = civilFromDays -- days since 1970-01-01 -> year, month, day (proleptic Gregorian)
DateLib.daysFromCivil = daysFromCivil -- year, month, day -> days since 1970-01-01
local MDAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
-- new(fields) -> Date (kind inferred from the fields present when not given)
function DateLib.new(f: { [string]: any }): Date
local d: any = {}
for k, v in f do
@@ -872,11 +811,9 @@ function DateLib.new(f: { [string]: any }): Date
end
return setmetatable(d, DateMeta) :: any
end
-- is(v) -> true for Dates
function DateLib.is(v: any): boolean
return type(v) == "table" and getmetatable(v) == DateMeta
end
-- valid(d) -> true when the fields are in range (month 1..12, the day exists in that month, hour < 24, ...)
function DateLib.valid(d: Date): boolean
if d.year then
local y, m, dd = d.year, d.month or 0, d.day or 0
@@ -897,8 +834,7 @@ function DateLib.valid(d: Date): boolean
end
return true
end
-- parse(s) -> Date | nil: RFC 3339 / ISO 8601 date-times and their TOML partial forms ("1979-05-27",
-- "07:32:00.999", "1979-05-27 07:32:00Z", lower-case t / z accepted); out-of-range fields return nil
-- parse: RFC 3339 / ISO 8601 date-times and the TOML partial forms; lower-case t / z accepted
function DateLib.parse(s: string): Date?
local d: any = {}
local rest: string = s
@@ -954,13 +890,11 @@ function DateLib.parse(s: string): Date?
end
return if DateLib.valid(d) then DateLib.new(d) else nil
end
-- toUnix(d) -> seconds since 1970-01-01T00:00:00Z (fractional; local times are taken as UTC)
function DateLib.toUnix(d: Date): number
local days = if d.year then daysFromCivil(d.year, d.month or 1, d.day or 1) else 0
local s = days * 86400 + (d.hour or 0) * 3600 + (d.minute or 0) * 60 + (d.second or 0) - (d.offset or 0) * 60
return s + (d.nanosecond or 0) / 1e9
end
-- fromUnix(seconds, offset?) -> a "datetime" Date (offset in minutes, default 0 = UTC)
function DateLib.fromUnix(t: number, offset: number?): Date
local off = offset or 0
local whole = math.floor(t)
@@ -1000,7 +934,6 @@ export type XmlNode = {
[string]: any,
}
-- ------------------------------------------------------------------------------------------------ Vector
export type Paint = { type: "color", color: { number } } | { type: "linear" | "radial", stops: { { number } }, [string]: any }
export type VectorPath = {
d: { { op: string, [number]: number } }, -- absolute M / L / C / Q / Z commands
@@ -1033,7 +966,6 @@ function Vector.new(width: number, height: number): Vector
end
Types.Vector = Vector
-- ------------------------------------------------------------------------------------------------ Layered (PSD, Aseprite)
-- blend: a codecs/image/Blend mode name ("normal", "multiply", ...; groups also "passThrough"). Optional: children (a group:
-- its layers bottom to top; its image is 0 x 0), clip (clipped to the alpha of the layer below), mask (a grey mask in
-- canvas coordinates; outside its rectangle the mask is `default`).
@@ -1051,17 +983,14 @@ local Layered = {}
function Layered.new(width: number, height: number): Layered
return { kind = "layered", width = width, height = height, layers = {}, frames = nil, meta = {} }
end
-- layer(name, image, x?, y?) -> a visible normal layer at full opacity
function Layered.layer(name: string, image: Image, x: number?, y: number?): Layer
return { name = name, image = image, x = x or 0, y = y or 0, opacity = 1, blend = "normal", visible = true }
end
-- group(name, children) -> a pass-through group layer
function Layered.group(name: string, children: { Layer }): Layer
return { name = name, image = Image.new(0, 0), x = 0, y = 0, opacity = 1, blend = "passThrough", visible = true, children = children }
end
Types.Layered = Layered
-- ------------------------------------------------------------------------------------------------ TileMap (Tiled)
-- gids are Tiled's: 0 = empty, the tile's firstGid-relative index, flip / rotation flags in the top bits (kept).
-- Tilesets keep their image as a reference (imageSource: the path as written; image: an Image only if a caller
-- loads it). Extra Tiled fields sit next to these (offsetX / offsetY, parallax, tintColor, class, chunks of infinite
@@ -1087,7 +1016,6 @@ function TileMap.new(width: number, height: number, tileWidth: number, tileHeigh
end
Types.TileMap = TileMap
-- ------------------------------------------------------------------------------------------------ Subtitles
export type Cue = { start: number, stop: number, text: string, style: string?, id: string?, [string]: any } -- seconds
export type Subtitles = { kind: "subtitles", cues: { Cue }, styles: { [string]: any }, meta: { [string]: any } }
local Subtitles = {}
@@ -1096,7 +1024,6 @@ function Subtitles.new(): Subtitles
end
Types.Subtitles = Subtitles
-- ------------------------------------------------------------------------------------------------ Playlist
-- the playlist-luau shape
export type PlaylistEntry = {
url: string,
@@ -1119,7 +1046,6 @@ export type Playlist = {
meta: { [string]: any },
}
-- ------------------------------------------------------------------------------------------------ the format contract
-- what every format folder's init.luau returns (checked by tools/lint.sh CONTRACT; see docs/STYLE.md)
export type Caps = { decode: boolean, encode: boolean, [string]: any }
export type Format = {